Debian Codegraph @

tests/nanonameserver.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 import contextlib
4 import enum
5 import errno
6 import functools
7 import logging
8 import logging.config
9 import socket
10 import ssl
11 import struct
12 import threading
13
14 import trio
15
16 import dns.asyncquery
17 import dns.inet
18 import dns.message
19 import dns.rcode
20 from tests.util import here
21
22 try:
23 import tests.doq
24
25 have_doq = True
26 except Exception:
27 have_doq = False
28
29 try:
30 import tests.doh
31
32 have_doh = True
33 except Exception as e:
34 have_doh = False
35
36
37 class ConnectionType(enum.IntEnum):
38 UDP = 1
39 TCP = 2
40 DOT = 3
41 DOH = 4
42 DOQ = 5
43 DOH3 = 6
44
45
46 async def read_exactly(stream, count):
47 """Read the specified number of bytes from stream. Keep trying until we
48 either get the desired amount, or we hit EOF.
49 """
50 s = b""
51 while count > 0:
52 n = await stream.receive_some(count)
53 if n == b"":
54 raise EOFError
55 count = count - len(n)
56 s = s + n
57 return s
58
59
60 class Request:
61 def __init__(self, message, wire, peer, local, connection_type):
62 self.message = message
63 self.wire = wire
64 self.peer = peer
65 self.local = local
66 self.connection_type = connection_type
67
68 @property
69 def question(self):
70 return self.message.question[0]
71
72 @property
73 def qname(self):
74 return self.question.name
75
76 @property
77 def qclass(self):
78 return self.question.rdclass
79
80 @property
81 def qtype(self):
82 return self.question.rdtype
83
84
85 class Server(threading.Thread):
86 """The nanoserver is a nameserver skeleton suitable for faking a DNS
87 server for various testing purposes. It executes with a trio run
88 loop in a dedicated thread, and is a context manager. Exiting the
89 context manager will ensure the server shuts down.
90
91 If a port is not specified, random ports will be chosen.
92
93 Applications should subclass the server and override the handle()
94 method to determine how the server responds to queries. The
95 default behavior is to refuse everything.
96
97 If use_thread is set to False in the constructor, then the
98 server's main() method can be used directly in a trio nursery,
99 allowing the server's cancellation to be managed in the Trio way.
100 In this case, no thread creation ever happens even though Server
101 is a subclass of thread, because the start() method is never
102 called.
103 """
104
105 def __init__(
106 self,
107 *,
108 address="127.0.0.1",
109 port=0,
110 dot_port=0,
111 doh_port=0,
112 protocols=tuple(p for p in ConnectionType),
113 use_thread=True,
114 origin=None,
115 keyring=None,
116 tls_chain=here("tls/public.crt"),
117 tls_key=here("tls/private.pem"),
118 ):
119 super().__init__()
120 self.address = address
121 self.port = port
122 self.dot_port = dot_port
123 self.doh_port = doh_port
124 self.protocols = set(protocols)
125 if not have_doq:
126 self.protocols.discard(ConnectionType.DOQ)
127 if not have_doh:
128 self.protocols.discard(ConnectionType.DOH)
129 self.protocols.discard(ConnectionType.DOH3)
130 self.use_thread = use_thread
131 self.origin = origin
132 self.keyring = keyring
133 self.left = None
134 self.right = None
135 self.sockets = {}
136 self.addresses = {}
137 self.tls_chain = tls_chain
138 self.tls_key = tls_key
139
140 def get_address(self, connection_type):
141 return self.addresses[connection_type]
142
143 # For backwards compatibility
144 @property
145 def udp_address(self):
146 return self.addresses[ConnectionType.UDP]
147
148 @property
149 def tcp_address(self):
150 return self.addresses[ConnectionType.TCP]
151
152 @property
153 def doq_address(self):
154 return self.addresses[ConnectionType.DOQ]
155
156 def caught(self, who, e):
157 print(who, "caught", type(e), e)
158
159 def open_sockets(self, port, udp_type, tcp_type):
160 want_udp = udp_type in self.protocols
161 want_tcp = tcp_type in self.protocols
162 udp = None
163 tcp = None
164 af = dns.inet.af_for_address(self.address)
165
166 if port != 0 or not (want_udp and want_tcp):
167 if want_udp:
168 udp = socket.socket(af, socket.SOCK_DGRAM, 0)
169 udp.bind((self.address, port))
170 self.sockets[udp_type] = udp
171 if want_tcp:
172 tcp = socket.create_server((self.address, port), family=af)
173 self.sockets[tcp_type] = tcp
174 return
175
176 open_udp_sockets = []
177 try:
178 while True:
179 udp = socket.socket(af, socket.SOCK_DGRAM, 0)
180 udp.bind((self.address, port))
181 try:
182 udp_port = udp.getsockname()[1]
183 tcp = socket.create_server((self.address, udp_port), family=af)
184 self.sockets[udp_type] = udp
185 self.sockets[tcp_type] = tcp
186 return
187 except OSError:
188 # We failed to open the corresponding TCP port. Keep the UDP socket
189 # open, try again, and hope we get a better port.
190 if len(open_udp_sockets) < 100:
191 open_udp_sockets.append(udp)
192 continue
193 # 100 tries to find a port is enough! Give up!
194 raise
195 finally:
196 for udp_socket in open_udp_sockets:
197 udp_socket.close()
198
199 def __enter__(self):
200 (self.left, self.right) = socket.socketpair()
201 # We're making the sockets now so they can be sent to by the
202 # caller immediately (i.e. no race with the listener starting
203 # in the thread).
204 self.open_sockets(self.port, ConnectionType.UDP, ConnectionType.TCP)
205 self.open_sockets(self.dot_port, ConnectionType.DOQ, ConnectionType.DOT)
206 self.open_sockets(self.doh_port, ConnectionType.DOH3, ConnectionType.DOH)
207 for proto, sock in self.sockets.items():
208 self.addresses[proto] = sock.getsockname()
209 if self.use_thread:
210 self.start()
211 return self
212
213 def __exit__(self, ex_ty, ex_va, ex_tr):
214 if self.left:
215 self.left.close()
216 if self.use_thread and self.is_alive():
217 self.join()
218 if self.right:
219 self.right.close()
220 for sock in self.sockets.values():
221 sock.close()
222
223 async def wait_for_input_or_eof(self):
224 #
225 # This trio task just waits for input on the right half of the
226 # socketpair (the left half is owned by the context manager
227 # returned by launch). As soon as something is read, or the
228 # socket returns EOF, EOFError is raised, causing a the
229 # nursery to cancel all other nursery tasks, in particular the
230 # listeners.
231 #
232 try:
233 with trio.socket.from_stdlib_socket(self.right) as sock:
234 self.right = None # we own cleanup
235 await sock.recv(1)
236 finally:
237 raise EOFError
238
239 def handle(self, request):
240 #
241 # Handle request 'request'. Override this method to change
242 # how the server behaves.
243 #
244 # The return value is either a dns.message.Message, a bytes,
245 # None, or a list of one of those. We allow a bytes to be
246 # returned for cases where handle wants to return an invalid
247 # DNS message for testing purposes. We allow None to be
248 # returned to indicate there is no response. If a list is
249 # returned, then the output code will run for each returned
250 # item.
251 #
252 r = dns.message.make_response(request.message)
253 r.set_rcode(dns.rcode.REFUSED)
254 return r
255
256 def maybe_listify(self, thing):
257 if isinstance(thing, list):
258 return thing
259 else:
260 return [thing]
261
262 def handle_wire(self, wire, peer, local, connection_type):
263 #
264 # This is the common code to parse wire format, call handle() on
265 # the message, and then generate response wire format (if handle()
266 # didn't do it).
267 #
268 # It also handles any exceptions from handle()
269 #
270 # Returns a (possibly empty) list of wire format message to send.
271 items = []
272 r = None
273 try:
274 q = dns.message.from_wire(wire, keyring=self.keyring)
275 except dns.message.ShortHeader:
276 # There is no hope of answering this one!
277 return
278 except Exception:
279 # Try to make a FORMERR using just the question section.
280 try:
281 q = dns.message.from_wire(wire, question_only=True)
282 r = dns.message.make_response(q)
283 r.set_rcode(dns.rcode.FORMERR)
284 items.append(r)
285 except Exception:
286 # We could try to make a response from only the header
287 # if dnspython had a header_only option to
288 # from_wire(), or if we truncated wire ourselves, but
289 # for now we just drop.
290 return
291 try:
292 # items might have been appended to above, so skip
293 # handle() if we already have a response.
294 if not items:
295 request = Request(q, wire, peer, local, connection_type)
296 items = self.maybe_listify(self.handle(request))
297 except Exception as e:
298 # Exceptions from handle get a SERVFAIL response, and a print because
299 # they are usually bugs in the the test!
300 self.caught("handle", e)
301 r = dns.message.make_response(q)
302 r.set_rcode(dns.rcode.SERVFAIL)
303 items = [r]
304
305 tsig_ctx = None
306 multi = len(items) > 1
307 for thing in items:
308 if isinstance(thing, dns.message.Message):
309 out = thing.to_wire(self.origin, multi=multi, tsig_ctx=tsig_ctx)
310 tsig_ctx = thing.tsig_ctx
311 yield out
312 elif thing is not None:
313 yield thing
314
315 async def serve_udp(self, connection_type):
316 with trio.socket.from_stdlib_socket(self.sockets[connection_type]) as sock:
317 self.sockets.pop(connection_type) # we own cleanup
318 local = self.addresses[connection_type]
319 while True:
320 try:
321 (wire, peer) = await sock.recvfrom(65535)
322 for wire in self.handle_wire(wire, peer, local, connection_type):
323 await sock.sendto(wire, peer)
324 except Exception as e:
325 self.caught("serve_udp", e)
326
327 async def serve_tcp(self, connection_type, stream):
328 try:
329 if connection_type == ConnectionType.DOT:
330 peer = stream.transport_stream.socket.getpeername()
331 local = stream.transport_stream.socket.getsockname()
332 else:
333 assert connection_type == ConnectionType.TCP
334 peer = stream.socket.getpeername()
335 local = stream.socket.getsockname()
336 while True:
337 ldata = await read_exactly(stream, 2)
338 (l,) = struct.unpack("!H", ldata)
339 wire = await read_exactly(stream, l)
340 for wire in self.handle_wire(wire, peer, local, connection_type):
341 l = len(wire)
342 stream_message = struct.pack("!H", l) + wire
343 await stream.send_all(stream_message)
344 except Exception as e:
345 self.caught("serve_tcp", e)
346
347 async def orchestrate_tcp(self, connection_type):
348 with trio.socket.from_stdlib_socket(self.sockets[connection_type]) as sock:
349 self.sockets.pop(connection_type) # we own cleanup
350 listener = trio.SocketListener(sock)
351 if connection_type == ConnectionType.DOT:
352 ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
353 ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
354 ssl_context.load_cert_chain(self.tls_chain, self.tls_key)
355 listener = trio.SSLListener(listener, ssl_context)
356 serve = functools.partial(self.serve_tcp, connection_type)
357 async with trio.open_nursery() as nursery:
358 serve = functools.partial(
359 trio.serve_listeners,
360 serve,
361 [listener],
362 handler_nursery=nursery,
363 )
364 nursery.start_soon(serve)
365
366 async def serve_doq(self, connection_type) -> None:
367 with trio.socket.from_stdlib_socket(self.sockets[connection_type]) as sock:
368 self.sockets.pop(connection_type) # we own cleanup
369 async with tests.doq.Listener(
370 self, sock, connection_type, self.tls_chain, self.tls_key
371 ) as listener:
372 try:
373 await listener.run()
374 except Exception as e:
375 self.caught("serve_doq", e)
376
377 async def serve_doh(self, connection_type) -> None:
378 server = tests.doh.make_server(
379 self,
380 self.sockets[connection_type],
381 connection_type,
382 self.tls_chain,
383 self.tls_key,
384 )
385 try:
386 await server()
387 except Exception as e:
388 self.caught("serve_doh", e)
389
390 async def main(self):
391 handlers = {
392 ConnectionType.UDP: self.serve_udp,
393 ConnectionType.TCP: self.orchestrate_tcp,
394 ConnectionType.DOT: self.orchestrate_tcp,
395 ConnectionType.DOH: self.serve_doh,
396 ConnectionType.DOH3: self.serve_doh,
397 ConnectionType.DOQ: self.serve_doq,
398 }
399
400 try:
401 async with trio.open_nursery() as nursery:
402 if self.use_thread:
403 nursery.start_soon(self.wait_for_input_or_eof)
404 for connection_type in self.protocols:
405 nursery.start_soon(handlers[connection_type], connection_type)
406
407 except Exception as e:
408 self.caught("nanoserver main", e)
409
410 def run(self):
411 if not self.use_thread:
412 raise RuntimeError("start() called on a use_thread=False Server")
413 trio.run(self.main)
414
415
416 if __name__ == "__main__":
417 import sys
418 import time
419
420 logger = logging.getLogger(__name__)
421 format = "%(asctime)s %(levelname)s: %(message)s"
422 logging.basicConfig(format=format, level=logging.INFO)
423 logging.config.dictConfig(
424 {
425 "version": 1,
426 "incremental": True,
427 "loggers": {
428 "quart.app": {
429 "level": "INFO",
430 },
431 "quart.serving": {
432 "propagate": False,
433 "level": "ERROR",
434 },
435 "quic": {
436 "level": "CRITICAL",
437 },
438 },
439 }
440 )
441
442 async def trio_main():
443 try:
444 with Server(
445 port=5354, dot_port=5355, doh_port=5356, use_thread=False
446 ) as server:
447 print("Trio mode")
448 for proto, address in server.addresses.items():
449 print(f" listening on {proto.name}: {address}")
450 async with trio.open_nursery() as nursery:
451 nursery.start_soon(server.main)
452 except Exception as e:
453 print("trio_main caught", type(e), e)
454
455 def threaded_main():
456 with Server(port=5354, dot_port=5355, doh_port=5356) as server:
457 print("Thread mode")
458 for proto, address in server.addresses.items():
459 print(f" listening on {proto.name}: {address}")
460 time.sleep(300)
461
462 if len(sys.argv) > 1 and sys.argv[1] == "trio":
463 trio.run(trio_main)
464 else:
465 threaded_main()