codekingpro/portable-devtools
114k
1# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license2 3import selectors4import socket5import ssl6import struct7import threading8import time9 10import aioquic.quic.configuration # type: ignore11import aioquic.quic.connection # type: ignore12import aioquic.quic.events # type: ignore13 14import dns.exception15import dns.inet16from dns.quic._common import (17 QUIC_MAX_DATAGRAM,18 BaseQuicConnection,19 BaseQuicManager,20 BaseQuicStream,21 UnexpectedEOF,22)23 24# Avoid circularity with dns.query25if hasattr(selectors, "PollSelector"):26 _selector_class = selectors.PollSelector # type: ignore27else:28 _selector_class = selectors.SelectSelector # type: ignore29 30 31class SyncQuicStream(BaseQuicStream):32 def __init__(self, connection, stream_id):33 super().__init__(connection, stream_id)34 self._wake_up = threading.Condition()35 self._lock = threading.Lock()36 37 def wait_for(self, amount, expiration):38 while True:39 timeout = self._timeout_from_expiration(expiration)40 with self._lock:41 if self._buffer.have(amount):42 return43 self._expecting = amount44 with self._wake_up:45 if not self._wake_up.wait(timeout):46 raise dns.exception.Timeout47 self._expecting = 048 49 def receive(self, timeout=None):50 expiration = self._expiration_from_timeout(timeout)51 self.wait_for(2, expiration)52 with self._lock:53 (size,) = struct.unpack("!H", self._buffer.get(2))54 self.wait_for(size, expiration)55 with self._lock:56 return self._buffer.get(size)57 58 def send(self, datagram, is_end=False):59 data = self._encapsulate(datagram)60 self._connection.write(self._stream_id, data, is_end)61 62 def _add_input(self, data, is_end):63 if self._common_add_input(data, is_end):64 with self._wake_up:65 self._wake_up.notify()66 67 def close(self):68 with self._lock:69 self._close()70 71 def __enter__(self):72 return self73 74 def __exit__(self, exc_type, exc_val, exc_tb):75 self.close()76 with self._wake_up:77 self._wake_up.notify()78 return False79 80 81class SyncQuicConnection(BaseQuicConnection):82 def __init__(self, connection, address, port, source, source_port, manager):83 super().__init__(connection, address, port, source, source_port, manager)84 self._socket = socket.socket(self._af, socket.SOCK_DGRAM, 0)85 if self._source is not None:86 try:87 self._socket.bind(88 dns.inet.low_level_address_tuple(self._source, self._af)89 )90 except Exception:91 self._socket.close()92 raise93 self._socket.connect(self._peer)94 (self._send_wakeup, self._receive_wakeup) = socket.socketpair()95 self._receive_wakeup.setblocking(False)96 self._socket.setblocking(False)97 self._handshake_complete = threading.Event()98 self._worker_thread = None99 self._lock = threading.Lock()100 101 def _read(self):102 count = 0103 while count < 10:104 count += 1105 try:106 datagram = self._socket.recv(QUIC_MAX_DATAGRAM)107 except BlockingIOError:108 return109 with self._lock:110 self._connection.receive_datagram(datagram, self._peer, time.time())111 112 def _drain_wakeup(self):113 while True:114 try:115 self._receive_wakeup.recv(32)116 except BlockingIOError:117 return118 119 def _worker(self):120 try:121 sel = _selector_class()122 sel.register(self._socket, selectors.EVENT_READ, self._read)123 sel.register(self._receive_wakeup, selectors.EVENT_READ, self._drain_wakeup)124 while not self._done:125 (expiration, interval) = self._get_timer_values(False)126 items = sel.select(interval)127 for key, _ in items:128 key.data()129 with self._lock:130 self._handle_timer(expiration)131 self._handle_events()132 with self._lock:133 datagrams = self._connection.datagrams_to_send(time.time())134 for datagram, _ in datagrams:135 try:136 self._socket.send(datagram)137 except BlockingIOError:138 # we let QUIC handle any lossage139 pass140 finally:141 with self._lock:142 self._done = True143 # Ensure anyone waiting for this gets woken up.144 self._handshake_complete.set()145 146 def _handle_events(self):147 while True:148 with self._lock:149 event = self._connection.next_event()150 if event is None:151 return152 if isinstance(event, aioquic.quic.events.StreamDataReceived):153 with self._lock:154 stream = self._streams.get(event.stream_id)155 if stream:156 stream._add_input(event.data, event.end_stream)157 elif isinstance(event, aioquic.quic.events.HandshakeCompleted):158 self._handshake_complete.set()159 elif isinstance(event, aioquic.quic.events.ConnectionTerminated):160 with self._lock:161 self._done = True162 elif isinstance(event, aioquic.quic.events.StreamReset):163 with self._lock:164 stream = self._streams.get(event.stream_id)165 if stream:166 stream._add_input(b"", True)167 168 def write(self, stream, data, is_end=False):169 with self._lock:170 self._connection.send_stream_data(stream, data, is_end)171 self._send_wakeup.send(b"\x01")172 173 def run(self):174 if self._closed:175 return176 self._worker_thread = threading.Thread(target=self._worker)177 self._worker_thread.start()178 179 def make_stream(self, timeout=None):180 if not self._handshake_complete.wait(timeout):181 raise dns.exception.Timeout182 with self._lock:183 if self._done:184 raise UnexpectedEOF185 stream_id = self._connection.get_next_available_stream_id(False)186 stream = SyncQuicStream(self, stream_id)187 self._streams[stream_id] = stream188 return stream189 190 def close_stream(self, stream_id):191 with self._lock:192 super().close_stream(stream_id)193 194 def close(self):195 with self._lock:196 if self._closed:197 return198 self._manager.closed(self._peer[0], self._peer[1])199 self._closed = True200 self._connection.close()201 self._send_wakeup.send(b"\x01")202 self._worker_thread.join()203 204 205class SyncQuicManager(BaseQuicManager):206 def __init__(self, conf=None, verify_mode=ssl.CERT_REQUIRED, server_name=None):207 super().__init__(conf, verify_mode, SyncQuicConnection, server_name)208 self._lock = threading.Lock()209 210 def connect(211 self, address, port=853, source=None, source_port=0, want_session_ticket=True212 ):213 with self._lock:214 (connection, start) = self._connect(215 address, port, source, source_port, want_session_ticket216 )217 if start:218 connection.run()219 return connection220 221 def closed(self, address, port):222 with self._lock:223 super().closed(address, port)224 225 def save_session_ticket(self, address, port, ticket):226 with self._lock:227 super().save_session_ticket(address, port, ticket)228 229 def __enter__(self):230 return self231 232 def __exit__(self, exc_type, exc_val, exc_tb):233 # Copy the iterator into a list as exiting things will mutate the connections234 # table.235 connections = list(self._connections.values())236 for connection in connections:237 connection.close()238 return False239 