2020-01-12 20:08:36 +01:00
|
|
|
#!/usr/bin/env python3
|
2020-01-13 02:36:00 +01:00
|
|
|
"""
|
|
|
|
Jetforce, an experimental Gemini server.
|
|
|
|
|
|
|
|
Overview
|
|
|
|
--------
|
|
|
|
|
|
|
|
GeminiServer:
|
|
|
|
An asynchronous TCP server built on top of python's asyncio stream
|
|
|
|
abstraction. This is a lightweight class that accepts incoming requests,
|
|
|
|
logs them, and sends them to a configurable request handler to be processed.
|
|
|
|
|
|
|
|
GeminiRequestHandler:
|
|
|
|
The request handler manages the life of a single gemini request. It exposes
|
|
|
|
a simplified interface to read the request URL and write the gemini response
|
|
|
|
status line and body to the socket. The request URL and other server
|
|
|
|
information is stuffed into an ``environ`` dictionary that encapsulates the
|
|
|
|
request at a low level. This dictionary, along with a callback to write the
|
|
|
|
response data, and passed to a configurable "application" function or class.
|
|
|
|
|
|
|
|
JetforceApplication:
|
|
|
|
This is a base class for writing jetforce server applications. It doesn't
|
|
|
|
anything on its own, but it does provide a convenient interface to define
|
|
|
|
custom server endpoints using route decorators. If you want to utilize
|
|
|
|
jetforce as a library and write your own server in python, this is the class
|
|
|
|
that you want to extend. The examples/ directory contains some examples of
|
|
|
|
how to accomplish this.
|
|
|
|
|
|
|
|
StaticDirectoryApplication:
|
|
|
|
This is a pre-built application that serves files from a static directory.
|
|
|
|
It provides an "out-of-the-box" gemini server without needing to write any
|
|
|
|
lines of code. This is what is invoked when you launch jetforce from the
|
|
|
|
command line.
|
|
|
|
"""
|
2019-08-29 04:33:58 +02:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2019-08-04 19:52:54 +02:00
|
|
|
import argparse
|
2020-05-13 05:50:12 +02:00
|
|
|
import base64
|
2019-08-27 05:41:10 +02:00
|
|
|
import codecs
|
2019-08-23 00:53:02 +02:00
|
|
|
import dataclasses
|
2020-05-09 06:58:16 +02:00
|
|
|
import datetime
|
2019-08-05 03:42:27 +02:00
|
|
|
import mimetypes
|
2019-08-06 16:35:03 +02:00
|
|
|
import os
|
2019-08-06 04:21:28 +02:00
|
|
|
import pathlib
|
2019-08-23 00:53:02 +02:00
|
|
|
import re
|
2020-01-13 01:31:08 +01:00
|
|
|
import socket
|
2019-08-06 04:49:48 +02:00
|
|
|
import subprocess
|
2019-08-04 19:52:54 +02:00
|
|
|
import sys
|
2019-08-06 04:49:48 +02:00
|
|
|
import tempfile
|
2019-09-23 03:59:20 +02:00
|
|
|
import time
|
2019-08-06 00:47:59 +02:00
|
|
|
import typing
|
2019-08-12 17:24:42 +02:00
|
|
|
import urllib.parse
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2020-05-09 06:58:16 +02:00
|
|
|
from cryptography import x509
|
|
|
|
from cryptography.hazmat.backends import default_backend
|
|
|
|
from cryptography.hazmat.primitives import hashes, serialization
|
|
|
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
2020-05-11 04:16:36 +02:00
|
|
|
from OpenSSL import SSL
|
2020-05-13 05:50:12 +02:00
|
|
|
from twisted.internet import reactor
|
2020-05-13 06:32:51 +02:00
|
|
|
from twisted.internet.address import IPv4Address, IPv6Address
|
2020-05-13 05:50:12 +02:00
|
|
|
from twisted.internet.base import ReactorBase
|
|
|
|
from twisted.internet.endpoints import SSL4ServerEndpoint
|
|
|
|
from twisted.internet.protocol import Factory
|
2020-05-15 06:11:09 +02:00
|
|
|
from twisted.internet.ssl import CertificateOptions, TLSVersion
|
2020-05-13 05:50:12 +02:00
|
|
|
from twisted.internet.tcp import Port
|
|
|
|
from twisted.protocols.basic import LineOnlyReceiver
|
2020-05-15 06:11:09 +02:00
|
|
|
from twisted.python.randbytes import secureRandom
|
2020-05-09 06:58:16 +02:00
|
|
|
|
2019-08-06 04:21:28 +02:00
|
|
|
if sys.version_info < (3, 7):
|
|
|
|
sys.exit("Fatal Error: jetforce requires Python 3.7+")
|
|
|
|
|
2020-03-31 16:41:39 +02:00
|
|
|
__version__ = "0.2.2"
|
2019-08-04 19:52:54 +02:00
|
|
|
__title__ = "Jetforce Gemini Server"
|
|
|
|
__author__ = "Michael Lazar"
|
2019-09-23 15:26:09 +02:00
|
|
|
__license__ = "Floodgap Free Software License"
|
2020-01-12 20:08:36 +01:00
|
|
|
__copyright__ = "(c) 2020 Michael Lazar"
|
2019-08-04 19:52:54 +02:00
|
|
|
|
|
|
|
ABOUT = fr"""
|
2019-08-05 03:42:27 +02:00
|
|
|
You are now riding on...
|
2019-08-04 19:52:54 +02:00
|
|
|
_________ _____________
|
|
|
|
______ /______ /___ __/_______________________
|
|
|
|
___ _ /_ _ \ __/_ /_ _ __ \_ ___/ ___/ _ \
|
|
|
|
/ /_/ / / __/ /_ _ __/ / /_/ / / / /__ / __/
|
|
|
|
\____/ \___/\__/ /_/ \____//_/ \___/ \___/
|
|
|
|
|
2019-08-05 03:42:27 +02:00
|
|
|
An Experimental Gemini Server, v{__version__}
|
2019-08-04 19:52:54 +02:00
|
|
|
https://github.com/michael-lazar/jetforce
|
|
|
|
"""
|
|
|
|
|
2020-05-15 06:11:09 +02:00
|
|
|
CN = x509.NameOID.COMMON_NAME
|
|
|
|
|
2019-08-12 16:04:37 +02:00
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
class Status:
|
|
|
|
"""
|
|
|
|
Gemini response status codes.
|
|
|
|
"""
|
|
|
|
|
|
|
|
INPUT = 10
|
|
|
|
|
|
|
|
SUCCESS = 20
|
|
|
|
SUCCESS_END_OF_SESSION = 21
|
|
|
|
|
|
|
|
REDIRECT_TEMPORARY = 30
|
|
|
|
REDIRECT_PERMANENT = 31
|
2019-08-12 16:04:37 +02:00
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
TEMPORARY_FAILURE = 40
|
|
|
|
SERVER_UNAVAILABLE = 41
|
|
|
|
CGI_ERROR = 42
|
|
|
|
PROXY_ERROR = 43
|
|
|
|
SLOW_DOWN = 44
|
2019-08-12 16:04:37 +02:00
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
PERMANENT_FAILURE = 50
|
|
|
|
NOT_FOUND = 51
|
|
|
|
GONE = 52
|
|
|
|
PROXY_REQUEST_REFUSED = 53
|
|
|
|
BAD_REQUEST = 59
|
2019-08-12 16:04:37 +02:00
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
CLIENT_CERTIFICATE_REQUIRED = 60
|
|
|
|
TRANSIENT_CERTIFICATE_REQUESTED = 61
|
|
|
|
AUTHORISED_CERTIFICATE_REQUIRED = 62
|
|
|
|
CERTIFICATE_NOT_ACCEPTED = 63
|
|
|
|
FUTURE_CERTIFICATE_REJECTED = 64
|
|
|
|
EXPIRED_CERTIFICATE_REJECTED = 65
|
2019-08-04 19:52:54 +02:00
|
|
|
|
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
class Request:
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
2019-08-23 00:53:02 +02:00
|
|
|
Object that encapsulates information about a single gemini request.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, environ: dict):
|
|
|
|
self.environ = environ
|
2019-08-27 05:41:10 +02:00
|
|
|
self.url = environ["GEMINI_URL"]
|
|
|
|
|
|
|
|
url_parts = urllib.parse.urlparse(self.url)
|
2020-01-12 23:15:19 +01:00
|
|
|
if not url_parts.hostname:
|
|
|
|
raise ValueError("URL must contain a `hostname` part")
|
|
|
|
|
|
|
|
if not url_parts.scheme:
|
|
|
|
# If scheme is missing, infer it to be gemini://
|
|
|
|
self.scheme = "gemini"
|
|
|
|
else:
|
|
|
|
self.scheme = url_parts.scheme
|
|
|
|
|
2019-08-27 05:41:10 +02:00
|
|
|
self.hostname = url_parts.hostname
|
|
|
|
self.port = url_parts.port
|
|
|
|
self.path = url_parts.path
|
|
|
|
self.params = url_parts.params
|
2019-08-29 04:33:58 +02:00
|
|
|
self.query = urllib.parse.unquote(url_parts.query)
|
2019-08-27 05:41:10 +02:00
|
|
|
self.fragment = url_parts.fragment
|
2019-08-21 03:17:58 +02:00
|
|
|
|
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
@dataclasses.dataclass
|
|
|
|
class Response:
|
|
|
|
"""
|
|
|
|
Object that encapsulates information about a single gemini response.
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
status: int
|
|
|
|
meta: str
|
|
|
|
body: typing.Union[None, bytes, str, typing.Iterator[bytes]] = None
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
|
|
|
|
@dataclasses.dataclass
|
|
|
|
class RoutePattern:
|
|
|
|
"""
|
|
|
|
A pattern for matching URLs with a single endpoint or route.
|
|
|
|
"""
|
|
|
|
|
2020-03-31 16:41:39 +02:00
|
|
|
path: str = ".*"
|
2019-08-23 00:53:02 +02:00
|
|
|
scheme: str = "gemini"
|
2020-03-11 05:06:22 +01:00
|
|
|
hostname: typing.Optional[str] = None
|
2020-01-13 00:24:04 +01:00
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
strict_hostname: bool = True
|
2020-01-13 00:24:04 +01:00
|
|
|
strict_port: bool = True
|
2019-08-23 00:53:02 +02:00
|
|
|
strict_trailing_slash: bool = False
|
|
|
|
|
2020-03-31 06:36:28 +02:00
|
|
|
def match(self, request: Request) -> typing.Optional[re.Match]:
|
2019-08-21 03:17:58 +02:00
|
|
|
"""
|
2019-08-23 00:53:02 +02:00
|
|
|
Check if the given request URL matches this route pattern.
|
2019-08-21 03:17:58 +02:00
|
|
|
"""
|
2020-03-11 05:06:22 +01:00
|
|
|
if self.hostname is None:
|
|
|
|
server_hostname = request.environ["HOSTNAME"]
|
|
|
|
else:
|
|
|
|
server_hostname = self.hostname
|
2020-01-13 00:24:04 +01:00
|
|
|
server_port = int(request.environ["SERVER_PORT"])
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
if self.strict_hostname and request.hostname != server_hostname:
|
2020-03-31 06:36:28 +02:00
|
|
|
return
|
2020-01-13 00:24:04 +01:00
|
|
|
if self.strict_port and request.port is not None:
|
|
|
|
if request.port != server_port:
|
2020-03-31 06:36:28 +02:00
|
|
|
return
|
2019-08-23 00:53:02 +02:00
|
|
|
if self.scheme and self.scheme != request.scheme:
|
2020-03-31 06:36:28 +02:00
|
|
|
return
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
if self.strict_trailing_slash:
|
|
|
|
request_path = request.path
|
|
|
|
else:
|
|
|
|
request_path = request.path.rstrip("/")
|
|
|
|
|
2020-03-31 06:36:28 +02:00
|
|
|
return re.fullmatch(self.path, request_path)
|
2019-08-23 00:53:02 +02:00
|
|
|
|
|
|
|
|
|
|
|
class JetforceApplication:
|
|
|
|
"""
|
|
|
|
Base Jetforce application class with primitive URL routing.
|
2020-01-13 02:36:00 +01:00
|
|
|
|
|
|
|
This is a base class for writing jetforce server applications. It doesn't
|
|
|
|
anything on its own, but it does provide a convenient interface to define
|
|
|
|
custom server endpoints using route decorators. If you want to utilize
|
|
|
|
jetforce as a library and write your own server in python, this is the class
|
|
|
|
that you want to extend. The examples/ directory contains some examples of
|
|
|
|
how to accomplish this.
|
2019-08-23 00:53:02 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self.routes: typing.List[
|
|
|
|
typing.Tuple[RoutePattern, typing.Callable[[Request], Response]]
|
|
|
|
] = []
|
|
|
|
|
2019-08-28 05:44:07 +02:00
|
|
|
def __call__(
|
|
|
|
self, environ: dict, send_status: typing.Callable
|
|
|
|
) -> typing.Iterator[bytes]:
|
2020-01-12 23:15:19 +01:00
|
|
|
try:
|
|
|
|
request = Request(environ)
|
|
|
|
except Exception:
|
|
|
|
send_status(Status.BAD_REQUEST, "Unrecognized URL format")
|
|
|
|
return
|
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
for route_pattern, callback in self.routes[::-1]:
|
|
|
|
if route_pattern.match(request):
|
|
|
|
break
|
|
|
|
else:
|
2020-01-12 23:51:52 +01:00
|
|
|
callback = self.default_callback
|
|
|
|
|
|
|
|
response = callback(request)
|
|
|
|
send_status(response.status, response.meta)
|
|
|
|
if isinstance(response.body, bytes):
|
|
|
|
yield response.body
|
|
|
|
elif isinstance(response.body, str):
|
|
|
|
yield response.body.encode()
|
|
|
|
elif response.body:
|
|
|
|
yield from response.body
|
2019-08-23 00:53:02 +02:00
|
|
|
|
|
|
|
def route(
|
|
|
|
self,
|
2020-03-31 06:36:28 +02:00
|
|
|
path: str = ".*",
|
2019-08-23 00:53:02 +02:00
|
|
|
scheme: str = "gemini",
|
2020-03-11 05:06:22 +01:00
|
|
|
hostname: typing.Optional[str] = None,
|
2019-08-23 00:53:02 +02:00
|
|
|
strict_hostname: bool = True,
|
|
|
|
strict_trailing_slash: bool = False,
|
|
|
|
) -> typing.Callable:
|
|
|
|
"""
|
|
|
|
Decorator for binding a function to a route based on the URL path.
|
|
|
|
|
|
|
|
app = JetforceApplication()
|
|
|
|
|
|
|
|
@app.route('/my-path')
|
|
|
|
def my_path(request):
|
|
|
|
return Response(Status.SUCCESS, 'text/plain', 'Hello world!')
|
|
|
|
"""
|
|
|
|
route_pattern = RoutePattern(
|
2020-03-11 05:06:22 +01:00
|
|
|
path, scheme, hostname, strict_hostname, strict_trailing_slash
|
2019-08-23 00:53:02 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
def wrap(func: typing.Callable) -> typing.Callable:
|
|
|
|
self.routes.append((route_pattern, func))
|
|
|
|
return func
|
|
|
|
|
|
|
|
return wrap
|
|
|
|
|
2020-01-12 23:51:52 +01:00
|
|
|
def default_callback(self, request: Request) -> Response:
|
|
|
|
"""
|
|
|
|
Set the error response based on the URL type.
|
|
|
|
"""
|
|
|
|
return Response(Status.PERMANENT_FAILURE, "Not Found")
|
|
|
|
|
2020-05-13 07:37:21 +02:00
|
|
|
@classmethod
|
|
|
|
def add_arguments(cls, parser: argparse.ArgumentParser) -> None:
|
|
|
|
"""
|
|
|
|
Add any application-specific arguments to the GeminiServer parser.
|
|
|
|
|
|
|
|
The destination variables for these arguments should match the method
|
|
|
|
signature for this class's __init__ method.
|
|
|
|
"""
|
|
|
|
return
|
|
|
|
|
2019-08-23 00:53:02 +02:00
|
|
|
|
|
|
|
class StaticDirectoryApplication(JetforceApplication):
|
2019-08-05 03:42:27 +02:00
|
|
|
"""
|
2020-01-13 02:36:00 +01:00
|
|
|
Application for serving static files & CGI over gemini.
|
|
|
|
|
|
|
|
This is a pre-built application that serves files from a static directory.
|
|
|
|
It provides an "out-of-the-box" gemini server without needing to write any
|
|
|
|
lines of code. This is what is invoked when you launch jetforce from the
|
|
|
|
command line.
|
2019-08-05 03:42:27 +02:00
|
|
|
|
2019-09-23 15:28:05 +02:00
|
|
|
If a directory contains a file with the name "index.gmi", that file will
|
|
|
|
be returned when the directory path is requested. Otherwise, a directory
|
2019-09-24 01:34:38 +02:00
|
|
|
listing will be auto-generated.
|
2019-08-05 03:42:27 +02:00
|
|
|
"""
|
|
|
|
|
2019-08-27 05:41:10 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
root_directory: str = "/var/gemini",
|
|
|
|
index_file: str = "index.gmi",
|
2019-08-28 04:52:38 +02:00
|
|
|
cgi_directory: str = "cgi-bin",
|
2019-08-27 05:41:10 +02:00
|
|
|
):
|
2019-08-23 00:53:02 +02:00
|
|
|
super().__init__()
|
|
|
|
self.routes.append((RoutePattern(), self.serve_static_file))
|
|
|
|
|
2019-08-27 05:41:10 +02:00
|
|
|
self.root = pathlib.Path(root_directory).resolve(strict=True)
|
|
|
|
self.cgi_directory = cgi_directory.strip("/") + "/"
|
|
|
|
|
2019-08-23 15:45:24 +02:00
|
|
|
self.index_file = index_file
|
2019-08-05 03:42:27 +02:00
|
|
|
self.mimetypes = mimetypes.MimeTypes()
|
2019-08-23 00:53:02 +02:00
|
|
|
self.mimetypes.add_type("text/gemini", ".gmi")
|
2019-08-23 15:45:24 +02:00
|
|
|
self.mimetypes.add_type("text/gemini", ".gemini")
|
2019-08-05 03:42:27 +02:00
|
|
|
|
2020-05-13 07:37:21 +02:00
|
|
|
@classmethod
|
|
|
|
def add_arguments(cls, parser: argparse.ArgumentParser):
|
|
|
|
# fmt: off
|
|
|
|
parser.add_argument(
|
|
|
|
"--dir",
|
|
|
|
help="Root directory on the filesystem to serve",
|
|
|
|
default="/var/gemini",
|
|
|
|
metavar="DIR",
|
|
|
|
dest="root_directory",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--cgi-dir",
|
|
|
|
help="CGI script directory, relative to the server's root directory",
|
|
|
|
default="cgi-bin",
|
|
|
|
metavar="DIR",
|
|
|
|
dest="cgi_directory",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--index-file",
|
|
|
|
help="If a directory contains a file with this name, "
|
|
|
|
"that file will be served instead of auto-generating an index page",
|
|
|
|
default="index.gmi",
|
|
|
|
metavar="FILE",
|
|
|
|
dest="index_file",
|
|
|
|
)
|
|
|
|
# fmt: on
|
|
|
|
|
2019-08-28 05:44:07 +02:00
|
|
|
def serve_static_file(self, request: Request) -> Response:
|
2019-08-27 15:47:53 +02:00
|
|
|
"""
|
|
|
|
Convert a URL into a filesystem path, and attempt to serve the file
|
|
|
|
or directory that is represented at that path.
|
|
|
|
"""
|
2019-08-23 00:53:02 +02:00
|
|
|
url_path = pathlib.Path(request.path.strip("/"))
|
2019-08-05 03:42:27 +02:00
|
|
|
|
2019-08-06 16:35:03 +02:00
|
|
|
filename = pathlib.Path(os.path.normpath(str(url_path)))
|
2019-08-07 05:47:11 +02:00
|
|
|
if filename.is_absolute() or str(filename.name).startswith(".."):
|
2019-08-05 03:42:27 +02:00
|
|
|
# Guard against breaking out of the directory
|
2019-08-23 00:53:02 +02:00
|
|
|
return Response(Status.NOT_FOUND, "Not Found")
|
2019-08-21 03:17:58 +02:00
|
|
|
|
|
|
|
filesystem_path = self.root / filename
|
2019-08-05 03:42:27 +02:00
|
|
|
|
2020-01-13 00:55:28 +01:00
|
|
|
try:
|
|
|
|
if not os.access(filesystem_path, os.R_OK):
|
|
|
|
# File not readable
|
|
|
|
return Response(Status.NOT_FOUND, "Not Found")
|
|
|
|
except OSError:
|
|
|
|
# Filename too large, etc.
|
|
|
|
return Response(Status.NOT_FOUND, "Not Found")
|
|
|
|
|
2019-08-06 04:21:28 +02:00
|
|
|
if filesystem_path.is_file():
|
2019-08-27 15:47:53 +02:00
|
|
|
is_cgi = str(filename).startswith(self.cgi_directory)
|
|
|
|
is_exe = os.access(filesystem_path, os.X_OK)
|
|
|
|
if is_cgi and is_exe:
|
|
|
|
return self.run_cgi_script(filesystem_path, request.environ)
|
|
|
|
|
2019-09-03 02:58:22 +02:00
|
|
|
mimetype = self.guess_mimetype(filesystem_path.name)
|
|
|
|
generator = self.load_file(filesystem_path)
|
|
|
|
return Response(Status.SUCCESS, mimetype, generator)
|
2019-08-27 15:47:53 +02:00
|
|
|
|
2019-08-06 04:21:28 +02:00
|
|
|
elif filesystem_path.is_dir():
|
2020-01-12 20:00:42 +01:00
|
|
|
if not request.path.endswith("/"):
|
2019-09-03 02:58:22 +02:00
|
|
|
url_parts = urllib.parse.urlparse(request.url)
|
2020-05-13 07:37:21 +02:00
|
|
|
# noinspection PyProtectedMember
|
2019-09-03 02:58:22 +02:00
|
|
|
url_parts = url_parts._replace(path=request.path + "/")
|
|
|
|
return Response(Status.REDIRECT_PERMANENT, url_parts.geturl())
|
|
|
|
|
2019-08-23 15:45:24 +02:00
|
|
|
index_file = filesystem_path / self.index_file
|
|
|
|
if index_file.exists():
|
|
|
|
generator = self.load_file(index_file)
|
2019-08-27 15:47:53 +02:00
|
|
|
return Response(Status.SUCCESS, "text/gemini", generator)
|
|
|
|
|
2019-09-03 02:58:22 +02:00
|
|
|
generator = self.list_directory(url_path, filesystem_path)
|
|
|
|
return Response(Status.SUCCESS, "text/gemini", generator)
|
2019-08-27 15:47:53 +02:00
|
|
|
|
2019-08-05 03:42:27 +02:00
|
|
|
else:
|
2019-08-23 00:53:02 +02:00
|
|
|
return Response(Status.NOT_FOUND, "Not Found")
|
2019-08-05 03:42:27 +02:00
|
|
|
|
2019-08-28 05:44:07 +02:00
|
|
|
def run_cgi_script(self, filesystem_path: pathlib.Path, environ: dict) -> Response:
|
2019-08-29 04:33:58 +02:00
|
|
|
"""
|
|
|
|
Execute the given file as a CGI script and return the script's stdout
|
|
|
|
stream to the client.
|
|
|
|
"""
|
2019-08-27 05:41:10 +02:00
|
|
|
script_name = str(filesystem_path)
|
|
|
|
cgi_env = environ.copy()
|
|
|
|
cgi_env["GATEWAY_INTERFACE"] = "GCI/1.1"
|
|
|
|
cgi_env["SCRIPT_NAME"] = script_name
|
|
|
|
|
2019-08-29 04:33:58 +02:00
|
|
|
# Decode the stream as unicode so we can parse the status line
|
|
|
|
# Use surrogateescape to preserve any non-UTF8 byte sequences.
|
2019-08-27 05:41:10 +02:00
|
|
|
out = subprocess.Popen(
|
|
|
|
[script_name],
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
env=cgi_env,
|
|
|
|
bufsize=1,
|
|
|
|
universal_newlines=True,
|
|
|
|
errors="surrogateescape",
|
|
|
|
)
|
|
|
|
|
2019-08-27 15:47:53 +02:00
|
|
|
status_line = out.stdout.readline().strip()
|
|
|
|
status_parts = status_line.split(maxsplit=1)
|
|
|
|
if len(status_parts) != 2 or not status_parts[0].isdecimal():
|
2019-08-27 16:38:38 +02:00
|
|
|
return Response(Status.CGI_ERROR, "Unexpected Error")
|
2019-08-27 15:47:53 +02:00
|
|
|
|
|
|
|
status, meta = status_parts
|
2019-08-27 05:41:10 +02:00
|
|
|
|
|
|
|
# Re-encode the rest of the body as bytes
|
|
|
|
body = codecs.iterencode(out.stdout, encoding="utf-8", errors="surrogateescape")
|
2019-08-27 15:47:53 +02:00
|
|
|
return Response(int(status), meta, body)
|
2019-08-27 05:41:10 +02:00
|
|
|
|
2019-08-28 05:44:07 +02:00
|
|
|
def load_file(self, filesystem_path: pathlib.Path) -> typing.Iterator[bytes]:
|
2019-08-27 15:47:53 +02:00
|
|
|
"""
|
2020-05-09 07:34:02 +02:00
|
|
|
Load a file in chunks to allow streaming to the TCP socket.
|
2019-08-27 15:47:53 +02:00
|
|
|
"""
|
2019-08-06 04:21:28 +02:00
|
|
|
with filesystem_path.open("rb") as fp:
|
2019-08-05 03:42:27 +02:00
|
|
|
data = fp.read(1024)
|
|
|
|
while data:
|
|
|
|
yield data
|
|
|
|
data = fp.read(1024)
|
|
|
|
|
2019-08-28 05:44:07 +02:00
|
|
|
def list_directory(
|
|
|
|
self, url_path: pathlib.Path, filesystem_path: pathlib.Path
|
|
|
|
) -> typing.Iterator[bytes]:
|
2019-08-23 00:53:02 +02:00
|
|
|
"""
|
|
|
|
Auto-generate a text/gemini document based on the contents of the file system.
|
|
|
|
"""
|
2019-08-06 04:21:28 +02:00
|
|
|
yield f"Directory: /{url_path}\r\n".encode()
|
|
|
|
if url_path.parent != url_path:
|
|
|
|
yield f"=>/{url_path.parent}\t..\r\n".encode()
|
|
|
|
|
|
|
|
for file in sorted(filesystem_path.iterdir()):
|
2020-01-12 20:03:37 +01:00
|
|
|
if file.name.startswith("."):
|
|
|
|
# Skip hidden directories/files that may contain sensitive info
|
2019-08-05 03:42:27 +02:00
|
|
|
continue
|
2019-08-06 04:21:28 +02:00
|
|
|
elif file.is_dir():
|
2019-09-03 02:58:22 +02:00
|
|
|
yield f"=>/{url_path / file.name}/\t{file.name}/\r\n".encode()
|
2019-08-06 04:21:28 +02:00
|
|
|
else:
|
|
|
|
yield f"=>/{url_path / file.name}\t{file.name}\r\n".encode()
|
2019-08-05 03:42:27 +02:00
|
|
|
|
2019-08-28 05:44:07 +02:00
|
|
|
def guess_mimetype(self, filename: str) -> str:
|
2019-08-27 15:47:53 +02:00
|
|
|
"""
|
|
|
|
Guess the mimetype of a file based on the file extension.
|
|
|
|
"""
|
2019-08-05 03:42:27 +02:00
|
|
|
mime, encoding = self.mimetypes.guess_type(filename)
|
|
|
|
if encoding:
|
|
|
|
return f"{mime}; charset={encoding}"
|
|
|
|
else:
|
2019-08-23 00:53:02 +02:00
|
|
|
return mime or "text/plain"
|
2019-08-05 03:42:27 +02:00
|
|
|
|
2020-01-12 23:51:52 +01:00
|
|
|
def default_callback(self, request: Request) -> Response:
|
|
|
|
"""
|
|
|
|
Since the StaticDirectoryApplication only serves gemini URLs, return
|
|
|
|
a proxy request refused for suspicious URLs.
|
|
|
|
"""
|
|
|
|
if request.scheme != "gemini":
|
|
|
|
return Response(
|
|
|
|
Status.PROXY_REQUEST_REFUSED,
|
|
|
|
"This server does not allow proxy requests",
|
|
|
|
)
|
|
|
|
elif request.hostname != request.environ["HOSTNAME"]:
|
|
|
|
return Response(
|
|
|
|
Status.PROXY_REQUEST_REFUSED,
|
|
|
|
"This server does not allow proxy requests",
|
|
|
|
)
|
|
|
|
elif request.port and request.port != request.environ["SERVER_PORT"]:
|
|
|
|
return Response(
|
|
|
|
Status.PROXY_REQUEST_REFUSED,
|
|
|
|
"This server does not allow proxy requests",
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
return Response(Status.NOT_FOUND, "Not Found")
|
|
|
|
|
2019-08-05 03:42:27 +02:00
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
class GeminiProtocol(LineOnlyReceiver):
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
|
|
|
Handle a single Gemini Protocol TCP request.
|
|
|
|
|
2020-01-13 02:36:00 +01:00
|
|
|
The request handler manages the life of a single gemini request. It exposes
|
|
|
|
a simplified interface to read the request URL and write the gemini response
|
|
|
|
status line and body to the socket. The request URL and other server
|
|
|
|
information is stuffed into an ``environ`` dictionary that encapsulates the
|
|
|
|
request at a low level. This dictionary, along with a callback to write the
|
|
|
|
response data, and passed to a configurable "application" function or class.
|
|
|
|
|
2019-08-04 19:52:54 +02:00
|
|
|
This design borrows heavily from the standard library's HTTP request
|
|
|
|
handler (http.server.BaseHTTPRequestHandler). However, I did not make any
|
|
|
|
attempts to directly emulate the existing conventions, because Gemini is an
|
|
|
|
inherently simpler protocol than HTTP and much of the boilerplate could be
|
2020-01-13 02:36:00 +01:00
|
|
|
removed.
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
|
|
|
|
2019-09-23 03:59:20 +02:00
|
|
|
TIMESTAMP_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
|
|
|
|
|
2020-05-13 06:32:51 +02:00
|
|
|
client_addr: typing.Union[IPv4Address, IPv6Address]
|
|
|
|
client_cert: typing.Optional[x509.Certificate]
|
2020-05-13 05:50:12 +02:00
|
|
|
connected_timestamp: time.struct_time
|
|
|
|
request: bytes
|
2019-09-24 01:34:38 +02:00
|
|
|
url: str
|
|
|
|
status: int
|
|
|
|
meta: str
|
|
|
|
response_buffer: str
|
|
|
|
response_size: int
|
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
def __init__(self, server: GeminiServer, app: JetforceApplication):
|
|
|
|
self.server = server
|
|
|
|
self.app = app
|
|
|
|
|
|
|
|
def connectionMade(self):
|
|
|
|
"""
|
|
|
|
This is invoked by twisted after the connection is first established.
|
|
|
|
"""
|
|
|
|
self.connected_timestamp = time.localtime()
|
2019-09-24 01:34:38 +02:00
|
|
|
self.response_size = 0
|
2020-05-09 07:34:02 +02:00
|
|
|
self.response_buffer = ""
|
2020-05-13 06:32:51 +02:00
|
|
|
self.client_addr = self.transport.getPeer()
|
|
|
|
self.client_cert = None
|
|
|
|
|
|
|
|
peer_cert = self.transport.getPeerCertificate()
|
|
|
|
if peer_cert:
|
|
|
|
self.client_cert = peer_cert.to_cryptography()
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
def lineReceived(self, line):
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
2020-05-13 05:50:12 +02:00
|
|
|
This method is invoked by LineOnlyReceiver for every incoming line.
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
Because Gemini requests are only ever a single line long, this will
|
|
|
|
only be called once and we can use it to handle the lifetime of the
|
|
|
|
connection without managing any state.
|
|
|
|
"""
|
|
|
|
self.request = line
|
|
|
|
try:
|
2020-05-13 06:32:51 +02:00
|
|
|
self.handle_request()
|
2020-05-13 05:50:12 +02:00
|
|
|
finally:
|
2020-05-13 06:32:51 +02:00
|
|
|
self.log_request()
|
2020-05-13 05:50:12 +02:00
|
|
|
self.transport.loseConnection()
|
|
|
|
|
2020-05-13 06:32:51 +02:00
|
|
|
def handle_request(self):
|
2019-08-04 19:52:54 +02:00
|
|
|
try:
|
2020-05-09 07:34:02 +02:00
|
|
|
self.parse_header()
|
2019-08-04 19:52:54 +02:00
|
|
|
except Exception:
|
|
|
|
# Malformed request, throw it away and exit immediately
|
2019-08-29 05:52:39 +02:00
|
|
|
self.write_status(Status.BAD_REQUEST, "Malformed request")
|
2020-05-13 06:32:51 +02:00
|
|
|
self.flush_status()
|
|
|
|
raise
|
2019-08-12 17:24:42 +02:00
|
|
|
|
2019-08-04 19:52:54 +02:00
|
|
|
try:
|
|
|
|
environ = self.build_environ()
|
2020-05-13 05:50:12 +02:00
|
|
|
response_generator = self.app(environ, self.write_status)
|
2020-05-09 07:34:02 +02:00
|
|
|
for data in response_generator:
|
|
|
|
self.write_body(data)
|
2020-01-13 00:55:28 +01:00
|
|
|
except Exception:
|
|
|
|
self.write_status(Status.CGI_ERROR, "An unexpected error occurred")
|
2020-05-13 06:32:51 +02:00
|
|
|
raise
|
|
|
|
finally:
|
|
|
|
self.flush_status()
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2019-08-06 00:47:59 +02:00
|
|
|
def build_environ(self) -> typing.Dict[str, typing.Any]:
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
|
|
|
Construct a dictionary that will be passed to the application handler.
|
2019-08-27 05:41:10 +02:00
|
|
|
|
|
|
|
Variable names conform to the CGI spec defined in RFC 3875.
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
2019-08-27 05:41:10 +02:00
|
|
|
url_parts = urllib.parse.urlparse(self.url)
|
2019-08-29 05:52:39 +02:00
|
|
|
environ = {
|
2019-08-27 05:41:10 +02:00
|
|
|
"GEMINI_URL": self.url,
|
2019-08-12 17:24:42 +02:00
|
|
|
"HOSTNAME": self.server.hostname,
|
2019-08-27 05:41:10 +02:00
|
|
|
"PATH_INFO": url_parts.path,
|
|
|
|
"QUERY_STRING": url_parts.query,
|
2020-05-13 06:32:51 +02:00
|
|
|
"REMOTE_ADDR": self.client_addr.host,
|
|
|
|
"REMOTE_HOST": self.client_addr.host,
|
2019-08-27 05:41:10 +02:00
|
|
|
"SERVER_NAME": self.server.hostname,
|
2020-05-13 06:32:51 +02:00
|
|
|
"SERVER_PORT": str(self.client_addr.port),
|
2019-08-27 05:41:10 +02:00
|
|
|
"SERVER_PROTOCOL": "GEMINI",
|
|
|
|
"SERVER_SOFTWARE": f"jetforce/{__version__}",
|
2019-08-04 19:52:54 +02:00
|
|
|
}
|
2020-05-13 06:32:51 +02:00
|
|
|
if self.client_cert:
|
2020-05-13 05:50:12 +02:00
|
|
|
# Extract useful information from the client certificate. These
|
|
|
|
# mostly follow the naming convention from GLV-1.12556
|
2020-05-13 06:32:51 +02:00
|
|
|
cert = self.client_cert
|
2020-05-13 05:50:12 +02:00
|
|
|
name_attrs = cert.subject.get_attributes_for_oid(CN)
|
|
|
|
common_name = name_attrs[0].value if name_attrs else ""
|
|
|
|
fingerprint_bytes = cert.fingerprint(hashes.SHA256())
|
|
|
|
fingerprint = base64.b64encode(fingerprint_bytes).decode()
|
|
|
|
not_before = cert.not_valid_before.strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
not_after = cert.not_valid_after.strftime("%Y-%m-%dT%H:%M:%SZ")
|
2019-08-29 05:52:39 +02:00
|
|
|
environ.update(
|
2020-03-12 04:26:47 +01:00
|
|
|
{
|
|
|
|
"AUTH_TYPE": "CERTIFICATE",
|
2020-05-13 05:50:12 +02:00
|
|
|
"REMOTE_USER": common_name,
|
|
|
|
"TLS_CLIENT_HASH": fingerprint,
|
|
|
|
"TLS_CLIENT_NOT_BEFORE": not_before,
|
|
|
|
"TLS_CLIENT_NOT_AFTER": not_after,
|
|
|
|
"TLS_CLIENT_SERIAL_NUMBER": cert.serial_number,
|
2020-03-12 04:26:47 +01:00
|
|
|
}
|
2019-08-29 05:52:39 +02:00
|
|
|
)
|
|
|
|
return environ
|
|
|
|
|
2020-05-09 07:34:02 +02:00
|
|
|
def parse_header(self) -> None:
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
2019-08-12 17:24:42 +02:00
|
|
|
Parse the gemini header line.
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2019-08-12 17:24:42 +02:00
|
|
|
The request is a single UTF-8 line formatted as: <URL>\r\n
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
2020-05-13 05:50:12 +02:00
|
|
|
if len(self.request) > 1024:
|
2019-08-12 17:24:42 +02:00
|
|
|
raise ValueError("URL exceeds max length of 1024 bytes")
|
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
self.url = self.request.decode()
|
2019-08-12 17:24:42 +02:00
|
|
|
|
|
|
|
def write_status(self, status: int, meta: str) -> None:
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
|
|
|
Write the gemini status line to an internal buffer.
|
|
|
|
|
|
|
|
The status line is a single UTF-8 line formatted as:
|
2019-08-12 17:24:42 +02:00
|
|
|
<code>\t<meta>\r\n
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2019-08-12 17:24:42 +02:00
|
|
|
If the response status is 2, the meta field will contain the mimetype
|
|
|
|
of the response data sent. If the status is something else, the meta
|
2019-08-04 19:52:54 +02:00
|
|
|
will contain a descriptive message.
|
|
|
|
|
|
|
|
The status is not written immediately, it's added to an internal buffer
|
|
|
|
that must be flushed. This is done so that the status can be updated as
|
|
|
|
long as no other data has been written to the stream yet.
|
|
|
|
"""
|
|
|
|
self.status = status
|
2019-08-12 17:24:42 +02:00
|
|
|
self.meta = meta
|
|
|
|
self.response_buffer = f"{status}\t{meta}\r\n"
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2020-05-09 07:34:02 +02:00
|
|
|
def write_body(self, data: bytes) -> None:
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
|
|
|
Write bytes to the gemini response body.
|
|
|
|
"""
|
2020-05-09 07:34:02 +02:00
|
|
|
self.flush_status()
|
2019-08-04 19:52:54 +02:00
|
|
|
self.response_size += len(data)
|
2020-05-13 05:50:12 +02:00
|
|
|
self.transport.write(data)
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2020-05-09 07:34:02 +02:00
|
|
|
def flush_status(self) -> None:
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
|
|
|
Flush the status line from the internal buffer to the socket stream.
|
|
|
|
"""
|
|
|
|
if self.response_buffer and not self.response_size:
|
|
|
|
data = self.response_buffer.encode()
|
|
|
|
self.response_size += len(data)
|
2020-05-13 05:50:12 +02:00
|
|
|
self.transport.write(data)
|
2019-09-24 01:34:38 +02:00
|
|
|
self.response_buffer = ""
|
2019-08-04 19:52:54 +02:00
|
|
|
|
|
|
|
def log_request(self) -> None:
|
|
|
|
"""
|
|
|
|
Log a gemini request using a format derived from the Common Log Format.
|
|
|
|
"""
|
2020-05-13 06:32:51 +02:00
|
|
|
try:
|
|
|
|
message = '{} [{}] "{}" {} {} {}'.format(
|
|
|
|
self.client_addr.host,
|
|
|
|
time.strftime(self.TIMESTAMP_FORMAT, self.connected_timestamp),
|
|
|
|
self.url,
|
|
|
|
self.status,
|
|
|
|
self.meta,
|
|
|
|
self.response_size,
|
|
|
|
)
|
|
|
|
except AttributeError:
|
|
|
|
# The connection ended before we got far enough to log anything
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
self.server.log_message(message)
|
2019-08-04 19:52:54 +02:00
|
|
|
|
|
|
|
|
2020-05-15 06:11:09 +02:00
|
|
|
def generate_ad_hoc_certificate(hostname: str) -> typing.Tuple[str, str]:
|
|
|
|
"""
|
|
|
|
Utility function to generate an ad-hoc self-signed SSL certificate.
|
|
|
|
"""
|
|
|
|
certfile = os.path.join(tempfile.gettempdir(), f"{hostname}.crt")
|
|
|
|
keyfile = os.path.join(tempfile.gettempdir(), f"{hostname}.key")
|
|
|
|
|
|
|
|
if not os.path.exists(certfile) or not os.path.exists(keyfile):
|
|
|
|
backend = default_backend()
|
|
|
|
|
|
|
|
print("Generating private key...", file=sys.stderr)
|
|
|
|
private_key = rsa.generate_private_key(65537, 2048, backend)
|
|
|
|
with open(keyfile, "wb") as fp:
|
|
|
|
# noinspection PyTypeChecker
|
|
|
|
key_data = private_key.private_bytes(
|
|
|
|
serialization.Encoding.PEM,
|
|
|
|
format=serialization.PrivateFormat.TraditionalOpenSSL,
|
|
|
|
encryption_algorithm=serialization.NoEncryption(),
|
|
|
|
)
|
|
|
|
fp.write(key_data)
|
|
|
|
|
|
|
|
print("Generating certificate...", file=sys.stderr)
|
|
|
|
common_name = x509.NameAttribute(CN, hostname)
|
|
|
|
subject_name = x509.Name([common_name])
|
|
|
|
not_valid_before = datetime.datetime.utcnow()
|
|
|
|
not_valid_after = not_valid_before + datetime.timedelta(days=365)
|
|
|
|
certificate = x509.CertificateBuilder(
|
|
|
|
subject_name=subject_name,
|
|
|
|
issuer_name=subject_name,
|
|
|
|
public_key=private_key.public_key(),
|
|
|
|
serial_number=x509.random_serial_number(),
|
|
|
|
not_valid_before=not_valid_before,
|
|
|
|
not_valid_after=not_valid_after,
|
|
|
|
)
|
|
|
|
certificate = certificate.sign(private_key, hashes.SHA256(), backend)
|
|
|
|
with open(certfile, "wb") as fp:
|
|
|
|
# noinspection PyTypeChecker
|
|
|
|
cert_data = certificate.public_bytes(serialization.Encoding.PEM)
|
|
|
|
fp.write(cert_data)
|
|
|
|
|
|
|
|
return certfile, keyfile
|
|
|
|
|
|
|
|
|
|
|
|
class GeminiOpenSSLCertificateOptions(CertificateOptions):
|
|
|
|
"""
|
|
|
|
CertificateOptions is a factory function that twisted uses to do all of the
|
|
|
|
gnarly OpenSSL setup and return a PyOpenSSL context object. Unfortunately,
|
|
|
|
it doesn't do *exactly* what I need it to do, so I need to subclass to add
|
|
|
|
some custom behavior.
|
|
|
|
|
|
|
|
References:
|
|
|
|
https://twistedmatrix.com/documents/16.1.1/core/howto/ssl.html
|
|
|
|
https://github.com/urllib3/urllib3/blob/master/src/urllib3/util/ssl_.py
|
|
|
|
https://github.com/twisted/twisted/blob/trunk/src/twisted/internet/_sslverify.py
|
|
|
|
"""
|
|
|
|
|
|
|
|
def verify_callback(self, conn, cert, errno, depth, preverify_ok):
|
|
|
|
"""
|
|
|
|
Callback used by OpenSSL for client certificate verification.
|
|
|
|
|
|
|
|
preverify_ok returns the verification result that OpenSSL has already
|
|
|
|
obtained, so return this value to cede control to the underlying
|
|
|
|
library. Returning true will always allow client certificates, even if
|
|
|
|
they are self-signed.
|
|
|
|
"""
|
|
|
|
return preverify_ok
|
|
|
|
|
|
|
|
def proto_select_callback(self, conn, protocols):
|
|
|
|
"""
|
|
|
|
Callback used by OpenSSL for ALPN support.
|
|
|
|
|
|
|
|
Return the first matching protocol in our list of acceptable values.
|
|
|
|
"""
|
|
|
|
for p in self._acceptableProtocols:
|
|
|
|
if p in protocols:
|
|
|
|
return p
|
|
|
|
else:
|
|
|
|
return b""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
certfile: str,
|
|
|
|
keyfile: typing.Optional[str] = None,
|
|
|
|
cafile: typing.Optional[str] = None,
|
|
|
|
capath: typing.Optional[str] = None,
|
|
|
|
**kwargs,
|
|
|
|
):
|
|
|
|
self.certfile = certfile
|
|
|
|
self.keyfile = keyfile
|
|
|
|
self.cafile = cafile
|
|
|
|
self.capath = capath
|
|
|
|
super().__init__(**kwargs)
|
|
|
|
|
|
|
|
def _makeContext(self):
|
|
|
|
"""
|
|
|
|
Most of this code is copied directly from the parent class method.
|
|
|
|
|
|
|
|
I switched to using the OpenSSL methods that read keys/certs from files
|
|
|
|
instead of manually loading the objects into memory. I also added
|
|
|
|
configurable verify & ALPN callbacks.
|
|
|
|
"""
|
|
|
|
ctx = self._contextFactory(self.method)
|
|
|
|
ctx.set_options(self._options)
|
|
|
|
ctx.set_mode(self._mode)
|
|
|
|
|
|
|
|
ctx.use_certificate_file(self.certfile)
|
|
|
|
ctx.use_privatekey_file(self.keyfile or self.certfile)
|
|
|
|
for extraCert in self.extraCertChain:
|
|
|
|
ctx.add_extra_chain_cert(extraCert)
|
|
|
|
# Sanity check
|
|
|
|
ctx.check_privatekey()
|
|
|
|
|
|
|
|
if self.cafile or self.capath:
|
|
|
|
ctx.load_verify_locations(self.cafile, self.capath)
|
|
|
|
|
|
|
|
verify_flags = SSL.VERIFY_PEER
|
|
|
|
if self.requireCertificate:
|
|
|
|
verify_flags |= SSL.VERIFY_FAIL_IF_NO_PEER_CERT
|
|
|
|
if self.verifyOnce:
|
|
|
|
verify_flags |= SSL.VERIFY_CLIENT_ONCE
|
|
|
|
|
|
|
|
ctx.set_verify(verify_flags, self.verify_callback)
|
|
|
|
if self.verifyDepth is not None:
|
|
|
|
ctx.set_verify_depth(self.verifyDepth)
|
|
|
|
|
|
|
|
if self.enableSessions:
|
|
|
|
session_name = secureRandom(32)
|
|
|
|
ctx.set_session_id(session_name)
|
|
|
|
|
|
|
|
ctx.set_cipher_list(self._cipherString.encode("ascii"))
|
|
|
|
|
|
|
|
self._ecChooser.configureECDHCurve(ctx)
|
|
|
|
|
|
|
|
if self._acceptableProtocols:
|
|
|
|
ctx.set_alpn_select_callback(self.proto_select_callback)
|
|
|
|
ctx.set_alpn_protos(self._acceptableProtocols)
|
|
|
|
|
|
|
|
return ctx
|
|
|
|
|
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
class GeminiServer(Factory):
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
2020-05-13 05:50:12 +02:00
|
|
|
This class acts as a wrapper around most of the plumbing for twisted.
|
2020-01-13 02:36:00 +01:00
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
There's not much going on here, the main intention is to make it as simple
|
|
|
|
as possible to import and run a server without needing to understand the
|
|
|
|
complicated class hierarchy and conventions defined by twisted.
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
# Request handler class, you probably don't want to override this.
|
|
|
|
protocol_class = GeminiProtocol
|
|
|
|
|
|
|
|
# The TLS twisted interface class is confusingly named SSL4, even though it
|
|
|
|
# will accept either IPv4 & IPv6 interfaces.
|
|
|
|
endpoint_class = SSL4ServerEndpoint
|
2019-08-04 19:52:54 +02:00
|
|
|
|
|
|
|
def __init__(
|
2019-08-12 16:04:37 +02:00
|
|
|
self,
|
|
|
|
app: typing.Callable,
|
2020-05-13 05:50:12 +02:00
|
|
|
reactor: ReactorBase = reactor,
|
2019-08-25 00:37:13 +02:00
|
|
|
host: str = "127.0.0.1",
|
|
|
|
port: int = 1965,
|
|
|
|
hostname: str = "localhost",
|
2020-05-13 05:50:12 +02:00
|
|
|
certfile: typing.Optional[str] = None,
|
|
|
|
keyfile: typing.Optional[str] = None,
|
|
|
|
cafile: typing.Optional[str] = None,
|
|
|
|
capath: typing.Optional[str] = None,
|
|
|
|
**_,
|
|
|
|
):
|
2020-05-15 06:11:09 +02:00
|
|
|
if certfile is None:
|
|
|
|
certfile, keyfile = generate_ad_hoc_certificate(hostname)
|
|
|
|
|
2019-08-04 19:52:54 +02:00
|
|
|
self.app = app
|
2020-05-13 05:50:12 +02:00
|
|
|
self.reactor = reactor
|
|
|
|
self.host = host
|
|
|
|
self.port = port
|
2020-05-09 07:34:02 +02:00
|
|
|
self.hostname = hostname
|
2020-05-13 05:50:12 +02:00
|
|
|
self.certfile = certfile
|
|
|
|
self.keyfile = keyfile
|
|
|
|
self.cafile = cafile
|
|
|
|
self.capath = capath
|
2019-08-21 03:17:58 +02:00
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
def log_message(self, message: str) -> None:
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
2020-05-13 05:50:12 +02:00
|
|
|
Log a diagnostic server message to stderr.
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
2020-05-13 05:50:12 +02:00
|
|
|
print(message, file=sys.stderr)
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
def on_bind_interface(self, port: Port) -> None:
|
|
|
|
"""
|
|
|
|
Log when the server binds to an interface.
|
|
|
|
"""
|
|
|
|
sock_ip, sock_port, *_ = port.socket.getsockname()
|
|
|
|
if port.addressFamily == socket.AF_INET:
|
2020-05-09 07:34:02 +02:00
|
|
|
self.log_message(f"Listening on {sock_ip}:{sock_port}")
|
|
|
|
else:
|
|
|
|
self.log_message(f"Listening on [{sock_ip}]:{sock_port}")
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
def buildProtocol(self, addr) -> GeminiProtocol:
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
2020-05-13 05:50:12 +02:00
|
|
|
This method is invoked by twisted once for every incoming connection.
|
|
|
|
|
|
|
|
It builds the protocol instance which acts as a request handler and
|
|
|
|
implements the actual Gemini protocol.
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
2020-05-13 05:50:12 +02:00
|
|
|
return GeminiProtocol(self, self.app)
|
2019-08-04 19:52:54 +02:00
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
def run(self) -> None:
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
2020-05-13 05:50:12 +02:00
|
|
|
This is the main server loop.
|
2019-08-04 19:52:54 +02:00
|
|
|
"""
|
2020-05-13 05:50:12 +02:00
|
|
|
self.log_message(ABOUT)
|
|
|
|
self.log_message(f"Server hostname is {self.hostname}")
|
2020-05-15 06:11:09 +02:00
|
|
|
self.log_message(f"TLS Certificate File: {self.certfile}")
|
|
|
|
self.log_message(f"TLS Private Key File: {self.keyfile}")
|
|
|
|
|
|
|
|
certificate_options = GeminiOpenSSLCertificateOptions(
|
2020-05-13 05:50:12 +02:00
|
|
|
certfile=self.certfile,
|
|
|
|
keyfile=self.keyfile,
|
|
|
|
cafile=self.cafile,
|
|
|
|
capath=self.capath,
|
2020-05-15 06:11:09 +02:00
|
|
|
raiseMinimumTo=TLSVersion.TLSv1_3,
|
|
|
|
requireCertificate=False,
|
|
|
|
fixBrokenPeers=True,
|
|
|
|
# ALPN, I may look into supporting this later
|
|
|
|
acceptableProtocols=None,
|
2019-08-29 04:33:58 +02:00
|
|
|
)
|
2020-05-13 06:32:51 +02:00
|
|
|
|
|
|
|
interfaces = [self.host] if self.host else ["0.0.0.0", "::"]
|
|
|
|
for interface in interfaces:
|
|
|
|
endpoint = self.endpoint_class(
|
|
|
|
reactor=self.reactor,
|
|
|
|
port=self.port,
|
2020-05-15 06:11:09 +02:00
|
|
|
sslContextFactory=certificate_options,
|
2020-05-13 06:32:51 +02:00
|
|
|
interface=interface,
|
|
|
|
)
|
|
|
|
endpoint.listen(self).addCallback(self.on_bind_interface)
|
|
|
|
|
2020-05-13 05:50:12 +02:00
|
|
|
self.reactor.run()
|
2019-08-06 04:49:48 +02:00
|
|
|
|
2020-05-13 07:37:21 +02:00
|
|
|
@classmethod
|
|
|
|
def build_argument_parser(cls):
|
|
|
|
"""
|
|
|
|
Build the default command line argument parser for the jetforce server.
|
|
|
|
"""
|
|
|
|
# fmt: off
|
|
|
|
# noinspection PyTypeChecker
|
|
|
|
parser = argparse.ArgumentParser(
|
|
|
|
prog="jetforce",
|
|
|
|
description="An Experimental Gemini Protocol Server",
|
|
|
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"-V", "--version",
|
|
|
|
action="version",
|
|
|
|
version="jetforce " + __version__
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--host",
|
|
|
|
help="Server address to bind to",
|
|
|
|
default="127.0.0.1"
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--port",
|
|
|
|
help="Server port to bind to",
|
|
|
|
type=int,
|
|
|
|
default=1965
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--hostname",
|
|
|
|
help="Server hostname",
|
|
|
|
default="localhost"
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--tls-certfile",
|
|
|
|
dest="certfile",
|
|
|
|
help="Server TLS certificate file",
|
|
|
|
metavar="FILE",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--tls-keyfile",
|
|
|
|
dest="keyfile",
|
|
|
|
help="Server TLS private key file",
|
|
|
|
metavar="FILE",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--tls-cafile",
|
|
|
|
dest="cafile",
|
|
|
|
help="A CA file to use for validating clients",
|
|
|
|
metavar="FILE",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--tls-capath",
|
|
|
|
dest="capath",
|
|
|
|
help="A directory containing CA files for validating clients",
|
|
|
|
metavar="DIR",
|
|
|
|
)
|
|
|
|
# fmt: on
|
|
|
|
return parser
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_argparse(
|
|
|
|
cls, app_class: typing.Type[JetforceApplication], reactor: ReactorBase = reactor
|
|
|
|
):
|
|
|
|
"""
|
|
|
|
Shortcut to parse command line arguments and build a server instance.
|
|
|
|
|
|
|
|
This only works with class-based Jetforce applications that subclass
|
|
|
|
from JetforceApplication.
|
|
|
|
"""
|
|
|
|
parser = cls.build_argument_parser()
|
|
|
|
app_class.add_arguments(parser)
|
|
|
|
|
|
|
|
args = vars(parser.parse_args())
|
2020-05-15 06:11:09 +02:00
|
|
|
|
|
|
|
# Split command line arguments into the group that should be passed to
|
|
|
|
# the server class, and the group that should be passed to the app class.
|
|
|
|
keys = cls.__init__.__annotations__.keys()
|
|
|
|
server_args = {k: v for k, v in args.items() if k in keys}
|
|
|
|
extra_args = {k: v for k, v in args.items() if k not in keys}
|
2020-05-13 07:37:21 +02:00
|
|
|
|
|
|
|
app = app_class(**extra_args)
|
|
|
|
return cls(app, reactor, **server_args)
|
|
|
|
|
2019-08-06 04:49:48 +02:00
|
|
|
|
2019-08-21 03:17:58 +02:00
|
|
|
def run_server() -> None:
|
|
|
|
"""
|
2019-08-28 05:45:10 +02:00
|
|
|
Entry point for running the static directory server.
|
2019-08-21 03:17:58 +02:00
|
|
|
"""
|
2020-05-13 07:37:21 +02:00
|
|
|
server = GeminiServer.from_argparse(app_class=StaticDirectoryApplication)
|
2020-05-09 07:34:02 +02:00
|
|
|
server.run()
|
2019-08-04 20:11:22 +02:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
run_server()
|