Debian Codegraph @

tests/doq.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 # Implement DNS-over-QUIC
4
5 import secrets
6 import struct
7 import time
8 from typing import Optional, Set, Tuple, Union
9
10 import aioquic
11 import aioquic.buffer
12 import aioquic.quic.configuration
13 import aioquic.quic.connection
14 import aioquic.quic.events
15 import aioquic.quic.logger
16 import aioquic.quic.packet
17 import aioquic.quic.retry
18 import trio
19
20 import dns.exception
21 from dns._asyncbackend import NullContext
22 from dns.quic._common import Buffer
23
24 MAX_SAVED_SESSIONS = 100
25
26
27 class Stream:
28 def __init__(self, connection, stream_id):
29 self.connection = connection
30 self.stream_id = stream_id
31 self.buffer = Buffer()
32 self.expecting = 0
33 self.wake_up = trio.Condition()
34 self.headers = None
35 self.trailers = None
36
37 async def wait_for(self, amount: int):
38 while True:
39 if self.buffer.have(amount):
40 return
41 self.expecting = amount
42 async with self.wake_up:
43 await self.wake_up.wait()
44 self.expecting = 0
45
46 async def receive(self, timeout: Optional[float] = None):
47 context: Union[trio.CancelScope, NullContext]
48 if timeout is None:
49 context = NullContext(None)
50 else:
51 context = trio.move_on_after(timeout)
52 with context:
53 await self.wait_for(2)
54 (size,) = struct.unpack("!H", self.buffer.get(2))
55 await self.wait_for(size)
56 return self.buffer.get(size)
57 raise dns.exception.Timeout
58
59 async def send(self, datagram: bytes, is_end=False):
60 l = len(datagram)
61 data = struct.pack("!H", l) + datagram
62 await self.connection.write(self.stream_id, data, is_end)
63
64 async def add_input(self, data: bytes, is_end: bool):
65 self.buffer.put(data, is_end)
66 # Note it is important that we wake up if we're ending!
67 if (self.expecting > 0 and self.buffer.have(self.expecting)) or is_end:
68 async with self.wake_up:
69 self.wake_up.notify()
70
71 def seen_end(self) -> bool:
72 return self.buffer.seen_end()
73
74 async def run(self):
75 try:
76 wire = await self.receive()
77 is_get = False
78 path: Optional[bytes]
79 for wire in self.connection.listener.server.handle_wire(
80 wire,
81 self.connection.peer,
82 self.connection.listener.socket.getsockname(),
83 self.connection.listener.connection_type,
84 ):
85 break
86 await self.send(wire, True)
87 except Exception:
88 if not self.seen_end():
89 self.connection.reset(self.stream_id)
90 finally:
91 self.connection.stream_done(self)
92
93
94 class Connection:
95 def __init__(self, listener, cid, peer, retry_cid=None):
96 self.original_cid: bytes = cid
97 self.listener = listener
98 self.cids: Set[bytes] = set()
99 self.cids.add(cid)
100 self.listener.connections[cid] = self
101 self.peer = peer
102 self.quic_connection = aioquic.quic.connection.QuicConnection(
103 configuration=listener.quic_config,
104 original_destination_connection_id=cid,
105 retry_source_connection_id=retry_cid,
106 session_ticket_fetcher=self.listener.pop_session_ticket,
107 session_ticket_handler=self.listener.store_session_ticket,
108 )
109 self.cids.add(self.quic_connection.host_cid)
110 self.listener.connections[self.quic_connection.host_cid] = self
111 self.send_channel: trio.MemorySendChannel
112 self.receive_channel: trio.MemoryReceiveChannel
113 self.send_channel, self.receive_channel = trio.open_memory_channel(100)
114 self.send_pending = False
115 self.done = False
116 self.worker_scope = None
117 self.streams = {}
118
119 def get_timer_values(self, now: float) -> Tuple[float, float]:
120 expiration = self.quic_connection.get_timer()
121 if expiration is None:
122 expiration = now + 3600 # arbitrary "big" value
123 interval = max(expiration - now, 0)
124 return (expiration, interval)
125
126 async def close_open_streams(self):
127 # We copy the list here as awaiting might let the dictionary change
128 # due to the stream finishing.
129 for stream in list(self.streams.values()):
130 if not stream.seen_end():
131 await stream.add_input(b"", True)
132
133 def create_stream(self, nursery: trio.Nursery, stream_id: int) -> Stream:
134 stream = Stream(self, stream_id)
135 self.streams[stream_id] = stream
136 nursery.start_soon(stream.run)
137 return stream
138
139 async def handle_events(self, nursery: trio.Nursery):
140 count = 0
141 while not self.done:
142 event = self.quic_connection.next_event()
143 if event is None:
144 return
145 if isinstance(event, aioquic.quic.events.StreamDataReceived):
146 stream = self.streams.get(event.stream_id)
147 if stream is None:
148 stream = self.create_stream(nursery, event.stream_id)
149 await stream.add_input(event.data, event.end_stream)
150 elif isinstance(event, aioquic.quic.events.ConnectionTerminated):
151 await self.close_open_streams()
152 self.done = True
153 elif isinstance(event, aioquic.quic.events.ConnectionIdIssued):
154 cid = event.connection_id
155 if cid not in self.cids:
156 self.cids.add(cid)
157 self.listener.connections[cid] = self
158 else:
159 self.done = True
160 elif isinstance(event, aioquic.quic.events.ConnectionIdRetired):
161 cid = event.connection_id
162 if cid in self.cids:
163 # These should not fail but we eat them just in case so we
164 # don't crash the whole connection.
165 self.cids.remove(cid)
166 del self.listener.connections[cid]
167 else:
168 self.done = True
169 count += 1
170 if count > 10:
171 # yield
172 count = 0
173 await trio.sleep(0)
174
175 async def run(self):
176 try:
177 async with trio.open_nursery() as nursery:
178 while not self.done:
179 now = time.time()
180 (expiration, interval) = self.get_timer_values(now)
181 # Note it must be trio.current_time() and not now due to how
182 # trio time works!
183 if self.send_pending:
184 interval = 0
185 self.send_pending = False
186 with trio.CancelScope(
187 deadline=trio.current_time() + interval
188 ) as self.worker_scope:
189 (datagram, peer) = await self.receive_channel.receive()
190 self.quic_connection.receive_datagram(datagram, peer, now)
191 self.worker_scope = None
192 now = time.time()
193 if expiration <= now:
194 self.quic_connection.handle_timer(now)
195 await self.handle_events(nursery)
196 datagrams = self.quic_connection.datagrams_to_send(now)
197 for datagram, _ in datagrams:
198 await self.listener.socket.sendto(datagram, self.peer)
199 finally:
200 await self.close_open_streams()
201 for cid in self.cids:
202 try:
203 del self.listener.connections[cid]
204 except KeyError:
205 pass
206
207 def maybe_wake_up(self):
208 self.send_pending = True
209 if self.worker_scope is not None:
210 self.worker_scope.cancel()
211
212 async def write(self, stream: int, data: bytes, is_end=False):
213 if not self.done:
214 self.quic_connection.send_stream_data(stream, data, is_end)
215 self.maybe_wake_up()
216
217 def reset(self, stream: int, error=0):
218 if not self.done:
219 self.quic_connection.reset_stream(stream, error)
220 self.maybe_wake_up()
221
222 def stream_done(self, stream: Stream):
223 try:
224 del self.streams[stream.stream_id]
225 except KeyError:
226 pass
227
228
229 class Listener:
230 def __init__(
231 self,
232 server,
233 socket,
234 connection_type,
235 tls_chain,
236 tls_key,
237 quic_log_directory=None,
238 quic_retry=False,
239 ):
240 self.server = server
241 self.socket = socket # note this is a trio socket
242 self.connection_type = connection_type
243 self.connections = {}
244 self.session_tickets = {}
245 self.done = False
246 alpn_protocols = ["doq"]
247 self.quic_config = aioquic.quic.configuration.QuicConfiguration(
248 is_client=False, alpn_protocols=alpn_protocols
249 )
250 if quic_log_directory is not None:
251 self.quic_config.quic_logger = aioquic.quic.logger.QuicFileLogger(
252 quic_log_directory
253 )
254 self.quic_config.load_cert_chain(tls_chain, tls_key)
255 self.retry: Optional[aioquic.quic.retry.QuicRetryTokenHandler]
256 if quic_retry:
257 self.retry = aioquic.quic.retry.QuicRetryTokenHandler()
258 else:
259 self.retry = None
260
261 def pop_session_ticket(self, key):
262 try:
263 return self.session_tickets.pop(key)
264 except KeyError:
265 return None
266
267 def store_session_ticket(self, session_ticket):
268 self.session_tickets[session_ticket.ticket] = session_ticket
269 while len(self.session_tickets) > MAX_SAVED_SESSIONS:
270 # Grab the first key
271 key = next(iter(self.session_tickets.keys()))
272 del self.session_tickets[key]
273
274 async def run(self):
275 async with trio.open_nursery() as nursery:
276 while True:
277 data = None
278 peer = None
279 try:
280 (data, peer) = await self.socket.recvfrom(65535)
281 except Exception:
282 continue
283 buffer = aioquic.buffer.Buffer(data=data)
284 try:
285 header = aioquic.quic.packet.pull_quic_header(
286 buffer, self.quic_config.connection_id_length
287 )
288 except Exception:
289 continue
290 cid = header.destination_cid
291 connection = self.connections.get(cid)
292 if (
293 connection is None
294 and header.version is not None
295 and len(data) >= 1200
296 and header.version not in self.quic_config.supported_versions
297 ):
298 wire = aioquic.quic.packet.encode_quic_version_negotiation(
299 source_cid=cid,
300 destination_cid=header.source_cid,
301 supported_versions=self.quic_config.supported_versions,
302 )
303 await self.socket.sendto(wire, peer)
304 continue
305
306 if (
307 connection is None
308 and len(data) >= 1200
309 and header.packet_type == aioquic.quic.packet.PACKET_TYPE_INITIAL
310 ):
311 retry_cid = None
312 if self.retry is not None:
313 if not header.token:
314 if header.version is None:
315 continue
316 source_cid = secrets.token_bytes(8)
317 wire = aioquic.quic.packet.encode_quic_retry(
318 version=header.version,
319 source_cid=source_cid,
320 destination_cid=header.source_cid,
321 original_destination_cid=header.destination_cid,
322 retry_token=self.retry.create_token(
323 peer, header.destination_cid, source_cid
324 ),
325 )
326 await self.socket.sendto(wire, peer)
327 continue
328 else:
329 try:
330 (cid, retry_cid) = self.retry.validate_token(
331 peer, header.token
332 )
333 # We need to recheck the cid here in case of duplicates,
334 # as we don't want to kick off another connection!
335 connection = self.connections.get(cid)
336 if connection is not None:
337 # duplicate!
338 continue
339 except ValueError:
340 continue
341
342 connection = Connection(self, cid, peer, retry_cid)
343 nursery.start_soon(connection.run)
344
345 if connection is not None:
346 try:
347 connection.send_channel.send_nowait((data, peer))
348 except trio.WouldBlock:
349 pass
350
351 # Listeners are async context managers
352
353 async def __aenter__(self):
354 return self
355
356 async def __aexit__(self, exc_type, exc_val, exc_tb):
357 return False