Debian Codegraph @

src/trio/testing/_fake_net.py

raw
1 # This should eventually be cleaned up and become public, but for right now I'm just
2 # implementing enough to test DTLS.
3
4 # TODO:
5 # - user-defined routers
6 # - TCP
7 # - UDP broadcast
8
9 from __future__ import annotations
10
11 import contextlib
12 import errno
13 import ipaddress
14 import os
15 import socket
16 import sys
17 from typing import TYPE_CHECKING, Any, NoReturn, TypeAlias, overload
18
19 import attrs
20
21 import trio
22 from trio._util import NoPublicConstructor, final
23
24 if TYPE_CHECKING:
25 import builtins
26 from collections.abc import Iterable
27 from socket import AddressFamily, SocketKind
28 from types import TracebackType
29
30 from typing_extensions import Buffer, Self
31
32 from trio._socket import AddressFormat
33
34 IPAddress: TypeAlias = ipaddress.IPv4Address | ipaddress.IPv6Address
35
36
37 def _family_for(ip: IPAddress) -> int:
38 if isinstance(ip, ipaddress.IPv4Address):
39 return trio.socket.AF_INET
40 elif isinstance(ip, ipaddress.IPv6Address):
41 return trio.socket.AF_INET6
42 raise NotImplementedError("Unhandled IPAddress instance type") # pragma: no cover
43
44
45 def _wildcard_ip_for(family: int) -> IPAddress:
46 if family == trio.socket.AF_INET:
47 return ipaddress.ip_address("0.0.0.0")
48 elif family == trio.socket.AF_INET6:
49 return ipaddress.ip_address("::")
50 raise NotImplementedError("Unhandled ip address family") # pragma: no cover
51
52
53 # not used anywhere
54 def _localhost_ip_for(family: int) -> IPAddress: # pragma: no cover
55 if family == trio.socket.AF_INET:
56 return ipaddress.ip_address("127.0.0.1")
57 elif family == trio.socket.AF_INET6:
58 return ipaddress.ip_address("::1")
59 raise NotImplementedError("Unhandled ip address family")
60
61
62 def _fake_err(code: int) -> NoReturn:
63 raise OSError(code, os.strerror(code))
64
65
66 def _scatter(data: bytes, buffers: Iterable[Buffer]) -> int:
67 written = 0
68 for buf in buffers: # pragma: no branch
69 next_piece = data[written : written + memoryview(buf).nbytes]
70 with memoryview(buf) as mbuf:
71 mbuf[: len(next_piece)] = next_piece
72 written += len(next_piece)
73 if written == len(data): # pragma: no branch
74 break
75 return written
76
77
78 @attrs.frozen
79 class UDPEndpoint:
80 ip: IPAddress
81 port: int
82
83 def as_python_sockaddr(self) -> tuple[str, int] | tuple[str, int, int, int]:
84 sockaddr: tuple[str, int] | tuple[str, int, int, int] = (
85 self.ip.compressed,
86 self.port,
87 )
88 if isinstance(self.ip, ipaddress.IPv6Address):
89 sockaddr += (0, 0) # type: ignore[assignment]
90 return sockaddr
91
92 @classmethod
93 def from_python_sockaddr(
94 cls,
95 sockaddr: tuple[str, int] | tuple[str, int, int, int],
96 ) -> UDPEndpoint:
97 ip, port = sockaddr[:2]
98 return cls(ip=ipaddress.ip_address(ip), port=port)
99
100
101 @attrs.frozen
102 class UDPBinding:
103 local: UDPEndpoint
104 # remote: UDPEndpoint # ??
105
106
107 @attrs.frozen
108 class UDPPacket:
109 source: UDPEndpoint
110 destination: UDPEndpoint
111 payload: bytes = attrs.field(repr=lambda p: p.hex())
112
113 # not used/tested anywhere
114 def reply(self, payload: bytes) -> UDPPacket: # pragma: no cover
115 return UDPPacket(
116 source=self.destination,
117 destination=self.source,
118 payload=payload,
119 )
120
121
122 @attrs.frozen
123 class FakeSocketFactory(trio.abc.SocketFactory):
124 fake_net: FakeNet
125
126 def socket(self, family: int, type_: int, proto: int) -> FakeSocket: # type: ignore[override]
127 return FakeSocket._create(self.fake_net, family, type_, proto)
128
129
130 @attrs.frozen
131 class FakeHostnameResolver(trio.abc.HostnameResolver):
132 fake_net: FakeNet
133
134 async def getaddrinfo(
135 self,
136 host: bytes | None,
137 port: bytes | str | int | None,
138 family: int = 0,
139 type: int = 0,
140 proto: int = 0,
141 flags: int = 0,
142 ) -> list[
143 tuple[
144 AddressFamily,
145 SocketKind,
146 int,
147 str,
148 tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes],
149 ]
150 ]:
151 raise NotImplementedError("FakeNet doesn't do fake DNS yet")
152
153 async def getnameinfo(
154 self,
155 sockaddr: tuple[str, int] | tuple[str, int, int, int],
156 flags: int,
157 ) -> tuple[str, str]:
158 raise NotImplementedError("FakeNet doesn't do fake DNS yet")
159
160
161 @final
162 class FakeNet:
163 def __init__(self) -> None:
164 # When we need to pick an arbitrary unique ip address/port, use these:
165 self._auto_ipv4_iter = ipaddress.IPv4Network("1.0.0.0/8").hosts() # untested
166 self._auto_ipv6_iter = ipaddress.IPv6Network("1::/16").hosts() # untested
167 self._auto_port_iter = iter(range(50000, 65535))
168
169 self._bound: dict[UDPBinding, FakeSocket] = {}
170
171 self.route_packet = None
172
173 def _bind(self, binding: UDPBinding, socket: FakeSocket) -> None:
174 if binding in self._bound:
175 _fake_err(errno.EADDRINUSE)
176 self._bound[binding] = socket
177
178 def enable(self) -> None:
179 trio.socket.set_custom_socket_factory(FakeSocketFactory(self))
180 trio.socket.set_custom_hostname_resolver(FakeHostnameResolver(self))
181
182 def send_packet(self, packet: UDPPacket) -> None:
183 if self.route_packet is None:
184 self.deliver_packet(packet)
185 else:
186 self.route_packet(packet)
187
188 def deliver_packet(self, packet: UDPPacket) -> None:
189 binding = UDPBinding(local=packet.destination)
190 if binding in self._bound:
191 self._bound[binding]._deliver_packet(packet)
192 else:
193 # No valid destination, so drop it
194 pass
195
196
197 @final
198 class FakeSocket(trio.socket.SocketType, metaclass=NoPublicConstructor):
199 def __init__(
200 self,
201 fake_net: FakeNet,
202 family: AddressFamily,
203 type: SocketKind,
204 proto: int,
205 ) -> None:
206 self._fake_net = fake_net
207
208 if not family: # pragma: no cover
209 family = trio.socket.AF_INET
210 if not type: # pragma: no cover
211 type = trio.socket.SOCK_STREAM # noqa: A001 # name shadowing builtin
212
213 if family not in (trio.socket.AF_INET, trio.socket.AF_INET6):
214 raise NotImplementedError(f"FakeNet doesn't (yet) support family={family}")
215 if type != trio.socket.SOCK_DGRAM:
216 raise NotImplementedError(f"FakeNet doesn't (yet) support type={type}")
217
218 self._family = family
219 self._type = type
220 self._proto = proto
221
222 self._closed = False
223
224 self._packet_sender, self._packet_receiver = trio.open_memory_channel[
225 UDPPacket
226 ](float("inf"))
227
228 # This is the source-of-truth for what port etc. this socket is bound to
229 self._binding: UDPBinding | None = None
230
231 @property
232 def type(self) -> SocketKind:
233 return self._type
234
235 @property
236 def family(self) -> AddressFamily:
237 return self._family
238
239 @property
240 def proto(self) -> int:
241 return self._proto
242
243 def _check_closed(self) -> None:
244 if self._closed:
245 _fake_err(errno.EBADF)
246
247 def close(self) -> None:
248 if self._closed:
249 return
250 self._closed = True
251 if self._binding is not None:
252 del self._fake_net._bound[self._binding]
253 self._packet_receiver.close()
254
255 async def _resolve_address_nocp(
256 self,
257 address: object,
258 *,
259 local: bool,
260 ) -> tuple[str, int]:
261 return await trio._socket._resolve_address_nocp( # type: ignore[no-any-return]
262 self.type,
263 self.family,
264 self.proto,
265 address=address,
266 ipv6_v6only=False,
267 local=local,
268 )
269
270 def _deliver_packet(self, packet: UDPPacket) -> None:
271 # sending to a closed socket -- UDP packets get dropped
272 with contextlib.suppress(trio.BrokenResourceError):
273 self._packet_sender.send_nowait(packet)
274
275 ################################################################
276 # Actual IO operation implementations
277 ################################################################
278
279 async def bind(self, addr: object) -> None:
280 self._check_closed()
281 if self._binding is not None:
282 _fake_err(errno.EINVAL)
283 await trio.lowlevel.checkpoint()
284 ip_str, port, *_ = await self._resolve_address_nocp(addr, local=True)
285 assert _ == [], "TODO: handle other values?"
286
287 ip = ipaddress.ip_address(ip_str)
288 assert _family_for(ip) == self.family
289 # We convert binds to INET_ANY into binds to localhost
290 if ip == ipaddress.ip_address("0.0.0.0"):
291 ip = ipaddress.ip_address("127.0.0.1")
292 elif ip == ipaddress.ip_address("::"):
293 ip = ipaddress.ip_address("::1")
294 if port == 0:
295 port = next(self._fake_net._auto_port_iter)
296 binding = UDPBinding(local=UDPEndpoint(ip, port))
297 self._fake_net._bind(binding, self)
298 self._binding = binding
299
300 async def connect(self, peer: object) -> NoReturn:
301 raise NotImplementedError("FakeNet does not (yet) support connected sockets")
302
303 async def _sendmsg(
304 self,
305 buffers: Iterable[Buffer],
306 ancdata: Iterable[tuple[int, int, Buffer]] = (),
307 flags: int = 0,
308 address: AddressFormat | None = None,
309 ) -> int:
310 self._check_closed()
311
312 await trio.lowlevel.checkpoint()
313
314 if address is not None:
315 address = await self._resolve_address_nocp(address, local=False)
316 if ancdata:
317 raise NotImplementedError("FakeNet doesn't support ancillary data")
318 if flags:
319 raise NotImplementedError(f"FakeNet send flags must be 0, not {flags}")
320
321 if address is None:
322 _fake_err(errno.ENOTCONN)
323
324 destination = UDPEndpoint.from_python_sockaddr(address)
325
326 if self._binding is None:
327 await self.bind((_wildcard_ip_for(self.family).compressed, 0))
328
329 payload = b"".join(buffers)
330
331 assert self._binding is not None
332 packet = UDPPacket(
333 source=self._binding.local,
334 destination=destination,
335 payload=payload,
336 )
337
338 self._fake_net.send_packet(packet)
339
340 return len(payload)
341
342 if sys.platform != "win32" or (
343 not TYPE_CHECKING and hasattr(socket.socket, "sendmsg")
344 ):
345 sendmsg = _sendmsg
346
347 async def _recvmsg_into(
348 self,
349 buffers: Iterable[Buffer],
350 ancbufsize: int = 0,
351 flags: int = 0,
352 ) -> tuple[
353 int,
354 list[tuple[int, int, bytes]],
355 int,
356 tuple[str, int] | tuple[str, int, int, int],
357 ]:
358 if ancbufsize != 0:
359 raise NotImplementedError("FakeNet doesn't support ancillary data")
360 if flags != 0:
361 raise NotImplementedError("FakeNet doesn't support any recv flags")
362 if self._binding is None:
363 # I messed this up a few times when writing tests ... but it also never happens
364 # in any of the existing tests, so maybe it could be intentional...
365 raise NotImplementedError(
366 "The code will most likely hang if you try to receive on a fakesocket "
367 "without a binding. If that is not the case, or you explicitly want to "
368 "test that, remove this warning.",
369 )
370
371 self._check_closed()
372
373 ancdata: list[tuple[int, int, bytes]] = []
374 msg_flags = 0
375
376 packet = await self._packet_receiver.receive()
377 address = packet.source.as_python_sockaddr()
378 written = _scatter(packet.payload, buffers)
379 if written < len(packet.payload):
380 msg_flags |= trio.socket.MSG_TRUNC
381 return written, ancdata, msg_flags, address
382
383 if sys.platform != "win32" or (
384 not TYPE_CHECKING and hasattr(socket.socket, "sendmsg")
385 ):
386 recvmsg_into = _recvmsg_into
387
388 ################################################################
389 # Simple state query stuff
390 ################################################################
391
392 def getsockname(self) -> tuple[str, int] | tuple[str, int, int, int]:
393 self._check_closed()
394 if self._binding is not None:
395 return self._binding.local.as_python_sockaddr()
396 elif self.family == trio.socket.AF_INET:
397 return ("0.0.0.0", 0)
398 else:
399 assert self.family == trio.socket.AF_INET6
400 return ("::", 0)
401
402 # TODO: This method is not tested, and seems to make incorrect assumptions. It should maybe raise NotImplementedError.
403 def getpeername(self) -> tuple[str, int] | tuple[str, int, int, int]:
404 self._check_closed()
405 if self._binding is not None:
406 assert hasattr(
407 self._binding,
408 "remote",
409 ), "This method seems to assume that self._binding has a remote UDPEndpoint"
410 if self._binding.remote is not None: # pragma: no cover
411 assert isinstance(
412 self._binding.remote,
413 UDPEndpoint,
414 ), "Self._binding.remote should be a UDPEndpoint"
415 return self._binding.remote.as_python_sockaddr()
416 _fake_err(errno.ENOTCONN)
417
418 @overload
419 def getsockopt(self, /, level: int, optname: int) -> int: ...
420
421 @overload
422 def getsockopt(self, /, level: int, optname: int, buflen: int) -> bytes: ...
423
424 def getsockopt(
425 self,
426 /,
427 level: int,
428 optname: int,
429 buflen: int | None = None,
430 ) -> int | bytes:
431 self._check_closed()
432 raise OSError(f"FakeNet doesn't implement getsockopt({level}, {optname})")
433
434 @overload
435 def setsockopt(self, /, level: int, optname: int, value: int | Buffer) -> None: ...
436
437 @overload
438 def setsockopt(
439 self,
440 /,
441 level: int,
442 optname: int,
443 value: None,
444 optlen: int,
445 ) -> None: ...
446
447 def setsockopt(
448 self,
449 /,
450 level: int,
451 optname: int,
452 value: int | Buffer | None,
453 optlen: int | None = None,
454 ) -> None:
455 self._check_closed()
456
457 if (level, optname) == (
458 trio.socket.IPPROTO_IPV6,
459 trio.socket.IPV6_V6ONLY,
460 ) and not value:
461 raise NotImplementedError("FakeNet always has IPV6_V6ONLY=True")
462
463 raise OSError(f"FakeNet doesn't implement setsockopt({level}, {optname}, ...)")
464
465 ################################################################
466 # Various boilerplate and trivial stubs
467 ################################################################
468
469 def __enter__(self) -> Self:
470 return self
471
472 def __exit__(
473 self,
474 exc_type: builtins.type[BaseException] | None,
475 exc_value: BaseException | None,
476 traceback: TracebackType | None,
477 ) -> None:
478 self.close()
479
480 async def send(self, data: Buffer, flags: int = 0) -> int:
481 return await self.sendto(data, flags, None)
482
483 # __ prefixed arguments because typeshed uses that and typechecker issues
484 @overload
485 async def sendto(
486 self,
487 __data: Buffer, # noqa: PYI063
488 __address: tuple[object, ...] | str | Buffer,
489 ) -> int: ...
490
491 # __ prefixed arguments because typeshed uses that and typechecker issues
492 @overload
493 async def sendto(
494 self,
495 __data: Buffer, # noqa: PYI063
496 __flags: int,
497 __address: tuple[object, ...] | str | Buffer | None,
498 ) -> int: ...
499
500 async def sendto( # type: ignore[explicit-any]
501 self,
502 *args: Any,
503 ) -> int:
504 data: Buffer
505 flags: int
506 address: tuple[object, ...] | str | Buffer
507 if len(args) == 2:
508 data, address = args
509 flags = 0
510 elif len(args) == 3:
511 data, flags, address = args
512 else:
513 raise TypeError("wrong number of arguments")
514 return await self._sendmsg([data], [], flags, address)
515
516 async def recv(self, bufsize: int, flags: int = 0) -> bytes:
517 data, _address = await self.recvfrom(bufsize, flags)
518 return data
519
520 async def recv_into(self, buf: Buffer, nbytes: int = 0, flags: int = 0) -> int:
521 got_bytes, _address = await self.recvfrom_into(buf, nbytes, flags)
522 return got_bytes
523
524 async def recvfrom(
525 self,
526 bufsize: int,
527 flags: int = 0,
528 ) -> tuple[bytes, AddressFormat]:
529 data, _ancdata, _msg_flags, address = await self._recvmsg(bufsize, flags)
530 return data, address
531
532 async def recvfrom_into(
533 self,
534 buf: Buffer,
535 nbytes: int = 0,
536 flags: int = 0,
537 ) -> tuple[int, AddressFormat]:
538 if nbytes != 0 and nbytes != memoryview(buf).nbytes:
539 raise NotImplementedError("partial recvfrom_into")
540 got_nbytes, _ancdata, _msg_flags, address = await self._recvmsg_into(
541 [buf],
542 0,
543 flags,
544 )
545 return got_nbytes, address
546
547 async def _recvmsg(
548 self,
549 bufsize: int,
550 ancbufsize: int = 0,
551 flags: int = 0,
552 ) -> tuple[bytes, list[tuple[int, int, bytes]], int, AddressFormat]:
553 buf = bytearray(bufsize)
554 got_nbytes, ancdata, msg_flags, address = await self._recvmsg_into(
555 [buf],
556 ancbufsize,
557 flags,
558 )
559 return (bytes(buf[:got_nbytes]), ancdata, msg_flags, address)
560
561 if sys.platform != "win32" or (
562 not TYPE_CHECKING and hasattr(socket.socket, "sendmsg")
563 ):
564 recvmsg = _recvmsg
565
566 def fileno(self) -> int:
567 raise NotImplementedError("can't get fileno() for FakeNet sockets")
568
569 def detach(self) -> int:
570 raise NotImplementedError("can't detach() a FakeNet socket")
571
572 def get_inheritable(self) -> bool:
573 return False
574
575 def set_inheritable(self, inheritable: bool) -> None:
576 if inheritable:
577 raise NotImplementedError("FakeNet can't make inheritable sockets")
578
579 if sys.platform == "win32" or (
580 not TYPE_CHECKING and hasattr(socket.socket, "share")
581 ):
582
583 def share(self, process_id: int) -> bytes:
584 raise NotImplementedError("FakeNet can't share sockets")