| 1 |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license |
| 2 |
|
| 3 |
import base64 |
| 4 |
import functools |
| 5 |
import socket |
| 6 |
|
| 7 |
import hypercorn.config |
| 8 |
import hypercorn.trio |
| 9 |
import quart |
| 10 |
import quart_trio |
| 11 |
|
| 12 |
|
| 13 |
def setup(server, connection_type): |
| 14 |
name = f"{__name__}-{connection_type.name}" |
| 15 |
app = quart_trio.QuartTrio(name) |
| 16 |
app.logger.handlers = [] |
| 17 |
|
| 18 |
@app.route("/dns-query", methods=["GET", "POST"]) |
| 19 |
async def dns_query(): |
| 20 |
if quart.request.method == "POST": |
| 21 |
wire = await quart.request.body |
| 22 |
else: |
| 23 |
encoded = quart.request.args["dns"] |
| 24 |
remainder = len(encoded) % 4 |
| 25 |
if remainder != 0: |
| 26 |
encoded += "=" * (4 - remainder) |
| 27 |
wire = base64.urlsafe_b64decode(encoded) |
| 28 |
for body in server.handle_wire( |
| 29 |
wire, |
| 30 |
quart.request.remote_addr, |
| 31 |
quart.request.server, |
| 32 |
connection_type, |
| 33 |
): |
| 34 |
if body is not None: |
| 35 |
return quart.Response(body, mimetype="application/dns-message") |
| 36 |
else: |
| 37 |
return quart.Response(status=500) |
| 38 |
|
| 39 |
return app |
| 40 |
|
| 41 |
|
| 42 |
def make_server(server, sock, connection_type, tls_chain, tls_key): |
| 43 |
doh_app = setup(server, connection_type) |
| 44 |
hconfig = hypercorn.config.Config() |
| 45 |
fd = sock.fileno() |
| 46 |
if sock.type == socket.SOCK_STREAM: |
| 47 |
# We put http/1.1 in the ALPN as we don't mind, but DoH is |
| 48 |
# supposed to be H2 officially. |
| 49 |
hconfig.alpn_protocols = ["h2", "http/1.1"] |
| 50 |
hconfig.bind = [f"fd://{fd}"] |
| 51 |
hconfig.quic_bind = [] |
| 52 |
else: |
| 53 |
hconfig.alpn_protocols = ["h3"] |
| 54 |
# We should be able to pass bind=[], but that triggers a bug in |
| 55 |
# hypercorn. So, create a dummy socket and bind to it. |
| 56 |
tmp_sock = socket.create_server(("127.0.0.1", 0)) |
| 57 |
hconfig.bind = [f"fd://{tmp_sock.fileno()}"] |
| 58 |
tmp_sock.detach() |
| 59 |
hconfig.quic_bind = [f"fd://{fd}"] |
| 60 |
sock.detach() |
| 61 |
hconfig.certfile = tls_chain |
| 62 |
hconfig.keyfile = tls_key |
| 63 |
hconfig.accesslog = None |
| 64 |
hconfig.errorlog = None |
| 65 |
return functools.partial(hypercorn.trio.serve, doh_app, hconfig) |