├── .editorconfig ├── examples ├── static │ ├── mimetypes │ │ ├── test.txt │ │ ├── caffeine.png │ │ └── index.gmi │ ├── empty-dir │ │ ├── one.gmi │ │ └── two.gmi │ ├── other.gmi │ ├── sub-dir │ │ └── index.gmi │ └── index.gmi └── templates │ └── template.txt ├── tests ├── caffeine.png ├── test_crlf.py ├── test_config.py ├── test_app_config.py ├── test_get_response.py ├── test_get_route.py ├── test_check_url.py ├── conftest.py ├── test_handlers.py └── test_responses.py ├── .gitignore ├── Makefile ├── tox.ini ├── gemeaux ├── exceptions.py ├── handlers.py ├── responses.py └── __init__.py ├── .github └── workflows │ └── tox-tests.yaml ├── LICENSE ├── pyproject.toml ├── CHANGELOG.md ├── example_app.py └── README.md /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.py] 2 | max_line_length = 88 3 | -------------------------------------------------------------------------------- /examples/static/mimetypes/test.txt: -------------------------------------------------------------------------------- 1 | Test text file, no markup. 2 | -------------------------------------------------------------------------------- /tests/caffeine.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brunobord/gemeaux/HEAD/tests/caffeine.png -------------------------------------------------------------------------------- /examples/static/empty-dir/one.gmi: -------------------------------------------------------------------------------- 1 | # One 2 | 3 | Document one 4 | 5 | => / Back to the root 6 | -------------------------------------------------------------------------------- /examples/static/empty-dir/two.gmi: -------------------------------------------------------------------------------- 1 | # Two 2 | 3 | Document Two. 4 | 5 | => / Back to the root 6 | -------------------------------------------------------------------------------- /examples/templates/template.txt: -------------------------------------------------------------------------------- 1 | I am a template file. Refresh me to see what time it is: $datetime 2 | -------------------------------------------------------------------------------- /examples/static/other.gmi: -------------------------------------------------------------------------------- 1 | # I am the second document 2 | 3 | Do you see me? 4 | 5 | => ../ Back to index 6 | -------------------------------------------------------------------------------- /examples/static/mimetypes/caffeine.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brunobord/gemeaux/HEAD/examples/static/mimetypes/caffeine.png -------------------------------------------------------------------------------- /examples/static/sub-dir/index.gmi: -------------------------------------------------------------------------------- 1 | # Subdir root 2 | 3 | I am the root of the sub-dir directory. 4 | 5 | => / Back to the root 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Do not commit certificates 2 | *.pem 3 | # Tests 4 | .tox/ 5 | # Python-generated files and dirs 6 | __pycache__ 7 | *.egg-info 8 | build/ 9 | dist/ 10 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | serve: 2 | python3 example_app.py 3 | 4 | cert: 5 | openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout key.pem -subj "/CN=localhost" -newkey rsa:4096 -addext "subjectAltName = DNS:localhost,DNS:127.0.0.1" 6 | 7 | # DEV ONLY 8 | lint: isort black flake8 9 | 10 | isort: 11 | isort --profile black . 12 | black: 13 | black . 14 | flake8: 15 | flake8 . 16 | -------------------------------------------------------------------------------- /examples/static/mimetypes/index.gmi: -------------------------------------------------------------------------------- 1 | # Alternate mimetypes & links 2 | 3 | Below is a link to an image. Your gemini client should download it. 4 | 5 | => caffeine.png 6 | 7 | source of the illustration (your client should open your web browser): 8 | 9 | => https://commons.wikimedia.org/wiki/File:Caffeine_molecule.png 10 | 11 | Now with a pure text file (extension .txt) 12 | 13 | => test.txt 14 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = lint,py39,py310,py311,py312,py313 3 | 4 | [testenv] 5 | deps = 6 | pytest 7 | commands = pytest {posargs} 8 | 9 | 10 | [testenv:lint] 11 | skip_install = true 12 | deps = 13 | black 14 | isort 15 | flake8 16 | commands = 17 | isort --check --profile black . 18 | black --check . 19 | flake8 . 20 | 21 | [flake8] 22 | ignore = E203, E501 23 | max-line-length = 88 24 | -------------------------------------------------------------------------------- /tests/test_crlf.py: -------------------------------------------------------------------------------- 1 | from gemeaux import crlf 2 | 3 | 4 | def test_crlf(multi_line_content, multi_line_content_crlf): 5 | multi_line_content = bytes(multi_line_content, encoding="utf-8") 6 | multi_line_content_crlf = bytes(multi_line_content_crlf, encoding="utf-8") 7 | assert crlf(multi_line_content) == multi_line_content_crlf 8 | 9 | 10 | def test_crlf_several_lf(): 11 | content = bytes("line\n\n\nlast line", encoding="utf-8") 12 | content_expected = bytes("line\r\n\r\n\r\nlast line\r\n", encoding="utf-8") 13 | assert crlf(content) == content_expected 14 | -------------------------------------------------------------------------------- /gemeaux/exceptions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Gemeaux specific exceptions 3 | """ 4 | 5 | 6 | class ImproperlyConfigured(Exception): 7 | """ 8 | When the configuration is a problem 9 | """ 10 | 11 | 12 | class TemplateError(Exception): 13 | """ 14 | When there's an issue with templating 15 | """ 16 | 17 | 18 | class BadRequestException(Exception): 19 | """ 20 | When the client sends a bad request. 21 | """ 22 | 23 | 24 | class TimeoutException(Exception): 25 | """ 26 | When the server needs to close the connection without returning a response. 27 | """ 28 | 29 | 30 | class ProxyRequestRefusedException(Exception): 31 | """ 32 | When you refuse a proxy request. 33 | """ 34 | -------------------------------------------------------------------------------- /tests/test_config.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import patch 2 | 3 | from gemeaux import ArgsConfig, ZeroConfig 4 | 5 | 6 | def test_zero_config(): 7 | config = ZeroConfig() 8 | assert config.ip == "localhost" 9 | assert config.port == 1965 10 | assert config.certfile == "cert.pem" 11 | assert config.keyfile == "key.pem" 12 | assert config.nb_connections == 5 13 | 14 | 15 | def test_args_config(): 16 | testargs = ["prog"] 17 | with patch("sys.argv", testargs): 18 | config = ArgsConfig() 19 | assert config.ip == "localhost" 20 | assert config.port == 1965 21 | assert config.certfile == "cert.pem" 22 | assert config.keyfile == "key.pem" 23 | assert config.nb_connections == 5 24 | -------------------------------------------------------------------------------- /.github/workflows/tox-tests.yaml: -------------------------------------------------------------------------------- 1 | name: Python package tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | tox_linter: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v4 10 | - name: Setup Python 11 | uses: actions/setup-python@v5 12 | - name: Install tox and any other packages 13 | run: pip install tox 14 | - name: Run tox 15 | # Run tox using the version of Python in `PATH` 16 | run: tox -e lint 17 | 18 | tox_tests: 19 | 20 | runs-on: ubuntu-latest 21 | strategy: 22 | matrix: 23 | python: ["3.9", "3.10", "3.11", "3.12", "3.13"] 24 | 25 | steps: 26 | - uses: actions/checkout@v4 27 | - name: Setup Python 28 | uses: actions/setup-python@v5 29 | with: 30 | python-version: ${{ matrix.python }} 31 | - name: Install tox and any other packages 32 | run: pip install tox 33 | - name: Run tox 34 | # Run tox using the version of Python in `PATH` 35 | run: tox -e py 36 | 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2020 Bruno Bord 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /tests/test_app_config.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import patch 2 | 3 | import pytest 4 | 5 | from gemeaux import App, ImproperlyConfigured, ZeroConfig 6 | 7 | 8 | def test_no_urls(): 9 | with pytest.raises(ImproperlyConfigured): 10 | App(urls=None, config=ZeroConfig()) 11 | 12 | 13 | def test_not_a_dict_urls(): 14 | with pytest.raises(ImproperlyConfigured): 15 | App(urls="", config=ZeroConfig()) 16 | 17 | 18 | def test_empty_urls(): 19 | with pytest.raises(ImproperlyConfigured): 20 | App(urls={}, config=ZeroConfig()) 21 | 22 | 23 | def test_not_a_handler_or_response_urls(): 24 | with pytest.raises(ImproperlyConfigured): 25 | App(urls={"": "I am not a Handler/Response obj"}, config=ZeroConfig()) 26 | 27 | 28 | @patch("ssl.SSLContext.load_cert_chain") 29 | def test_urls_handler(mock_ssl_context, fake_handler): 30 | app = App(urls={"": fake_handler}, config=ZeroConfig()) 31 | assert app 32 | 33 | 34 | @patch("ssl.SSLContext.load_cert_chain") 35 | def test_urls_response(mock_ssl_context, fake_response): 36 | app = App(urls={"": fake_response}, config=ZeroConfig()) 37 | assert app 38 | -------------------------------------------------------------------------------- /examples/static/index.gmi: -------------------------------------------------------------------------------- 1 | # Hello 2 | 3 | ## Title 2 4 | 5 | ### Title 3 6 | 7 | 8 | Lorem ipsum dolor sit amet, **consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua**. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui *officia deserunt mollit anim id est laborum*. 9 | 10 | => other.gmi Link to other.gmi 11 | => gemini://localhost/other.gmi link with the gemini protocol 12 | 13 | * This is a list item 14 | * … and another list item 15 | * And the last list item! 16 | 17 | ### Title 3 again 18 | 19 | ``` 20 | # code block for whichever use you want to use. 21 | if __name__ == '__main__': 22 | config = { 23 | "ip": '', 24 | "port": 1965, 25 | "pemfile": 'cert.pem', 26 | "keyfile": 'cert.key' 27 | } 28 | app = App(**config) 29 | try: 30 | app.run() 31 | except KeyboardInterrupt: 32 | print("bye") 33 | sys.exit() 34 | ``` 35 | -------------------------------------------------------------------------------- /tests/test_get_response.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import patch 2 | 3 | from gemeaux import App, NotFoundResponse, ZeroConfig 4 | 5 | 6 | @patch("ssl.SSLContext.load_cert_chain") 7 | def test_get_response_handler(mock_ssl_context, fake_handler, fake_response): 8 | app = App( 9 | urls={"/handler": fake_handler, "/response": fake_response}, config=ZeroConfig() 10 | ) 11 | 12 | # Just to make sure we're going through the get_route 13 | response = app.get_response("") 14 | assert isinstance(response, NotFoundResponse) 15 | assert response.reason == "Route Not Found" 16 | 17 | # Response from handler 18 | response = app.get_response("/handler") 19 | assert response.origin == "handler" 20 | 21 | # Direct response 22 | response = app.get_response("/response") 23 | assert response.origin == "direct" 24 | 25 | 26 | @patch("ssl.SSLContext.load_cert_chain") 27 | def test_get_response_exception(mock_ssl_context, fake_handler_exception): 28 | app = App(urls={"": fake_handler_exception}, config=ZeroConfig()) 29 | 30 | response = app.get_response("") 31 | assert isinstance(response, NotFoundResponse) 32 | 33 | response = app.get_response("/other") 34 | assert isinstance(response, NotFoundResponse) 35 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling"] 3 | build-backend = "hatchling.build" 4 | 5 | [project] 6 | name = "gemeaux" 7 | dynamic = ["version"] 8 | description = "A Python Gemini server" 9 | readme = "README.md" 10 | license = "MIT" 11 | license-files = ["LICENSE"] 12 | requires-python = ">=3.9" 13 | authors = [ 14 | { name = "Bruno Bord", email = "bruno@jehaisleprintemps.net" }, 15 | ] 16 | keywords = [ 17 | "gemini", 18 | "protocol", 19 | "server", 20 | ] 21 | classifiers = [ 22 | "Development Status :: 3 - Alpha", 23 | "Intended Audience :: Developers", 24 | "License :: OSI Approved :: MIT License", 25 | "Operating System :: OS Independent", 26 | "Programming Language :: Python", 27 | "Programming Language :: Python :: 3", 28 | "Programming Language :: Python :: 3.9", 29 | "Programming Language :: Python :: 3.10", 30 | "Programming Language :: Python :: 3.11", 31 | "Programming Language :: Python :: 3.12", 32 | "Programming Language :: Python :: 3.13", 33 | ] 34 | 35 | [project.urls] 36 | homepage = "https://github.com/brunobord/gemeaux" 37 | 38 | [tool.hatch.version] 39 | path = "gemeaux/__init__.py" 40 | 41 | [tool.hatch.build.targets.sdist] 42 | include = [ 43 | "/gemeaux", 44 | ] 45 | -------------------------------------------------------------------------------- /tests/test_get_route.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import patch 2 | 3 | import pytest 4 | 5 | from gemeaux import App, ZeroConfig 6 | 7 | 8 | @patch("ssl.SSLContext.load_cert_chain") 9 | def test_get_route_handler(mock_ssl_context, fake_handler, fake_response): 10 | app = App(urls={"": fake_handler, "/other": fake_response}, config=ZeroConfig()) 11 | # direct route 12 | assert app.get_route("") == ("", fake_handler) 13 | assert app.get_route("/") == ("", fake_handler) 14 | # Other 15 | assert app.get_route("/other") == ("/other", fake_response) 16 | # Catchall 17 | assert app.get_route("/something") == ("", fake_handler) 18 | 19 | 20 | @patch("ssl.SSLContext.load_cert_chain") 21 | def test_get_route_no_catchall(mock_ssl_context, fake_response): 22 | app = App(urls={"/hello": fake_response}, config=ZeroConfig()) 23 | with pytest.raises(FileNotFoundError): 24 | app.get_route("") 25 | 26 | with pytest.raises(FileNotFoundError): 27 | app.get_route("/") 28 | 29 | with pytest.raises(FileNotFoundError): 30 | app.get_route("/something") 31 | 32 | 33 | @patch("ssl.SSLContext.load_cert_chain") 34 | def test_get_route_same_prefix(mock_ssl_context, fake_handler, fake_response): 35 | app = App( 36 | urls={"/test": fake_handler, "/test2": fake_response}, config=ZeroConfig() 37 | ) 38 | assert app.get_route("/test") == ("/test", fake_handler) 39 | assert app.get_route("/test2") == ("/test2", fake_response) 40 | -------------------------------------------------------------------------------- /tests/test_check_url.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from gemeaux import ( 4 | BadRequestException, 5 | ProxyRequestRefusedException, 6 | TimeoutException, 7 | check_url, 8 | ) 9 | 10 | PORT = 1965 11 | 12 | 13 | def test_check_url_root(): 14 | assert check_url("gemini://localhost\r\n", PORT) 15 | assert check_url("gemini://localhost/\r\n", PORT) 16 | assert check_url("gemini://localhost:1965\r\n", PORT) 17 | assert check_url("gemini://localhost:1965/\r\n", PORT) 18 | 19 | 20 | def test_check_url_no_crlf(): 21 | with pytest.raises(TimeoutException): 22 | check_url("gemini://localhost\n", PORT) 23 | with pytest.raises(TimeoutException): 24 | check_url("gemini://localhost\r", PORT) 25 | with pytest.raises(TimeoutException): 26 | check_url("gemini://localhost", PORT) 27 | 28 | 29 | def test_check_url_no_gemini(): 30 | with pytest.raises(BadRequestException): 31 | check_url("localhost\r\n", PORT) 32 | 33 | with pytest.raises(ProxyRequestRefusedException): 34 | check_url("https://localhost\r\n", PORT) 35 | 36 | 37 | def test_check_url_length(): 38 | # Max length of the stripped URL is 1024 39 | length = 1024 - len("gemini://localhost") 40 | s = length * "0" 41 | assert check_url(f"gemini://localhost{s}\r\n", PORT) 42 | 43 | s = (length + 1) * "0" 44 | with pytest.raises(BadRequestException): 45 | check_url(f"gemini://localhost{s}\r\n", PORT) 46 | 47 | 48 | def test_check_url_bad_port(): 49 | with pytest.raises(ProxyRequestRefusedException): 50 | check_url("gemini://localhost:1968\r\n", PORT) 51 | 52 | 53 | def test_check_input_response(): 54 | assert check_url("gemini://localhost?\r\n", PORT) 55 | assert check_url("gemini://localhost?hello\r\n", PORT) 56 | assert check_url("gemini://localhost?hello+world\r\n", PORT) 57 | assert check_url("gemini://localhost?hello%20world\r\n", PORT) 58 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | from os.path import abspath, dirname, join 2 | 3 | import pytest 4 | 5 | from gemeaux import Handler, Response, TemplateResponse 6 | 7 | 8 | class FakeResponse(Response): 9 | def __init__(self, origin): 10 | self.origin = origin 11 | 12 | 13 | class FakeHandler(Handler): 14 | def handle(self, *args, **kwargs): 15 | return FakeResponse(origin="handler") 16 | 17 | 18 | class FakeHandlerRaiseException(Handler): 19 | def handle(self, *args, **kwargs): 20 | raise Exception 21 | 22 | 23 | @pytest.fixture 24 | def fake_response(): 25 | return FakeResponse(origin="direct") 26 | 27 | 28 | @pytest.fixture 29 | def fake_handler(): 30 | return FakeHandler() 31 | 32 | 33 | @pytest.fixture 34 | def fake_handler_exception(): 35 | return FakeHandlerRaiseException() 36 | 37 | 38 | @pytest.fixture() 39 | def index_content(): 40 | return """# Title\r\nI am the content of index""" 41 | 42 | 43 | @pytest.fixture() 44 | def other_content(): 45 | return """# Title\r\nI am the content of other""" 46 | 47 | 48 | @pytest.fixture() 49 | def sub_content(): 50 | return """# Title\r\nI am the content of sub""" 51 | 52 | 53 | @pytest.fixture() 54 | def multi_line_content(): 55 | return "First line\nSecond line\rThird line\r\nLast line." 56 | 57 | 58 | @pytest.fixture() 59 | def multi_line_content_crlf(): 60 | return "First line\r\nSecond line\r\nThird line\r\nLast line.\r\n" 61 | 62 | 63 | @pytest.fixture() 64 | def image_content(): 65 | path = dirname(abspath(__file__)) 66 | with open(join(path, "caffeine.png"), "rb") as fd: 67 | return fd.read() 68 | 69 | 70 | @pytest.fixture() 71 | def index_directory( 72 | tmpdir_factory, 73 | index_content, 74 | other_content, 75 | sub_content, 76 | multi_line_content, 77 | image_content, 78 | ): 79 | p = tmpdir_factory.mktemp("var") 80 | # Create index file 81 | pp = p.join("index.gmi") 82 | pp.write_text(index_content, encoding="utf-8") 83 | # Other file 84 | pp = p.join("other.gmi") 85 | pp.write_text(other_content, encoding="utf-8") 86 | # Multi line file 87 | pp = p.join("multi_line.gmi") 88 | pp.write_text(multi_line_content, encoding="utf-8") 89 | 90 | sub = p.mkdir("subdir").join("sub.gmi") 91 | sub.write_text(sub_content, encoding="utf-8") 92 | 93 | # Write the image content into the image file 94 | image = p.join("image.png") 95 | image.write_binary(image_content) 96 | 97 | # Return directory 98 | return p 99 | 100 | 101 | class FakeTemplateResponse(TemplateResponse): 102 | pass 103 | 104 | 105 | @pytest.fixture() 106 | def template_file(tmpdir_factory): 107 | p = tmpdir_factory.mktemp("templates") 108 | pp = p.join("template.txt") 109 | pp.write_text("First var: $var1 / Second var: $var2", encoding="utf-8") 110 | return pp 111 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Gemeaux changelog 2 | 3 | ## master (unreleased) 4 | 5 | Nothing here yet. 6 | 7 | ## v0.0.3 (2025-04-06) 8 | 9 | ### Features 10 | 11 | * Fix `InputResponse` handling when transmitting the answer to the prompt. 12 | * Added unittests to the `check_url` function. 13 | * Small refactor of basic classes, to force users to define their status code in derivative classes. 14 | * Change strategy for loading configuration / arguments. Easier testing and less naughty side-effects. 15 | 16 | ### Maintenance 17 | 18 | * [BREAKING CHANGE] Removed support of Python 3.6, 3.7 and 3.8. 19 | * Confirm support of Python 3.9, 3.10, 3.11, 3.12, 3.13 20 | * Fixed the collections import in main file so its code is future-proof. Thanks @JonStratton (#13) 21 | * Switched from Travis CI to Github Workflows 22 | * Added the option `SO_REUSEADDR` to the severs socket. Thanks @airmack (#11) 23 | * Switch from `setup.cfg` to `pyproject.toml`, as all cool kids do (#20). 24 | 25 | ### Documentation 26 | 27 | * Added `BadRequestResponse` and `ProxyRequestRefusedResponse` to the example application. 28 | * Added documentation about the available `Response` classes. 29 | * Added the phonetics of the word "gémeaux" in French. 30 | * Added nice badges to `README.md` file. 31 | * Added a small badge for GH workflows 32 | * Updating links to the Gemini Protocol canonical website and Bollux project page on the README 33 | 34 | ## v0.0.2 (2020-12-07) 35 | 36 | ### Following the Specs 37 | 38 | * Added `TemplateResponse` & `TemplateHandler` classes for generating Gemini content using template files. 39 | * Make sure returned responses endlines are not mixed, only CRLF. 40 | * Handling mimetypes other than `text/gemini`. Clients would have to download them instead of trying to display them. Example app is amended. 41 | * Redirect clients when pointing at a static subdirectory without a trailing slash. It caused misdirections because the client was requesting the "/document.gmi" instead of the "/subdir/document.gmi". 42 | * Improve application resilience after auditing it with [gemini-diagnostic](https://github.com/michael-lazar/gemini-diagnostics). Everything is not perfect, but that's a good start, to be honest. 43 | * Added `BadRequestResponse`, `ProxyRequestRefusedResponse` classes 44 | 45 | ### Other changes 46 | 47 | * Improved conftest for pytest using fixtures for document content. 48 | * Return version number when using the `--version` option. 49 | * Display version number at startup on the welcome message. 50 | * Added mimetype of response to the access log. 51 | * Added documentation for Handlers. 52 | 53 | ## v0.0.1 (2020-12-04) 54 | 55 | This is the first release of `Gemeaux` server. 56 | 57 | ### Main features 58 | 59 | * Implementation of the TLS-required Gemini protocol communication workflow. The most used parts of the specifications are covered, but there are still lots of improvements to make, 60 | * Serving a static directory tree made of `.gmi` files. Configuration options: index file name, directory listing, 61 | * Serving a textual content, 62 | * Redirection (permanent or temporary) responses, 63 | * Customizable Handlers, 64 | * Tested with Python 3.6, 3.7, 3.8 through pytest and Travis-CI. 65 | * Example application to show how to use the core features. 66 | -------------------------------------------------------------------------------- /example_app.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | from gemeaux import ( 4 | App, 5 | BadRequestResponse, 6 | Handler, 7 | InputResponse, 8 | NotFoundResponse, 9 | PermanentRedirectResponse, 10 | ProxyRequestRefusedResponse, 11 | RedirectResponse, 12 | SensitiveInputResponse, 13 | StaticHandler, 14 | TemplateHandler, 15 | TemplateResponse, 16 | TextResponse, 17 | ) 18 | 19 | 20 | class HelloWorldHandler(Handler): 21 | """ 22 | Proof-of-concept dynamic handler 23 | """ 24 | 25 | def get_response(self): 26 | return TextResponse("Title", "Hello World!") 27 | 28 | def handle(self, url, path): 29 | response = self.get_response() 30 | return response 31 | 32 | 33 | class DatetimeTemplateHandler(TemplateHandler): 34 | template_file = "examples/templates/template.txt" 35 | 36 | def get_context(self, *args, **kwargs): 37 | return {"datetime": datetime.datetime.now()} 38 | 39 | 40 | if __name__ == "__main__": 41 | urls = { 42 | "": StaticHandler( 43 | # Static pages, with directory listing 44 | static_dir="examples/static/", 45 | directory_listing=True, 46 | ), 47 | "/test": StaticHandler( 48 | # Static pages, no directory listing 49 | static_dir="examples/static/", 50 | directory_listing=False, 51 | ), 52 | "/with-sub": StaticHandler( 53 | # Static pages, pointing at a "deep" directory with an index.gmi file 54 | static_dir="examples/static/sub-dir", 55 | ), 56 | "/index-file": StaticHandler( 57 | # Static pages, pointing at a directory with an alternate index file 58 | static_dir="examples/static/empty-dir", 59 | index_file="one.gmi", 60 | ), 61 | # Custom Handler 62 | "/hello": HelloWorldHandler(), 63 | "/template": DatetimeTemplateHandler(), 64 | # Direct response 65 | "/direct": TextResponse(title="Direct Response", body="I am here"), 66 | "/template-response": TemplateResponse( 67 | template_file="examples/templates/template.txt", 68 | datetime="Not the dynamic datetime you were expecting", 69 | ), 70 | # Standard responses 71 | "/10": InputResponse(prompt="What's the ultimate answer?"), 72 | "/11": SensitiveInputResponse(prompt="What's the ultimate answer?"), 73 | "/30": RedirectResponse(target="/hello"), 74 | "/31": PermanentRedirectResponse(target="/hello"), 75 | # TODO: 40 TEMPORARY FAILURE 76 | # TODO: 41 SERVER UNAVAILABLE 77 | # TODO: 42 (?) CGI ERROR 78 | # TODO: 43 (?) PROXY ERROR 79 | # TODO: 44 SLOW DOWN 80 | # TODO: 50 PERMANENT FAILURE 81 | # TODO: 51 NOT FOUND (already covered by other response, but nice to have) 82 | "/51": NotFoundResponse("Nobody will escape the Area 51"), 83 | # TODO: 52 GONE 84 | "/53": ProxyRequestRefusedResponse(), 85 | "/59": BadRequestResponse(), 86 | # TODO: 60 (?) CLIENT CERTIFICATE REQUIRED 87 | # TODO: 61 (?) CERTIFICATE NOT AUTHORISED 88 | # TODO: 62 (?) CERTIFICATE NOT VALID 89 | # Configration errors. Uncomment to see how they're handled 90 | # "error": "I am an error", 91 | # "error": StaticHandler(static_dir="/tmp/not-a-directory"), 92 | } 93 | app = App(urls) 94 | app.run() 95 | -------------------------------------------------------------------------------- /gemeaux/handlers.py: -------------------------------------------------------------------------------- 1 | from os.path import abspath, isdir, isfile, join 2 | 3 | from .exceptions import ImproperlyConfigured 4 | from .responses import ( 5 | DirectoryListingResponse, 6 | DocumentResponse, 7 | RedirectResponse, 8 | TemplateResponse, 9 | ) 10 | 11 | 12 | class Handler: 13 | def __init__(self, *args, **kwargs): 14 | pass 15 | 16 | def get_response(self, *args, **kwargs): 17 | raise NotImplementedError 18 | 19 | def handle(self, url, path): 20 | """ 21 | Handle the request to return the appropriate response. 22 | 23 | Override/write this method if you need extra processing before returning the 24 | standard Response. 25 | """ 26 | response = self.get_response(url, path) 27 | return response 28 | 29 | 30 | class StaticHandler(Handler): 31 | """ 32 | Handler for serving static Gemini pages from a directory on your filesystem. 33 | """ 34 | 35 | def __init__(self, static_dir, directory_listing=True, index_file="index.gmi"): 36 | self.static_dir = abspath(static_dir) 37 | if not isdir(self.static_dir): 38 | raise ImproperlyConfigured(f"{self.static_dir} is not a directory") 39 | self.directory_listing = directory_listing 40 | self.index_file = index_file 41 | 42 | def __repr__(self): 43 | return f"" 44 | 45 | def get_response(self, url, path): 46 | """ 47 | Return the static page response according to the configuration & file tree. 48 | 49 | * If the path is a file -> return DocumentResponse for this file. 50 | * If the path is a directory -> search for "index_file" 51 | * If index is found => DocumentResponse 52 | * If not found, depending on the directory_listing arg: 53 | * If activated, it'll return the DirectoryListingResponse 54 | * If deactivated => raises a FileNotFoundError. 55 | * If none of the cases above is satisfied, it raises a FileNotFoundError 56 | """ 57 | # A bit paranoid… 58 | if path.startswith(url): 59 | path = path[len(url) :] 60 | if path.startswith("/"): # Should be a relative path 61 | path = path[1:] 62 | 63 | full_path = join(self.static_dir, path) 64 | # print(f"StaticHandler: path='{full_path}'") 65 | # The path leads to a directory 66 | if isdir(full_path): 67 | # Directory. Redirect if not root? 68 | if path and not path.endswith("/"): 69 | return RedirectResponse(f"{path}/") 70 | # Directory -> index? 71 | index_path = join(full_path, self.index_file) 72 | if isfile(index_path): 73 | return DocumentResponse(index_path, self.static_dir) 74 | elif self.directory_listing: 75 | return DirectoryListingResponse(full_path, self.static_dir) 76 | # The path is a file 77 | elif isfile(full_path): 78 | return DocumentResponse(full_path, self.static_dir) 79 | # Else, not found or error 80 | raise FileNotFoundError("Path not found") 81 | 82 | 83 | class TemplateHandler(Handler): 84 | """ 85 | Template Handler 86 | """ 87 | 88 | template_file = None 89 | 90 | def get_response(self, url, path): 91 | """ 92 | Feeds the context variable into the template file to return dynamic content. 93 | """ 94 | context = self.get_context() 95 | return TemplateResponse(self.get_template_file(), **context) 96 | 97 | def get_context(self): 98 | """ 99 | Return a dictionary containing context variables to inject into the template. 100 | 101 | Override this method to inject your dynamic content. 102 | """ 103 | return {} 104 | 105 | def get_template_file(self): 106 | """ 107 | Return the path to the template file to use with the `TemplateResponse`. 108 | 109 | You can either define a `template_file` class property or overwrite this method to return the appropriate template. 110 | """ 111 | if self.template_file: 112 | return self.template_file 113 | raise NotImplementedError( 114 | "Implement a `get_template_file` method or define a `template_file` class attribute" 115 | ) 116 | -------------------------------------------------------------------------------- /tests/test_handlers.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | import pytest 4 | 5 | from gemeaux import ( 6 | DirectoryListingResponse, 7 | DocumentResponse, 8 | ImproperlyConfigured, 9 | RedirectResponse, 10 | StaticHandler, 11 | TemplateHandler, 12 | TemplateResponse, 13 | ) 14 | 15 | 16 | def test_static_handler_not_a_directory(): 17 | with pytest.raises(ImproperlyConfigured): 18 | StaticHandler("/tmp/not-a-directory") 19 | 20 | 21 | def test_static_handler_document(index_directory, index_content, other_content): 22 | handler = StaticHandler(index_directory) 23 | response = handler.get_response("", "/") 24 | assert isinstance(response, DocumentResponse) 25 | assert response.content == bytes(index_content, encoding="utf-8") 26 | 27 | # Reaching directly index.gmi 28 | handler = StaticHandler(index_directory) 29 | response = handler.get_response("", "/index.gmi") 30 | assert isinstance(response, DocumentResponse) 31 | assert response.content == bytes(index_content, encoding="utf-8") 32 | 33 | # Reaching directly index.gmi / no starting slash 34 | handler = StaticHandler(index_directory) 35 | response = handler.get_response("/", "index.gmi") 36 | assert isinstance(response, DocumentResponse) 37 | assert response.content == bytes(index_content, encoding="utf-8") 38 | 39 | # Reaching directly other.gmi 40 | handler = StaticHandler(index_directory) 41 | response = handler.get_response("", "/other.gmi") 42 | assert isinstance(response, DocumentResponse) 43 | assert response.content == bytes(other_content, encoding="utf-8") 44 | 45 | 46 | def test_static_handler_subdir(index_directory, sub_content): 47 | # Reaching direct /subdir/sub.gmi 48 | handler = StaticHandler(index_directory) 49 | response = handler.get_response("", "/subdir/sub.gmi") 50 | assert isinstance(response, DocumentResponse) 51 | assert response.content == bytes(sub_content, encoding="utf-8") 52 | 53 | # No Index -> Directory Listing 54 | handler = StaticHandler(index_directory) 55 | response = handler.get_response("", "/subdir/") 56 | assert isinstance(response, DirectoryListingResponse) 57 | assert response.content.startswith(b"# Directory listing for `/subdir`\r\n") 58 | 59 | # No Index + No slash -> Directory Listing 60 | handler = StaticHandler(index_directory) 61 | response = handler.get_response("", "/subdir") 62 | assert isinstance(response, RedirectResponse) 63 | assert response.target == "subdir/" 64 | 65 | 66 | def test_static_handler_sub_url(index_directory, index_content): 67 | handler = StaticHandler(index_directory) 68 | response = handler.get_response("/test", "/test/index.gmi") 69 | assert isinstance(response, DocumentResponse) 70 | assert response.content == bytes(index_content, encoding="utf-8") 71 | 72 | 73 | def test_static_handler_not_found(index_directory): 74 | handler = StaticHandler(index_directory) 75 | with pytest.raises(FileNotFoundError): 76 | handler.get_response("", "/not-found") 77 | 78 | with pytest.raises(FileNotFoundError): 79 | handler.get_response("", "/not-found.gmi") 80 | 81 | with pytest.raises(FileNotFoundError): 82 | handler.get_response("", "/subdir/not-found/") 83 | 84 | with pytest.raises(FileNotFoundError): 85 | handler.get_response("", "/subdir/not-found.gmi") 86 | 87 | 88 | def test_static_handler_no_directory_listing( 89 | index_directory, index_content, sub_content 90 | ): 91 | handler = StaticHandler(index_directory, directory_listing=False) 92 | # No change in response for "/" 93 | response = handler.get_response("", "/") 94 | assert isinstance(response, DocumentResponse) 95 | assert response.content == bytes(index_content, encoding="utf-8") 96 | 97 | # Subdir + no slash -> Redirect to "/" 98 | response = handler.get_response("", "/subdir") 99 | assert isinstance(response, RedirectResponse) 100 | assert response.target == "subdir/" 101 | 102 | # Subdir -> no index -> no directory listing 103 | with pytest.raises(FileNotFoundError): 104 | handler.get_response("", "/subdir/") 105 | 106 | # subdir/sub.gmi 107 | response = handler.get_response("", "/subdir/sub.gmi") 108 | assert isinstance(response, DocumentResponse) 109 | assert response.content == bytes(sub_content, encoding="utf-8") 110 | 111 | 112 | def test_static_handler_alternate_index(index_directory, other_content): 113 | handler = StaticHandler(index_directory, index_file="other.gmi") 114 | # "/" returns other.gmi content 115 | response = handler.get_response("", "/") 116 | assert isinstance(response, DocumentResponse) 117 | assert response.content == bytes(other_content, encoding="utf-8") 118 | 119 | # Subdir -> no other.gmi -> directory listing 120 | response = handler.get_response("", "/subdir/") 121 | assert isinstance(response, DirectoryListingResponse) 122 | assert response.content.startswith(b"# Directory listing for `/subdir`\r\n") 123 | 124 | 125 | def test_static_handler_alternate_index_no_dirlist(index_directory, other_content): 126 | handler = StaticHandler( 127 | index_directory, directory_listing=False, index_file="other.gmi" 128 | ) 129 | # "/" returns other.gmi content 130 | response = handler.get_response("", "/") 131 | assert isinstance(response, DocumentResponse) 132 | assert response.content == bytes(other_content, encoding="utf-8") 133 | 134 | # Subdir -> no other.gmi -> no directory listing 135 | with pytest.raises(FileNotFoundError): 136 | response = handler.get_response("", "/subdir/") 137 | 138 | 139 | def test_template_handler_getter(template_file): 140 | class TemplateHandlerWithGetter(TemplateHandler): 141 | def get_context(self, *args, **kwargs): 142 | return {"var1": date.today(), "var2": "hello"} 143 | 144 | def get_template_file(self): 145 | return template_file 146 | 147 | handler = TemplateHandlerWithGetter() 148 | response = handler.get_response("", "/") 149 | 150 | assert isinstance(response, TemplateResponse) 151 | assert response.status == 20 152 | expected_body = f"First var: {date.today()} / Second var: hello" 153 | assert response.__body__().startswith(bytes(expected_body, encoding="utf-8")) 154 | 155 | 156 | def test_template_handler_classattr(template_file): 157 | class TemplateHandlerWithClassattr(TemplateHandler): 158 | def get_context(self, *args, **kwargs): 159 | return {"var1": date.today(), "var2": "hello"} 160 | 161 | TemplateHandlerWithClassattr.template_file = template_file 162 | 163 | handler = TemplateHandlerWithClassattr() 164 | response = handler.get_response("", "/") 165 | 166 | assert isinstance(response, TemplateResponse) 167 | assert response.status == 20 168 | expected_body = f"First var: {date.today()} / Second var: hello" 169 | assert response.__body__().startswith(bytes(expected_body, encoding="utf-8")) 170 | -------------------------------------------------------------------------------- /tests/test_responses.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from gemeaux import ( 4 | BadRequestResponse, 5 | DirectoryListingResponse, 6 | DocumentResponse, 7 | InputResponse, 8 | NotFoundResponse, 9 | PermanentFailureResponse, 10 | PermanentRedirectResponse, 11 | ProxyRequestRefusedResponse, 12 | RedirectResponse, 13 | Response, 14 | SensitiveInputResponse, 15 | SuccessResponse, 16 | TemplateError, 17 | TemplateResponse, 18 | TextResponse, 19 | crlf, 20 | ) 21 | 22 | 23 | def test_base_response(): 24 | response = Response() 25 | with pytest.raises(NotImplementedError): 26 | response.status 27 | assert response.__body__() is None 28 | with pytest.raises(NotImplementedError): 29 | response.__meta__() 30 | 31 | 32 | def test_success_response(): 33 | response = SuccessResponse() 34 | assert response.status == 20 35 | assert response.__body__() is None 36 | assert response.__meta__() == b"20 text/gemini; charset=utf-8" 37 | 38 | 39 | def test_input_response(): 40 | response = InputResponse("What's the meaning of life?") 41 | assert response.status == 10 42 | assert response.__body__() is None 43 | assert bytes(response) == b"10 What's the meaning of life?\r\n" 44 | 45 | 46 | def test_sensitive_input_response(): 47 | response = SensitiveInputResponse("What's the meaning of life?") 48 | assert response.status == 11 49 | assert response.__body__() is None 50 | assert bytes(response) == b"11 What's the meaning of life?\r\n" 51 | 52 | 53 | def test_redirect_response(): 54 | response = RedirectResponse("gemini://localhost/") 55 | assert response.status == 30 56 | assert response.__body__() is None 57 | assert bytes(response) == b"30 gemini://localhost/\r\n" 58 | 59 | 60 | def test_permanent_redirect_response(): 61 | response = PermanentRedirectResponse("gemini://localhost/") 62 | assert response.status == 31 63 | assert response.__body__() is None 64 | assert bytes(response) == b"31 gemini://localhost/\r\n" 65 | 66 | 67 | def test_permanent_failure_response(): 68 | response = PermanentFailureResponse() 69 | assert response.status == 50 70 | assert response.__body__() is None 71 | assert bytes(response) == b"50 PERMANENT FAILURE\r\n" 72 | 73 | 74 | def test_permanent_failure_response_reason(): 75 | response = PermanentFailureResponse(reason="This resource is broken") 76 | assert response.status == 50 77 | assert response.__body__() is None 78 | assert bytes(response) == b"50 This resource is broken\r\n" 79 | 80 | 81 | def test_not_found_response(): 82 | response = NotFoundResponse() 83 | assert response.status == 51 84 | assert response.__body__() is None 85 | assert bytes(response) == b"51 NOT FOUND\r\n" 86 | 87 | 88 | def test_not_found_response_reason(): 89 | response = NotFoundResponse(reason="The document is unreadable") 90 | assert response.status == 51 91 | assert response.__body__() is None 92 | assert bytes(response) == b"51 The document is unreadable\r\n" 93 | 94 | 95 | def test_proxy_refused_response(): 96 | response = ProxyRequestRefusedResponse() 97 | assert response.status == 53 98 | assert response.__body__() is None 99 | assert bytes(response) == b"53 PROXY REQUEST REFUSED\r\n" 100 | 101 | 102 | def test_bad_request_response(): 103 | response = BadRequestResponse() 104 | assert response.status == 59 105 | assert response.__body__() is None 106 | assert bytes(response) == b"59 BAD REQUEST\r\n" 107 | 108 | 109 | def test_bad_request_response_reason(): 110 | response = BadRequestResponse(reason="You sent me a wrong request") 111 | assert response.status == 59 112 | assert response.__body__() is None 113 | assert bytes(response) == b"59 You sent me a wrong request\r\n" 114 | 115 | 116 | def test_document_response(index_directory, index_content): 117 | response = DocumentResponse( 118 | index_directory.join("index.gmi").strpath, index_directory.strpath 119 | ) 120 | assert response.status == 20 121 | bytes_content = bytes(index_content, encoding="utf-8") 122 | bytes_body = b"20 text/gemini\r\n" + bytes_content + b"\r\n" 123 | assert response.__body__() == bytes_content 124 | assert bytes(response) == bytes_body 125 | 126 | 127 | def test_document_response_not_in_root_dir(index_directory): 128 | with pytest.raises(FileNotFoundError): 129 | DocumentResponse(index_directory.join("index.gmi").strpath, "/you/do/not/exist") 130 | 131 | 132 | def test_document_response_not_a_file(index_directory): 133 | with pytest.raises(FileNotFoundError): 134 | DocumentResponse(index_directory.strpath, index_directory.strpath) 135 | 136 | with pytest.raises(FileNotFoundError): 137 | DocumentResponse( 138 | index_directory.join("not-found.gmi").strpath, index_directory.strpath 139 | ) 140 | 141 | 142 | def test_document_response_crlf( 143 | index_directory, multi_line_content, multi_line_content_crlf 144 | ): 145 | response = DocumentResponse( 146 | index_directory.join("multi_line.gmi").strpath, index_directory.strpath 147 | ) 148 | assert response.status == 20 149 | multi_line_body_expected = bytes(multi_line_content_crlf, encoding="utf-8") 150 | bytes_body = b"20 text/gemini\r\n" + multi_line_body_expected 151 | assert bytes(response) == bytes_body 152 | 153 | 154 | def test_document_response_binary(index_directory, image_content): 155 | response = DocumentResponse( 156 | index_directory.join("image.png").strpath, index_directory.strpath 157 | ) 158 | assert response.status == 20 159 | bytes_body = b"20 image/png\r\n" + image_content 160 | assert bytes(response) == bytes_body 161 | 162 | 163 | def test_directory_listing(index_directory): 164 | response = DirectoryListingResponse( 165 | index_directory.strpath, index_directory.strpath 166 | ) 167 | 168 | assert response.status == 20 169 | assert response.__meta__() == b"20 text/gemini; charset=utf-8" 170 | assert response.__body__().startswith(b"# Directory listing for ``") 171 | assert b"=> /subdir" in response.__body__() 172 | assert b"=> /other.gmi" in response.__body__() 173 | 174 | 175 | def test_directory_listing_crlf(index_directory): 176 | response = DirectoryListingResponse( 177 | index_directory.strpath, index_directory.strpath 178 | ) 179 | assert bytes(response) == crlf(bytes(response)) 180 | 181 | 182 | def test_directory_listing_subdir(index_directory): 183 | response = DirectoryListingResponse( 184 | index_directory.join("subdir").strpath, index_directory.strpath 185 | ) 186 | 187 | assert response.status == 20 188 | assert response.__meta__() == b"20 text/gemini; charset=utf-8" 189 | assert response.__body__().startswith(b"# Directory listing for `/subdir`\r\n") 190 | assert b"=> /subdir/sub.gmi\r\n" in response.__body__() 191 | 192 | 193 | def test_directory_listing_not_in_root_dir(index_directory): 194 | with pytest.raises(FileNotFoundError): 195 | DirectoryListingResponse(index_directory.strpath, "/you/do/not/exist") 196 | with pytest.raises(FileNotFoundError): 197 | DirectoryListingResponse( 198 | index_directory.join("subdir").strpath, "/you/do/not/exist" 199 | ) 200 | 201 | 202 | def test_text_response(): 203 | # No title, no body 204 | response = TextResponse() 205 | assert bytes(response) == b"20 text/gemini; charset=utf-8\r\n" 206 | 207 | # A title, no body 208 | response = TextResponse(title="Title") 209 | assert bytes(response) == ( 210 | b"20 text/gemini; charset=utf-8\r\n" # header 211 | b"# Title\r\n" # Title 212 | b"\r\n" # empty line 213 | ) 214 | 215 | # No title, A body 216 | response = TextResponse(body="My body") 217 | assert bytes(response) == ( 218 | b"20 text/gemini; charset=utf-8\r\nMy body\r\n" # header + Body 219 | ) 220 | 221 | # A title and a body 222 | response = TextResponse(title="Title", body="My body") 223 | assert bytes(response) == ( 224 | b"20 text/gemini; charset=utf-8\r\n" # header 225 | b"# Title\r\n" # Title 226 | b"\r\n" # Empty line 227 | b"My body\r\n" # Body 228 | ) 229 | 230 | 231 | def test_template_response(template_file): 232 | response = TemplateResponse(template_file, **{"var1": "value1", "var2": "value2"}) 233 | assert response.status == 20 234 | assert response.__body__() == b"First var: value1 / Second var: value2" 235 | 236 | response = TemplateResponse( 237 | template_file, **{"var1": "value1", "var2": "value2", "var_other": "other"} 238 | ) 239 | assert response.status == 20 240 | assert response.__body__() == b"First var: value1 / Second var: value2" 241 | assert bytes(response) == ( 242 | b"20 text/gemini; charset=utf-8\r\n" 243 | b"First var: value1 / Second var: value2\r\n" 244 | ) 245 | 246 | 247 | def test_template_response_wrong_context(template_file): 248 | # Empty context 249 | response = TemplateResponse(template_file) 250 | with pytest.raises(TemplateError): 251 | bytes(response) 252 | 253 | # Incomplete context 254 | response = TemplateResponse(template_file, **{"var1": "value1"}) 255 | with pytest.raises(TemplateError): 256 | bytes(response) 257 | 258 | 259 | def test_template_response_not_a_template(): 260 | with pytest.raises(TemplateError): 261 | TemplateResponse("/tmp/not-a-template") 262 | try: 263 | TemplateResponse("/tmp/not-a-template") 264 | except Exception as exc: 265 | assert exc.args == ("Template file not found: `/tmp/not-a-template`",) 266 | -------------------------------------------------------------------------------- /gemeaux/responses.py: -------------------------------------------------------------------------------- 1 | import mimetypes 2 | from itertools import chain 3 | from os import listdir 4 | from os.path import abspath, isdir, isfile 5 | from string import Template 6 | 7 | from .exceptions import TemplateError 8 | 9 | MIMETYPES = mimetypes.MimeTypes() 10 | # All known mimetypes have to be read in the system. 11 | # https://bugs.python.org/issue38656 12 | for fn in mimetypes.knownfiles: 13 | if isfile(fn): 14 | MIMETYPES.read(fn) 15 | MIMETYPES.add_type("text/gemini", ".gmi") 16 | MIMETYPES.add_type("text/gemini", ".gemini") 17 | 18 | 19 | def crlf(text): 20 | r""" 21 | Normalize line endings to unix (``\r\n``). Text should be bytes. 22 | """ 23 | lines = text.splitlines() # Will remove all types of linefeeds 24 | lines = map(lambda x: x + b"\r\n", lines) # append the "true" linefeed 25 | return b"".join(lines) 26 | 27 | 28 | class Response: 29 | """ 30 | Basic Gemini response 31 | """ 32 | 33 | mimetype = "text/gemini; charset=utf-8" 34 | 35 | @property 36 | def status(self): 37 | raise NotImplementedError("You need to define this response `status` code.") 38 | 39 | def __meta__(self): 40 | """ 41 | Return the meta line (without the CRLF). 42 | """ 43 | meta = f"{self.status} {self.mimetype}" 44 | return bytes(meta, encoding="utf-8") 45 | 46 | def __body__(self): 47 | """ 48 | Default Response body is None and will not be returned to the client. 49 | """ 50 | return None 51 | 52 | def __bytes__(self): 53 | """ 54 | Return the response sent via the connection 55 | """ 56 | # Use cache whenever it's possible to avoid round trip with bool() in log 57 | if hasattr(self, "__bytes"): 58 | return getattr(self, "__bytes") 59 | 60 | # Composed of the META line and the body 61 | response = [self.__meta__(), self.__body__()] 62 | # Only non-empty items are sent 63 | response = filter(bool, response) 64 | # Joining using the right linefeed separator 65 | response = b"\r\n".join(response) 66 | 67 | # Binary bodies should be returned as is. 68 | if not self.mimetype.startswith("text/"): 69 | setattr(self, "__bytes", response) 70 | return response 71 | 72 | response = crlf(response) 73 | setattr(self, "__bytes", response) 74 | return response 75 | 76 | def __len__(self): 77 | """ 78 | Return the length of the response 79 | """ 80 | return len(bytes(self)) 81 | 82 | 83 | class SuccessResponse(Response): 84 | """ 85 | Success Response base class. Status: 20. 86 | """ 87 | 88 | status = 20 89 | 90 | 91 | class InputResponse(Response): 92 | """ 93 | Input response. Status code: 10. 94 | """ 95 | 96 | status = 10 97 | 98 | def __init__(self, prompt): 99 | self.prompt = prompt 100 | 101 | def __meta__(self): 102 | meta = f"{self.status} {self.prompt}" 103 | return bytes(meta, encoding="utf-8") 104 | 105 | 106 | class SensitiveInputResponse(InputResponse): 107 | """ 108 | Sensitive Input response. Status code: 11 109 | """ 110 | 111 | status = 11 112 | 113 | 114 | class RedirectResponse(Response): 115 | """ 116 | Temporary redirect. Status code: 30 117 | """ 118 | 119 | status = 30 120 | 121 | def __init__(self, target): 122 | self.target = target 123 | 124 | def __meta__(self): 125 | meta = f"{self.status} {self.target}" 126 | return bytes(meta, encoding="utf-8") 127 | 128 | 129 | class PermanentRedirectResponse(RedirectResponse): 130 | """ 131 | Permanent redirect. Status code: 31 132 | """ 133 | 134 | status = 31 135 | 136 | 137 | class PermanentFailureResponse(Response): 138 | """ 139 | Permanent Failure response. Status code: 50. 140 | """ 141 | 142 | status = 50 143 | 144 | def __init__(self, reason=None): 145 | if not reason: 146 | reason = "PERMANENT FAILURE" 147 | self.reason = reason 148 | 149 | def __meta__(self): 150 | meta = f"{self.status} {self.reason}" 151 | return bytes(meta, encoding="utf-8") 152 | 153 | 154 | class NotFoundResponse(Response): 155 | """ 156 | Not Found Error response. Status code: 51. 157 | """ 158 | 159 | status = 51 160 | 161 | def __init__(self, reason=None): 162 | if not reason: 163 | reason = "NOT FOUND" 164 | self.reason = reason 165 | 166 | def __meta__(self): 167 | meta = f"{self.status} {self.reason}" 168 | return bytes(meta, encoding="utf-8") 169 | 170 | 171 | class ProxyRequestRefusedResponse(Response): 172 | """ 173 | Proxy Request Refused response. Status code: 53 174 | """ 175 | 176 | status = 53 177 | 178 | def __meta__(self): 179 | meta = f"{self.status} PROXY REQUEST REFUSED" 180 | return bytes(meta, encoding="utf-8") 181 | 182 | 183 | class BadRequestResponse(Response): 184 | """ 185 | Bad Request response. Status code: 59. 186 | """ 187 | 188 | status = 59 189 | 190 | def __init__(self, reason=None): 191 | if not reason: 192 | reason = "BAD REQUEST" 193 | self.reason = reason 194 | 195 | def __meta__(self): 196 | meta = f"{self.status} {self.reason}" 197 | return bytes(meta, encoding="utf-8") 198 | 199 | 200 | # *** GEMEAUX CUSTOM RESPONSES *** 201 | class TextResponse(SuccessResponse): 202 | """ 203 | Simple text response, composed of a ``title`` and a text content. Status code: 20. 204 | """ 205 | 206 | def __init__(self, title=None, body=None): 207 | """ 208 | Raw dynamic text content. 209 | 210 | Arguments: 211 | 212 | * ``title``: The main title of the document. Will be flushed to the user as a 1st level title. 213 | * ``body``: The main content of the response. All line feeds will be converted into ``\\r\\n``. 214 | """ 215 | content = [] 216 | # Remove empty bodies 217 | if title: 218 | content.append(f"# {title}") 219 | content.append("") 220 | if body: 221 | content.append(body) 222 | content = map(lambda x: x + "\r\n", content) 223 | content = "".join(content) 224 | self.content = bytes(content, encoding="utf-8") 225 | 226 | def __body__(self): 227 | return self.content 228 | 229 | 230 | class DocumentResponse(SuccessResponse): 231 | """ 232 | Document response 233 | 234 | This reponse is the content a text document. 235 | """ 236 | 237 | def __init__(self, full_path, root_dir): 238 | """ 239 | Open the document and read its content. 240 | 241 | Arguments: 242 | 243 | * full_path: The full path for the file you want to read. 244 | * root_dir: The root directory of your static content tree. The full document path should belong to this directory. 245 | """ 246 | full_path = abspath(full_path) 247 | if not full_path.startswith(root_dir): 248 | raise FileNotFoundError("Forbidden path") 249 | if not isfile(full_path): 250 | raise FileNotFoundError 251 | with open(full_path, "rb") as fd: 252 | self.content = fd.read() 253 | self.mimetype = self.guess_mimetype(full_path) 254 | 255 | def guess_mimetype(self, filename): 256 | """ 257 | Guess the mimetype of a file based on the file extension. 258 | """ 259 | mime, encoding = MIMETYPES.guess_type(filename) 260 | if encoding: 261 | return f"{mime}; charset={encoding}" 262 | else: 263 | return mime or "application/octet-stream" 264 | 265 | def __meta__(self): 266 | meta = f"{self.status} {self.mimetype}" 267 | return bytes(meta, encoding="utf-8") 268 | 269 | def __body__(self): 270 | return self.content 271 | 272 | 273 | class DirectoryListingResponse(SuccessResponse): 274 | """ 275 | List contents of a Directory. Status code: 20 276 | 277 | Will raise a ``FileNotFoundError`` if the path passed as an argument is not a 278 | directory or if the path is not a sub-directory of the root path. 279 | """ 280 | 281 | def __init__(self, full_path, root_dir): 282 | # Just in case 283 | full_path = abspath(full_path) 284 | if not full_path.startswith(root_dir): 285 | raise FileNotFoundError("Forbidden path") 286 | if not isdir(full_path): 287 | raise FileNotFoundError 288 | relative_path = full_path[len(root_dir) :] 289 | 290 | heading = [f"# Directory listing for `{relative_path}`\r\n", "\r\n"] 291 | body = listdir(full_path) 292 | body = map(lambda x: f"=> {relative_path}/{x}\r\n", body) 293 | body = chain(heading, body) 294 | body = map(lambda item: bytes(item, encoding="utf8"), body) 295 | body = list(body) 296 | self.content = b"".join(body) 297 | 298 | def __body__(self): 299 | return self.content 300 | 301 | 302 | class TemplateResponse(SuccessResponse): 303 | """ 304 | Template Response. Uses the stdlib Template engine to render Gemini content. 305 | """ 306 | 307 | def __init__(self, template_file, **context): 308 | """ 309 | Leverage ``string.Template`` API to render dynamic Gemini content through a template file. 310 | 311 | Arguments: 312 | 313 | * ``template_file``: full path to your template file. 314 | * ``context``: multiple variables to pass in your template as template variables. 315 | """ 316 | if not isfile(template_file): 317 | raise TemplateError(f"Template file not found: `{template_file}`") 318 | with open(template_file, "r") as fd: 319 | self.template = Template(fd.read()) 320 | self.context = context 321 | 322 | def __body__(self): 323 | try: 324 | body = self.template.substitute(self.context) 325 | return bytes(body, encoding="utf-8") 326 | except KeyError as exc: 327 | raise TemplateError(exc.args[0]) 328 | -------------------------------------------------------------------------------- /gemeaux/__init__.py: -------------------------------------------------------------------------------- 1 | import collections.abc 2 | import ssl 3 | import sys 4 | import time 5 | from argparse import ArgumentParser 6 | from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket 7 | from ssl import PROTOCOL_TLS_SERVER, SSLContext 8 | from urllib.parse import urlparse 9 | 10 | from .exceptions import ( 11 | BadRequestException, 12 | ImproperlyConfigured, 13 | ProxyRequestRefusedException, 14 | TemplateError, 15 | TimeoutException, 16 | ) 17 | from .handlers import Handler, StaticHandler, TemplateHandler 18 | from .responses import ( 19 | BadRequestResponse, 20 | DirectoryListingResponse, 21 | DocumentResponse, 22 | InputResponse, 23 | NotFoundResponse, 24 | PermanentFailureResponse, 25 | PermanentRedirectResponse, 26 | ProxyRequestRefusedResponse, 27 | RedirectResponse, 28 | Response, 29 | SensitiveInputResponse, 30 | SuccessResponse, 31 | TemplateResponse, 32 | TextResponse, 33 | crlf, 34 | ) 35 | 36 | __version__ = "0.0.4.dev0" 37 | 38 | 39 | class ZeroConfig: 40 | ip = "localhost" 41 | port = 1965 42 | certfile = "cert.pem" 43 | keyfile = "key.pem" 44 | nb_connections = 5 45 | 46 | 47 | class ArgsConfig: 48 | def __init__(self): 49 | 50 | parser = ArgumentParser("Gemeaux: a Python Gemini server") 51 | parser.add_argument( 52 | "--ip", 53 | default="localhost", 54 | help="IP/Host of your server — default: localhost.", 55 | ) 56 | parser.add_argument( 57 | "--port", default=1965, type=int, help="Listening port — default: 1965." 58 | ) 59 | parser.add_argument("--certfile", default="cert.pem") 60 | parser.add_argument("--keyfile", default="key.pem") 61 | parser.add_argument( 62 | "--nb-connections", 63 | default=5, 64 | type=int, 65 | help="Maximum number of connections — default: 5", 66 | ) 67 | parser.add_argument( 68 | "--version", 69 | help="Return version and exits", 70 | action="store_true", 71 | default=False, 72 | ) 73 | 74 | args = parser.parse_args() 75 | 76 | if args.version: 77 | sys.exit(__version__) 78 | 79 | self.ip = args.ip 80 | self.port = args.port 81 | self.certfile = args.certfile 82 | self.keyfile = args.keyfile 83 | self.nb_connections = args.nb_connections 84 | 85 | 86 | def get_path(url): 87 | """ 88 | Parse a URL and return a path relative to the root 89 | """ 90 | url = url.strip() 91 | parsed = urlparse(url, "gemini") 92 | path = parsed.path 93 | return path 94 | 95 | 96 | def check_url(url, server_port): 97 | """ 98 | Check for the client URL conformity. 99 | 100 | Raise exception or return None 101 | """ 102 | parsed = urlparse(url, "gemini") 103 | 104 | # Check for bad request 105 | # Note: the URL will be cleaned before being used 106 | if not url.endswith("\r\n"): 107 | # TimeoutException will cause no response 108 | raise TimeoutException((url, parsed)) 109 | # Other than Gemini will trigger a PROXY ERROR 110 | if parsed.scheme != "gemini": 111 | raise ProxyRequestRefusedException 112 | # You need to provide the right scheme 113 | if not url.startswith("gemini://"): 114 | # BadRequestException will return BadRequestResponse 115 | raise BadRequestException 116 | # URL max length is 1024. 117 | if len(url.strip()) > 1024: 118 | # BadRequestException will return BadRequestResponse 119 | raise BadRequestException 120 | # Not the right port 121 | if ":" in parsed.netloc: 122 | location, port = parsed.netloc.split(":") 123 | if int(port) != server_port: 124 | raise ProxyRequestRefusedException 125 | return True 126 | 127 | 128 | class App: 129 | 130 | TIMESTAMP_FORMAT = "%d/%b/%Y:%H:%M:%S %z" 131 | BANNER = f""" 132 | ♊ Welcome to your Gémeaux server (v{__version__}) ♊ 133 | """ 134 | 135 | def __init__(self, urls, config=None): 136 | # Check the urls 137 | if not isinstance(urls, collections.abc.Mapping): 138 | # Not of the dict type 139 | raise ImproperlyConfigured("Bad url configuration: not a dict or dict-like") 140 | 141 | if not urls: 142 | # Empty dictionary or Falsy value 143 | raise ImproperlyConfigured("Bad url configuration: empty dict") 144 | 145 | for k, v in urls.items(): 146 | if not isinstance(v, (Handler, Response)): 147 | msg = f"URL configuration: wrong type for `{k}`. Should be of type Handler or Response." 148 | raise ImproperlyConfigured(msg) 149 | 150 | self.urls = urls 151 | self.config = config or ArgsConfig() 152 | 153 | def log(self, message, error=False): 154 | """ 155 | Log to standard output 156 | """ 157 | out = sys.stdout 158 | if error: 159 | out = sys.stderr 160 | print(message, file=out) 161 | 162 | def log_access(self, address, url, response=None): 163 | """ 164 | Log for access to the server 165 | """ 166 | status = mimetype = "??" 167 | response_size = 0 168 | if response: 169 | error = response.status > 20 170 | status = response.status 171 | response_size = len(response) 172 | mimetype = response.mimetype.split(";")[0] 173 | else: 174 | error = True 175 | message = '{} [{}] "{}" {} {} {}'.format( 176 | address, 177 | time.strftime(self.TIMESTAMP_FORMAT, time.localtime()), 178 | url.strip(), 179 | mimetype, 180 | status, 181 | response_size, 182 | ) 183 | self.log(message, error=error) 184 | 185 | def get_route(self, path): 186 | 187 | matching = [] 188 | 189 | for k_url, k_value in self.urls.items(): 190 | if not k_url: # Skip the catchall 191 | continue 192 | if path.startswith(k_url): 193 | matching.append(k_url) 194 | 195 | # One match or more. We'll take the "biggest" match. 196 | if len(matching) >= 1: 197 | k_url = max(matching, key=len) 198 | return (k_url, self.urls[k_url]) 199 | 200 | # Catch all 201 | if "" in self.urls: 202 | return "", self.urls[""] 203 | 204 | raise FileNotFoundError("Route Not Found") 205 | 206 | def exception_handling(self, exception, connection): 207 | """ 208 | Handle exceptions and errors when the client is requesting a resource. 209 | """ 210 | response = None 211 | if isinstance(exception, OSError): 212 | response = PermanentFailureResponse("OS Error") 213 | elif isinstance(exception, (ssl.SSLEOFError, ssl.SSLError)): 214 | response = PermanentFailureResponse("SSL Error") 215 | elif isinstance(exception, UnicodeDecodeError): 216 | response = BadRequestResponse("Unicode Decode Error") 217 | elif isinstance(exception, BadRequestException): 218 | response = BadRequestResponse() 219 | elif isinstance(exception, ProxyRequestRefusedException): 220 | response = ProxyRequestRefusedResponse() 221 | elif isinstance(exception, ConnectionResetError): 222 | # No response sent 223 | self.log("Connection reset by peer...", error=True) 224 | else: 225 | self.log(f"Exception: {exception} / {type(exception)}", error=True) 226 | 227 | try: 228 | if response and connection: 229 | connection.sendall(bytes(response)) 230 | except Exception as exc: 231 | self.log(f"Exception while processing exception… {exc}", error=True) 232 | 233 | def get_response(self, url): 234 | path = get_path(url) 235 | reason = None 236 | try: 237 | k_url, k_value = self.get_route(path) 238 | if isinstance(k_value, Handler): 239 | return k_value.handle(k_url, path) 240 | elif isinstance(k_value, Response): 241 | return k_value 242 | except TemplateError as exc: 243 | if exc.args: 244 | reason = exc.args[0] 245 | return PermanentFailureResponse(reason) 246 | except Exception as exc: 247 | if exc.args: 248 | reason = exc.args[0] 249 | self.log(f"Error: {type(exc)} / {reason}", error=True) 250 | 251 | return NotFoundResponse(reason) 252 | 253 | def mainloop(self, tls): 254 | while True: 255 | connection = response = None 256 | address = url = "" 257 | do_log = False 258 | try: 259 | connection, (address, _) = tls.accept() 260 | url = connection.recv(2048).decode() 261 | 262 | # Check URL conformity. 263 | check_url(url, self.port) 264 | 265 | response = self.get_response(url) 266 | connection.sendall(bytes(response)) 267 | do_log = True 268 | except KeyboardInterrupt: 269 | print("bye") 270 | sys.exit() 271 | except Exception as exc: 272 | self.exception_handling(exc, connection) 273 | finally: 274 | if connection: 275 | connection.close() 276 | if do_log: 277 | self.log_access(address, url, response) 278 | 279 | def run(self): 280 | """ 281 | Main run function. 282 | 283 | Load the configuration from the command line args. 284 | Launch the server 285 | """ 286 | # Loading config only at runtime, not initialization 287 | self.port = self.config.port 288 | context = SSLContext(PROTOCOL_TLS_SERVER) 289 | context.load_cert_chain(self.config.certfile, self.config.keyfile) 290 | 291 | with socket(AF_INET, SOCK_STREAM) as server: 292 | server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 293 | server.bind((self.config.ip, self.config.port)) 294 | server.listen(self.config.nb_connections) 295 | print(self.BANNER) 296 | with context.wrap_socket(server, server_side=True) as tls: 297 | print( 298 | f"Application started…, listening to {self.config.ip}:{self.config.port}" 299 | ) 300 | self.mainloop(tls) 301 | 302 | 303 | __all__ = [ 304 | # Core 305 | "App", 306 | # Exceptions 307 | "ImproperlyConfigured", 308 | "TemplateError", 309 | # Handlers 310 | "Handler", 311 | "StaticHandler", 312 | "TemplateHandler", 313 | # Responses 314 | "crlf", # Response tool 315 | "Response", 316 | "SuccessResponse", # Basic brick for building "OK" content 317 | "InputResponse", 318 | "SensitiveInputResponse", 319 | "RedirectResponse", 320 | "PermanentRedirectResponse", 321 | "PermanentFailureResponse", 322 | "NotFoundResponse", 323 | "BadRequestResponse", 324 | # Advanced responses 325 | "DocumentResponse", 326 | "DirectoryListingResponse", 327 | "TextResponse", 328 | "TemplateResponse", 329 | ] 330 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gemeaux: a Python Gemini Server 2 | 3 | ![Python tests](https://github.com/brunobord/gemeaux/actions/workflows/tox-tests.yaml/badge.svg) 4 | 5 | [![PyPI version of gemeaux](https://badge.fury.io/py/gemeaux.svg)](https://pypi.python.org/pypi/gemeaux/) [![PyPI license](https://img.shields.io/pypi/l/gemeaux.svg)](https://pypi.python.org/pypi/gemeaux/) [![PyPI pyversions](https://img.shields.io/pypi/pyversions/gemeaux.svg)](https://pypi.python.org/pypi/gemeaux/) 6 | 7 | The [Gemini protocol](https://gemini.circumlunar.space/) is an ongoing initiative to build a clutter-free content-focused Internet browsing, *à la* [Gopher](https://en.wikipedia.org/wiki/Gopher_(protocol)), but modernized. It focuses on Privacy (TLS + no user tracking) and eliminates the fluff around the modern web: cookies, ads, overweight Javascript apps, browser incompatibilities, etc. 8 | 9 | It has been designed for enabling a developer to build a client or a server within a few hours of work. I have been able to serve Gemini static content after two afternoons, so I guess I'm an average developer. But after that, I've tried to improve it, make it more flexible and extensible. 10 | 11 | So, here it is: the `Gemeaux` server. 12 | 13 | **IMPORTANT NOTE**: since this project is still in its earliest stages, it's worth saying that this software **IS DEFINITELY NOT READY FOR PRODUCTION** — and would probably never will ;o). 14 | 15 | ## Clients 16 | 17 | A quick word about Gemini protocol. Since it's a different protocol from HTTP, or Gopher, or FTP, etc., it means that you'll have to drop your beloved Web Browser to access Gemini content. Hopefully, several clients are available. 18 | 19 | * [A list of clients on the canonical Gemini Space](https://geminiprotocol.net/clients.html) 20 | * [A curated list of clients on "awesome Gemini"](https://github.com/kr1sp1n/awesome-gemini#clients) 21 | 22 | Download and install a couple of clients, pick one that fits your needs, or if you feel like it, build one yourself, and you'll be ready to spacewalk the Gemini ecosystem. 23 | 24 | For development purposes, I'd recommend [bollux](https://tildegit.org/acdw/bollux), a browser made for bash, because it displays helpful debug messages (and it's as fast as you can dream). 25 | 26 | ## Requirements 27 | 28 | `Gemeaux` is built around **the standard Python 3.9+ library** and syntax. There are **no external dependencies**. 29 | 30 | Automated tests are launched using Python 3.9, 3.10, 3.11, 3.12 and 3.13 so the internals of `Gemeaux` are safe with these versions of Python. 31 | 32 | You'll also need `openssl` to generate certificates. 33 | 34 | ## Quickstart 35 | 36 | ### Install via PyPI 37 | 38 | To install the latest release of `gemeaux` package, inside a virtualenv, or in a safe environment, run the following: 39 | 40 | ```sh 41 | pip install gemeaux 42 | ``` 43 | 44 | ### Developer mode 45 | 46 | ```sh 47 | git clone https://github.com/brunobord/gemeaux.git 48 | # You may also want to use this source: git@github.com:brunobord/gemeaux.git 49 | cd gemeaux/ 50 | pip install -e . 51 | ``` 52 | 53 | ### Generate certificates 54 | 55 | Since TLS is mandatory, you'll have to generate your own SSL certificate files. Use the following command to generate self-signed certificate files, targeting a localhost/developer mode: 56 | 57 | ```sh 58 | make cert 59 | ``` 60 | 61 | This command will generate two files: `cert.pem` and `key.pem`. 62 | 63 | Again, this will probably not be safe for production. 64 | 65 | ### Usage 66 | 67 | The "hello world" of this *proof of concept* would be to serve a directory containing an ``index.gmi`` file. 68 | 69 | For example, the `index.gmi` can look like this: 70 | 71 | ``` 72 | # Hello World! 73 | 74 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor 75 | incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis 76 | nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 77 | Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu 78 | fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in 79 | culpa qui officia deserunt mollit anim id est laborum. 80 | ``` 81 | 82 | Then you'll create a python file (e.g.: `app.py`) containing the following: 83 | 84 | ```python 85 | from gemeaux import App, StaticHandler 86 | 87 | if __name__ == "__main__": 88 | urls = { 89 | "": StaticHandler( 90 | static_dir="path/to/your/directory/" 91 | ), 92 | } 93 | app = App(urls) 94 | app.run() 95 | ``` 96 | 97 | *Note*: The `static_dir` argument can be a relative or an absolute path. 98 | 99 | Then you'll run your program using Python 3+: 100 | 101 | ```sh 102 | python app.py 103 | ``` 104 | 105 | You can then point your client at `gemini://localhost/` and you'll see the content of your home page. 106 | 107 | By default, the application will listen at port `1965` on your `localhost` (`127.0.0.1`) host, and will use the previously generated `cert.pem` and `key.pem` files. 108 | 109 | In order to open your server to "the world", you can change the `--ip` option like this: 110 | 111 | ```sh 112 | python app.py --ip 0.0.0.0 113 | ``` 114 | 115 | **BIG WARNING**: opening your server to external connections is **DEFINITELY NOT A GOOD IDEA**, since this software **IS NOT PRODUCTION-READY**. 116 | 117 | You can change the default configuration values using the optional arguments. For more details, run: 118 | 119 | ```sh 120 | python app.py --help 121 | ``` 122 | 123 | ## Advanced usage 124 | 125 | The `urls` configuration is at the core of the application workflow. By combining the available `Handler` and `Response` classes, you have the ability to create more complex Gemini spaces. 126 | 127 | You may read the example application, in the `example_app.py` file if you want to see an advanced usage of handlers & responses. 128 | 129 | Several classes are provided in this library. **All classes described below can be imported from the `gemeaux` module directly**, as in `from gemeaux import `. 130 | 131 | ### Handlers 132 | 133 | Most of the time, when working with `Handler` basic classes, you'll have to implement/override two methods: 134 | 135 | * `Handler.__init__(*args, **kwargs)`: The class constructor will accept `args` and `kwargs` for providing parameters. 136 | * `Handler.get_response(*args, *kwargs)`: Based on the parameters and your current context, you would generate a Gemini-compatible response, either based on the `Response` classes provided, or ones you can build yourself. 137 | 138 | #### StaticHandler 139 | 140 | This handler is used for serving a static directory and its subdirectories. 141 | 142 | How to instantiate: 143 | 144 | ```python 145 | StaticHandler( 146 | static_dir, 147 | directory_listing=True, 148 | index_file="index.gmi" 149 | ) 150 | ``` 151 | 152 | * `static_dir`: the path (relative to your program or absolute) of the root directory to serve. 153 | * `directory_listing` (default: `True`): if set to `True`, in case there's no "index file" in a directory, the application will display the directory listing. If set to `False`, and if there's still no index file in this directory, it'll return a `NotFoundResponse` to the client. 154 | * `index_file` (default: `"index.gmi"`): when the client tries to reach a directory, it's this filename that would be searched to be rendered as the "homepage". 155 | 156 | *Note*: If your client is trying to reach a subdirectory like this: `gemini://localhost/subdirectory` (without the trailing slash), the client will receive a Redirection Response targetting `gemini://localhost/subdirectory/` (with the trailing slash). 157 | 158 | #### TemplateHandler 159 | 160 | This handler provides methods to render Gemini content, mixing a text template and context variables. 161 | 162 | The constructor has no specific arguments, but accepts `*args` and `**kwargs`. You'll have to overwrite/override two methods in order to correctly mix the template content with the context variables. 163 | 164 | To retrieve the template file, you can overwrite/override the `get_template_file()` method: 165 | 166 | ```python 167 | TemplateHandler.get_template_file() 168 | ``` 169 | 170 | Alternatively, you may assign it a static `template_file` attribute, like this: 171 | 172 | ```python 173 | class MyTemplateHandler(TemplateHandler): 174 | template_file = "/path/to/template.txt" 175 | ``` 176 | 177 | The template file name doesn't require a specific file extension. By default, `TemplateHandler` instances will use the [`string.Template` module from the standard library](https://docs.python.org/3/library/string.html#string.Template) to render content. 178 | 179 | **Note**: we know that this "template engine" is a bit too minimalist for advanced purposes ; but as this project mantra is "no external dependencies". Still, this project is a Python project ; so you can plug your favorite template engine and serve dynamic content the way you want. 180 | 181 | Example template: 182 | 183 | ``` 184 | I am a template file. Refresh me to see what time it is: $datetime 185 | ``` 186 | 187 | To generate your context variable(s), you'll have to overwrite/override the `get_context()` method: 188 | 189 | ```python 190 | class DatetimeTemplateHandler(TemplateHandler): 191 | template_file = "/path/to/template.txt" 192 | 193 | def get_context(self, *args, **kwargs): 194 | return {"datetime": datetime.datetime.now()} 195 | ``` 196 | 197 | This `get_context()` method should return a dictionary. When accessed, the `$datetime` variable will be replaced by its value from the context dictionary. 198 | 199 | ### Responses 200 | 201 | Response classes are the direct links when it comes to returning content to the client. All responses are inheriting from the `gemeaux.responses.Response`. 202 | Reponses are blocks of text, returned as Python `bytes` to the client via the communication socket. Responses are composed of two main elements: 203 | 204 | * the `meta` block: It's a line containing the status code (a two-digit code) and an (optional) meta text, in which you'll return the mimetype of the content for "OK" responses, while for error responses, you may also send a human-readable explanation about this error. 205 | * the `body`: if you're returning a "OK" response, this block will be the contents of your content (page, file, etc). 206 | 207 | **Note:** If you check with the Gemini project specification, you may see that some response types are missing. They'll eventually be added in a further release. 208 | 209 | #### 10: InputResponse 210 | 211 | *Usage*: 212 | 213 | ```python 214 | InputResponse(prompt="What's your name?") 215 | ``` 216 | 217 | This response will prompt the user. When the user will answer the question, the client is supposed to send a new request, adding the answer to the prompt at the end of the originating URL. For example: 218 | 219 | * The client requests the 220 | * The server returns an `InputResponse` with the appropriate prompt. 221 | * The end-user may answer to the prompt. Let's say they enter "Forty-Two". 222 | * The client will then send a request to 223 | 224 | It's the integrator duty to proceed with the client answer, then. 225 | 226 | #### 11: SensitiveInputResponse 227 | 228 | *Usage*: 229 | 230 | ```python 231 | SensitiveInputResponse(prompt="What's your name?") 232 | ``` 233 | 234 | Same as for the `InputResponse`, except that your answer will be hidden on your client interface when you'll type it. 235 | 236 | #### 20: SuccessResponse 237 | 238 | *Usage*: 239 | 240 | ```python 241 | SuccessResponse() 242 | ``` 243 | 244 | You'll probably never use this response class directly, since it'll return no response body. It'll be your parent class for your custom responses, when the request is successful. See the Custom Responses below. 245 | 246 | #### 30: RedirectResponse 247 | 248 | *Usage*: 249 | 250 | ```python 251 | RedirectResponse(target="gemini://localhost/moon/") 252 | ``` 253 | 254 | This class will send a Redirect response, with `target` being the next URL. This default redirection is supposed to be temporary, for example if it follows an application workflow. 255 | 256 | #### 31: PermanentRedirectResponse 257 | 258 | *Usage*: 259 | 260 | ```python 261 | PermanentRedirectResponse(target="gemini://localhost/moon/base/") 262 | ``` 263 | 264 | Whether the redirection is permanent or temporary, clients will behave alike. But crawlers and search engine spiders will consider the permanent redirections differently, and should remember to crawl the new target and deprecate the previous URL. 265 | 266 | #### 50: PermanentFailureResponse 267 | 268 | *Usage*: 269 | 270 | ```python 271 | PermanentFailureResponse(reason="You forgot to say 'please'") 272 | ``` 273 | 274 | Your application has failed for a "good" reason and it'll always fail when your user requests this resource this way. The `reason` argument is optional. If omitted, the message will read `50 PERMANENT FAILURE`. 275 | 276 | #### 51: NotFoundResponse 277 | 278 | *Usage*: 279 | 280 | ```python 281 | NotFoundResponse(reason="These are not the droids you are looking for") 282 | ``` 283 | 284 | The requested resource is not found (its code is `51`, because you'll never find what's in the *Area 51*). The `reason` argument is optional. If omitted, the message will read `51 NOT FOUND`. 285 | 286 | #### 54: ProxyRequestRefusedResponse 287 | 288 | *Usage*: 289 | 290 | ```python 291 | ProxyRequestRefusedResponse() 292 | ``` 293 | 294 | This response is returned when the server is receiving a query not directly related to its host(name). 295 | 296 | ##### The proxy use case 297 | 298 | You're building a Gemini server called `moonbase`. It receives requests for local resources, but you're allowing your server to act as a proxy for the server named `lunarstation`. It can be another Gemini server *or* an HTTP(s) server, or Gopher, etc. So if you allow it, you can authorize incoming requests for `https://lunarstation/example/resource`, fetch this resource by yourself, transcribe it into a regular Gemini `Response` and return it to your client. 299 | 300 | Otherwise, if you don't allow it, simply return the `ProxyRequestRefusedResponse` as described above. 301 | 302 | **Note:** The proxy feature is not implemented yet in ``Gemeaux``, but it's planned for a future release. 303 | 304 | #### 59: BadRequestResponse 305 | 306 | *Usage*: 307 | 308 | ```python 309 | BadRequestResponse(reason="You've been very naughty, no cake for you") 310 | ``` 311 | 312 | Return this Bad Request response whenever the request doesn't fulfill the Gemini specs or is wrong in a way or another. The `reason` argument is optional. If omitted, the response will read: `59: BAD REQUEST`. 313 | 314 | ### Custom Response classes 315 | 316 | In order to ease development of Gemini websites / applications, *Gemeaux* is providing a few Response classes to return classic Gemini content. 317 | 318 | #### TextResponse 319 | 320 | The text response is composed of a `title` and a `body` content. It's one of the most direct way to return Gemini markup. You may use it to return dynamic content. 321 | 322 | Here is an example: 323 | 324 | ```python 325 | from random import randint 326 | from gemeaux import TextResponse 327 | response = TextResponse( 328 | title="Fancy a game?", 329 | body=f"Rolled: {randint(1, 6)}\r\nRefresh the page to make another roll." 330 | ) 331 | ``` 332 | 333 | The arguments `title` and `body` are both optional. But of course, returning an empty content can be puzzling for your users. 334 | 335 | The `title` will be rendered as `# Fancy a game?`. The rest of the content (the `body` variable) will be flushed to the user. Please note that all combinations of `\n` & `\r` will be converted into `\r\n`. 336 | 337 | #### DocumentResponse 338 | 339 | Another quick way to return Gemini content is write it down in a text file. You can then return your response to the client as if it was served by a static web server, except that it'll be a Gemini response. 340 | 341 | Example: 342 | 343 | ```python 344 | DocumentResponse( 345 | full_path="/var/gemini/content/file.gmi", 346 | root_dir="/var/gemini/content" 347 | ) 348 | ``` 349 | 350 | Please note that both `full_path` and `root_dir` arguments are **mandatory**. The `root_dir` argument should prevent your application to try to access a file that doesn't belong to the root directory of your static content. You wouldn't like your `/etc/passwd` file to be revealed using a `DocumentResponse` instance, would you? 351 | 352 | #### DirectoryListingResponse 353 | 354 | One may consider too annoying to make a homepage for a static directory yourself. The `DirectoryListingResponse` is providing you a way to display the list of the given directory. 355 | 356 | Example: 357 | 358 | ```python 359 | DirectoryListingResponse( 360 | full_path="/var/gemini/content/moon/base/", 361 | root_dir="/var/gemini/content" 362 | ) 363 | ``` 364 | 365 | **Note**: if the provided path is not a directory, or is not part of the `root_dir`path, a `FileNotFoundError` will be raised. 366 | 367 | #### TemplateResponse 368 | 369 | When you want your dynamic content to respect some sort of structure, you may want to leverage templates to avoid repeating yourself. 370 | 371 | The `TemplateResponse` class constructor has one mandatory argument: `template_file`, which is the path to the template file. Then there's a `context` kwargs, that will be transmitted to the template. 372 | 373 | A template file is a text file that respects the [String subsitution API described here](https://docs.python.org/3/library/string.html#template-strings). 374 | 375 | *Example template:* 376 | 377 | ``` 378 | Hello, $full_name! Welcome aboard. 379 | ``` 380 | 381 | Now let's imagine your `TemplateResponse` class is instantiated like this: 382 | 383 | ```python 384 | TemplateResponse("/path/to/hello.txt", full_name="Gus Grissom") 385 | ``` 386 | 387 | When returned to the client as a Response, This will be rendered as: 388 | 389 | ``` 390 | Hello, Gus Grissom! Welcome aboard. 391 | ``` 392 | 393 | You can pass as many context variables as you want, but here are some important notes: 394 | 395 | 1. For each template variable (like `$stuff`), you must give it a value. 396 | 2. Basic Python types will be properly rendered, but the stdlib `string.Template` has no advanced template features: no loops over a list of items, etc. *There are plans to make it easier to plug your favorite template engine in the future (in the meantime, you can try to make the mix of your templates and dynamic variables in your Handler class and return a `TextResponse` yourself).* 397 | 398 | ## Known bugs & limitations 399 | 400 | This project is mostly for education purposes, although it can possibly be used through a local network, serving Gemini content. There are important steps & bugs to fix before becoming a more solid alternative to other Gemini server software. 401 | 402 | * The internals of `Gemeaux` are being tested on Python3.9+, but not the mainloop mechanics. 403 | * The vast majority of Gemini Standard responses are not implemented. 404 | * The Response documentation is missing, along with docstrings. 405 | * Performances are probably very low, there might be room for optimisation. 406 | 407 | ---- 408 | 409 | ## What's in the name? 410 | 411 | *"Gémeaux"* is the French word for *"Gemini"*. And incidentally, I was born a Gemini. In French it's pronounced \\ʒe.mo\\. 412 | 413 | *Disclaimer*: I don't believe in astrology. 414 | 415 | ## Other projects 416 | 417 | * [Jetforce](https://github.com/michael-lazar/jetforce) is a Python-based Gemini server, using the Twisted framework. 418 | * [GeGoBi](https://tildegit.org/solderpunk/gegobi) uses a single Python file ; it's a dual-protocol server, for both Gopher & Gemini. 419 | 420 | ## License 421 | 422 | `Gemeaux` server is distributed as Free Software under the terms of the MIT License. See the contents of the `LICENSE` file for more details. 423 | --------------------------------------------------------------------------------