Debian Codegraph @

src/trio/_tests/test_socket.py

raw
1 from __future__ import annotations
2
3 import errno
4 import inspect
5 import os
6 import socket as stdlib_socket
7 import sys
8 import tempfile
9 from pathlib import Path
10 from socket import AddressFamily, SocketKind
11 from typing import TYPE_CHECKING, TypeAlias, cast
12
13 import attrs
14 import pytest
15
16 from .. import _core, socket as tsocket
17 from .._core._tests.tutil import binds_ipv6, can_create_ipv6, creates_ipv6, slow
18 from .._socket import _NUMERIC_ONLY, AddressFormat, SocketType, _SocketType, _try_sync
19 from ..testing import assert_checkpoints, wait_all_tasks_blocked
20
21 if TYPE_CHECKING:
22 from collections.abc import Callable
23
24 from .._highlevel_socket import SocketStream
25
26 GaiTuple: TypeAlias = tuple[
27 AddressFamily,
28 SocketKind,
29 int,
30 str,
31 tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes],
32 ]
33 GetAddrInfoResponse: TypeAlias = list[GaiTuple]
34 GetAddrInfoArgs: TypeAlias = tuple[
35 str | bytes | None,
36 str | bytes | int | None,
37 int,
38 int,
39 int,
40 int,
41 ]
42 else:
43 GaiTuple: object
44 GetAddrInfoResponse = object
45 GetAddrInfoArgs = object
46
47 ################################################################
48 # utils
49 ################################################################
50
51
52 class MonkeypatchedGAI:
53 __slots__ = ("_orig_getaddrinfo", "_responses", "record")
54
55 def __init__(
56 self,
57 orig_getaddrinfo: Callable[
58 [str | bytes | None, str | bytes | int | None, int, int, int, int],
59 GetAddrInfoResponse,
60 ],
61 ) -> None:
62 self._orig_getaddrinfo = orig_getaddrinfo
63 self._responses: dict[
64 GetAddrInfoArgs,
65 GetAddrInfoResponse | str,
66 ] = {}
67 self.record: list[GetAddrInfoArgs] = []
68
69 # get a normalized getaddrinfo argument tuple
70 def _frozenbind(
71 self,
72 host: str | bytes | None,
73 port: str | bytes | int | None,
74 family: int = 0,
75 type: int = 0,
76 proto: int = 0,
77 flags: int = 0,
78 ) -> GetAddrInfoArgs:
79 sig = inspect.signature(self._orig_getaddrinfo)
80 bound = sig.bind(host, port, family=family, type=type, proto=proto, flags=flags)
81 bound.apply_defaults()
82 frozenbound = bound.args
83 assert not bound.kwargs
84 return frozenbound
85
86 def set(
87 self,
88 response: GetAddrInfoResponse | str,
89 host: str | bytes | None,
90 port: str | bytes | int | None,
91 family: int = 0,
92 type: int = 0,
93 proto: int = 0,
94 flags: int = 0,
95 ) -> None:
96 self._responses[
97 self._frozenbind(
98 host,
99 port,
100 family=family,
101 type=type,
102 proto=proto,
103 flags=flags,
104 )
105 ] = response
106
107 def getaddrinfo(
108 self,
109 host: str | bytes | None,
110 port: str | bytes | int | None,
111 family: int = 0,
112 type: int = 0,
113 proto: int = 0,
114 flags: int = 0,
115 ) -> GetAddrInfoResponse | str:
116 bound = self._frozenbind(host, port, family, type, proto, flags)
117 self.record.append(bound)
118 if bound in self._responses:
119 return self._responses[bound]
120 elif flags & stdlib_socket.AI_NUMERICHOST:
121 return self._orig_getaddrinfo(host, port, family, type, proto, flags)
122 else:
123 raise RuntimeError(f"gai called with unexpected arguments {bound}")
124
125
126 @pytest.fixture
127 def monkeygai(monkeypatch: pytest.MonkeyPatch) -> MonkeypatchedGAI:
128 controller = MonkeypatchedGAI(stdlib_socket.getaddrinfo)
129 monkeypatch.setattr(stdlib_socket, "getaddrinfo", controller.getaddrinfo)
130 return controller
131
132
133 async def test__try_sync() -> None:
134 with assert_checkpoints():
135 async with _try_sync():
136 pass
137
138 with assert_checkpoints():
139 with pytest.raises(KeyError):
140 async with _try_sync():
141 raise KeyError
142
143 async with _try_sync():
144 raise BlockingIOError
145
146 def _is_ValueError(exc: BaseException) -> bool:
147 return isinstance(exc, ValueError)
148
149 async with _try_sync(_is_ValueError):
150 raise ValueError
151
152 with assert_checkpoints():
153 with pytest.raises(BlockingIOError):
154 async with _try_sync(_is_ValueError):
155 raise BlockingIOError
156
157
158 ################################################################
159 # basic re-exports
160 ################################################################
161
162
163 def test_socket_has_some_reexports() -> None:
164 assert tsocket.SOL_SOCKET == stdlib_socket.SOL_SOCKET
165 assert tsocket.TCP_NODELAY == stdlib_socket.TCP_NODELAY
166 assert tsocket.gaierror == stdlib_socket.gaierror
167 assert tsocket.ntohs == stdlib_socket.ntohs
168
169
170 ################################################################
171 # name resolution
172 ################################################################
173
174
175 async def test_getaddrinfo(monkeygai: MonkeypatchedGAI) -> None:
176 def check(got: GetAddrInfoResponse, expected: GetAddrInfoResponse) -> None:
177 # win32 returns 0 for the proto field
178 # musl and glibc have inconsistent handling of the canonical name
179 # field (https://github.com/python-trio/trio/issues/1499)
180 # Neither field gets used much and there isn't much opportunity for us
181 # to mess them up, so we don't bother checking them here
182 def interesting_fields(
183 gai_tup: GaiTuple,
184 ) -> tuple[
185 AddressFamily,
186 SocketKind,
187 tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes],
188 ]:
189 # (family, type, proto, canonname, sockaddr)
190 family, type_, _proto, _canonname, sockaddr = gai_tup
191 return (family, type_, sockaddr)
192
193 def filtered(
194 gai_list: GetAddrInfoResponse,
195 ) -> list[
196 tuple[
197 AddressFamily,
198 SocketKind,
199 tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes],
200 ]
201 ]:
202 return [interesting_fields(gai_tup) for gai_tup in gai_list]
203
204 assert filtered(got) == filtered(expected)
205
206 # Simple non-blocking non-error cases, ipv4 and ipv6:
207 with assert_checkpoints():
208 res = await tsocket.getaddrinfo("127.0.0.1", "12345", type=tsocket.SOCK_STREAM)
209
210 check(
211 res,
212 [
213 (
214 tsocket.AF_INET, # 127.0.0.1 is ipv4
215 tsocket.SOCK_STREAM,
216 tsocket.IPPROTO_TCP,
217 "",
218 ("127.0.0.1", 12345),
219 ),
220 ],
221 )
222
223 with assert_checkpoints():
224 res = await tsocket.getaddrinfo("::1", "12345", type=tsocket.SOCK_DGRAM)
225 check(
226 res,
227 [
228 (
229 tsocket.AF_INET6,
230 tsocket.SOCK_DGRAM,
231 tsocket.IPPROTO_UDP,
232 "",
233 ("::1", 12345, 0, 0),
234 ),
235 ],
236 )
237
238 monkeygai.set("x", b"host", "port", family=0, type=0, proto=0, flags=0)
239 with assert_checkpoints():
240 res = await tsocket.getaddrinfo("host", "port")
241 assert res == "x"
242 assert monkeygai.record[-1] == (b"host", "port", 0, 0, 0, 0)
243
244 # check raising an error from a non-blocking getaddrinfo
245 with assert_checkpoints():
246 with pytest.raises(tsocket.gaierror) as excinfo:
247 await tsocket.getaddrinfo("::1", "12345", type=-1)
248 # Linux + glibc, Windows
249 expected_errnos = {tsocket.EAI_SOCKTYPE}
250 # Linux + musl
251 expected_errnos.add(tsocket.EAI_SERVICE)
252 # macOS
253 if hasattr(tsocket, "EAI_BADHINTS"):
254 expected_errnos.add(tsocket.EAI_BADHINTS)
255 assert excinfo.value.errno in expected_errnos
256
257 # check raising an error from a blocking getaddrinfo (exploits the fact
258 # that monkeygai raises if it gets a non-numeric request it hasn't been
259 # given an answer for)
260 with assert_checkpoints():
261 with pytest.raises(RuntimeError):
262 await tsocket.getaddrinfo("asdf", "12345")
263
264
265 async def test_getnameinfo() -> None:
266 # Trivial test:
267 ni_numeric = stdlib_socket.NI_NUMERICHOST | stdlib_socket.NI_NUMERICSERV
268 with assert_checkpoints():
269 got = await tsocket.getnameinfo(("127.0.0.1", 1234), ni_numeric)
270 assert got == ("127.0.0.1", "1234")
271
272 # getnameinfo requires a numeric address as input:
273 with assert_checkpoints():
274 with pytest.raises(tsocket.gaierror):
275 await tsocket.getnameinfo(("google.com", 80), 0)
276
277 with assert_checkpoints():
278 with pytest.raises(tsocket.gaierror):
279 await tsocket.getnameinfo(("localhost", 80), 0)
280
281 # Blocking call to get expected values:
282 host, service = stdlib_socket.getnameinfo(("127.0.0.1", 80), 0)
283
284 # Some working calls:
285 got = await tsocket.getnameinfo(("127.0.0.1", 80), 0)
286 assert got == (host, service)
287
288 got = await tsocket.getnameinfo(("127.0.0.1", 80), tsocket.NI_NUMERICHOST)
289 assert got == ("127.0.0.1", service)
290
291 got = await tsocket.getnameinfo(("127.0.0.1", 80), tsocket.NI_NUMERICSERV)
292 assert got == (host, "80")
293
294
295 ################################################################
296 # constructors
297 ################################################################
298
299
300 async def test_from_stdlib_socket() -> None:
301 sa, sb = stdlib_socket.socketpair()
302 assert not isinstance(sa, tsocket.SocketType)
303 with sa, sb:
304 ta = tsocket.from_stdlib_socket(sa)
305 assert isinstance(ta, tsocket.SocketType)
306 assert sa.fileno() == ta.fileno()
307 await ta.send(b"x")
308 assert sb.recv(1) == b"x"
309
310 # rejects other types
311 with pytest.raises(TypeError):
312 tsocket.from_stdlib_socket(1) # type: ignore[arg-type]
313
314 class MySocket(stdlib_socket.socket):
315 pass
316
317 with MySocket() as mysock:
318 with pytest.raises(TypeError):
319 tsocket.from_stdlib_socket(mysock)
320
321
322 async def test_from_fd() -> None:
323 sa, sb = stdlib_socket.socketpair()
324 ta = tsocket.fromfd(sa.fileno(), sa.family, sa.type, sa.proto)
325 with sa, sb, ta:
326 assert ta.fileno() != sa.fileno()
327 await ta.send(b"x")
328 assert sb.recv(3) == b"x"
329
330
331 async def test_socketpair_simple() -> None:
332 async def child(sock: SocketType) -> None:
333 print("sending hello")
334 await sock.send(b"h")
335 assert await sock.recv(1) == b"h"
336
337 a, b = tsocket.socketpair()
338 with a, b:
339 async with _core.open_nursery() as nursery:
340 nursery.start_soon(child, a)
341 nursery.start_soon(child, b)
342
343
344 @pytest.mark.skipif(not hasattr(tsocket, "fromshare"), reason="windows only")
345 async def test_fromshare() -> None:
346 if TYPE_CHECKING and sys.platform != "win32": # pragma: no cover
347 return
348 a, b = tsocket.socketpair()
349 with a, b:
350 # share with ourselves
351 shared = a.share(os.getpid())
352 a2 = tsocket.fromshare(shared)
353 with a2:
354 assert a.fileno() != a2.fileno()
355 await a2.send(b"x")
356 assert await b.recv(1) == b"x"
357
358
359 async def test_socket() -> None:
360 with tsocket.socket() as s:
361 assert isinstance(s, tsocket.SocketType)
362 assert s.family == tsocket.AF_INET
363
364
365 @creates_ipv6
366 async def test_socket_v6() -> None:
367 with tsocket.socket(tsocket.AF_INET6, tsocket.SOCK_DGRAM) as s:
368 assert isinstance(s, tsocket.SocketType)
369 assert s.family == tsocket.AF_INET6
370
371
372 @pytest.mark.skipif(sys.platform != "linux", reason="linux only")
373 async def test_sniff_sockopts() -> None:
374 from socket import AF_INET, AF_INET6, SOCK_DGRAM, SOCK_STREAM
375
376 # generate the combinations of families/types we're testing:
377 families = (AF_INET, AF_INET6) if can_create_ipv6 else (AF_INET,)
378 sockets = [
379 stdlib_socket.socket(family, type_)
380 for family in families
381 for type_ in [SOCK_DGRAM, SOCK_STREAM]
382 ]
383 for socket in sockets:
384 # regular Trio socket constructor
385 tsocket_socket = tsocket.socket(fileno=socket.fileno())
386 # check family / type for correctness:
387 assert tsocket_socket.family == socket.family
388 assert tsocket_socket.type == socket.type
389 tsocket_socket.detach()
390
391 # fromfd constructor
392 tsocket_from_fd = tsocket.fromfd(socket.fileno(), AF_INET, SOCK_STREAM)
393 # check family / type for correctness:
394 assert tsocket_from_fd.family == socket.family
395 assert tsocket_from_fd.type == socket.type
396 tsocket_from_fd.close()
397
398 socket.close()
399
400
401 ################################################################
402 # _SocketType
403 ################################################################
404
405
406 async def test_SocketType_basics() -> None:
407 sock = tsocket.socket()
408 with sock as cm_enter_value:
409 assert cm_enter_value is sock
410 assert isinstance(sock.fileno(), int)
411 assert not sock.get_inheritable()
412 sock.set_inheritable(True)
413 assert sock.get_inheritable()
414
415 sock.setsockopt(tsocket.IPPROTO_TCP, tsocket.TCP_NODELAY, False)
416 assert not sock.getsockopt(tsocket.IPPROTO_TCP, tsocket.TCP_NODELAY)
417 sock.setsockopt(tsocket.IPPROTO_TCP, tsocket.TCP_NODELAY, True)
418 assert sock.getsockopt(tsocket.IPPROTO_TCP, tsocket.TCP_NODELAY)
419 # closed sockets have fileno() == -1
420 assert sock.fileno() == -1
421
422 # smoke test
423 repr(sock)
424
425 # detach
426 with tsocket.socket() as sock:
427 fd = sock.fileno()
428 assert sock.detach() == fd
429 assert sock.fileno() == -1
430
431 # close
432 sock = tsocket.socket()
433 assert sock.fileno() >= 0
434 sock.close()
435 assert sock.fileno() == -1
436
437 # share was tested above together with fromshare
438
439 # check __dir__
440 assert "family" in dir(sock)
441 assert "recv" in dir(sock)
442 assert "setsockopt" in dir(sock)
443
444 # our __getattr__ handles unknown names
445 with pytest.raises(AttributeError):
446 sock.asdf # type: ignore[attr-defined] # noqa: B018
447
448 # type family proto
449 stdlib_sock = stdlib_socket.socket()
450 sock = tsocket.from_stdlib_socket(stdlib_sock)
451 assert sock.type == stdlib_sock.type
452 assert sock.family == stdlib_sock.family
453 assert sock.proto == stdlib_sock.proto
454 sock.close()
455
456
457 async def test_SocketType_setsockopt() -> None:
458 sock = tsocket.socket()
459 with sock as _:
460 setsockopt_tests(sock)
461
462
463 def setsockopt_tests(sock: SocketType | SocketStream) -> None:
464 """Extract these out, to be reused for SocketStream also."""
465 # specifying optlen. Not supported on pypy, and I couldn't find
466 # valid calls on darwin or win32.
467 if hasattr(tsocket, "SO_BINDTODEVICE"):
468 try:
469 sock.setsockopt(tsocket.SOL_SOCKET, tsocket.SO_BINDTODEVICE, None, 0)
470 except (
471 OSError
472 ) as e: # pragma: no cover # all CI runners support SO_BINDTODEVICE
473 assert e.errno in [ # noqa: PT017
474 # some versions of Python have the attribute yet can run on
475 # platforms that do not support it. For instance, MacOS 15
476 # gained support for SO_BINDTODEVICE and CPython 3.13.1 was
477 # built on it (presumably), but our CI runners ran MacOS 14 and
478 # so failed.
479 42,
480 # Older Linux kernels (prior to patch
481 # https://lore.kernel.org/netdev/[email protected]/t/)
482 # do not support SO_BINDTODEVICE as an unprivileged user.
483 errno.EPERM,
484 ]
485
486 # specifying value
487 sock.setsockopt(tsocket.IPPROTO_TCP, tsocket.TCP_NODELAY, False)
488
489 # specifying both
490 with pytest.raises(TypeError, match="invalid value for argument 'value'"):
491 sock.setsockopt(tsocket.IPPROTO_TCP, tsocket.TCP_NODELAY, False, 5) # type: ignore[call-overload]
492
493 # specifying neither
494 with pytest.raises(TypeError, match="invalid value for argument 'value'"):
495 sock.setsockopt(tsocket.IPPROTO_TCP, tsocket.TCP_NODELAY, None) # type: ignore[call-overload]
496
497
498 async def test_SocketType_dup() -> None:
499 a, b = tsocket.socketpair()
500 with a, b:
501 a2 = a.dup()
502 with a2:
503 assert isinstance(a2, tsocket.SocketType)
504 assert a2.fileno() != a.fileno()
505 a.close()
506 await a2.send(b"x")
507 assert await b.recv(1) == b"x"
508
509
510 async def test_SocketType_shutdown() -> None:
511 a, b = tsocket.socketpair()
512 with a, b:
513 await a.send(b"x")
514 assert await b.recv(1) == b"x"
515 assert not a.did_shutdown_SHUT_WR
516 assert not b.did_shutdown_SHUT_WR
517 a.shutdown(tsocket.SHUT_WR)
518 assert a.did_shutdown_SHUT_WR
519 assert not b.did_shutdown_SHUT_WR
520 assert await b.recv(1) == b""
521 await b.send(b"y")
522 assert await a.recv(1) == b"y"
523
524 a, b = tsocket.socketpair()
525 with a, b:
526 assert not a.did_shutdown_SHUT_WR
527 a.shutdown(tsocket.SHUT_RD)
528 assert not a.did_shutdown_SHUT_WR
529
530 a, b = tsocket.socketpair()
531 with a, b:
532 assert not a.did_shutdown_SHUT_WR
533 a.shutdown(tsocket.SHUT_RDWR)
534 assert a.did_shutdown_SHUT_WR
535
536
537 @pytest.mark.parametrize(
538 ("address", "socket_type"),
539 [
540 ("127.0.0.1", tsocket.AF_INET),
541 pytest.param("::1", tsocket.AF_INET6, marks=binds_ipv6),
542 ],
543 )
544 async def test_SocketType_simple_server(
545 address: str,
546 socket_type: AddressFamily,
547 ) -> None:
548 # listen, bind, accept, connect, getpeername, getsockname
549 listener = tsocket.socket(socket_type)
550 client = tsocket.socket(socket_type)
551 with listener, client:
552 await listener.bind((address, 0))
553 listener.listen(20)
554 addr = listener.getsockname()[:2]
555 async with _core.open_nursery() as nursery:
556 nursery.start_soon(client.connect, addr)
557 server, client_addr = await listener.accept()
558 with server:
559 assert client_addr == server.getpeername() == client.getsockname()
560 await server.send(b"x")
561 assert await client.recv(1) == b"x"
562
563
564 async def test_SocketType_is_readable() -> None:
565 a, b = tsocket.socketpair()
566 with a, b:
567 assert not a.is_readable()
568 await b.send(b"x")
569 await _core.wait_readable(a)
570 assert a.is_readable()
571 assert await a.recv(1) == b"x"
572 assert not a.is_readable()
573
574
575 # On some macOS systems, getaddrinfo likes to return V4-mapped addresses even
576 # when we *don't* pass AI_V4MAPPED.
577 # https://github.com/python-trio/trio/issues/580
578 def gai_without_v4mapped_is_buggy() -> bool: # pragma: no cover
579 try:
580 stdlib_socket.getaddrinfo("1.2.3.4", 0, family=stdlib_socket.AF_INET6)
581 except stdlib_socket.gaierror:
582 return False
583 else:
584 return True
585
586
587 @attrs.define(slots=False)
588 class Addresses:
589 bind_all: str
590 localhost: str
591 arbitrary: str
592 broadcast: str
593
594
595 # Direct thorough tests of the implicit resolver helpers
596 @pytest.mark.parametrize(
597 ("socket_type", "addrs"),
598 [
599 (
600 tsocket.AF_INET,
601 Addresses(
602 bind_all="0.0.0.0",
603 localhost="127.0.0.1",
604 arbitrary="1.2.3.4",
605 broadcast="255.255.255.255",
606 ),
607 ),
608 pytest.param(
609 tsocket.AF_INET6,
610 Addresses(
611 bind_all="::",
612 localhost="::1",
613 arbitrary="1::2",
614 broadcast="::ffff:255.255.255.255",
615 ),
616 marks=creates_ipv6,
617 ),
618 ],
619 )
620 async def test_SocketType_resolve(socket_type: AddressFamily, addrs: Addresses) -> None:
621 v6 = socket_type == tsocket.AF_INET6
622
623 def pad(addr: tuple[str | int, ...]) -> tuple[str | int, ...]:
624 if v6:
625 while len(addr) < 4:
626 addr += (0,)
627 return addr
628
629 def assert_eq(
630 actual: tuple[str | int, ...],
631 expected: tuple[str | int, ...],
632 ) -> None:
633 assert pad(expected) == pad(actual)
634
635 with tsocket.socket(family=socket_type) as sock:
636 # testing internal functionality, so we check it against the internal type
637 assert isinstance(sock, _SocketType)
638
639 # For some reason the stdlib special-cases "" to pass NULL to
640 # getaddrinfo. They also error out on None, but whatever, None is much
641 # more consistent, so we accept it too.
642 # TODO: this implies that we can send host=None, but what does that imply for the return value, and other stuff?
643 for null in [None, ""]:
644 got = await sock._resolve_address_nocp((null, 80), local=True)
645 assert not isinstance(got, (str, bytes))
646 assert_eq(got, (addrs.bind_all, 80))
647 got = await sock._resolve_address_nocp((null, 80), local=False)
648 assert not isinstance(got, (str, bytes))
649 assert_eq(got, (addrs.localhost, 80))
650
651 # AI_PASSIVE only affects the wildcard address, so for everything else
652 # local=True/local=False should work the same:
653 for local in [False, True]:
654
655 async def res(
656 args: (
657 tuple[str, int]
658 | tuple[str, int, int]
659 | tuple[str, int, int, int]
660 | tuple[str, str]
661 | tuple[str, str, int]
662 | tuple[str, str, int, int]
663 ),
664 ) -> tuple[str | int, ...]:
665 value = await sock._resolve_address_nocp(
666 args,
667 local=local, # noqa: B023 # local is not bound in function definition
668 )
669 assert isinstance(value, tuple)
670 return cast("tuple[str | int, ...]", value)
671
672 assert_eq(await res((addrs.arbitrary, "http")), (addrs.arbitrary, 80))
673 if v6:
674 # Check handling of different length ipv6 address tuples
675 assert_eq(await res(("1::2", 80)), ("1::2", 80, 0, 0))
676 assert_eq(await res(("1::2", 80, 0)), ("1::2", 80, 0, 0))
677 assert_eq(await res(("1::2", 80, 0, 0)), ("1::2", 80, 0, 0))
678 # Non-zero flowinfo/scopeid get passed through
679 assert_eq(await res(("1::2", 80, 1)), ("1::2", 80, 1, 0))
680 assert_eq(await res(("1::2", 80, 1, 2)), ("1::2", 80, 1, 2))
681
682 # And again with a string port, as a trick to avoid the
683 # already-resolved address fastpath and make sure we call
684 # getaddrinfo
685 assert_eq(await res(("1::2", "80")), ("1::2", 80, 0, 0))
686 assert_eq(await res(("1::2", "80", 0)), ("1::2", 80, 0, 0))
687 assert_eq(await res(("1::2", "80", 0, 0)), ("1::2", 80, 0, 0))
688 assert_eq(await res(("1::2", "80", 1)), ("1::2", 80, 1, 0))
689 assert_eq(await res(("1::2", "80", 1, 2)), ("1::2", 80, 1, 2))
690
691 # V4 mapped addresses resolved if V6ONLY is False
692 sock.setsockopt(tsocket.IPPROTO_IPV6, tsocket.IPV6_V6ONLY, False)
693 assert_eq(await res(("1.2.3.4", "http")), ("::ffff:1.2.3.4", 80))
694
695 # Check the <broadcast> special case, because why not
696 assert_eq(await res(("<broadcast>", 123)), (addrs.broadcast, 123))
697
698 # But not if it's true (at least on systems where getaddrinfo works
699 # correctly)
700 if v6 and not gai_without_v4mapped_is_buggy():
701 sock.setsockopt(tsocket.IPPROTO_IPV6, tsocket.IPV6_V6ONLY, True)
702 with pytest.raises(tsocket.gaierror) as excinfo:
703 await res(("1.2.3.4", 80))
704 # Windows, macOS, musl/Linux
705 expected_errnos = {tsocket.EAI_NONAME, tsocket.EAI_NODATA}
706 # Linux
707 if hasattr(tsocket, "EAI_ADDRFAMILY"):
708 expected_errnos.add(tsocket.EAI_ADDRFAMILY)
709 assert excinfo.value.errno in expected_errnos
710
711 # A family where we know nothing about the addresses, so should just
712 # pass them through. This should work on Linux, which is enough to
713 # smoke test the basic functionality...
714 try:
715 netlink_sock = tsocket.socket(
716 family=tsocket.AF_NETLINK,
717 type=tsocket.SOCK_DGRAM,
718 )
719 except (AttributeError, OSError):
720 pass
721 else:
722 assert isinstance(netlink_sock, _SocketType)
723 assert (
724 await netlink_sock._resolve_address_nocp("asdf", local=local)
725 == "asdf"
726 )
727 netlink_sock.close()
728
729 address = r"^address should be a \(host, port(, \[flowinfo, \[scopeid\]\])*\) tuple$"
730 with pytest.raises(ValueError, match=address):
731 await res("1.2.3.4") # type: ignore[arg-type]
732 with pytest.raises(ValueError, match=address):
733 await res(("1.2.3.4",)) # type: ignore[arg-type]
734 with pytest.raises(
735 ValueError,
736 match=address,
737 ):
738 if v6:
739 await res(("1.2.3.4", 80, 0, 0, 0)) # type: ignore[arg-type]
740 else:
741 # I guess in theory there could be enough overloads that this could error?
742 await res(("1.2.3.4", 80, 0, 0))
743
744
745 async def test_SocketType_unresolved_names() -> None:
746 with tsocket.socket() as sock:
747 await sock.bind(("localhost", 0))
748 assert sock.getsockname()[0] == "127.0.0.1"
749 sock.listen(10)
750
751 with tsocket.socket() as sock2:
752 await sock2.connect(("localhost", sock.getsockname()[1]))
753 assert sock2.getpeername() == sock.getsockname()
754
755 # check gaierror propagates out
756 with tsocket.socket() as sock:
757 with pytest.raises(tsocket.gaierror):
758 # definitely not a valid request
759 await sock.bind(("1.2:3", -1))
760
761
762 # This tests all the complicated paths through _nonblocking_helper, using recv
763 # as a stand-in for all the methods that use _nonblocking_helper.
764 async def test_SocketType_non_blocking_paths() -> None:
765 a, b = stdlib_socket.socketpair()
766 with a, b:
767 ta = tsocket.from_stdlib_socket(a)
768 b.setblocking(False)
769
770 # cancel before even calling
771 b.send(b"1")
772 with _core.CancelScope() as cscope:
773 cscope.cancel()
774 with assert_checkpoints():
775 with pytest.raises(_core.Cancelled):
776 await ta.recv(10)
777 # immediate success (also checks that the previous attempt didn't
778 # actually read anything)
779 with assert_checkpoints():
780 assert await ta.recv(10) == b"1"
781 # immediate failure
782 with assert_checkpoints():
783 with pytest.raises(TypeError):
784 await ta.recv("haha") # type: ignore[arg-type]
785 # block then succeed
786
787 async def do_successful_blocking_recv() -> None:
788 with assert_checkpoints():
789 assert await ta.recv(10) == b"2"
790
791 async with _core.open_nursery() as nursery:
792 nursery.start_soon(do_successful_blocking_recv)
793 await wait_all_tasks_blocked()
794 b.send(b"2")
795 # block then cancelled
796
797 async def do_cancelled_blocking_recv() -> None:
798 with assert_checkpoints():
799 with pytest.raises(_core.Cancelled):
800 await ta.recv(10)
801
802 async with _core.open_nursery() as nursery:
803 nursery.start_soon(do_cancelled_blocking_recv)
804 await wait_all_tasks_blocked()
805 nursery.cancel_scope.cancel()
806 # Okay, here's the trickiest one: we want to exercise the path where
807 # the task is signaled to wake, goes to recv, but then the recv fails,
808 # so it has to go back to sleep and try again. Strategy: have two
809 # tasks waiting on two sockets (to work around the rule against having
810 # two tasks waiting on the same socket), wake them both up at the same
811 # time, and whichever one runs first "steals" the data from the
812 # other:
813 tb = tsocket.from_stdlib_socket(b)
814
815 async def t1() -> None:
816 with assert_checkpoints():
817 assert await ta.recv(1) == b"a"
818 with assert_checkpoints():
819 assert await tb.recv(1) == b"b"
820
821 async def t2() -> None:
822 with assert_checkpoints():
823 assert await tb.recv(1) == b"b"
824 with assert_checkpoints():
825 assert await ta.recv(1) == b"a"
826
827 async with _core.open_nursery() as nursery:
828 nursery.start_soon(t1)
829 nursery.start_soon(t2)
830 await wait_all_tasks_blocked()
831 a.send(b"b")
832 b.send(b"a")
833 await wait_all_tasks_blocked()
834 a.send(b"b")
835 b.send(b"a")
836
837
838 # This tests the complicated paths through connect
839 @slow
840 async def test_SocketType_connect_paths() -> None:
841 with tsocket.socket() as sock:
842 with pytest.raises(
843 ValueError,
844 match=r"^address should be a \(host, port(, \[flowinfo, \[scopeid\]\])*\) tuple$",
845 ):
846 # Should be a tuple
847 await sock.connect("localhost")
848
849 # cancelled before we start
850 with tsocket.socket() as sock:
851 with _core.CancelScope() as cancel_scope:
852 cancel_scope.cancel()
853 with pytest.raises(_core.Cancelled):
854 await sock.connect(("127.0.0.1", 80))
855
856 # Cancelled in between the connect() call and the connect completing
857 with _core.CancelScope() as cancel_scope:
858 with tsocket.socket() as sock, tsocket.socket() as listener:
859 await listener.bind(("127.0.0.1", 0))
860 listener.listen()
861
862 # Swap in our weird subclass under the trio.socket._SocketType's
863 # nose -- and then swap it back out again before we hit
864 # wait_socket_writable, which insists on a real socket.
865 class CancelSocket(stdlib_socket.socket):
866 def connect(
867 self,
868 address: AddressFormat,
869 ) -> None:
870 # accessing private method only available in _SocketType
871 assert isinstance(sock, _SocketType)
872
873 cancel_scope.cancel()
874 sock._sock = stdlib_socket.fromfd(
875 self.detach(),
876 self.family,
877 self.type,
878 )
879 sock._sock.connect(address)
880 # If connect *doesn't* raise, then pretend it did
881 raise BlockingIOError # pragma: no cover
882
883 # accessing private method only available in _SocketType
884 assert isinstance(sock, _SocketType)
885 sock._sock.close()
886 sock._sock = CancelSocket()
887
888 with assert_checkpoints():
889 with pytest.raises(_core.Cancelled):
890 await sock.connect(listener.getsockname())
891 assert sock.fileno() == -1
892
893 # Failed connect (hopefully after raising BlockingIOError)
894 with tsocket.socket() as sock:
895 with pytest.raises(
896 OSError,
897 match=r"^\[\w+ \d+\] Error connecting to \('127\.0\.0\.\d', \d+\): (Connection refused|Unknown error)$",
898 ):
899 # TCP port 2 is not assigned. Pretty sure nothing will be
900 # listening there. (We used to bind a port and then *not* call
901 # listen() to ensure nothing was listening there, but it turns
902 # out on macOS if you do this it takes 30 seconds for the
903 # connect to fail. Really. Also if you use a non-routable
904 # address. This way fails instantly though. As long as nothing
905 # is listening on port 2.)
906
907 # Windows retries failed connections so this takes seconds
908 # (and that's why this is marked @slow)
909 await sock.connect(("127.0.0.1", 2))
910
911
912 # Fix issue #1810
913 @slow
914 async def test_address_in_socket_error() -> None:
915 address = "127.0.0.1"
916 with tsocket.socket() as sock:
917 with pytest.raises(
918 OSError,
919 match=rf"^\[\w+ \d+\] Error connecting to \({address!r}, 2\): (Connection refused|Unknown error)$",
920 ):
921 # Windows retries failed connections so this takes seconds
922 # (and that's why this is marked @slow)
923 await sock.connect((address, 2))
924
925
926 async def test_resolve_address_exception_in_connect_closes_socket() -> None:
927 # Here we are testing issue 247, any cancellation will leave the socket closed
928 with _core.CancelScope() as cancel_scope:
929 with tsocket.socket() as sock:
930
931 async def _resolve_address_nocp(
932 address: AddressFormat,
933 *,
934 local: bool,
935 ) -> None:
936 assert address == ""
937 assert not local
938 cancel_scope.cancel()
939 await _core.checkpoint()
940
941 assert isinstance(sock, _SocketType)
942 sock._resolve_address_nocp = _resolve_address_nocp # type: ignore[method-assign]
943 with assert_checkpoints():
944 with pytest.raises(_core.Cancelled):
945 await sock.connect("")
946 assert sock.fileno() == -1
947
948
949 async def test_send_recv_variants() -> None:
950 a, b = tsocket.socketpair()
951 with a, b:
952 # recv, including with flags
953 assert await a.send(b"x") == 1
954 assert await b.recv(10, tsocket.MSG_PEEK) == b"x"
955 assert await b.recv(10) == b"x"
956
957 # recv_into
958 await a.send(b"x")
959 buf = bytearray(10)
960 await b.recv_into(buf)
961 assert buf == b"x" + b"\x00" * 9
962
963 if hasattr(a, "sendmsg"):
964 assert await a.sendmsg([b"xxx"], []) == 3
965 assert await b.recv(10) == b"xxx"
966
967 a = tsocket.socket(type=tsocket.SOCK_DGRAM)
968 b = tsocket.socket(type=tsocket.SOCK_DGRAM)
969 with a, b:
970 await a.bind(("127.0.0.1", 0))
971 await b.bind(("127.0.0.1", 0))
972
973 targets = [b.getsockname(), ("localhost", b.getsockname()[1])]
974
975 # recvfrom + sendto, with and without names
976 for target in targets:
977 assert await a.sendto(b"xxx", target) == 3
978 data, addr = await b.recvfrom(10)
979 assert data == b"xxx"
980 assert addr == a.getsockname()
981
982 # sendto + flags
983 #
984 # I can't find any flags that send() accepts... on Linux at least
985 # passing MSG_MORE to send_some on a connected UDP socket seems to
986 # just be ignored.
987 #
988 # But there's no MSG_MORE on Windows or macOS. I guess send_some flags
989 # are really not very useful, but at least this tests them a bit.
990 if hasattr(tsocket, "MSG_MORE"):
991 await a.sendto(b"xxx", tsocket.MSG_MORE, b.getsockname())
992 await a.sendto(b"yyy", tsocket.MSG_MORE, b.getsockname())
993 await a.sendto(b"zzz", b.getsockname())
994 data, addr = await b.recvfrom(10)
995 assert data == b"xxxyyyzzz"
996 assert addr == a.getsockname()
997
998 # recvfrom_into
999 assert await a.sendto(b"xxx", b.getsockname()) == 3
1000 buf = bytearray(10)
1001 nbytes, addr = await b.recvfrom_into(buf)
1002 assert nbytes == 3
1003 assert buf == b"xxx" + b"\x00" * 7
1004 assert addr == a.getsockname()
1005
1006 if hasattr(b, "recvmsg"):
1007 assert await a.sendto(b"xxx", b.getsockname()) == 3
1008 data, ancdata, msg_flags, addr = await b.recvmsg(10)
1009 assert data == b"xxx"
1010 assert ancdata == []
1011 assert msg_flags == 0
1012 assert addr == a.getsockname()
1013
1014 if hasattr(b, "recvmsg_into"):
1015 assert await a.sendto(b"xyzw", b.getsockname()) == 4
1016 buf1 = bytearray(2)
1017 buf2 = bytearray(3)
1018 ret = await b.recvmsg_into([buf1, buf2])
1019 nbytes, ancdata, msg_flags, addr = ret
1020 assert nbytes == 4
1021 assert buf1 == b"xy"
1022 assert buf2 == b"zw" + b"\x00"
1023 assert ancdata == []
1024 assert msg_flags == 0
1025 assert addr == a.getsockname()
1026
1027 if hasattr(a, "sendmsg"):
1028 for target in targets:
1029 assert await a.sendmsg([b"x", b"yz"], [], 0, target) == 3
1030 assert await b.recvfrom(10) == (b"xyz", a.getsockname())
1031
1032 a = tsocket.socket(type=tsocket.SOCK_DGRAM)
1033 b = tsocket.socket(type=tsocket.SOCK_DGRAM)
1034 with a, b:
1035 await b.bind(("127.0.0.1", 0))
1036 await a.connect(b.getsockname())
1037 # send on a connected udp socket; each call creates a separate
1038 # datagram
1039 await a.send(b"xxx")
1040 await a.send(b"yyy")
1041 assert await b.recv(10) == b"xxx"
1042 assert await b.recv(10) == b"yyy"
1043
1044
1045 async def test_idna(monkeygai: MonkeypatchedGAI) -> None:
1046 # This is the encoding for "faß.de", which uses one of the characters that
1047 # IDNA 2003 handles incorrectly:
1048 monkeygai.set("ok faß.de", b"xn--fa-hia.de", 80)
1049 monkeygai.set("ok ::1", "::1", 80, flags=_NUMERIC_ONLY)
1050 monkeygai.set("ok ::1", b"::1", 80, flags=_NUMERIC_ONLY)
1051 # Some things that should not reach the underlying socket.getaddrinfo:
1052 monkeygai.set("bad", "fass.de", 80)
1053 # We always call socket.getaddrinfo with bytes objects:
1054 monkeygai.set("bad", "xn--fa-hia.de", 80)
1055
1056 assert await tsocket.getaddrinfo("::1", 80) == "ok ::1"
1057 assert await tsocket.getaddrinfo(b"::1", 80) == "ok ::1"
1058 assert await tsocket.getaddrinfo("faß.de", 80) == "ok faß.de"
1059 assert await tsocket.getaddrinfo("xn--fa-hia.de", 80) == "ok faß.de"
1060 assert await tsocket.getaddrinfo(b"xn--fa-hia.de", 80) == "ok faß.de"
1061
1062
1063 async def test_getprotobyname() -> None:
1064 # These are the constants used in IP header fields, so the numeric values
1065 # had *better* be stable across systems...
1066 assert await tsocket.getprotobyname("udp") == 17
1067 assert await tsocket.getprotobyname("tcp") == 6
1068
1069
1070 async def test_custom_hostname_resolver(monkeygai: MonkeypatchedGAI) -> None:
1071 # This intentionally breaks the signatures used in HostnameResolver
1072 class CustomResolver:
1073 async def getaddrinfo(
1074 self,
1075 host: str,
1076 port: str,
1077 family: int,
1078 type: int,
1079 proto: int,
1080 flags: int,
1081 ) -> tuple[str, str, str, int, int, int, int]:
1082 return ("custom_gai", host, port, family, type, proto, flags)
1083
1084 async def getnameinfo(
1085 self,
1086 sockaddr: tuple[str, int] | tuple[str, int, int, int],
1087 flags: int,
1088 ) -> tuple[str, tuple[str, int] | tuple[str, int, int, int], int]:
1089 return ("custom_gni", sockaddr, flags)
1090
1091 cr = CustomResolver()
1092
1093 assert tsocket.set_custom_hostname_resolver(cr) is None # type: ignore[arg-type]
1094
1095 # Check that the arguments are all getting passed through.
1096 # We have to use valid calls to avoid making the underlying system
1097 # getaddrinfo cranky when it's used for NUMERIC checks.
1098 for vals in [
1099 (tsocket.AF_INET, 0, 0, 0),
1100 (0, tsocket.SOCK_STREAM, 0, 0),
1101 (0, 0, tsocket.IPPROTO_TCP, 0),
1102 (0, 0, 0, tsocket.AI_CANONNAME),
1103 ]:
1104 assert await tsocket.getaddrinfo("localhost", "foo", *vals) == (
1105 "custom_gai",
1106 b"localhost",
1107 "foo",
1108 *vals,
1109 )
1110
1111 # IDNA encoding is handled before calling the special object
1112 got = await tsocket.getaddrinfo("föö", "foo")
1113 expected = ("custom_gai", b"xn--f-1gaa", "foo", 0, 0, 0, 0)
1114 assert got == expected
1115
1116 assert await tsocket.getnameinfo("a", 0) == ( # type: ignore[arg-type]
1117 "custom_gni",
1118 "a",
1119 0,
1120 )
1121
1122 # We can set it back to None
1123 assert tsocket.set_custom_hostname_resolver(None) is cr
1124
1125 # And now Trio switches back to calling socket.getaddrinfo (specifically
1126 # our monkeypatched version of socket.getaddrinfo)
1127 monkeygai.set("x", b"host", "port", family=0, type=0, proto=0, flags=0)
1128 assert await tsocket.getaddrinfo("host", "port") == "x"
1129
1130
1131 async def test_custom_socket_factory() -> None:
1132 class CustomSocketFactory:
1133 def socket(
1134 self,
1135 family: AddressFamily,
1136 type: SocketKind,
1137 proto: int,
1138 ) -> tuple[str, AddressFamily, SocketKind, int]:
1139 return ("hi", family, type, proto)
1140
1141 csf = CustomSocketFactory()
1142
1143 assert tsocket.set_custom_socket_factory(csf) is None # type: ignore[arg-type]
1144
1145 assert tsocket.socket() == ("hi", tsocket.AF_INET, tsocket.SOCK_STREAM, 0)
1146 assert tsocket.socket(1, 2, 3) == ("hi", 1, 2, 3)
1147
1148 # socket with fileno= doesn't call our custom method
1149 fd = stdlib_socket.socket().detach()
1150 wrapped = tsocket.socket(fileno=fd)
1151 assert hasattr(wrapped, "bind")
1152 wrapped.close()
1153
1154 # Likewise for socketpair
1155 a, b = tsocket.socketpair()
1156 with a, b:
1157 assert hasattr(a, "bind")
1158 assert hasattr(b, "bind")
1159
1160 assert tsocket.set_custom_socket_factory(None) is csf
1161
1162
1163 def test_SocketType_is_abstract() -> None:
1164 with pytest.raises(TypeError):
1165 tsocket.SocketType()
1166
1167
1168 @pytest.mark.skipif(not hasattr(tsocket, "AF_UNIX"), reason="no unix domain sockets")
1169 async def test_unix_domain_socket() -> None:
1170 # Bind has a special branch to use a thread, since it has to do filesystem
1171 # traversal. Maybe connect should too? Not sure.
1172
1173 async def check_AF_UNIX(path: str | bytes | os.PathLike[str]) -> None:
1174 with tsocket.socket(family=tsocket.AF_UNIX) as lsock:
1175 await lsock.bind(path)
1176 lsock.listen(10)
1177 with tsocket.socket(family=tsocket.AF_UNIX) as csock:
1178 await csock.connect(path)
1179 ssock, _ = await lsock.accept()
1180 with ssock:
1181 await csock.send(b"x")
1182 assert await ssock.recv(1) == b"x"
1183
1184 # Can't use tmpdir fixture, because we can exceed the maximum AF_UNIX path
1185 # length on macOS.
1186 with tempfile.TemporaryDirectory() as tmpdir:
1187 # Test passing various supported types as path
1188 # Must use different filenames to prevent "address already in use"
1189 await check_AF_UNIX(f"{tmpdir}/sock")
1190 await check_AF_UNIX(Path(f"{tmpdir}/sock1"))
1191 await check_AF_UNIX(os.fsencode(f"{tmpdir}/sock2"))
1192
1193 try:
1194 cookie = os.urandom(20).hex().encode("ascii")
1195 await check_AF_UNIX(b"\x00trio-test-" + cookie)
1196 except FileNotFoundError:
1197 # macOS doesn't support abstract filenames with the leading NUL byte
1198 pass
1199
1200
1201 async def test_interrupted_by_close() -> None:
1202 a_stdlib, b_stdlib = stdlib_socket.socketpair()
1203 with a_stdlib, b_stdlib:
1204 a_stdlib.setblocking(False)
1205
1206 data = b"x" * 99999
1207
1208 try:
1209 while True:
1210 a_stdlib.send(data)
1211 except BlockingIOError:
1212 pass
1213
1214 a = tsocket.from_stdlib_socket(a_stdlib)
1215
1216 async def sender() -> None:
1217 with pytest.raises(_core.ClosedResourceError):
1218 await a.send(data)
1219
1220 async def receiver() -> None:
1221 with pytest.raises(_core.ClosedResourceError):
1222 await a.recv(1)
1223
1224 async with _core.open_nursery() as nursery:
1225 nursery.start_soon(sender)
1226 nursery.start_soon(receiver)
1227 await wait_all_tasks_blocked()
1228 a.close()
1229
1230
1231 async def test_many_sockets() -> None:
1232 total = 1000 # Must be more than MAX_AFD_GROUP_SIZE
1233 sockets = []
1234 # Open at most <total> socket pairs
1235 for opened in range(0, total, 2):
1236 try:
1237 a, b = stdlib_socket.socketpair()
1238 except OSError as exc: # pragma: no cover
1239 # Semi-expecting following errors (sockets are files):
1240 # EMFILE: "Too many open files" (reached kernel cap)
1241 # ENFILE: "File table overflow" (beyond kernel cap)
1242 assert exc.errno in (errno.EMFILE, errno.ENFILE) # noqa: PT017
1243 print(f"Unable to open more than {opened} sockets.")
1244 # Stop opening any more sockets if too many are open
1245 break
1246 sockets += [a, b]
1247 async with _core.open_nursery() as nursery:
1248 for socket in sockets:
1249 nursery.start_soon(_core.wait_readable, socket)
1250 await _core.wait_all_tasks_blocked()
1251 nursery.cancel_scope.cancel()
1252 for socket in sockets:
1253 socket.close()