Debian Codegraph @

dns/quic/_trio.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 import socket
4 import ssl
5 import struct
6 import time
7
8 import aioquic.h3.connection # type: ignore
9 import aioquic.h3.events # type: ignore
10 import aioquic.quic.configuration # type: ignore
11 import aioquic.quic.connection # type: ignore
12 import aioquic.quic.events # type: ignore
13 import trio
14
15 import dns.exception
16 import dns.inet
17 from dns._asyncbackend import NullContext
18 from dns.quic._common import (
19 QUIC_MAX_DATAGRAM,
20 AsyncQuicConnection,
21 AsyncQuicManager,
22 BaseQuicStream,
23 UnexpectedEOF,
24 )
25
26
27 class TrioQuicStream(BaseQuicStream):
28 def __init__(self, connection, stream_id):
29 super().__init__(connection, stream_id)
30 self._wake_up = trio.Condition()
31
32 async def wait_for(self, amount):
33 while True:
34 if self._buffer.have(amount):
35 return
36 self._expecting = amount
37 async with self._wake_up:
38 await self._wake_up.wait()
39 self._expecting = 0
40
41 async def wait_for_end(self):
42 while True:
43 if self._buffer.seen_end():
44 return
45 async with self._wake_up:
46 await self._wake_up.wait()
47
48 async def receive(self, timeout=None):
49 if timeout is None:
50 context = NullContext(None)
51 else:
52 context = trio.move_on_after(timeout)
53 with context:
54 if self._connection.is_h3():
55 await self.wait_for_end()
56 return self._buffer.get_all()
57 else:
58 await self.wait_for(2)
59 (size,) = struct.unpack("!H", self._buffer.get(2))
60 await self.wait_for(size)
61 return self._buffer.get(size)
62 raise dns.exception.Timeout
63
64 async def send(self, datagram, is_end=False):
65 data = self._encapsulate(datagram)
66 await self._connection.write(self._stream_id, data, is_end)
67
68 async def _add_input(self, data, is_end):
69 if self._common_add_input(data, is_end):
70 async with self._wake_up:
71 self._wake_up.notify()
72
73 async def close(self):
74 self._close()
75
76 # Streams are async context managers
77
78 async def __aenter__(self):
79 return self
80
81 async def __aexit__(self, exc_type, exc_val, exc_tb):
82 await self.close()
83 async with self._wake_up:
84 self._wake_up.notify()
85 return False
86
87
88 class TrioQuicConnection(AsyncQuicConnection):
89 def __init__(self, connection, address, port, source, source_port, manager=None):
90 super().__init__(connection, address, port, source, source_port, manager)
91 self._socket = trio.socket.socket(self._af, socket.SOCK_DGRAM, 0)
92 self._handshake_complete = trio.Event()
93 self._run_done = trio.Event()
94 self._worker_scope = None
95 self._send_pending = False
96
97 async def _worker(self):
98 try:
99 if self._source:
100 await self._socket.bind(
101 dns.inet.low_level_address_tuple(self._source, self._af)
102 )
103 await self._socket.connect(self._peer)
104 while not self._done:
105 (expiration, interval) = self._get_timer_values(False)
106 if self._send_pending:
107 # Do not block forever if sends are pending. Even though we
108 # have a wake-up mechanism if we've already started the blocking
109 # read, the possibility of context switching in send means that
110 # more writes can happen while we have no wake up context, so
111 # we need self._send_pending to avoid (effectively) a "lost wakeup"
112 # race.
113 interval = 0.0
114 with trio.CancelScope(
115 deadline=trio.current_time() + interval # pyright: ignore
116 ) as self._worker_scope:
117 datagram = await self._socket.recv(QUIC_MAX_DATAGRAM)
118 self._connection.receive_datagram(datagram, self._peer, time.time())
119 self._worker_scope = None
120 self._handle_timer(expiration)
121 await self._handle_events()
122 # We clear this now, before sending anything, as sending can cause
123 # context switches that do more sends. We want to know if that
124 # happens so we don't block a long time on the recv() above.
125 self._send_pending = False
126 datagrams = self._connection.datagrams_to_send(time.time())
127 for datagram, _ in datagrams:
128 await self._socket.send(datagram)
129 finally:
130 self._done = True
131 self._socket.close()
132 self._handshake_complete.set()
133
134 async def _handle_events(self):
135 count = 0
136 while True:
137 event = self._connection.next_event()
138 if event is None:
139 return
140 if isinstance(event, aioquic.quic.events.StreamDataReceived):
141 if self.is_h3():
142 assert self._h3_conn is not None
143 h3_events = self._h3_conn.handle_event(event)
144 for h3_event in h3_events:
145 if isinstance(h3_event, aioquic.h3.events.HeadersReceived):
146 stream = self._streams.get(event.stream_id)
147 if stream:
148 if stream._headers is None:
149 stream._headers = h3_event.headers
150 elif stream._trailers is None:
151 stream._trailers = h3_event.headers
152 if h3_event.stream_ended:
153 await stream._add_input(b"", True)
154 elif isinstance(h3_event, aioquic.h3.events.DataReceived):
155 stream = self._streams.get(event.stream_id)
156 if stream:
157 await stream._add_input(
158 h3_event.data, h3_event.stream_ended
159 )
160 else:
161 stream = self._streams.get(event.stream_id)
162 if stream:
163 await stream._add_input(event.data, event.end_stream)
164 elif isinstance(event, aioquic.quic.events.HandshakeCompleted):
165 self._handshake_complete.set()
166 elif isinstance(event, aioquic.quic.events.ConnectionTerminated):
167 self._done = True
168 self._socket.close()
169 elif isinstance(event, aioquic.quic.events.StreamReset):
170 stream = self._streams.get(event.stream_id)
171 if stream:
172 await stream._add_input(b"", True)
173 count += 1
174 if count > 10:
175 # yield
176 count = 0
177 await trio.sleep(0)
178
179 async def write(self, stream, data, is_end=False):
180 self._connection.send_stream_data(stream, data, is_end)
181 self._send_pending = True
182 if self._worker_scope is not None:
183 self._worker_scope.cancel()
184
185 async def run(self):
186 if self._closed:
187 return
188 async with trio.open_nursery() as nursery:
189 nursery.start_soon(self._worker)
190 self._run_done.set()
191
192 async def make_stream(self, timeout=None):
193 if timeout is None:
194 context = NullContext(None)
195 else:
196 context = trio.move_on_after(timeout)
197 with context:
198 await self._handshake_complete.wait()
199 if self._done:
200 raise UnexpectedEOF
201 stream_id = self._connection.get_next_available_stream_id(False)
202 stream = TrioQuicStream(self, stream_id)
203 self._streams[stream_id] = stream
204 return stream
205 raise dns.exception.Timeout
206
207 async def close(self):
208 if not self._closed:
209 if self._manager is not None:
210 self._manager.closed(self._peer[0], self._peer[1])
211 self._closed = True
212 self._connection.close()
213 self._send_pending = True
214 if self._worker_scope is not None:
215 self._worker_scope.cancel()
216 await self._run_done.wait()
217
218
219 class TrioQuicManager(AsyncQuicManager):
220 def __init__(
221 self,
222 nursery,
223 conf=None,
224 verify_mode=ssl.CERT_REQUIRED,
225 server_name=None,
226 h3=False,
227 ):
228 super().__init__(conf, verify_mode, TrioQuicConnection, server_name, h3)
229 self._nursery = nursery
230
231 def connect(
232 self, address, port=853, source=None, source_port=0, want_session_ticket=True
233 ):
234 (connection, start) = self._connect(
235 address, port, source, source_port, want_session_ticket
236 )
237 if start:
238 self._nursery.start_soon(connection.run)
239 return connection
240
241 async def __aenter__(self):
242 return self
243
244 async def __aexit__(self, exc_type, exc_val, exc_tb):
245 # Copy the iterator into a list as exiting things will mutate the connections
246 # table.
247 connections = list(self._connections.values())
248 for connection in connections:
249 await connection.close()
250 return False