Skip to main content

rustpython_stdlib/
socket.rs

1// spell-checker:disable
2
3pub(crate) use _socket::module_def;
4
5#[cfg(feature = "ssl")]
6pub(super) use _socket::{PySocket, SockWaitKind, sock_wait, timeout_error_msg};
7
8#[pymodule]
9mod _socket {
10    use crate::common::{
11        inet,
12        lock::{PyMappedRwLockReadGuard, PyRwLock, PyRwLockReadGuard},
13    };
14    #[cfg(all(unix, not(target_os = "redox")))]
15    use crate::vm::convert::ToPyException;
16    use crate::vm::{
17        AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
18        builtins::{
19            PyBaseExceptionRef, PyListRef, PyModule, PyOSError, PyStrRef, PyTupleRef, PyTypeRef,
20            PyUtf8StrRef,
21        },
22        convert::{IntoPyException, ToPyObject, TryFromBorrowedObject, TryFromObject},
23        function::{
24            ArgBytesLike, ArgIntoFloat, ArgMemoryBuffer, ArgStrOrBytesLike, Either, FsPath,
25            FuncArgs, OptionalArg,
26        },
27        types::{Constructor, DefaultConstructor, Destructor, Initializer, Representable},
28        utils::ToCString,
29    };
30    use rustpython_host_env::os::ErrorExt;
31    #[cfg(any(unix, windows))]
32    use rustpython_host_env::socket as host_socket;
33    #[cfg(windows)]
34    use rustpython_host_env::windows as host_windows;
35    #[cfg(windows)]
36    use rustpython_host_env::windows::ToWideString;
37
38    #[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")]
39    pub(crate) fn module_exec(vm: &VirtualMachine, module: &Py<PyModule>) -> PyResult<()> {
40        #[cfg(windows)]
41        host_windows::init_winsock();
42
43        __module_exec(vm, module);
44        Ok(())
45    }
46
47    use core::sync::atomic::{AtomicI32, Ordering};
48    use core::{
49        mem::ManuallyDrop,
50        net::{Ipv4Addr, Ipv6Addr, SocketAddr},
51        time::Duration,
52    };
53    use crossbeam_utils::atomic::AtomicCell;
54    use host_socket::raw::Socket;
55    use num_traits::ToPrimitive;
56    use std::{
57        ffi,
58        io::{self, Read, Write},
59        net::{self, Shutdown, ToSocketAddrs},
60        time::Instant,
61    };
62
63    #[cfg(unix)]
64    use libc as c;
65    #[cfg(windows)]
66    mod c {
67        // Syscall/type names the shared body still reads as `c::`. Integer
68        // pyattrs come from `host_socket` directly.
69        pub(super) use rustpython_host_env::socket::{
70            AF_BLUETOOTH, AF_HYPERV, AF_INET, AF_INET6, AF_UNSPEC, AI_NUMERICHOST, AI_PASSIVE,
71            INADDR_BROADCAST, SHUT_RD, SHUT_RDWR, SHUT_WR, SIO_KEEPALIVE_VALS,
72            SIO_LOOPBACK_FAST_PATH, SIO_RCVALL, SOCK_DGRAM, SOCK_STREAM, WSAEBADF, WSAENOTSOCK,
73            WSAEWOULDBLOCK, getprotobyname, getservbyname, getservbyport,
74        };
75    }
76    // constants
77    #[pyattr(name = "has_ipv6")]
78    const HAS_IPV6: bool = true;
79    #[pyattr]
80    // put IPPROTO_MAX later
81    use host_socket::{
82        AF_INET, AF_INET6, AF_UNSPEC, INADDR_ANY, INADDR_LOOPBACK, INADDR_NONE, IPPROTO_ICMP,
83        IPPROTO_ICMPV6, IPPROTO_IP, IPPROTO_IPV6, IPPROTO_TCP, IPPROTO_TCP as SOL_TCP, IPPROTO_UDP,
84        MSG_CTRUNC, MSG_DONTROUTE, MSG_OOB, MSG_PEEK, MSG_TRUNC, MSG_WAITALL, NI_DGRAM, NI_MAXHOST,
85        NI_NAMEREQD, NI_NOFQDN, NI_NUMERICHOST, NI_NUMERICSERV, SHUT_RD, SHUT_RDWR, SHUT_WR,
86        SO_BROADCAST, SO_ERROR, SO_KEEPALIVE, SO_LINGER, SO_OOBINLINE, SO_RCVBUF, SO_REUSEADDR,
87        SO_SNDBUF, SO_TYPE, SOCK_DGRAM, SOCK_STREAM, SOL_SOCKET, TCP_NODELAY,
88    };
89
90    #[cfg(not(target_os = "redox"))]
91    #[pyattr]
92    use host_socket::{
93        AF_APPLETALK, AF_DECnet, AF_IPX, IPPROTO_AH, IPPROTO_DSTOPTS, IPPROTO_EGP, IPPROTO_ESP,
94        IPPROTO_FRAGMENT, IPPROTO_HOPOPTS, IPPROTO_IDP, IPPROTO_IGMP, IPPROTO_IPIP, IPPROTO_NONE,
95        IPPROTO_PIM, IPPROTO_PUP, IPPROTO_RAW, IPPROTO_ROUTING,
96    };
97
98    #[cfg(unix)]
99    #[pyattr]
100    use host_socket::{AF_UNIX, SO_REUSEPORT};
101
102    #[pyattr]
103    use host_socket::{AI_ADDRCONFIG, AI_NUMERICHOST, AI_NUMERICSERV, AI_PASSIVE};
104
105    #[cfg(not(target_os = "redox"))]
106    #[pyattr]
107    use host_socket::{SOCK_RAW, SOCK_RDM, SOCK_SEQPACKET};
108
109    #[cfg(target_os = "android")]
110    #[pyattr]
111    use host_socket::{SOL_ATALK, SOL_AX25, SOL_IPX, SOL_NETROM, SOL_ROSE};
112
113    #[cfg(target_os = "freebsd")]
114    #[pyattr]
115    use host_socket::SO_SETFIB;
116
117    #[cfg(target_vendor = "apple")]
118    #[pyattr]
119    use host_socket::{
120        IP_ADD_SOURCE_MEMBERSHIP, IP_BLOCK_SOURCE, IP_DROP_SOURCE_MEMBERSHIP, IP_PKTINFO,
121        IP_RECVTTL, IP_UNBLOCK_SOURCE, IPPROTO_MAX, IPPROTO_SCTP, MSG_NOSIGNAL,
122        TCP_CONNECTION_INFO,
123    };
124
125    #[cfg(target_os = "linux")]
126    #[pyattr]
127    use host_socket::{
128        CAN_BCM, CAN_EFF_FLAG, CAN_EFF_MASK, CAN_ERR_FLAG, CAN_ERR_MASK, CAN_ISOTP, CAN_J1939,
129        CAN_RAW, CAN_RAW_ERR_FILTER, CAN_RAW_FD_FRAMES, CAN_RAW_FILTER, CAN_RAW_JOIN_FILTERS,
130        CAN_RAW_LOOPBACK, CAN_RAW_RECV_OWN_MSGS, CAN_RTR_FLAG, CAN_SFF_MASK, IPPROTO_MPTCP,
131        J1939_IDLE_ADDR, J1939_MAX_UNICAST_ADDR, J1939_NLA_BYTES_ACKED, J1939_NLA_PAD,
132        J1939_NO_ADDR, J1939_NO_NAME, J1939_NO_PGN, J1939_PGN_ADDRESS_CLAIMED,
133        J1939_PGN_ADDRESS_COMMANDED, J1939_PGN_MAX, J1939_PGN_PDU1_MAX, J1939_PGN_REQUEST,
134        SCM_J1939_DEST_ADDR, SCM_J1939_DEST_NAME, SCM_J1939_ERRQUEUE, SCM_J1939_PRIO,
135        SO_J1939_ERRQUEUE, SO_J1939_FILTER, SO_J1939_PROMISC, SO_J1939_SEND_PRIO, SOL_CAN_BASE,
136        SOL_CAN_RAW,
137    };
138
139    #[cfg(target_os = "linux")]
140    #[pyattr]
141    const J1939_EE_INFO_NONE: i32 = 0;
142    #[cfg(target_os = "linux")]
143    #[pyattr]
144    const J1939_EE_INFO_TX_ABORT: i32 = 1;
145    #[cfg(target_os = "linux")]
146    #[pyattr]
147    const J1939_FILTER_MAX: i32 = 512;
148
149    #[cfg(target_os = "linux")]
150    #[pyattr]
151    use host_socket::{
152        CAN_BCM_CAN_FD_FRAME, CAN_BCM_RX_ANNOUNCE_RESUME, CAN_BCM_RX_CHANGED, CAN_BCM_RX_CHECK_DLC,
153        CAN_BCM_RX_DELETE, CAN_BCM_RX_FILTER_ID, CAN_BCM_RX_NO_AUTOTIMER, CAN_BCM_RX_READ,
154        CAN_BCM_RX_RTR_FRAME, CAN_BCM_RX_SETUP, CAN_BCM_RX_STATUS, CAN_BCM_RX_TIMEOUT,
155        CAN_BCM_SETTIMER, CAN_BCM_STARTTIMER, CAN_BCM_TX_ANNOUNCE, CAN_BCM_TX_COUNTEVT,
156        CAN_BCM_TX_CP_CAN_ID, CAN_BCM_TX_DELETE, CAN_BCM_TX_EXPIRED, CAN_BCM_TX_READ,
157        CAN_BCM_TX_RESET_MULTI_IDX, CAN_BCM_TX_SEND, CAN_BCM_TX_SETUP, CAN_BCM_TX_STATUS,
158    };
159
160    #[cfg(all(target_os = "linux", target_env = "gnu"))]
161    #[pyattr]
162    use host_socket::SOL_RDS;
163
164    #[cfg(target_os = "netbsd")]
165    #[pyattr]
166    use host_socket::IPPROTO_VRRP;
167
168    #[cfg(target_vendor = "apple")]
169    #[pyattr]
170    use host_socket::{AF_SYSTEM, PF_SYSTEM, SYSPROTO_CONTROL, TCP_KEEPALIVE};
171
172    #[cfg(target_vendor = "apple")]
173    #[pyattr]
174    use host_socket::{
175        IPV6_DSTOPTS, IPV6_HOPOPTS, IPV6_NEXTHOP, IPV6_PATHMTU, IPV6_RECVDSTOPTS,
176        IPV6_RECVHOPLIMIT, IPV6_RECVHOPOPTS, IPV6_RECVPATHMTU, IPV6_RECVRTHDR, IPV6_RTHDR,
177        IPV6_RTHDR_TYPE_0, IPV6_RTHDRDSTOPTS, IPV6_USE_MIN_MTU,
178    };
179
180    #[cfg(windows)]
181    #[pyattr]
182    use host_socket::{
183        IPPORT_RESERVED, IPPROTO_IPV4, RCVALL_IPLEVEL, RCVALL_OFF, RCVALL_ON,
184        RCVALL_SOCKETLEVELONLY, SIO_KEEPALIVE_VALS, SIO_LOOPBACK_FAST_PATH, SIO_RCVALL,
185        SO_EXCLUSIVEADDRUSE,
186    };
187
188    #[cfg(not(windows))]
189    #[pyattr]
190    use host_socket::IPPORT_RESERVED;
191
192    #[pyattr]
193    use host_socket::IPPORT_USERRESERVED;
194
195    #[cfg(any(unix, target_os = "android"))]
196    #[pyattr]
197    use host_socket::{
198        EAI_SYSTEM, MSG_EOR, SO_ACCEPTCONN, SO_DEBUG, SO_DONTROUTE, SO_RCVLOWAT, SO_RCVTIMEO,
199        SO_SNDLOWAT, SO_SNDTIMEO,
200    };
201
202    #[cfg(any(target_os = "android", target_os = "linux"))]
203    #[pyattr]
204    use host_socket::{
205        ALG_OP_DECRYPT, ALG_OP_ENCRYPT, ALG_SET_AEAD_ASSOCLEN, ALG_SET_AEAD_AUTHSIZE, ALG_SET_IV,
206        ALG_SET_KEY, ALG_SET_OP, IP_DEFAULT_MULTICAST_LOOP, IP_RECVOPTS, IP_RETOPTS, IPV6_DSTOPTS,
207        IPV6_NEXTHOP, IPV6_PATHMTU, IPV6_RECVDSTOPTS, IPV6_RECVHOPLIMIT, IPV6_RECVHOPOPTS,
208        IPV6_RECVPATHMTU, IPV6_RTHDRDSTOPTS, NETLINK_CRYPTO, NETLINK_DNRTMSG, NETLINK_FIREWALL,
209        NETLINK_IP6_FW, NETLINK_NFLOG, NETLINK_ROUTE, NETLINK_USERSOCK, NETLINK_XFRM, SO_PASSSEC,
210        SO_PEERSEC, SOL_ALG,
211    };
212
213    #[cfg(any(target_os = "android", target_vendor = "apple"))]
214    #[pyattr]
215    use host_socket::{AI_DEFAULT, AI_MASK, AI_V4MAPPED_CFG};
216
217    #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
218    #[pyattr]
219    use host_socket::MSG_NOTIFICATION;
220
221    #[cfg(any(target_os = "fuchsia", target_os = "linux"))]
222    #[pyattr]
223    use host_socket::TCP_USER_TIMEOUT;
224
225    #[cfg(any(unix, target_os = "android", windows))]
226    #[pyattr]
227    use host_socket::{
228        INADDR_BROADCAST, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP, IP_MULTICAST_IF,
229        IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_TTL, IPV6_MULTICAST_HOPS, IPV6_MULTICAST_IF,
230        IPV6_MULTICAST_LOOP, IPV6_UNICAST_HOPS, IPV6_V6ONLY,
231    };
232
233    #[cfg(unix)]
234    #[pyattr]
235    use host_socket::{INADDR_ALLHOSTS_GROUP, INADDR_MAX_LOCAL_GROUP, INADDR_UNSPEC_GROUP};
236
237    #[cfg(windows)]
238    #[pyattr]
239    use host_socket::{INADDR_ALLHOSTS_GROUP, INADDR_MAX_LOCAL_GROUP, INADDR_UNSPEC_GROUP};
240
241    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
242    #[pyattr]
243    use host_socket::{
244        AF_ALG, AF_ASH, AF_ATMPVC, AF_ATMSVC, AF_AX25, AF_BRIDGE, AF_CAN, AF_ECONET, AF_IRDA,
245        AF_LLC, AF_NETBEUI, AF_NETLINK, AF_NETROM, AF_PACKET, AF_PPPOX, AF_RDS, AF_SECURITY,
246        AF_TIPC, AF_VSOCK, AF_WANPIPE, AF_X25, IP_TRANSPARENT, MSG_CONFIRM, MSG_ERRQUEUE,
247        MSG_FASTOPEN, MSG_MORE, PF_CAN, PF_PACKET, PF_RDS, SCM_CREDENTIALS, SO_BINDTODEVICE,
248        SO_MARK, SOL_IP, SOL_TIPC, SOL_UDP, TCP_CORK, TCP_DEFER_ACCEPT, TCP_LINGER2, TCP_QUICKACK,
249        TCP_SYNCNT, TCP_WINDOW_CLAMP,
250    };
251
252    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
253    #[pyattr]
254    use host_socket::{
255        SO_VM_SOCKETS_BUFFER_MAX_SIZE, SO_VM_SOCKETS_BUFFER_MIN_SIZE, SO_VM_SOCKETS_BUFFER_SIZE,
256        VM_SOCKETS_INVALID_VERSION, VMADDR_CID_ANY, VMADDR_CID_HOST, VMADDR_PORT_ANY,
257    };
258
259    // TODO: gated on https://github.com/rust-lang/libc/pull/1662
260    // // gated on presence of AF_VSOCK:
261    // #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
262    // #[pyattr(name = "IOCTL_VM_SOCKETS_GET_LOCAL_CID", once)]
263    // fn ioctl_vm_sockets_get_local_cid(_vm: &VirtualMachine) -> i32 {
264    //     c::_IO(7, 0xb9)
265    // }
266
267    #[cfg(not(any(target_os = "android", target_os = "fuchsia", target_os = "linux")))]
268    #[pyattr]
269    use host_socket::{SOL_IP, SOL_UDP};
270
271    #[cfg(any(target_os = "android", target_os = "linux", windows))]
272    #[pyattr]
273    use host_socket::{IP_OPTIONS, IPV6_HOPOPTS, IPV6_RECVRTHDR, IPV6_RTHDR};
274
275    #[cfg(any(
276        target_os = "dragonfly",
277        target_os = "freebsd",
278        target_vendor = "apple"
279    ))]
280    #[pyattr]
281    use host_socket::{IPPROTO_HELLO, IPPROTO_XTP, LOCAL_PEERCRED, MSG_EOF};
282
283    #[cfg(any(target_os = "netbsd", target_os = "openbsd", windows))]
284    #[pyattr]
285    use host_socket::{MSG_BCAST, MSG_MCAST};
286
287    #[cfg(any(
288        target_os = "android",
289        target_os = "fuchsia",
290        target_os = "freebsd",
291        target_os = "linux"
292    ))]
293    #[pyattr]
294    use host_socket::{IPPROTO_UDPLITE, TCP_CONGESTION};
295
296    #[cfg(any(
297        target_os = "android",
298        target_os = "fuchsia",
299        target_os = "freebsd",
300        target_os = "linux"
301    ))]
302    #[pyattr]
303    use host_socket::{UDPLITE_RECV_CSCOV, UDPLITE_SEND_CSCOV};
304
305    #[cfg(any(
306        target_os = "android",
307        target_os = "fuchsia",
308        target_os = "linux",
309        target_os = "openbsd"
310    ))]
311    #[pyattr]
312    use host_socket::AF_KEY;
313
314    #[cfg(any(
315        target_os = "android",
316        target_os = "fuchsia",
317        target_os = "linux",
318        target_os = "redox"
319    ))]
320    #[pyattr]
321    use host_socket::SO_DOMAIN;
322
323    #[cfg(any(
324        target_os = "android",
325        target_os = "fuchsia",
326        all(
327            target_os = "linux",
328            any(
329                target_arch = "aarch64",
330                target_arch = "x86",
331                target_arch = "loongarch64",
332                target_arch = "mips",
333                target_arch = "powerpc",
334                target_arch = "powerpc64",
335                target_arch = "riscv64",
336                target_arch = "s390x",
337                target_arch = "x86_64"
338            )
339        ),
340        target_os = "redox"
341    ))]
342    #[pyattr]
343    use host_socket::SO_PRIORITY;
344
345    #[cfg(any(
346        target_os = "dragonfly",
347        target_os = "freebsd",
348        target_os = "netbsd",
349        target_os = "openbsd"
350    ))]
351    #[pyattr]
352    use host_socket::IPPROTO_MOBILE;
353
354    #[cfg(any(
355        target_os = "dragonfly",
356        target_os = "freebsd",
357        target_os = "netbsd",
358        target_vendor = "apple"
359    ))]
360    #[pyattr]
361    use host_socket::SCM_CREDS;
362
363    #[cfg(any(
364        target_os = "freebsd",
365        target_os = "fuchsia",
366        target_os = "linux",
367        target_vendor = "apple"
368    ))]
369    #[pyattr]
370    use host_socket::TCP_FASTOPEN;
371
372    #[cfg(any(
373        target_os = "android",
374        target_os = "freebsd",
375        target_os = "fuchsia",
376        all(
377            target_os = "linux",
378            any(
379                target_arch = "aarch64",
380                target_arch = "x86",
381                target_arch = "loongarch64",
382                target_arch = "mips",
383                target_arch = "powerpc",
384                target_arch = "powerpc64",
385                target_arch = "riscv64",
386                target_arch = "s390x",
387                target_arch = "x86_64"
388            )
389        ),
390        target_os = "redox"
391    ))]
392    #[pyattr]
393    use host_socket::SO_PROTOCOL;
394
395    #[cfg(any(
396        target_os = "android",
397        target_os = "dragonfly",
398        target_os = "freebsd",
399        target_os = "linux",
400        target_vendor = "apple",
401        windows
402    ))]
403    #[pyattr]
404    use host_socket::IPV6_DONTFRAG;
405
406    #[cfg(any(
407        target_os = "android",
408        target_os = "dragonfly",
409        target_os = "fuchsia",
410        target_os = "linux",
411        target_os = "redox"
412    ))]
413    #[pyattr]
414    use host_socket::{SO_PASSCRED, SO_PEERCRED};
415
416    #[cfg(any(
417        target_os = "android",
418        target_os = "freebsd",
419        target_os = "fuchsia",
420        target_os = "linux",
421        target_os = "netbsd"
422    ))]
423    #[pyattr]
424    use host_socket::TCP_INFO;
425
426    #[cfg(any(
427        target_os = "android",
428        target_os = "freebsd",
429        target_os = "fuchsia",
430        target_os = "linux",
431        target_vendor = "apple"
432    ))]
433    #[pyattr]
434    use host_socket::IP_RECVTOS;
435
436    #[cfg(any(
437        target_os = "android",
438        target_os = "netbsd",
439        target_os = "redox",
440        target_vendor = "apple",
441        windows
442    ))]
443    #[pyattr]
444    use host_socket::NI_MAXSERV;
445
446    #[cfg(any(
447        target_os = "dragonfly",
448        target_os = "freebsd",
449        target_os = "netbsd",
450        target_os = "openbsd",
451        target_vendor = "apple"
452    ))]
453    #[pyattr]
454    use host_socket::{IPPROTO_EON, IPPROTO_IPCOMP};
455
456    #[cfg(any(
457        target_os = "dragonfly",
458        target_os = "freebsd",
459        target_os = "netbsd",
460        target_vendor = "apple",
461        windows
462    ))]
463    #[pyattr]
464    use host_socket::IPPROTO_ND;
465
466    #[cfg(any(
467        target_os = "android",
468        target_os = "dragonfly",
469        target_os = "freebsd",
470        target_os = "linux",
471        target_vendor = "apple",
472        windows
473    ))]
474    #[pyattr]
475    use host_socket::{IPV6_CHECKSUM, IPV6_HOPLIMIT};
476
477    #[cfg(any(
478        target_os = "android",
479        target_os = "freebsd",
480        target_os = "fuchsia",
481        target_os = "linux",
482        target_os = "netbsd"
483    ))]
484    #[pyattr]
485    use host_socket::IPPROTO_SCTP; // also in windows
486
487    #[cfg(any(
488        target_os = "android",
489        target_os = "freebsd",
490        target_os = "fuchsia",
491        target_os = "linux",
492        target_vendor = "apple",
493        windows
494    ))]
495    #[pyattr]
496    use host_socket::{AI_ALL, AI_V4MAPPED};
497
498    #[cfg(any(
499        target_os = "android",
500        target_os = "linux",
501        target_os = "netbsd",
502        target_os = "openbsd",
503        target_vendor = "apple",
504        windows
505    ))]
506    #[pyattr]
507    use host_socket::EAI_NODATA;
508
509    #[cfg(any(
510        target_os = "dragonfly",
511        target_os = "freebsd",
512        target_os = "netbsd",
513        target_os = "openbsd",
514        target_vendor = "apple",
515        windows
516    ))]
517    #[pyattr]
518    use host_socket::{
519        AF_LINK, IP_RECVDSTADDR, IPPROTO_GGP, IPV6_JOIN_GROUP, IPV6_LEAVE_GROUP, SO_USELOOPBACK,
520    };
521
522    #[cfg(any(
523        target_os = "android",
524        target_os = "dragonfly",
525        target_os = "freebsd",
526        target_os = "fuchsia",
527        target_os = "linux",
528        target_os = "netbsd",
529        target_os = "openbsd"
530    ))]
531    #[pyattr]
532    use host_socket::{MSG_CMSG_CLOEXEC, MSG_NOSIGNAL};
533
534    #[cfg(any(
535        target_os = "android",
536        target_os = "dragonfly",
537        target_os = "freebsd",
538        target_os = "fuchsia",
539        target_os = "linux",
540        target_os = "netbsd",
541        target_os = "redox"
542    ))]
543    #[pyattr]
544    use host_socket::TCP_KEEPIDLE;
545
546    #[cfg(any(
547        target_os = "android",
548        target_os = "dragonfly",
549        target_os = "freebsd",
550        target_os = "fuchsia",
551        target_os = "linux",
552        target_os = "netbsd",
553        target_vendor = "apple"
554    ))]
555    #[pyattr]
556    use host_socket::{TCP_KEEPCNT, TCP_KEEPINTVL};
557
558    #[cfg(any(
559        target_os = "android",
560        target_os = "dragonfly",
561        target_os = "freebsd",
562        target_os = "fuchsia",
563        target_os = "linux",
564        target_os = "netbsd",
565        target_os = "openbsd",
566        target_os = "redox"
567    ))]
568    #[pyattr]
569    use host_socket::{SOCK_CLOEXEC, SOCK_NONBLOCK};
570
571    #[cfg(any(
572        target_os = "android",
573        target_os = "dragonfly",
574        target_os = "freebsd",
575        target_os = "fuchsia",
576        target_os = "linux",
577        target_os = "netbsd",
578        target_os = "openbsd",
579        target_vendor = "apple"
580    ))]
581    #[pyattr]
582    use host_socket::{
583        AF_ROUTE, AF_SNA, EAI_OVERFLOW, IPPROTO_GRE, IPPROTO_RSVP, IPPROTO_TP, IPV6_RECVPKTINFO,
584        MSG_DONTWAIT, SCM_RIGHTS, TCP_MAXSEG,
585    };
586
587    #[cfg(any(
588        target_os = "android",
589        target_os = "dragonfly",
590        target_os = "freebsd",
591        target_os = "linux",
592        target_os = "netbsd",
593        target_os = "openbsd",
594        target_vendor = "apple",
595        windows
596    ))]
597    #[pyattr]
598    use host_socket::IPV6_PKTINFO;
599
600    #[cfg(any(
601        target_os = "android",
602        target_os = "freebsd",
603        target_os = "fuchsia",
604        target_os = "linux",
605        target_os = "netbsd",
606        target_os = "openbsd",
607        target_vendor = "apple",
608        windows
609    ))]
610    #[pyattr]
611    use host_socket::AI_CANONNAME;
612
613    #[cfg(any(
614        target_os = "android",
615        target_os = "dragonfly",
616        target_os = "freebsd",
617        target_os = "fuchsia",
618        target_os = "linux",
619        target_os = "netbsd",
620        target_os = "openbsd",
621        target_vendor = "apple",
622        windows
623    ))]
624    #[pyattr]
625    use host_socket::{
626        EAI_AGAIN, EAI_BADFLAGS, EAI_FAIL, EAI_FAMILY, EAI_MEMORY, EAI_NONAME, EAI_SERVICE,
627        EAI_SOCKTYPE, IP_HDRINCL, IP_TOS, IPV6_RECVTCLASS, IPV6_TCLASS, SOMAXCONN,
628    };
629
630    #[cfg(not(any(
631        target_os = "android",
632        target_os = "dragonfly",
633        target_os = "freebsd",
634        target_os = "fuchsia",
635        target_os = "linux",
636        target_os = "netbsd",
637        target_os = "openbsd",
638        target_vendor = "apple",
639        windows
640    )))]
641    #[pyattr]
642    use host_socket::SOMAXCONN;
643
644    // HERE IS WHERE THE BLUETOOTH CONSTANTS START
645    // TODO: there should be a more intelligent way of detecting bluetooth on a platform.
646    //       CPython uses header-detection, but blocks NetBSD and DragonFly BSD
647    #[cfg(any(
648        target_os = "android",
649        target_os = "freebsd",
650        target_os = "fuchsia",
651        target_os = "linux",
652        target_os = "openbsd"
653    ))]
654    #[pyattr]
655    use host_socket::AF_BLUETOOTH;
656
657    #[cfg(any(
658        target_os = "android",
659        target_os = "freebsd",
660        target_os = "fuchsia",
661        target_os = "linux",
662        target_os = "openbsd"
663    ))]
664    #[pyattr]
665    use host_socket::{BDADDR_ANY, BDADDR_LOCAL};
666
667    #[cfg(any(
668        target_os = "android",
669        target_os = "fuchsia",
670        target_os = "linux",
671        target_os = "openbsd"
672    ))]
673    #[pyattr]
674    const BTPROTO_L2CAP: i32 = 0;
675    #[cfg(target_os = "freebsd")]
676    #[pyattr]
677    const BTPROTO_L2CAP: i32 = 135;
678    #[cfg(any(
679        target_os = "android",
680        target_os = "fuchsia",
681        target_os = "linux",
682        target_os = "openbsd"
683    ))]
684    #[pyattr]
685    const BTPROTO_HCI: i32 = 1;
686    #[cfg(target_os = "freebsd")]
687    #[pyattr]
688    const BTPROTO_HCI: i32 = 134;
689    #[cfg(any(
690        target_os = "android",
691        target_os = "fuchsia",
692        target_os = "linux",
693        target_os = "openbsd"
694    ))]
695    #[pyattr]
696    const BTPROTO_SCO: i32 = 2;
697    #[cfg(target_os = "freebsd")]
698    #[pyattr]
699    const BTPROTO_SCO: i32 = 137;
700    #[cfg(any(
701        target_os = "android",
702        target_os = "fuchsia",
703        target_os = "linux",
704        target_os = "openbsd"
705    ))]
706    #[pyattr]
707    const BTPROTO_RFCOMM: i32 = 3;
708    #[cfg(target_os = "freebsd")]
709    #[pyattr]
710    const BTPROTO_RFCOMM: i32 = 136;
711    #[cfg(any(
712        target_os = "android",
713        target_os = "fuchsia",
714        target_os = "linux",
715        target_os = "openbsd"
716    ))]
717    #[pyattr]
718    const SOL_HCI: i32 = 0;
719    #[cfg(target_os = "freebsd")]
720    #[pyattr]
721    const SOL_HCI: i32 = 0x0802;
722    #[cfg(any(
723        target_os = "android",
724        target_os = "fuchsia",
725        target_os = "linux",
726        target_os = "openbsd"
727    ))]
728    #[pyattr]
729    const HCI_DATA_DIR: i32 = 1;
730    #[cfg(target_os = "freebsd")]
731    #[pyattr]
732    const HCI_DATA_DIR: i32 = 2;
733    #[cfg(any(
734        target_os = "android",
735        target_os = "fuchsia",
736        target_os = "linux",
737        target_os = "openbsd"
738    ))]
739    #[pyattr]
740    const SOL_L2CAP: i32 = 6;
741    #[cfg(target_os = "freebsd")]
742    #[pyattr]
743    const SOL_L2CAP: i32 = 0x1609;
744    #[cfg(any(
745        target_os = "android",
746        target_os = "fuchsia",
747        target_os = "linux",
748        target_os = "openbsd"
749    ))]
750    #[pyattr]
751    const SOL_SCO: i32 = 17;
752    #[cfg(target_os = "freebsd")]
753    #[pyattr]
754    const SOL_SCO: i32 = 0x0209;
755    #[cfg(any(
756        target_os = "android",
757        target_os = "fuchsia",
758        target_os = "linux",
759        target_os = "openbsd"
760    ))]
761    #[pyattr]
762    const SOL_RFCOMM: i32 = 18;
763    #[cfg(target_os = "freebsd")]
764    #[pyattr]
765    const SOL_RFCOMM: i32 = 0x0816;
766
767    // Linux <bluetooth/bluetooth.h> / <bluetooth/hci.h> / <bluetooth/l2cap.h>
768    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
769    #[pyattr]
770    const SOL_BLUETOOTH: i32 = 274;
771    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
772    #[pyattr]
773    const HCI_DEV_NONE: i32 = 0xffff;
774    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
775    #[pyattr]
776    const HCI_CHANNEL_RAW: i32 = 0;
777    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
778    #[pyattr]
779    const HCI_CHANNEL_USER: i32 = 1;
780    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
781    #[pyattr]
782    const HCI_CHANNEL_MONITOR: i32 = 2;
783    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
784    #[pyattr]
785    const HCI_CHANNEL_CONTROL: i32 = 3;
786    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
787    #[pyattr]
788    const HCI_CHANNEL_LOGGING: i32 = 4;
789    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
790    #[pyattr]
791    const HCI_TIME_STAMP: i32 = 3;
792    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
793    #[pyattr]
794    const BT_SECURITY: i32 = 4;
795    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
796    #[pyattr]
797    const BT_SECURITY_SDP: i32 = 0;
798    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
799    #[pyattr]
800    const BT_SECURITY_LOW: i32 = 1;
801    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
802    #[pyattr]
803    const BT_SECURITY_MEDIUM: i32 = 2;
804    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
805    #[pyattr]
806    const BT_SECURITY_HIGH: i32 = 3;
807    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
808    #[pyattr]
809    const BT_SECURITY_FIPS: i32 = 4;
810    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
811    #[pyattr]
812    const BT_FLUSHABLE: i32 = 8;
813    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
814    #[pyattr]
815    const BT_FLUSHABLE_OFF: i32 = 0;
816    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
817    #[pyattr]
818    const BT_FLUSHABLE_ON: i32 = 1;
819    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
820    #[pyattr]
821    const BT_POWER: i32 = 9;
822    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
823    #[pyattr]
824    const BT_POWER_FORCE_ACTIVE_OFF: i32 = 0;
825    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
826    #[pyattr]
827    const BT_POWER_FORCE_ACTIVE_ON: i32 = 1;
828    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
829    #[pyattr]
830    const BT_CHANNEL_POLICY: i32 = 10;
831    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
832    #[pyattr]
833    const BT_CHANNEL_POLICY_BREDR_ONLY: i32 = 0;
834    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
835    #[pyattr]
836    const BT_CHANNEL_POLICY_BREDR_PREFERRED: i32 = 1;
837    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
838    #[pyattr]
839    const BT_CHANNEL_POLICY_AMP_PREFERRED: i32 = 2;
840    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
841    #[pyattr]
842    const BT_VOICE: i32 = 11;
843    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
844    #[pyattr]
845    const BT_VOICE_TRANSPARENT: i32 = 0x0003;
846    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
847    #[pyattr]
848    const BT_VOICE_CVSD_16BIT: i32 = 0x0060;
849    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
850    #[pyattr]
851    const BT_SNDMTU: i32 = 12;
852    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
853    #[pyattr]
854    const BT_RCVMTU: i32 = 13;
855    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
856    #[pyattr]
857    const BT_PHY: i32 = 14;
858    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
859    #[pyattr]
860    const BT_PHY_BR_1M_1SLOT: i32 = 0x0001;
861    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
862    #[pyattr]
863    const BT_MODE: i32 = 16;
864    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
865    #[pyattr]
866    const BT_MODE_BASIC: i32 = 0x00;
867    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
868    #[pyattr]
869    const L2CAP_LM: i32 = 0x03;
870    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
871    #[pyattr]
872    const L2CAP_LM_MASTER: i32 = 0x0001;
873    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
874    #[pyattr]
875    const L2CAP_LM_AUTH: i32 = 0x0002;
876    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
877    #[pyattr]
878    const L2CAP_LM_ENCRYPT: i32 = 0x0004;
879    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
880    #[pyattr]
881    const L2CAP_LM_TRUSTED: i32 = 0x0008;
882    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
883    #[pyattr]
884    const L2CAP_LM_RELIABLE: i32 = 0x0010;
885    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
886    #[pyattr]
887    const L2CAP_LM_SECURE: i32 = 0x0020;
888    #[cfg(any(
889        target_os = "android",
890        target_os = "freebsd",
891        target_os = "fuchsia",
892        target_os = "linux"
893    ))]
894    #[pyattr]
895    const BDADDR_BREDR: i32 = 0x00;
896    #[cfg(any(
897        target_os = "android",
898        target_os = "freebsd",
899        target_os = "fuchsia",
900        target_os = "linux"
901    ))]
902    #[pyattr]
903    const BDADDR_LE_PUBLIC: i32 = 0x01;
904    #[cfg(any(
905        target_os = "android",
906        target_os = "freebsd",
907        target_os = "fuchsia",
908        target_os = "linux"
909    ))]
910    #[pyattr]
911    const BDADDR_LE_RANDOM: i32 = 0x02;
912    #[cfg(any(
913        target_os = "android",
914        target_os = "freebsd",
915        target_os = "fuchsia",
916        target_os = "linux"
917    ))]
918    #[pyattr]
919    const HCI_FILTER: i32 = 2;
920    // HERE IS WHERE THE BLUETOOTH CONSTANTS END
921
922    #[cfg(windows)]
923    #[pyattr]
924    use host_socket::{
925        AF_BLUETOOTH, AF_HYPERV, AF_IRDA, AF_SNA, BTHPROTO_RFCOMM,
926        BTHPROTO_RFCOMM as BTPROTO_RFCOMM, HV_PROTOCOL_RAW, HVSOCKET_ADDRESS_FLAG_PASSTHRU,
927        HVSOCKET_CONNECT_TIMEOUT, HVSOCKET_CONNECT_TIMEOUT_MAX, HVSOCKET_CONNECTED_SUSPEND,
928        IP_ADD_SOURCE_MEMBERSHIP, IP_BLOCK_SOURCE, IP_DROP_SOURCE_MEMBERSHIP, IP_PKTINFO,
929        IP_RECVERR, IP_RECVTOS, IP_RECVTTL, IP_UNBLOCK_SOURCE, IPPROTO_CBT, IPPROTO_ICLFXBM,
930        IPPROTO_IGP, IPPROTO_L2TP, IPPROTO_PGM, IPPROTO_RDP, IPPROTO_SCTP, IPPROTO_ST,
931        IPV6_RECVERR, MSG_ERRQUEUE, RCVALL_MAX, SIO_TCP_SET_ACK_FREQUENCY, SO_ACCEPTCONN,
932        SO_BTH_ENCRYPT, SO_BTH_MTU, SO_BTH_MTU_MAX, SO_BTH_MTU_MIN, SO_DEBUG, SO_DONTROUTE,
933        SO_ORIGINAL_DST, SO_RCVLOWAT, SO_RCVTIMEO, SO_SNDLOWAT, SO_SNDTIMEO, SOL_RFCOMM,
934        TCP_FASTOPEN, TCP_KEEPCNT, TCP_KEEPIDLE, TCP_KEEPINTVL,
935    };
936
937    #[cfg(windows)]
938    #[pyattr]
939    const BDADDR_ANY: &str = host_socket::BDADDR_ANY;
940    #[cfg(windows)]
941    #[pyattr]
942    const BDADDR_LOCAL: &str = host_socket::BDADDR_LOCAL;
943
944    #[cfg(windows)]
945    #[pyattr]
946    const HV_GUID_ZERO: &str = host_socket::HV_GUID_ZERO;
947    #[cfg(windows)]
948    #[pyattr]
949    const HV_GUID_WILDCARD: &str = host_socket::HV_GUID_WILDCARD;
950    #[cfg(windows)]
951    #[pyattr]
952    const HV_GUID_BROADCAST: &str = host_socket::HV_GUID_BROADCAST;
953    #[cfg(windows)]
954    #[pyattr]
955    const HV_GUID_CHILDREN: &str = host_socket::HV_GUID_CHILDREN;
956    #[cfg(windows)]
957    #[pyattr]
958    const HV_GUID_LOOPBACK: &str = host_socket::HV_GUID_LOOPBACK;
959    #[cfg(windows)]
960    #[pyattr]
961    const HV_GUID_PARENT: &str = host_socket::HV_GUID_PARENT;
962
963    #[pyattr]
964    fn error(vm: &VirtualMachine) -> PyTypeRef {
965        vm.ctx.exceptions.os_error.to_owned()
966    }
967
968    #[pyattr]
969    fn timeout(vm: &VirtualMachine) -> PyTypeRef {
970        vm.ctx.exceptions.timeout_error.to_owned()
971    }
972
973    #[pyattr(once)]
974    fn herror(vm: &VirtualMachine) -> PyTypeRef {
975        vm.ctx.new_exception_type(
976            "socket",
977            "herror",
978            Some(vec![vm.ctx.exceptions.os_error.to_owned()]),
979        )
980    }
981    #[pyattr(once)]
982    fn gaierror(vm: &VirtualMachine) -> PyTypeRef {
983        vm.ctx.new_exception_type(
984            "socket",
985            "gaierror",
986            Some(vec![vm.ctx.exceptions.os_error.to_owned()]),
987        )
988    }
989
990    #[pyfunction]
991    const fn htonl(integer: u32) -> u32 {
992        u32::to_be(integer)
993    }
994
995    #[pyfunction]
996    const fn htons(integer: u16) -> u16 {
997        u16::to_be(integer)
998    }
999
1000    #[pyfunction]
1001    const fn ntohl(integer: u32) -> u32 {
1002        u32::from_be(integer)
1003    }
1004
1005    #[pyfunction]
1006    const fn ntohs(integer: u16) -> u16 {
1007        u16::from_be(integer)
1008    }
1009
1010    #[cfg(unix)]
1011    type RawSocket = std::os::unix::io::RawFd;
1012    #[cfg(windows)]
1013    type RawSocket = std::os::windows::raw::SOCKET;
1014
1015    #[cfg(unix)]
1016    macro_rules! errcode {
1017        ($e:ident) => {
1018            c::$e
1019        };
1020    }
1021
1022    #[cfg(windows)]
1023    macro_rules! errcode {
1024    ($e:ident) => {
1025        paste::paste!(c::[<WSA $e>])
1026    };
1027}
1028
1029    fn get_raw_sock(obj: &PyObject, vm: &VirtualMachine) -> PyResult<RawSocket> {
1030        #[cfg(unix)]
1031        type CastFrom = core::ffi::c_long;
1032        #[cfg(windows)]
1033        type CastFrom = core::ffi::c_longlong;
1034
1035        // should really just be to_index() but test_socket tests the error messages explicitly
1036        if obj.fast_isinstance(vm.ctx.types.float_type) {
1037            return Err(vm.new_type_error("integer argument expected, got float"));
1038        }
1039        let int = obj
1040            .try_index_opt(vm)
1041            .unwrap_or_else(|| Err(vm.new_type_error("an integer is required")))?;
1042        int.try_to_primitive::<CastFrom>(vm)
1043            .map(|sock| sock as RawSocket)
1044    }
1045
1046    #[cfg(target_os = "linux")]
1047    #[derive(FromArgs)]
1048    struct SendmsgAfalgArgs {
1049        #[pyarg(any, default)]
1050        msg: Vec<ArgBytesLike>,
1051        #[pyarg(named)]
1052        op: u32,
1053        #[pyarg(named, default)]
1054        iv: Option<ArgBytesLike>,
1055        #[pyarg(named, default)]
1056        assoclen: OptionalArg<isize>,
1057        #[pyarg(named, default)]
1058        flags: i32,
1059    }
1060
1061    #[pyattr(name = "socket")]
1062    #[pyattr(name = "SocketType")]
1063    #[pyclass(name = "socket")]
1064    #[derive(Debug, PyPayload)]
1065    pub struct PySocket {
1066        #[pymember(name = "type")]
1067        kind: AtomicI32,
1068        #[pymember]
1069        family: AtomicI32,
1070        #[pymember]
1071        proto: AtomicI32,
1072        pub(crate) timeout: AtomicCell<f64>,
1073        sock: PyRwLock<Option<Socket>>,
1074    }
1075
1076    const _: () = assert!(core::mem::size_of::<Option<Socket>>() == core::mem::size_of::<Socket>());
1077
1078    impl Default for PySocket {
1079        fn default() -> Self {
1080            Self {
1081                kind: AtomicI32::new(0),
1082                family: AtomicI32::new(0),
1083                proto: AtomicI32::new(0),
1084                timeout: AtomicCell::new(-1.0),
1085                sock: PyRwLock::new(None),
1086            }
1087        }
1088    }
1089
1090    #[cfg(windows)]
1091    const CLOSED_ERR: i32 = c::WSAENOTSOCK;
1092    #[cfg(unix)]
1093    const CLOSED_ERR: i32 = c::EBADF;
1094
1095    impl Read for &PySocket {
1096        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1097            (&mut &*self.sock_snapshot()?).read(buf)
1098        }
1099    }
1100
1101    impl Write for &PySocket {
1102        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1103            (&mut &*self.sock_snapshot()?).write(buf)
1104        }
1105
1106        fn flush(&mut self) -> std::io::Result<()> {
1107            (&mut &*self.sock_snapshot()?).flush()
1108        }
1109    }
1110
1111    impl PySocket {
1112        pub fn sock_opt(&self) -> Option<PyMappedRwLockReadGuard<'_, Socket>> {
1113            let sock = PyRwLockReadGuard::try_map(self.sock.read(), |sock| sock.as_ref());
1114            sock.ok()
1115        }
1116
1117        pub fn sock(&self) -> io::Result<PyMappedRwLockReadGuard<'_, Socket>> {
1118            self.sock_opt()
1119                .ok_or_else(|| io::Error::from_raw_os_error(CLOSED_ERR))
1120        }
1121
1122        /// Snapshot the inner socket without holding `self.sock` across a syscall.
1123        ///
1124        /// Blocking accept/recv/send must not keep the RwLock: `close()` needs
1125        /// the write side, and a lock held by a thread that did not survive
1126        /// `fork()` stays locked forever in the child.
1127        pub(crate) fn sock_snapshot(&self) -> io::Result<ManuallyDrop<Socket>> {
1128            let guard = self.sock()?;
1129            let fd = sock_fileno(&guard);
1130            drop(guard);
1131            // SAFETY: PySocket remains the owner of `fd`. Drop is suppressed so
1132            // this wrapper does not close it. A concurrent close() may
1133            // invalidate `fd`; the syscall then fails with EBADF.
1134            Ok(ManuallyDrop::new(unsafe { sock_from_raw_unchecked(fd) }))
1135        }
1136
1137        fn init_inner(
1138            &self,
1139            family: i32,
1140            socket_kind: i32,
1141            proto: i32,
1142            sock: Socket,
1143        ) -> io::Result<()> {
1144            self.family.store(family, Ordering::Relaxed);
1145            // Mask out SOCK_NONBLOCK and SOCK_CLOEXEC flags from stored type
1146            // to ensure consistent cross-platform behavior
1147            #[cfg(any(
1148                target_os = "android",
1149                target_os = "dragonfly",
1150                target_os = "freebsd",
1151                target_os = "fuchsia",
1152                target_os = "illumos",
1153                target_os = "linux",
1154                target_os = "netbsd",
1155                target_os = "openbsd",
1156                target_os = "redox"
1157            ))]
1158            let masked_kind = socket_kind & !(c::SOCK_NONBLOCK | c::SOCK_CLOEXEC);
1159            #[cfg(not(any(
1160                target_os = "android",
1161                target_os = "dragonfly",
1162                target_os = "freebsd",
1163                target_os = "fuchsia",
1164                target_os = "illumos",
1165                target_os = "linux",
1166                target_os = "netbsd",
1167                target_os = "openbsd",
1168                target_os = "redox"
1169            )))]
1170            let masked_kind = socket_kind;
1171            self.kind.store(masked_kind, Ordering::Relaxed);
1172            self.proto.store(proto, Ordering::Relaxed);
1173            let mut s = self.sock.write();
1174            let sock = s.insert(sock);
1175            // If SOCK_NONBLOCK is set, use timeout 0 (non-blocking)
1176            #[cfg(any(
1177                target_os = "android",
1178                target_os = "dragonfly",
1179                target_os = "freebsd",
1180                target_os = "fuchsia",
1181                target_os = "illumos",
1182                target_os = "linux",
1183                target_os = "netbsd",
1184                target_os = "openbsd",
1185                target_os = "redox"
1186            ))]
1187            let timeout = if socket_kind & c::SOCK_NONBLOCK != 0 {
1188                0.0
1189            } else {
1190                DEFAULT_TIMEOUT.load()
1191            };
1192            #[cfg(not(any(
1193                target_os = "android",
1194                target_os = "dragonfly",
1195                target_os = "freebsd",
1196                target_os = "fuchsia",
1197                target_os = "illumos",
1198                target_os = "linux",
1199                target_os = "netbsd",
1200                target_os = "openbsd",
1201                target_os = "redox"
1202            )))]
1203            let timeout = DEFAULT_TIMEOUT.load();
1204            self.timeout.store(timeout);
1205            if timeout >= 0.0 {
1206                sock.set_nonblocking(true)?;
1207            }
1208            Ok(())
1209        }
1210
1211        /// returns Err(blocking)
1212        pub fn get_timeout(&self) -> Result<Duration, bool> {
1213            let timeout = self.timeout.load();
1214            if timeout > 0.0 {
1215                Ok(Duration::from_secs_f64(timeout))
1216            } else {
1217                Err(timeout != 0.0)
1218            }
1219        }
1220
1221        fn sock_op<F, R>(
1222            &self,
1223            vm: &VirtualMachine,
1224            wait_kind: SockWaitKind,
1225            f: F,
1226        ) -> Result<R, IoOrPyException>
1227        where
1228            F: FnMut() -> io::Result<R>,
1229        {
1230            let timeout = self.get_timeout().ok();
1231            let mut deadline = None;
1232            self.sock_op_timeout_err(vm, wait_kind, &mut deadline, timeout, f)
1233        }
1234
1235        fn sock_op_timeout_err<F, R>(
1236            &self,
1237            vm: &VirtualMachine,
1238            wait_kind: SockWaitKind,
1239            deadline: &mut Option<Deadline>,
1240            timeout: Option<Duration>,
1241            mut f: F,
1242        ) -> Result<R, IoOrPyException>
1243        where
1244            F: FnMut() -> io::Result<R>,
1245        {
1246            loop {
1247                if timeout.is_some() || matches!(wait_kind, SockWaitKind::Connect) {
1248                    let sock = self.sock_snapshot()?;
1249                    // Start the clock after the snapshot so lock/scheduling
1250                    // delay is not subtracted from a short timeout before poll.
1251                    if deadline.is_none() {
1252                        *deadline = timeout.map(Deadline::new);
1253                    }
1254                    sock_wait_deadline(&sock, wait_kind, deadline.as_ref(), vm)?;
1255                }
1256
1257                let err = loop {
1258                    // Detach thread state around the blocking syscall so
1259                    // stop-the-world can park this thread (e.g. before fork).
1260                    match vm.allow_threads(&mut f) {
1261                        Ok(x) => return Ok(x),
1262                        Err(e) if e.kind() == io::ErrorKind::Interrupted => vm.check_signals()?,
1263                        Err(e) => break e,
1264                    }
1265                };
1266                if timeout.is_some() && err.kind() == io::ErrorKind::WouldBlock {
1267                    continue;
1268                }
1269                return Err(err.into());
1270            }
1271        }
1272
1273        fn extract_address(
1274            &self,
1275            addr: PyObjectRef,
1276            caller: &str,
1277            vm: &VirtualMachine,
1278        ) -> Result<host_socket::raw::SockAddr, IoOrPyException> {
1279            let family = self.family.load(Ordering::Relaxed);
1280            match family {
1281                #[cfg(unix)]
1282                c::AF_UNIX => {
1283                    use crate::vm::function::ArgStrOrBytesLike;
1284                    use std::os::unix::ffi::OsStrExt;
1285                    let buf = ArgStrOrBytesLike::try_from_object(vm, addr)?;
1286                    let bytes = &*buf.borrow_bytes();
1287                    let path = match &buf {
1288                        ArgStrOrBytesLike::Buf(_) => ffi::OsStr::from_bytes(bytes).into(),
1289                        ArgStrOrBytesLike::Str(s) => vm.fsencode(s)?,
1290                    };
1291                    host_socket::raw::SockAddr::unix(path)
1292                        .map_err(|_| vm.new_os_error("AF_UNIX path too long").into())
1293                }
1294                c::AF_INET => {
1295                    let tuple: PyTupleRef = addr.downcast().map_err(|obj| {
1296                        vm.new_type_error(format!(
1297                            "{}(): AF_INET address must be tuple, not {}",
1298                            caller,
1299                            obj.class().name()
1300                        ))
1301                    })?;
1302                    if tuple.as_slice().len() != 2 {
1303                        return Err(vm
1304                            .new_type_error("AF_INET address must be a pair (host, post)")
1305                            .into());
1306                    }
1307                    let addr = Address::from_tuple(tuple.as_slice(), vm)?;
1308                    let mut addr4 = get_addr(vm, addr.host, c::AF_INET)?;
1309                    match &mut addr4 {
1310                        SocketAddr::V4(addr4) => {
1311                            addr4.set_port(addr.port);
1312                        }
1313                        SocketAddr::V6(_) => unreachable!(),
1314                    }
1315                    Ok(addr4.into())
1316                }
1317                c::AF_INET6 => {
1318                    let tuple: PyTupleRef = addr.downcast().map_err(|obj| {
1319                        vm.new_type_error(format!(
1320                            "{}(): AF_INET6 address must be tuple, not {}",
1321                            caller,
1322                            obj.class().name()
1323                        ))
1324                    })?;
1325                    match tuple.as_slice().len() {
1326                        2..=4 => {}
1327                        _ => return Err(vm.new_type_error(
1328                            "AF_INET6 address must be a tuple (host, port[, flowinfo[, scopeid]])",
1329                        ).into()),
1330                    }
1331                    let (addr, flowinfo, scopeid) = Address::from_tuple_ipv6(tuple.as_slice(), vm)?;
1332                    let mut addr6 = get_addr(vm, addr.host, c::AF_INET6)?;
1333                    match &mut addr6 {
1334                        SocketAddr::V6(addr6) => {
1335                            addr6.set_port(addr.port);
1336                            addr6.set_flowinfo(flowinfo);
1337                            addr6.set_scope_id(scopeid);
1338                        }
1339                        SocketAddr::V4(_) => unreachable!(),
1340                    }
1341                    Ok(addr6.into())
1342                }
1343                #[cfg(windows)]
1344                family if family == c::AF_HYPERV => {
1345                    if self.proto.load(Ordering::Relaxed) != host_socket::HV_PROTOCOL_RAW {
1346                        return Err(vm
1347                            .new_os_error(format!(
1348                                "{caller}(): unsupported AF_HYPERV protocol: {}",
1349                                self.proto.load(Ordering::Relaxed)
1350                            ))
1351                            .into());
1352                    }
1353                    let tuple: PyTupleRef = addr.downcast().map_err(|obj| {
1354                        vm.new_type_error(format!(
1355                            "{caller}(): AF_HYPERV address must be tuple, not {}",
1356                            obj.class().name()
1357                        ))
1358                    })?;
1359                    if tuple.as_slice().len() != 2 {
1360                        return Err(vm
1361                            .new_type_error(
1362                                "AF_HYPERV address must be a str tuple (vm_id, service_id)",
1363                            )
1364                            .into());
1365                    }
1366                    let vm_id: PyStrRef = tuple.as_slice()[0].clone().downcast().map_err(|_| {
1367                        vm.new_type_error(
1368                            "AF_HYPERV address must be a str tuple (vm_id, service_id)",
1369                        )
1370                    })?;
1371                    let service_id: PyStrRef =
1372                        tuple.as_slice()[1].clone().downcast().map_err(|_| {
1373                            vm.new_type_error(
1374                                "AF_HYPERV address must be a str tuple (vm_id, service_id)",
1375                            )
1376                        })?;
1377                    let vm_wide = vm_id.as_wtf8().to_wide_cstring().map_err(|_| {
1378                        vm.new_value_error(format!(
1379                            "{caller}(): AF_HYPERV address vm_id is not a valid UUID string"
1380                        ))
1381                    })?;
1382                    let service_wide = service_id.as_wtf8().to_wide_cstring().map_err(|_| {
1383                        vm.new_value_error(format!(
1384                            "{caller}(): AF_HYPERV address service_id is not a valid UUID string"
1385                        ))
1386                    })?;
1387                    let vm_guid = host_socket::uuid_from_string_w(&vm_wide).map_err(|_| {
1388                        vm.new_value_error(format!(
1389                            "{caller}(): AF_HYPERV address vm_id is not a valid UUID string"
1390                        ))
1391                    })?;
1392                    let service_guid =
1393                        host_socket::uuid_from_string_w(&service_wide).map_err(|_| {
1394                            vm.new_value_error(format!(
1395                            "{caller}(): AF_HYPERV address service_id is not a valid UUID string"
1396                        ))
1397                        })?;
1398                    let hv = host_socket::sockaddr_hv(vm_guid, service_guid);
1399                    let mut storage: host_socket::raw::SockAddrStorage =
1400                        unsafe { core::mem::zeroed() };
1401                    unsafe {
1402                        core::ptr::write(core::ptr::from_mut(&mut storage).cast(), hv);
1403                    }
1404                    Ok(unsafe {
1405                        host_socket::raw::SockAddr::new(storage, core::mem::size_of_val(&hv) as _)
1406                    })
1407                }
1408                #[cfg(windows)]
1409                family if family == c::AF_BLUETOOTH => {
1410                    if self.proto.load(Ordering::Relaxed) != host_socket::BTHPROTO_RFCOMM {
1411                        return Err(vm
1412                            .new_os_error(format!("{caller}(): unknown Bluetooth protocol"))
1413                            .into());
1414                    }
1415                    let tuple: PyTupleRef = addr
1416                        .downcast()
1417                        .map_err(|_| vm.new_os_error(format!("{caller}(): wrong format")))?;
1418                    if tuple.as_slice().len() != 2 {
1419                        return Err(vm.new_os_error(format!("{caller}(): wrong format")).into());
1420                    }
1421                    let name: PyStrRef = tuple.as_slice()[0]
1422                        .clone()
1423                        .downcast()
1424                        .map_err(|_| vm.new_os_error(format!("{caller}(): wrong format")))?;
1425                    let channel = i64::try_from_object(vm, tuple.as_slice()[1].clone())
1426                        .map_err(|_| vm.new_os_error(format!("{caller}(): wrong format")))?;
1427                    let name = name
1428                        .try_into_utf8(vm)
1429                        .map_err(|_| vm.new_os_error(format!("{caller}(): wrong format")))?;
1430                    let name = name.as_str();
1431                    if name.contains('\0') {
1432                        return Err(vm.new_os_error(format!("{caller}(): wrong format")).into());
1433                    }
1434                    let bd_addr = host_socket::parse_bdaddr(name)
1435                        .ok_or_else(|| vm.new_os_error("bad bluetooth address"))?;
1436                    let bth = host_socket::sockaddr_bth_rfcomm(bd_addr, channel as u32);
1437                    let mut storage: host_socket::raw::SockAddrStorage =
1438                        unsafe { core::mem::zeroed() };
1439                    unsafe {
1440                        core::ptr::write(core::ptr::from_mut(&mut storage).cast(), bth);
1441                    }
1442                    Ok(unsafe {
1443                        host_socket::raw::SockAddr::new(storage, core::mem::size_of_val(&bth) as _)
1444                    })
1445                }
1446                #[cfg(target_os = "linux")]
1447                c::AF_CAN => {
1448                    let tuple: PyTupleRef = addr.downcast().map_err(|obj| {
1449                        vm.new_type_error(format!(
1450                            "{}(): AF_CAN address must be tuple, not {}",
1451                            caller,
1452                            obj.class().name()
1453                        ))
1454                    })?;
1455                    let proto = self.proto.load(Ordering::Relaxed);
1456                    let interface: PyStrRef = tuple
1457                        .as_slice()
1458                        .first()
1459                        .cloned()
1460                        .ok_or_else(|| {
1461                            vm.new_type_error("AF_CAN address must be a tuple (interface, )")
1462                        })?
1463                        .downcast()
1464                        .map_err(|obj| {
1465                            vm.new_type_error(format!(
1466                                "{}(): AF_CAN interface must be str, not {}",
1467                                caller,
1468                                obj.class().name()
1469                            ))
1470                        })?;
1471                    let interface = interface.try_into_utf8(vm).map_err(IoOrPyException::from)?;
1472                    let ifname = interface.as_str();
1473
1474                    let ifindex = if ifname.is_empty() {
1475                        0
1476                    } else if ifname.len() >= 16 {
1477                        return Err(vm.new_os_error("AF_CAN interface name too long").into());
1478                    } else {
1479                        let cstr = alloc::ffi::CString::new(ifname)
1480                            .map_err(|_| vm.new_os_error("invalid interface name"))?;
1481                        host_socket::if_nametoindex_checked(cstr.as_c_str())? as i32
1482                    };
1483
1484                    let mut storage: c::sockaddr_storage = unsafe { core::mem::zeroed() };
1485                    let can_addr = &mut storage as *mut c::sockaddr_storage as *mut c::sockaddr_can;
1486                    unsafe {
1487                        (*can_addr).can_family = c::AF_CAN as c::sa_family_t;
1488                        (*can_addr).can_ifindex = ifindex;
1489                    }
1490
1491                    match proto {
1492                        c::CAN_RAW | c::CAN_BCM => {
1493                            if tuple.as_slice().len() != 1 {
1494                                return Err(vm
1495                                    .new_type_error("AF_CAN address must be a tuple (interface, )")
1496                                    .into());
1497                            }
1498                        }
1499                        c::CAN_ISOTP => {
1500                            if tuple.as_slice().len() != 3 {
1501                                return Err(vm
1502                                    .new_type_error(
1503                                        "AF_CAN ISOTP address must be a tuple (interface, rx_id, tx_id)",
1504                                    )
1505                                    .into());
1506                            }
1507                            let rx_id = tuple.as_slice()[1]
1508                                .try_index(vm)?
1509                                .try_to_primitive::<u32>(vm)?;
1510                            let tx_id = tuple.as_slice()[2]
1511                                .try_index(vm)?
1512                                .try_to_primitive::<u32>(vm)?;
1513                            unsafe {
1514                                (*can_addr).can_addr.tp.rx_id = rx_id;
1515                                (*can_addr).can_addr.tp.tx_id = tx_id;
1516                            }
1517                        }
1518                        c::CAN_J1939 => {
1519                            if tuple.as_slice().len() != 4 {
1520                                return Err(vm
1521                                    .new_type_error(
1522                                        "AF_CAN J1939 address must be a tuple (interface, name, pgn, addr)",
1523                                    )
1524                                    .into());
1525                            }
1526                            let name = tuple.as_slice()[1]
1527                                .try_index(vm)?
1528                                .try_to_primitive::<u64>(vm)?;
1529                            let pgn = tuple.as_slice()[2]
1530                                .try_index(vm)?
1531                                .try_to_primitive::<u32>(vm)?;
1532                            let jaddr = tuple.as_slice()[3]
1533                                .try_index(vm)?
1534                                .try_to_primitive::<u8>(vm)?;
1535                            unsafe {
1536                                (*can_addr).can_addr.j1939.name = name;
1537                                (*can_addr).can_addr.j1939.pgn = pgn;
1538                                (*can_addr).can_addr.j1939.addr = jaddr;
1539                            }
1540                        }
1541                        _ => {
1542                            return Err(vm
1543                                .new_os_error(format!("{caller}(): unsupported CAN protocol"))
1544                                .into());
1545                        }
1546                    }
1547
1548                    let storage: host_socket::raw::SockAddrStorage =
1549                        unsafe { core::mem::transmute(storage) };
1550                    Ok(unsafe {
1551                        host_socket::raw::SockAddr::new(
1552                            storage,
1553                            core::mem::size_of::<c::sockaddr_can>() as c::socklen_t,
1554                        )
1555                    })
1556                }
1557                #[cfg(target_os = "linux")]
1558                c::AF_ALG => {
1559                    let tuple: PyTupleRef = addr.downcast().map_err(|obj| {
1560                        vm.new_type_error(format!(
1561                            "{}(): AF_ALG address must be tuple, not {}",
1562                            caller,
1563                            obj.class().name()
1564                        ))
1565                    })?;
1566                    if tuple.as_slice().len() != 2 {
1567                        return Err(vm
1568                            .new_type_error("AF_ALG address must be a tuple (type, name)")
1569                            .into());
1570                    }
1571                    let alg_type: PyStrRef =
1572                        tuple.as_slice()[0].clone().downcast().map_err(|obj| {
1573                            vm.new_type_error(format!(
1574                                "{}(): AF_ALG type must be str, not {}",
1575                                caller,
1576                                obj.class().name()
1577                            ))
1578                        })?;
1579                    let alg_name: PyStrRef =
1580                        tuple.as_slice()[1].clone().downcast().map_err(|obj| {
1581                            vm.new_type_error(format!(
1582                                "{}(): AF_ALG name must be str, not {}",
1583                                caller,
1584                                obj.class().name()
1585                            ))
1586                        })?;
1587
1588                    let alg_type = alg_type.try_into_utf8(vm).map_err(IoOrPyException::from)?;
1589                    let alg_name = alg_name.try_into_utf8(vm).map_err(IoOrPyException::from)?;
1590                    let type_str = alg_type.as_str();
1591                    let name_str = alg_name.as_str();
1592
1593                    // salg_type is 14 bytes, salg_name is 64 bytes
1594                    if type_str.len() >= 14 {
1595                        return Err(vm.new_value_error("type too long").into());
1596                    }
1597                    if name_str.len() >= 64 {
1598                        return Err(vm.new_value_error("name too long").into());
1599                    }
1600
1601                    // Create sockaddr_alg
1602                    let mut storage: c::sockaddr_storage = unsafe { core::mem::zeroed() };
1603                    let alg_addr = &mut storage as *mut c::sockaddr_storage as *mut c::sockaddr_alg;
1604                    unsafe {
1605                        (*alg_addr).salg_family = c::AF_ALG as c::sa_family_t;
1606                        // Copy type string
1607                        for (i, b) in type_str.bytes().enumerate() {
1608                            (*alg_addr).salg_type[i] = b;
1609                        }
1610                        // Copy name string
1611                        for (i, b) in name_str.bytes().enumerate() {
1612                            (*alg_addr).salg_name[i] = b;
1613                        }
1614                    }
1615                    let storage: host_socket::raw::SockAddrStorage =
1616                        unsafe { core::mem::transmute(storage) };
1617                    Ok(unsafe {
1618                        host_socket::raw::SockAddr::new(
1619                            storage,
1620                            core::mem::size_of::<c::sockaddr_alg>() as c::socklen_t,
1621                        )
1622                    })
1623                }
1624                _ => Err(vm.new_os_error(format!("{caller}(): bad family")).into()),
1625            }
1626        }
1627
1628        fn connect_inner(
1629            &self,
1630            address: PyObjectRef,
1631            caller: &str,
1632            vm: &VirtualMachine,
1633        ) -> Result<(), IoOrPyException> {
1634            let sock_addr = self.extract_address(address, caller, vm)?;
1635
1636            let sock = self.sock_snapshot()?;
1637            let err = match vm.allow_threads(|| sock.connect(&sock_addr)) {
1638                Ok(()) => return Ok(()),
1639                Err(e) => e,
1640            };
1641
1642            let wait_connect = if err.kind() == io::ErrorKind::Interrupted {
1643                vm.check_signals()?;
1644                self.timeout.load() != 0.0
1645            } else {
1646                #[cfg(unix)]
1647                use c::EINPROGRESS;
1648                #[cfg(windows)]
1649                use c::WSAEWOULDBLOCK as EINPROGRESS;
1650
1651                self.timeout.load() > 0.0 && err.raw_os_error() == Some(EINPROGRESS)
1652            };
1653
1654            if wait_connect {
1655                self.sock_op(vm, SockWaitKind::Connect, || {
1656                    let sock = self.sock_snapshot()?;
1657                    let err = sock.take_error()?;
1658                    match err {
1659                        Some(e) => Err(e),
1660                        None => Ok(()),
1661                    }
1662                })
1663            } else {
1664                Err(err.into())
1665            }
1666        }
1667    }
1668
1669    impl DefaultConstructor for PySocket {}
1670
1671    #[derive(FromArgs)]
1672    pub struct SocketInitArgs {
1673        #[pyarg(any, default = -1)]
1674        family: i32,
1675        #[pyarg(any, default = -1)]
1676        r#type: i32,
1677        #[pyarg(any, default = -1)]
1678        proto: i32,
1679        #[pyarg(any, optional)]
1680        fileno: Option<PyObjectRef>,
1681    }
1682
1683    #[cfg(all(unix, not(target_os = "redox")))]
1684    #[derive(FromArgs)]
1685    struct SendmsgAddr {
1686        #[pyarg(positional, optional)]
1687        addr: Option<PyObjectRef>,
1688    }
1689
1690    impl Initializer for PySocket {
1691        type Args = SocketInitArgs;
1692
1693        fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
1694            Self::_init(zelf, args, vm).map_err(|e| e.into_pyexception(vm))
1695        }
1696    }
1697
1698    impl Representable for PySocket {
1699        #[inline]
1700        fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
1701            Ok(format!(
1702                "<socket object, fd={}, family={}, type={}, proto={}>",
1703                Self::fileno(zelf),
1704                zelf.family.load(Ordering::Relaxed),
1705                zelf.kind.load(Ordering::Relaxed),
1706                zelf.proto.load(Ordering::Relaxed),
1707            ))
1708        }
1709    }
1710
1711    impl Destructor for PySocket {
1712        fn del(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<()> {
1713            // Emit ResourceWarning if socket is still open
1714            if zelf.sock.read().is_some() {
1715                let repr = zelf
1716                    .as_object()
1717                    .repr(vm)
1718                    .unwrap_or_else(|_| vm.ctx.new_str("<socket>"));
1719                let msg = format!("unclosed {}", repr.as_wtf8());
1720                let _ = crate::vm::warn::warn(
1721                    vm.ctx.new_str(msg).into(),
1722                    Some(vm.ctx.exceptions.resource_warning.to_owned()),
1723                    1,
1724                    None,
1725                    vm,
1726                );
1727            }
1728            let _ = Self::close(zelf);
1729            Ok(())
1730        }
1731    }
1732
1733    #[pyclass(
1734        with(Constructor, Initializer, Representable, Destructor),
1735        flags(BASETYPE, HEAPTYPE)
1736    )]
1737    impl PySocket {
1738        fn _init(
1739            zelf: &Py<Self>,
1740            args: <Self as Initializer>::Args,
1741            vm: &VirtualMachine,
1742        ) -> Result<(), IoOrPyException> {
1743            let mut family = args.family;
1744            let mut socket_kind = args.r#type;
1745            let mut proto = args.proto;
1746
1747            vm.audit("socket.__new__", || (family, socket_kind, proto))?;
1748
1749            let fileno = args.fileno;
1750            let sock;
1751
1752            // On Windows, fileno can be bytes from socket.share() for fromshare()
1753            #[cfg(windows)]
1754            if let Some(fileno_obj) = fileno {
1755                use crate::vm::builtins::PyBytes;
1756                if let Ok(bytes) = fileno_obj.clone().downcast::<PyBytes>() {
1757                    let bytes_data = bytes.as_bytes();
1758                    let expected_size = host_socket::protocol_info_size();
1759
1760                    if bytes_data.len() != expected_size {
1761                        return Err(vm
1762                            .new_value_error(format!(
1763                                "socket descriptor string has wrong size, should be {expected_size} bytes"
1764                            ))
1765                            .into());
1766                    }
1767
1768                    let shared = host_socket::socket_from_share_data(bytes_data)?;
1769                    family = shared.family;
1770                    socket_kind = shared.socket_type;
1771                    proto = shared.protocol;
1772                    sock = unsafe { sock_from_raw_unchecked(shared.raw as RawSocket) };
1773                    return Ok(zelf.init_inner(family, socket_kind, proto, sock)?);
1774                }
1775
1776                // Not bytes, treat as regular fileno
1777                let fileno = get_raw_sock(&fileno_obj, vm)?;
1778                sock = sock_from_raw(fileno, vm)?;
1779                match sock.local_addr() {
1780                    Ok(addr) if family == -1 => family = addr.family() as i32,
1781                    Err(e)
1782                        if family == -1
1783                            || matches!(
1784                                e.raw_os_error(),
1785                                Some(errcode!(ENOTSOCK) | errcode!(EBADF))
1786                            ) =>
1787                    {
1788                        core::mem::forget(sock);
1789                        return Err(e.into());
1790                    }
1791                    _ => {}
1792                }
1793                if socket_kind == -1 {
1794                    socket_kind = sock.r#type().map_err(|e| e.into_pyexception(vm))?.into();
1795                }
1796                proto = 0;
1797                return Ok(zelf.init_inner(family, socket_kind, proto, sock)?);
1798            }
1799
1800            #[cfg(not(windows))]
1801            let fileno = fileno.map(|obj| get_raw_sock(&obj, vm)).transpose()?;
1802            #[cfg(not(windows))]
1803            if let Some(fileno) = fileno {
1804                sock = sock_from_raw(fileno, vm)?;
1805                match sock.local_addr() {
1806                    Ok(addr) if family == -1 => family = addr.family() as i32,
1807                    Err(e)
1808                        if family == -1
1809                            || matches!(e.raw_os_error(), Some(c::ENOTSOCK | c::EBADF)) =>
1810                    {
1811                        core::mem::forget(sock);
1812                        return Err(e.into());
1813                    }
1814                    _ => {}
1815                }
1816                if socket_kind == -1 {
1817                    socket_kind = sock.r#type().map_err(|e| e.into_pyexception(vm))?.into();
1818                }
1819
1820                cfg_select! {
1821                    any(
1822                        target_os = "android",
1823                        target_os = "freebsd",
1824                        target_os = "fuchsia",
1825                        target_os = "linux",
1826                    ) => {
1827                        if proto == -1 {
1828                            proto = sock.protocol()?.map_or(0, Into::into);
1829                        }
1830                    }
1831                    _ => {
1832                        proto = 0;
1833                    }
1834                }
1835
1836                return Ok(zelf.init_inner(family, socket_kind, proto, sock)?);
1837            }
1838
1839            // No fileno provided, create new socket
1840            {
1841                if family == -1 {
1842                    family = c::AF_INET as _
1843                }
1844                if socket_kind == -1 {
1845                    socket_kind = c::SOCK_STREAM
1846                }
1847                if proto == -1 {
1848                    proto = 0
1849                }
1850                sock = Socket::new(family.into(), socket_kind.into(), Some(proto.into()))?;
1851            };
1852            Ok(zelf.init_inner(family, socket_kind, proto, sock)?)
1853        }
1854
1855        #[pymethod]
1856        fn connect(
1857            zelf: &Py<Self>,
1858            object: PyObjectRef,
1859            vm: &VirtualMachine,
1860        ) -> Result<(), IoOrPyException> {
1861            zelf.connect_inner(object, "connect", vm)
1862        }
1863
1864        #[pymethod]
1865        fn connect_ex(zelf: &Py<Self>, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<i32> {
1866            match zelf.connect_inner(object, "connect_ex", vm) {
1867                Ok(()) => Ok(0),
1868                Err(err) => err.errno(),
1869            }
1870        }
1871
1872        #[pymethod]
1873        fn bind(
1874            zelf: &Py<Self>,
1875            object: PyObjectRef,
1876            vm: &VirtualMachine,
1877        ) -> Result<(), IoOrPyException> {
1878            let sock_addr = zelf.extract_address(object, "bind", vm)?;
1879
1880            if let Some(addr) = sock_addr.as_socket() {
1881                vm.audit("socket.bind", || {
1882                    let (ip, port) = match addr {
1883                        SocketAddr::V4(addr) => (addr.ip().to_string(), addr.port()),
1884                        SocketAddr::V6(addr) => (addr.ip().to_string(), addr.port()),
1885                    };
1886                    ((ip, port),)
1887                })?;
1888            }
1889
1890            Ok(zelf.sock()?.bind(&sock_addr)?)
1891        }
1892
1893        #[pymethod]
1894        fn listen(zelf: &Py<Self>, backlog: OptionalArg<i32>) -> io::Result<()> {
1895            let backlog = backlog.unwrap_or(128);
1896            let backlog = if backlog < 0 { 0 } else { backlog };
1897            zelf.sock()?.listen(backlog)
1898        }
1899
1900        #[pymethod]
1901        fn _accept(
1902            zelf: &Py<Self>,
1903            vm: &VirtualMachine,
1904        ) -> Result<(RawSocket, PyObjectRef), IoOrPyException> {
1905            // Use accept_raw() instead of accept() to avoid socket2's set_common_flags()
1906            // which tries to set SO_NOSIGPIPE and fails with EINVAL on Unix domain sockets on macOS
1907            let (sock, addr) = zelf.sock_op(vm, SockWaitKind::Read, || {
1908                zelf.sock_snapshot()?.accept_raw()
1909            })?;
1910            let fd = into_sock_fileno(sock);
1911            Ok((
1912                fd,
1913                get_addr_tuple(&addr, zelf.proto.load(Ordering::Relaxed), vm),
1914            ))
1915        }
1916
1917        #[pymethod]
1918        fn recv(
1919            zelf: &Py<Self>,
1920            bufsize: usize,
1921            flags: OptionalArg<i32>,
1922            vm: &VirtualMachine,
1923        ) -> Result<Vec<u8>, IoOrPyException> {
1924            let flags = flags.unwrap_or(0);
1925            let mut buffer = Vec::new();
1926            buffer
1927                .try_reserve_exact(bufsize)
1928                .map_err(|_| vm.no_memory_error())?;
1929            let n = zelf.sock_op(vm, SockWaitKind::Read, || {
1930                zelf.sock_snapshot()?
1931                    .recv_with_flags(buffer.spare_capacity_mut(), flags)
1932            })?;
1933            unsafe { buffer.set_len(n) };
1934            Ok(buffer)
1935        }
1936
1937        #[pymethod]
1938        fn recv_into(
1939            zelf: &Py<Self>,
1940            buf: ArgMemoryBuffer,
1941            nbytes: OptionalArg<isize>,
1942            flags: OptionalArg<i32>,
1943            vm: &VirtualMachine,
1944        ) -> Result<usize, IoOrPyException> {
1945            let flags = flags.unwrap_or(0);
1946
1947            // Handle nbytes parameter
1948            let read_len = if let OptionalArg::Present(nbytes) = nbytes {
1949                let nbytes = nbytes
1950                    .to_usize()
1951                    .ok_or_else(|| vm.new_value_error("negative buffersize in recv_into"))?;
1952                nbytes.min(buf.len())
1953            } else {
1954                buf.len()
1955            };
1956
1957            let mut scratch = alloc_recv_scratch(read_len, vm)?;
1958            let n = zelf.sock_op(vm, SockWaitKind::Read, || {
1959                zelf.sock_snapshot()?
1960                    .recv_with_flags(&mut scratch.spare_capacity_mut()[..read_len], flags)
1961            })?;
1962            unsafe { scratch.set_len(n) };
1963            buf.borrow_buf_mut()[..n].copy_from_slice(&scratch);
1964            Ok(n)
1965        }
1966
1967        #[pymethod]
1968        fn recvfrom(
1969            zelf: &Py<Self>,
1970            bufsize: isize,
1971            flags: OptionalArg<i32>,
1972            vm: &VirtualMachine,
1973        ) -> Result<(Vec<u8>, PyObjectRef), IoOrPyException> {
1974            let flags = flags.unwrap_or(0);
1975            let bufsize = bufsize
1976                .to_usize()
1977                .ok_or_else(|| vm.new_value_error("negative buffersize in recvfrom"))?;
1978            let mut buffer = Vec::new();
1979            buffer
1980                .try_reserve_exact(bufsize)
1981                .map_err(|_| vm.no_memory_error())?;
1982            let (n, addr) = zelf.sock_op(vm, SockWaitKind::Read, || {
1983                zelf.sock_snapshot()?
1984                    .recv_from_with_flags(buffer.spare_capacity_mut(), flags)
1985            })?;
1986            unsafe { buffer.set_len(n) };
1987            Ok((
1988                buffer,
1989                get_addr_tuple(&addr, zelf.proto.load(Ordering::Relaxed), vm),
1990            ))
1991        }
1992
1993        #[pymethod]
1994        fn recvfrom_into(
1995            zelf: &Py<Self>,
1996            buf: ArgMemoryBuffer,
1997            nbytes: OptionalArg<isize>,
1998            flags: OptionalArg<i32>,
1999            vm: &VirtualMachine,
2000        ) -> Result<(usize, PyObjectRef), IoOrPyException> {
2001            let read_len = match nbytes {
2002                OptionalArg::Present(i) => {
2003                    let i = i.to_usize().ok_or_else(|| {
2004                        vm.new_value_error("negative buffersize in recvfrom_into")
2005                    })?;
2006                    if i > buf.len() {
2007                        return Err(vm
2008                            .new_value_error("nbytes is greater than the length of the buffer")
2009                            .into());
2010                    }
2011                    i
2012                }
2013                OptionalArg::Missing => buf.len(),
2014            };
2015            let flags = flags.unwrap_or(0);
2016            let mut scratch = alloc_recv_scratch(read_len, vm)?;
2017            let (n, addr) = zelf.sock_op(vm, SockWaitKind::Read, || {
2018                zelf.sock_snapshot()?
2019                    .recv_from_with_flags(&mut scratch.spare_capacity_mut()[..read_len], flags)
2020            })?;
2021            unsafe { scratch.set_len(n) };
2022            buf.borrow_buf_mut()[..n].copy_from_slice(&scratch);
2023            Ok((
2024                n,
2025                get_addr_tuple(&addr, zelf.proto.load(Ordering::Relaxed), vm),
2026            ))
2027        }
2028
2029        #[pymethod]
2030        fn send(
2031            zelf: &Py<Self>,
2032            bytes: ArgBytesLike,
2033            flags: OptionalArg<i32>,
2034            vm: &VirtualMachine,
2035        ) -> Result<usize, IoOrPyException> {
2036            let flags = flags.unwrap_or(0);
2037            let buf = bytes.borrow_buf_unlocked(vm)?;
2038            let buf = &*buf;
2039            zelf.sock_op(vm, SockWaitKind::Write, || {
2040                zelf.sock_snapshot()?.send_with_flags(buf, flags)
2041            })
2042        }
2043
2044        #[pymethod]
2045        fn sendall(
2046            zelf: &Py<Self>,
2047            bytes: ArgBytesLike,
2048            flags: OptionalArg<i32>,
2049            vm: &VirtualMachine,
2050        ) -> Result<(), IoOrPyException> {
2051            let flags = flags.unwrap_or(0);
2052
2053            let timeout = zelf.get_timeout().ok();
2054            let mut deadline = None;
2055
2056            let buf = bytes.borrow_buf_unlocked(vm)?;
2057            let buf = &*buf;
2058            let mut buf_offset = 0;
2059            // now we have like 3 layers of interrupt loop :)
2060            while buf_offset < buf.len() {
2061                zelf.sock_op_timeout_err(vm, SockWaitKind::Write, &mut deadline, timeout, || {
2062                    let subbuf = &buf[buf_offset..];
2063                    buf_offset += zelf.sock_snapshot()?.send_with_flags(subbuf, flags)?;
2064                    Ok(())
2065                })?;
2066                vm.check_signals()?;
2067            }
2068            Ok(())
2069        }
2070
2071        #[pymethod]
2072        fn sendto(
2073            zelf: &Py<Self>,
2074            args: FuncArgs,
2075            vm: &VirtualMachine,
2076        ) -> Result<usize, IoOrPyException> {
2077            if !args.kwargs.is_empty() {
2078                return Err(vm
2079                    .new_type_error("sendto() takes no keyword arguments")
2080                    .into());
2081            }
2082            let n = args.args.len();
2083            let (bytes, flags, address) = match n {
2084                2 => (args.args[0].clone(), 0, args.args[1].clone()),
2085                3 => {
2086                    let flags = args.args[1].try_index(vm)?.try_to_primitive::<i32>(vm)?;
2087                    (args.args[0].clone(), flags, args.args[2].clone())
2088                }
2089                _ => {
2090                    return Err(vm
2091                        .new_type_error(format!("sendto() takes 2 or 3 arguments ({n} given)"))
2092                        .into());
2093                }
2094            };
2095            let bytes = ArgBytesLike::try_from_object(vm, bytes)?;
2096            let addr = zelf.extract_address(address, "sendto", vm)?;
2097            let buf = bytes.borrow_buf_unlocked(vm)?;
2098            let buf = &*buf;
2099            zelf.sock_op(vm, SockWaitKind::Write, || {
2100                zelf.sock_snapshot()?.send_to_with_flags(buf, &addr, flags)
2101            })
2102        }
2103
2104        #[cfg(all(unix, not(target_os = "redox")))]
2105        #[pymethod]
2106        fn sendmsg(
2107            zelf: &Py<Self>,
2108            buffers: PyObjectRef,
2109            ancdata: OptionalArg<PyObjectRef>,
2110            flags: OptionalArg<i32>,
2111            addr: SendmsgAddr,
2112            vm: &VirtualMachine,
2113        ) -> PyResult<usize> {
2114            let flags = flags.unwrap_or(0);
2115            let mut msg = host_socket::raw::MsgHdr::new();
2116
2117            let sockaddr;
2118            if let Some(addr) = addr.addr {
2119                sockaddr = zelf
2120                    .extract_address(addr, "sendmsg", vm)
2121                    .map_err(|e| e.into_pyexception(vm))?;
2122                msg = msg.with_addr(&sockaddr);
2123            }
2124
2125            let collect_iterable =
2126                |obj: &PyObject, msg: &'static str| -> PyResult<Vec<PyObjectRef>> {
2127                    match vm.extract_elements_with(obj, Ok) {
2128                        Ok(items) => Ok(items),
2129                        Err(e) if e.fast_isinstance(vm.ctx.exceptions.type_error) => {
2130                            Err(vm.new_type_error(msg))
2131                        }
2132                        Err(e) => Err(e),
2133                    }
2134                };
2135
2136            let buffer_items =
2137                collect_iterable(&buffers, "sendmsg() argument 1 must be an iterable")?;
2138            let buffers = buffer_items
2139                .into_iter()
2140                .map(|obj| ArgBytesLike::try_from_object(vm, obj))
2141                .collect::<PyResult<Vec<_>>>()?;
2142            let buffers = buffers
2143                .iter()
2144                .map(|buf| buf.borrow_buf_unlocked(vm))
2145                .collect::<PyResult<Vec<_>>>()?;
2146            let buffers = buffers
2147                .iter()
2148                .map(|buf| io::IoSlice::new(buf))
2149                .collect::<Vec<_>>();
2150            msg = msg.with_buffers(&buffers);
2151
2152            let control_buf;
2153            if let OptionalArg::Present(ancdata) = ancdata {
2154                let cmsg_fast =
2155                    collect_iterable(&ancdata, "sendmsg() argument 2 must be an iterable")?;
2156                let cmsgs = cmsg_fast
2157                    .into_iter()
2158                    .map(|item| -> PyResult<(i32, i32, ArgBytesLike)> {
2159                        let seq: Vec<PyObjectRef> = item.try_into_value(vm)?;
2160                        let [lvl, typ, data]: [PyObjectRef; 3] = seq
2161                            .try_into()
2162                            .map_err(|_| vm.new_type_error("[sendmsg() ancillary data items]"))?;
2163                        Ok((
2164                            lvl.try_index(vm)?.try_to_primitive::<i32>(vm)?,
2165                            typ.try_index(vm)?.try_to_primitive::<i32>(vm)?,
2166                            ArgBytesLike::try_from_object(vm, data)?,
2167                        ))
2168                    })
2169                    .collect::<PyResult<Vec<_>>>()?;
2170                control_buf = Self::pack_cmsgs_to_send(&cmsgs, vm)?;
2171                if !control_buf.is_empty() {
2172                    msg = msg.with_control(&control_buf);
2173                }
2174            }
2175
2176            zelf.sock_op(vm, SockWaitKind::Write, || {
2177                let sock = zelf.sock_snapshot()?;
2178                sock.sendmsg(&msg, flags)
2179            })
2180            .map_err(|e| e.into_pyexception(vm))
2181        }
2182
2183        #[cfg(target_os = "linux")]
2184        #[pymethod]
2185        fn sendmsg_afalg(
2186            zelf: &Py<Self>,
2187            args: SendmsgAfalgArgs,
2188            vm: &VirtualMachine,
2189        ) -> PyResult<usize> {
2190            use std::os::fd::BorrowedFd;
2191
2192            let msg = args.msg;
2193            let op = args.op;
2194            let iv = args.iv;
2195            let flags = args.flags;
2196
2197            // Validate assoclen - must be non-negative if provided
2198            let assoclen: Option<u32> = match args.assoclen {
2199                OptionalArg::Present(val) if val < 0 => {
2200                    return Err(vm.new_type_error("assoclen must be non-negative"));
2201                }
2202                OptionalArg::Present(val) => Some(val as u32),
2203                OptionalArg::Missing => None,
2204            };
2205
2206            let buffers = msg.iter().map(|buf| buf.borrow_buf()).collect::<Vec<_>>();
2207            let buffers = buffers
2208                .iter()
2209                .map(|buf| io::IoSlice::new(buf))
2210                .collect::<Vec<_>>();
2211            let iv = iv.map(|iv| iv.borrow_buf().to_vec());
2212
2213            zelf.sock_op(vm, SockWaitKind::Write, || {
2214                let sock = zelf.sock_snapshot()?;
2215                let fd = unsafe { BorrowedFd::borrow_raw(sock_fileno(&sock)) };
2216                host_socket::sendmsg_afalg(fd, &buffers, op, iv.as_deref(), assoclen, flags)
2217            })
2218            .map_err(|e| e.into_pyexception(vm))
2219        }
2220
2221        #[cfg(all(unix, not(target_os = "redox")))]
2222        #[pymethod]
2223        fn recvmsg(
2224            zelf: &Py<Self>,
2225            bufsize: isize,
2226            ancbufsize: OptionalArg<isize>,
2227            flags: OptionalArg<i32>,
2228            vm: &VirtualMachine,
2229        ) -> PyResult<PyTupleRef> {
2230            if bufsize < 0 {
2231                return Err(vm.new_value_error("negative buffer size in recvmsg"));
2232            }
2233            let bufsize = bufsize as usize;
2234
2235            let ancbufsize = ancbufsize.unwrap_or(0);
2236            if ancbufsize < 0 {
2237                return Err(vm.new_value_error("negative ancillary buffer size in recvmsg"));
2238            }
2239            let ancbufsize = ancbufsize as usize;
2240            let flags = flags.unwrap_or(0);
2241
2242            let msg = zelf
2243                .sock_op(vm, SockWaitKind::Read, || {
2244                    let sock = zelf.sock_snapshot()?;
2245                    let fd = unsafe { std::os::fd::BorrowedFd::borrow_raw(sock_fileno(&sock)) };
2246                    host_socket::recvmsg(fd, bufsize, ancbufsize, flags)
2247                })
2248                .map_err(|e| e.into_pyexception(vm))?;
2249
2250            // Build ancdata list
2251            let ancdata = Self::parse_ancillary_data(&msg.ancdata, vm);
2252
2253            // Build address tuple
2254            let address = if let Some(address) = msg.address {
2255                let storage: host_socket::raw::SockAddrStorage =
2256                    unsafe { core::mem::transmute(address.storage) };
2257                let addr = unsafe { host_socket::raw::SockAddr::new(storage, address.len as _) };
2258                get_addr_tuple(&addr, zelf.proto.load(Ordering::Relaxed), vm)
2259            } else {
2260                vm.ctx.none()
2261            };
2262
2263            Ok(vm.ctx.new_tuple(vec![
2264                vm.ctx.new_bytes(msg.data).into(),
2265                ancdata,
2266                vm.ctx.new_int(msg.msg_flags).into(),
2267                address,
2268            ]))
2269        }
2270
2271        /// Parse ancillary data from a received message header
2272        #[cfg(all(unix, not(target_os = "redox")))]
2273        fn parse_ancillary_data(
2274            control: &[host_socket::AncillaryMessage],
2275            vm: &VirtualMachine,
2276        ) -> PyObjectRef {
2277            let mut result = Vec::new();
2278            for cmsg in control {
2279                let tuple = vm.ctx.new_tuple(vec![
2280                    vm.ctx.new_int(cmsg.level).into(),
2281                    vm.ctx.new_int(cmsg.kind).into(),
2282                    vm.ctx.new_bytes(cmsg.data.clone()).into(),
2283                ]);
2284                result.push(tuple.into());
2285            }
2286
2287            vm.ctx.new_list(result).into()
2288        }
2289
2290        // based on nix's implementation
2291        #[cfg(all(unix, not(target_os = "redox")))]
2292        fn pack_cmsgs_to_send(
2293            cmsgs: &[(i32, i32, ArgBytesLike)],
2294            vm: &VirtualMachine,
2295        ) -> PyResult<Vec<u8>> {
2296            if cmsgs.is_empty() {
2297                return Ok(vec![]);
2298            }
2299            let data = cmsgs
2300                .iter()
2301                .map(|(lvl, typ, buf)| {
2302                    let data = buf.borrow_buf();
2303                    (*lvl, *typ, data.to_vec())
2304                })
2305                .collect::<Vec<_>>();
2306            let data_refs = data
2307                .iter()
2308                .map(|(lvl, typ, data)| (*lvl, *typ, data.as_slice()))
2309                .collect::<Vec<_>>();
2310
2311            host_socket::pack_ancillary_messages(&data_refs).map_err(|err| err.to_pyexception(vm))
2312        }
2313
2314        #[pymethod]
2315        fn close(zelf: &Py<Self>) -> io::Result<()> {
2316            let sock = zelf.sock.write().take();
2317            if let Some(sock) = sock {
2318                close_inner(into_sock_fileno(sock))?;
2319            }
2320            Ok(())
2321        }
2322
2323        #[pymethod]
2324        #[inline]
2325        fn detach(zelf: &Py<Self>) -> i64 {
2326            let sock = zelf.sock.write().take();
2327            sock.map_or(INVALID_SOCKET as i64, |s| into_sock_fileno(s) as i64)
2328        }
2329
2330        #[pymethod]
2331        fn fileno(zelf: &Py<Self>) -> i64 {
2332            zelf.sock
2333                .read()
2334                .as_ref()
2335                .map_or(INVALID_SOCKET as i64, |s| sock_fileno(s) as i64)
2336        }
2337
2338        #[pymethod]
2339        fn getsockname(zelf: &Py<Self>, vm: &VirtualMachine) -> std::io::Result<PyObjectRef> {
2340            let addr = zelf.sock()?.local_addr()?;
2341
2342            Ok(get_addr_tuple(
2343                &addr,
2344                zelf.proto.load(Ordering::Relaxed),
2345                vm,
2346            ))
2347        }
2348
2349        #[pymethod]
2350        fn getpeername(zelf: &Py<Self>, vm: &VirtualMachine) -> std::io::Result<PyObjectRef> {
2351            let addr = zelf.sock()?.peer_addr()?;
2352
2353            Ok(get_addr_tuple(
2354                &addr,
2355                zelf.proto.load(Ordering::Relaxed),
2356                vm,
2357            ))
2358        }
2359
2360        #[pymethod]
2361        fn gettimeout(zelf: &Py<Self>) -> Option<f64> {
2362            let timeout = zelf.timeout.load();
2363            if timeout >= 0.0 { Some(timeout) } else { None }
2364        }
2365
2366        #[pymethod]
2367        fn setblocking(zelf: &Py<Self>, object: bool) -> io::Result<()> {
2368            zelf.timeout.store(if object { -1.0 } else { 0.0 });
2369            zelf.sock()?.set_nonblocking(!object)
2370        }
2371
2372        #[pymethod]
2373        fn getblocking(zelf: &Py<Self>) -> bool {
2374            zelf.timeout.load() != 0.0
2375        }
2376
2377        #[pymethod]
2378        fn settimeout(
2379            zelf: &Py<Self>,
2380            object: Option<ArgIntoFloat>,
2381            vm: &VirtualMachine,
2382        ) -> PyResult<()> {
2383            let timeout = match object {
2384                Some(t) => {
2385                    let f = t.into_float();
2386                    if f.is_nan() {
2387                        return Err(vm.new_value_error("Invalid value NaN (not a number)"));
2388                    }
2389                    if f < 0.0 || !f.is_finite() {
2390                        return Err(vm.new_value_error("Timeout value out of range"));
2391                    }
2392                    Some(f)
2393                }
2394                None => None,
2395            };
2396            zelf.timeout.store(timeout.unwrap_or(-1.0));
2397            // even if timeout is > 0 the socket needs to be nonblocking in order for us to select() on
2398            // it
2399            zelf.sock()
2400                .map_err(|e| e.into_pyexception(vm))?
2401                .set_nonblocking(timeout.is_some())
2402                .map_err(|e| e.into_pyexception(vm))
2403        }
2404
2405        #[pymethod]
2406        fn getsockopt(
2407            zelf: &Py<Self>,
2408            level: i32,
2409            name: i32,
2410            buflen: OptionalArg<i32>,
2411            vm: &VirtualMachine,
2412        ) -> Result<PyObjectRef, IoOrPyException> {
2413            let sock = zelf.sock()?;
2414            let fd = sock_fileno(&sock);
2415            let buflen = buflen.unwrap_or(0);
2416            if buflen == 0 {
2417                let flag = host_socket::getsockopt_int(fd as _, level, name)?;
2418                Ok(vm.ctx.new_int(flag).into())
2419            } else {
2420                if buflen <= 0 || buflen > 1024 {
2421                    return Err(vm.new_os_error("getsockopt buflen out of range").into());
2422                }
2423                let buf = host_socket::getsockopt_bytes(fd as _, level, name, buflen as usize)?;
2424                Ok(vm.ctx.new_bytes(buf).into())
2425            }
2426        }
2427
2428        #[pymethod]
2429        fn setsockopt(
2430            zelf: &Py<Self>,
2431            level: i32,
2432            name: i32,
2433            value: Option<Either<ArgBytesLike, i32>>,
2434            optlen: OptionalArg<u32>,
2435            vm: &VirtualMachine,
2436        ) -> Result<(), IoOrPyException> {
2437            let sock = zelf.sock()?;
2438            let fd = sock_fileno(&sock);
2439            match (value, optlen) {
2440                (Some(Either::A(b)), OptionalArg::Missing) => {
2441                    b.with_ref(|b| host_socket::setsockopt_bytes(fd as _, level, name, b))?
2442                }
2443                (Some(Either::B(val)), OptionalArg::Missing) => {
2444                    host_socket::setsockopt_int(fd as _, level, name, val)?
2445                }
2446                (None, OptionalArg::Present(optlen)) => {
2447                    host_socket::setsockopt_none(fd as _, level, name, optlen)?
2448                }
2449                _ => {
2450                    return Err(vm
2451                        .new_type_error("expected the value arg xor the optlen arg")
2452                        .into());
2453                }
2454            }
2455            Ok(())
2456        }
2457
2458        #[pymethod]
2459        fn shutdown(
2460            zelf: &Py<Self>,
2461            object: i32,
2462            vm: &VirtualMachine,
2463        ) -> Result<(), IoOrPyException> {
2464            let how = match object {
2465                c::SHUT_RD => Shutdown::Read,
2466                c::SHUT_WR => Shutdown::Write,
2467                c::SHUT_RDWR => Shutdown::Both,
2468                _ => {
2469                    return Err(vm
2470                        .new_value_error("`how` must be SHUT_RD, SHUT_WR, or SHUT_RDWR")
2471                        .into());
2472                }
2473            };
2474            Ok(zelf.sock()?.shutdown(how)?)
2475        }
2476
2477        #[cfg(windows)]
2478        #[pymethod]
2479        fn ioctl(
2480            zelf: &Py<Self>,
2481            cmd: PyObjectRef,
2482            option: PyObjectRef,
2483            vm: &VirtualMachine,
2484        ) -> Result<u32, IoOrPyException> {
2485            use crate::vm::builtins::PyInt;
2486            use crate::vm::convert::TryFromObject;
2487
2488            let sock = zelf.sock()?;
2489            let fd = sock_fileno(&sock);
2490
2491            // Convert cmd to u32, returning ValueError for invalid/negative values
2492            let cmd_int = cmd
2493                .downcast::<PyInt>()
2494                .map_err(|_| vm.new_type_error("an integer is required"))?;
2495            let cmd_val = cmd_int.as_bigint();
2496            let cmd: u32 = cmd_val
2497                .to_u32()
2498                .ok_or_else(|| vm.new_value_error(format!("invalid ioctl command {cmd_val}")))?;
2499
2500            match cmd {
2501                c::SIO_RCVALL | c::SIO_LOOPBACK_FAST_PATH => {
2502                    // Option must be an integer, not None
2503                    if vm.is_none(&option) {
2504                        return Err(vm
2505                            .new_type_error("an integer is required (got type NoneType)")
2506                            .into());
2507                    }
2508                    let option_val: u32 = TryFromObject::try_from_object(vm, option)?;
2509                    host_socket::ioctl_u32(fd as _, cmd, option_val).map_err(Into::into)
2510                }
2511                c::SIO_KEEPALIVE_VALS => {
2512                    let tuple: PyTupleRef = option
2513                        .downcast()
2514                        .map_err(|_| vm.new_type_error("SIO_KEEPALIVE_VALS requires a tuple"))?;
2515                    if tuple.as_slice().len() != 3 {
2516                        return Err(vm
2517                            .new_type_error(
2518                                "SIO_KEEPALIVE_VALS requires (onoff, keepalivetime, keepaliveinterval)",
2519                            )
2520                            .into());
2521                    }
2522
2523                    let ka = host_socket::TcpKeepalive {
2524                        onoff: TryFromObject::try_from_object(vm, tuple.as_slice()[0].clone())?,
2525                        keepalivetime: TryFromObject::try_from_object(
2526                            vm,
2527                            tuple.as_slice()[1].clone(),
2528                        )?,
2529                        keepaliveinterval: TryFromObject::try_from_object(
2530                            vm,
2531                            tuple.as_slice()[2].clone(),
2532                        )?,
2533                    };
2534
2535                    if cmd != c::SIO_KEEPALIVE_VALS {
2536                        return Err(vm
2537                            .new_value_error(format!("invalid ioctl command {cmd}"))
2538                            .into());
2539                    }
2540                    host_socket::ioctl_keepalive(fd as _, ka).map_err(Into::into)
2541                }
2542                _ => Err(vm
2543                    .new_value_error(format!("invalid ioctl command {cmd}"))
2544                    .into()),
2545            }
2546        }
2547
2548        #[cfg(windows)]
2549        #[pymethod]
2550        fn share(
2551            zelf: &Py<Self>,
2552            process_id: u32,
2553            _vm: &VirtualMachine,
2554        ) -> Result<Vec<u8>, IoOrPyException> {
2555            let sock = zelf.sock()?;
2556            let fd = sock_fileno(&sock);
2557            host_socket::share_socket(fd as _, process_id).map_err(Into::into)
2558        }
2559    }
2560
2561    struct Address {
2562        host: PyUtf8StrRef,
2563        port: u16,
2564    }
2565
2566    impl ToSocketAddrs for Address {
2567        type Iter = alloc::vec::IntoIter<SocketAddr>;
2568        fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
2569            (self.host.as_str(), self.port).to_socket_addrs()
2570        }
2571    }
2572
2573    impl TryFromObject for Address {
2574        fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
2575            let tuple = PyTupleRef::try_from_object(vm, obj)?;
2576            if tuple.as_slice().len() != 2 {
2577                Err(vm.new_type_error("Address tuple should have only 2 values"))
2578            } else {
2579                Self::from_tuple(tuple.as_slice(), vm)
2580            }
2581        }
2582    }
2583
2584    impl Address {
2585        fn from_tuple(tuple: &[PyObjectRef], vm: &VirtualMachine) -> PyResult<Self> {
2586            let host = PyStrRef::try_from_object(vm, tuple[0].clone())?;
2587            let host = host.try_into_utf8(vm)?;
2588            let port = i32::try_from_borrowed_object(vm, &tuple[1])?;
2589            let port = port
2590                .to_u16()
2591                .ok_or_else(|| vm.new_overflow_error("port must be 0-65535."))?;
2592            Ok(Self { host, port })
2593        }
2594
2595        fn from_tuple_ipv6(
2596            tuple: &[PyObjectRef],
2597            vm: &VirtualMachine,
2598        ) -> PyResult<(Self, u32, u32)> {
2599            let addr = Self::from_tuple(tuple, vm)?;
2600            let flowinfo = tuple
2601                .get(2)
2602                .map(|obj| obj.clone().try_index(vm)?.try_to_primitive_in_range(vm))
2603                .transpose()?
2604                .unwrap_or(0);
2605            let scopeid = tuple
2606                .get(3)
2607                .map(|obj| u32::try_from_borrowed_object(vm, obj))
2608                .transpose()?
2609                .unwrap_or(0);
2610            if flowinfo > 0xfffff {
2611                return Err(vm.new_overflow_error("flowinfo must be 0-1048575."));
2612            }
2613            Ok((addr, flowinfo, scopeid))
2614        }
2615    }
2616
2617    fn get_ip_addr_tuple(addr: &SocketAddr, vm: &VirtualMachine) -> PyObjectRef {
2618        match addr {
2619            SocketAddr::V4(addr) => (addr.ip().to_string(), addr.port()).to_pyobject(vm),
2620            SocketAddr::V6(addr) => (
2621                addr.ip().to_string(),
2622                addr.port(),
2623                addr.flowinfo(),
2624                addr.scope_id(),
2625            )
2626                .to_pyobject(vm),
2627        }
2628    }
2629
2630    fn get_addr_tuple(
2631        addr: &host_socket::raw::SockAddr,
2632        #[cfg_attr(not(target_os = "linux"), allow(unused_variables))] proto: i32,
2633        vm: &VirtualMachine,
2634    ) -> PyObjectRef {
2635        if let Some(addr) = addr.as_socket() {
2636            return get_ip_addr_tuple(&addr, vm);
2637        }
2638        #[cfg(unix)]
2639        if addr.is_unix() {
2640            use std::os::unix::ffi::OsStrExt;
2641            if let Some(abstractpath) = addr.as_abstract_namespace() {
2642                return vm.ctx.new_bytes([b"\0", abstractpath].concat()).into();
2643            }
2644            // necessary on macos
2645            let path =
2646                ffi::OsStr::as_bytes(addr.as_pathname().unwrap_or_else(|| "".as_ref()).as_ref());
2647            let nul_pos = memchr::memchr(b'\0', path).unwrap_or(path.len());
2648            let path = ffi::OsStr::from_bytes(&path[..nul_pos]);
2649            return vm.fsdecode(path).into();
2650        }
2651        #[cfg(target_os = "linux")]
2652        {
2653            let family = addr.family();
2654            if family == c::AF_CAN as c::sa_family_t {
2655                let can_addr = unsafe { &*(addr.as_ptr() as *const c::sockaddr_can) };
2656                let ifindex = can_addr.can_ifindex;
2657                let ifname = if ifindex == 0 {
2658                    String::new()
2659                } else {
2660                    host_socket::if_indextoname_checked(ifindex as u32).unwrap_or_default()
2661                };
2662                let ifname_obj: PyObjectRef = vm.ctx.new_str(ifname).into();
2663                return match proto {
2664                    c::CAN_ISOTP => vm
2665                        .ctx
2666                        .new_tuple(vec![
2667                            ifname_obj,
2668                            vm.ctx.new_int(unsafe { can_addr.can_addr.tp.rx_id }).into(),
2669                            vm.ctx.new_int(unsafe { can_addr.can_addr.tp.tx_id }).into(),
2670                        ])
2671                        .into(),
2672                    c::CAN_J1939 => vm
2673                        .ctx
2674                        .new_tuple(vec![
2675                            ifname_obj,
2676                            vm.ctx
2677                                .new_int(unsafe { can_addr.can_addr.j1939.name })
2678                                .into(),
2679                            vm.ctx
2680                                .new_int(unsafe { can_addr.can_addr.j1939.pgn })
2681                                .into(),
2682                            vm.ctx
2683                                .new_int(unsafe { can_addr.can_addr.j1939.addr })
2684                                .into(),
2685                        ])
2686                        .into(),
2687                    _ => vm.ctx.new_tuple(vec![ifname_obj]).into(),
2688                };
2689            }
2690            if family == c::AF_ALG as c::sa_family_t {
2691                // AF_ALG address: (type, name)
2692                let alg_addr = unsafe { &*(addr.as_ptr() as *const c::sockaddr_alg) };
2693                let type_bytes = &alg_addr.salg_type;
2694                let name_bytes = &alg_addr.salg_name;
2695                let type_nul = memchr::memchr(b'\0', type_bytes).unwrap_or(type_bytes.len());
2696                let name_nul = memchr::memchr(b'\0', name_bytes).unwrap_or(name_bytes.len());
2697                let type_str = String::from_utf8_lossy(&type_bytes[..type_nul]).into_owned();
2698                let name_str = String::from_utf8_lossy(&name_bytes[..name_nul]).into_owned();
2699                return vm
2700                    .ctx
2701                    .new_tuple(vec![
2702                        vm.ctx.new_str(type_str).into(),
2703                        vm.ctx.new_str(name_str).into(),
2704                    ])
2705                    .into();
2706            }
2707        }
2708        #[cfg(windows)]
2709        {
2710            let family = addr.family() as i32;
2711            if family == c::AF_HYPERV {
2712                let hv = unsafe { &*(addr.as_ptr() as *const host_socket::SockaddrHv) };
2713                let vm_id = host_socket::uuid_to_string_w(&hv.vm_id).unwrap_or_default();
2714                let service_id = host_socket::uuid_to_string_w(&hv.service_id).unwrap_or_default();
2715                return vm
2716                    .ctx
2717                    .new_tuple(vec![
2718                        vm.ctx.new_str(vm_id).into(),
2719                        vm.ctx.new_str(service_id).into(),
2720                    ])
2721                    .into();
2722            }
2723            if family == c::AF_BLUETOOTH {
2724                let (bd_addr, port) = host_socket::unpack_sockaddr_bth(addr.as_ptr().cast());
2725                let name = host_socket::format_bdaddr(bd_addr);
2726                return vm
2727                    .ctx
2728                    .new_tuple(vec![
2729                        vm.ctx.new_str(name).into(),
2730                        vm.ctx.new_int(port).into(),
2731                    ])
2732                    .into();
2733            }
2734        }
2735        // TODO: support more address families
2736        (String::new(), 0).to_pyobject(vm)
2737    }
2738
2739    #[pyfunction]
2740    fn gethostname(vm: &VirtualMachine) -> PyResult<PyStrRef> {
2741        vm.audit("socket.gethostname", || ())?;
2742
2743        rustpython_host_env::socket::hostname()
2744            .into_string()
2745            .map(|hostname| vm.ctx.new_str(hostname))
2746            .map_err(|err| vm.new_os_error(err.into_string().unwrap()))
2747    }
2748
2749    #[cfg(all(unix, not(any(target_os = "redox", target_os = "android"))))]
2750    #[pyfunction]
2751    fn sethostname(hostname: FsPath) -> std::io::Result<()> {
2752        host_socket::sethostname(hostname.as_bytes())
2753    }
2754
2755    #[pyfunction]
2756    fn inet_aton(ip_addr: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
2757        inet::aton(ip_addr.as_str().as_bytes())
2758            .map(Vec::from)
2759            .ok_or_else(|| vm.new_os_error("illegal IP address string passed to inet_aton"))
2760    }
2761
2762    #[pyfunction]
2763    fn inet_ntoa(packed_ip: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyStrRef> {
2764        let packed_ip = packed_ip.borrow_buf();
2765        let packed_ip = <[u8; 4]>::try_from(&*packed_ip)
2766            .map_err(|_| vm.new_os_error("packed IP wrong length for inet_ntoa"))?;
2767        Ok(vm.ctx.new_str(inet::ntoa(packed_ip)))
2768    }
2769
2770    fn cstr_opt_as_ptr(x: &OptionalArg<ffi::CString>) -> *const core::ffi::c_char {
2771        x.as_ref().map_or_else(core::ptr::null, |s| s.as_ptr())
2772    }
2773
2774    #[pyfunction]
2775    fn getservbyname(
2776        servicename: PyStrRef,
2777        protocolname: OptionalArg<PyStrRef>,
2778        vm: &VirtualMachine,
2779    ) -> PyResult<u16> {
2780        let cstr_name = servicename.to_cstring(vm)?;
2781        let cstr_proto = protocolname
2782            .as_ref()
2783            .map(|s| s.to_cstring(vm))
2784            .transpose()?;
2785        let cstr_proto = cstr_opt_as_ptr(&cstr_proto);
2786        let serv = unsafe { c::getservbyname(cstr_name.as_ptr() as _, cstr_proto as _) };
2787        if serv.is_null() {
2788            return Err(vm.new_os_error("service/proto not found"));
2789        }
2790        let port = unsafe { (*serv).s_port };
2791        Ok(u16::from_be(port as u16))
2792    }
2793
2794    #[pyfunction]
2795    fn getservbyport(
2796        port: i32,
2797        protocolname: OptionalArg<PyStrRef>,
2798        vm: &VirtualMachine,
2799    ) -> PyResult<String> {
2800        let port = port
2801            .to_u16()
2802            .ok_or_else(|| vm.new_overflow_error("getservbyport: port must be 0-65535."))?;
2803        let cstr_proto = protocolname
2804            .as_ref()
2805            .map(|s| s.to_cstring(vm))
2806            .transpose()?;
2807        let cstr_proto = cstr_opt_as_ptr(&cstr_proto);
2808        let serv = unsafe { c::getservbyport(port.to_be() as _, cstr_proto as _) };
2809        if serv.is_null() {
2810            return Err(vm.new_os_error("port/proto not found"));
2811        }
2812        let s = unsafe { ffi::CStr::from_ptr((*serv).s_name as _) };
2813        Ok(s.to_string_lossy().into_owned())
2814    }
2815
2816    /// Room to receive into that belongs to no Python object.
2817    ///
2818    /// A peer may never send, so the wait for it is unbounded. The export of
2819    /// the caller's buffer is held for the whole call, which is what keeps it
2820    /// from being resized, but the borrow that reaches its bytes is a lock
2821    /// every other thread touching that object waits on, and a thread waiting
2822    /// on a lock never reaches a safepoint — holding it across the wait stops
2823    /// the world from being stopped at all. The bytes are copied over once
2824    /// they have arrived.
2825    fn alloc_recv_scratch(len: usize, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
2826        let mut scratch = Vec::new();
2827        scratch
2828            .try_reserve_exact(len)
2829            .map_err(|_| vm.no_memory_error())?;
2830        Ok(scratch)
2831    }
2832
2833    enum IoOrPyException {
2834        Timeout,
2835        Py(PyBaseExceptionRef),
2836        Io(io::Error),
2837    }
2838    impl From<PyBaseExceptionRef> for IoOrPyException {
2839        fn from(exc: PyBaseExceptionRef) -> Self {
2840            Self::Py(exc)
2841        }
2842    }
2843    impl From<PyRef<PyOSError>> for IoOrPyException {
2844        fn from(exc: PyRef<PyOSError>) -> Self {
2845            Self::Py(exc.upcast())
2846        }
2847    }
2848    impl From<io::Error> for IoOrPyException {
2849        fn from(err: io::Error) -> Self {
2850            Self::Io(err)
2851        }
2852    }
2853    impl IoOrPyException {
2854        fn errno(self) -> PyResult<i32> {
2855            match self {
2856                Self::Timeout => Ok(errcode!(EWOULDBLOCK)),
2857                Self::Io(err) => Ok(err.posix_errno()),
2858                Self::Py(exc) => Err(exc),
2859            }
2860        }
2861    }
2862    impl IntoPyException for IoOrPyException {
2863        #[inline]
2864        fn into_pyexception(self, vm: &VirtualMachine) -> PyBaseExceptionRef {
2865            match self {
2866                Self::Timeout => timeout_error(vm).upcast(),
2867                Self::Py(exc) => exc,
2868                Self::Io(err) => err.into_pyexception(vm),
2869            }
2870        }
2871    }
2872
2873    #[derive(Copy, Clone)]
2874    pub(crate) enum SockWaitKind {
2875        Read,
2876        Write,
2877        Connect,
2878    }
2879
2880    /// returns Ok(true) on timeout
2881    #[cfg(feature = "ssl")]
2882    pub(crate) fn sock_wait(
2883        sock: &Socket,
2884        wait_kind: SockWaitKind,
2885        timeout: Option<Duration>,
2886        vm: &VirtualMachine,
2887    ) -> PyResult<bool> {
2888        match sock_wait_deadline(sock, wait_kind, timeout.map(Deadline::new).as_ref(), vm) {
2889            Ok(()) => Ok(false),
2890            Err(IoOrPyException::Timeout) => Ok(true),
2891            Err(e) => Err(e.into_pyexception(vm)),
2892        }
2893    }
2894
2895    /// returns Err(IoOrPyException::Timeout) on timeout
2896    fn sock_wait_deadline(
2897        sock: &Socket,
2898        wait_kind: SockWaitKind,
2899        deadline: Option<&Deadline>,
2900        vm: &VirtualMachine,
2901    ) -> Result<(), IoOrPyException> {
2902        use rustpython_host_env::select::{WaitFd, WaitFdError, WaitKind, wait_fd};
2903
2904        let kind = match wait_kind {
2905            SockWaitKind::Read => WaitKind::Read,
2906            SockWaitKind::Write | SockWaitKind::Connect => WaitKind::Write,
2907        };
2908        let deadline = deadline.map(Deadline::instant);
2909        loop {
2910            match vm.allow_threads(|| wait_fd(sock_fileno(sock), kind, deadline)) {
2911                Ok(WaitFd::Ready) => return Ok(()),
2912                Ok(WaitFd::Timeout) => return Err(IoOrPyException::Timeout),
2913                Err(WaitFdError::Interrupted) => vm.check_signals()?,
2914                Err(WaitFdError::Io(err)) => return Err(err.into()),
2915            }
2916        }
2917    }
2918
2919    #[derive(FromArgs)]
2920    struct GAIOptions {
2921        #[pyarg(any)]
2922        host: Option<ArgStrOrBytesLike>,
2923        #[pyarg(any)]
2924        port: Option<Either<ArgStrOrBytesLike, i32>>,
2925
2926        #[pyarg(any, default = c::AF_UNSPEC)]
2927        family: i32,
2928        #[pyarg(any, name = "type", default)]
2929        ty: i32,
2930        #[pyarg(any, default)]
2931        proto: i32,
2932        #[pyarg(any, default)]
2933        flags: i32,
2934    }
2935
2936    #[pyfunction]
2937    fn getaddrinfo(
2938        opts: GAIOptions,
2939        vm: &VirtualMachine,
2940    ) -> Result<Vec<PyObjectRef>, IoOrPyException> {
2941        let hints = host_socket::dns::AddrInfoHints {
2942            socktype: opts.ty,
2943            protocol: opts.proto,
2944            address: opts.family,
2945            flags: opts.flags,
2946        };
2947
2948        // Encode host: str uses IDNA encoding, bytes must be valid UTF-8
2949        let host_encoded: Option<String> = match opts.host.as_ref() {
2950            Some(ArgStrOrBytesLike::Str(s)) => {
2951                let encoded =
2952                    vm.state
2953                        .codec_registry
2954                        .encode_text(s.to_owned(), "idna", None, vm)?;
2955                let host_str = core::str::from_utf8(encoded.as_bytes())
2956                    .map_err(|_| vm.new_runtime_error("idna output is not utf8"))?;
2957                Some(host_str.to_owned())
2958            }
2959            Some(ArgStrOrBytesLike::Buf(b)) => {
2960                let bytes = b.borrow_buf();
2961                let host_str = core::str::from_utf8(&bytes).map_err(|e| {
2962                    vm.new_unicode_decode_error(
2963                        vm.ctx.new_str("utf-8"),
2964                        vm.ctx.new_bytes(bytes.to_vec()),
2965                        e.valid_up_to(),
2966                        e.error_len().map_or(bytes.len(), |n| e.valid_up_to() + n),
2967                        vm.ctx.new_str("host bytes is not utf8"),
2968                    )
2969                })?;
2970                Some(host_str.to_owned())
2971            }
2972            None => None,
2973        };
2974        let host = host_encoded.as_deref();
2975
2976        // Encode port: str/bytes as service name, int as port number
2977        let port_encoded: Option<String> = match opts.port.as_ref() {
2978            Some(Either::A(sb)) => {
2979                let port_str = match sb {
2980                    ArgStrOrBytesLike::Str(s) => {
2981                        // For str, check for surrogates and raise UnicodeEncodeError if found
2982                        s.to_str()
2983                            .ok_or_else(|| {
2984                                let start = s
2985                                    .as_wtf8()
2986                                    .code_points()
2987                                    .position(|c| c.to_char().is_none())
2988                                    .unwrap();
2989                                vm.new_unicode_encode_error(
2990                                    vm.ctx.new_str("utf-8"),
2991                                    (*s).clone(),
2992                                    start,
2993                                    start + 1,
2994                                    vm.ctx.new_str("surrogates not allowed"),
2995                                )
2996                            })?
2997                            .to_owned()
2998                    }
2999                    ArgStrOrBytesLike::Buf(b) => {
3000                        // For bytes, check if it's valid UTF-8
3001                        let bytes = b.borrow_buf();
3002                        core::str::from_utf8(&bytes)
3003                            .map_err(|e| {
3004                                vm.new_unicode_decode_error(
3005                                    vm.ctx.new_str("utf-8"),
3006                                    vm.ctx.new_bytes(bytes.to_vec()),
3007                                    e.valid_up_to(),
3008                                    e.error_len().map_or(bytes.len(), |n| e.valid_up_to() + n),
3009                                    vm.ctx.new_str("port is not utf8"),
3010                                )
3011                            })?
3012                            .to_owned()
3013                    }
3014                };
3015                Some(port_str)
3016            }
3017            Some(Either::B(i)) => Some(i.to_string()),
3018            None => None,
3019        };
3020        let port = port_encoded.as_deref();
3021
3022        let addrs = host_socket::dns::getaddrinfo(host, port, Some(hints))
3023            .map_err(|err| convert_socket_error(vm, err, SocketError::GaiError))?;
3024
3025        let list = addrs
3026            .map(|ai| {
3027                ai.map(|ai| {
3028                    vm.new_tuple((
3029                        ai.address,
3030                        ai.socktype,
3031                        ai.protocol,
3032                        ai.canonname,
3033                        get_ip_addr_tuple(&ai.sockaddr, vm),
3034                    ))
3035                    .into()
3036                })
3037            })
3038            .collect::<io::Result<Vec<_>>>()?;
3039        Ok(list)
3040    }
3041
3042    #[pyfunction]
3043    fn gethostbyaddr(
3044        addr: PyUtf8StrRef,
3045        vm: &VirtualMachine,
3046    ) -> Result<(String, PyListRef, PyListRef), IoOrPyException> {
3047        let addr = get_addr(vm, addr, c::AF_UNSPEC)?;
3048        let (hostname, _) = host_socket::dns::getnameinfo(&addr, 0)
3049            .map_err(|e| convert_socket_error(vm, e, SocketError::HError))?;
3050        Ok((
3051            hostname,
3052            vm.ctx.new_list(vec![]),
3053            vm.ctx
3054                .new_list(vec![vm.ctx.new_str(addr.ip().to_string()).into()]),
3055        ))
3056    }
3057
3058    #[pyfunction]
3059    fn gethostbyname(name: PyUtf8StrRef, vm: &VirtualMachine) -> Result<String, IoOrPyException> {
3060        let addr = get_addr(vm, name, c::AF_INET)?;
3061        match addr {
3062            SocketAddr::V4(ip) => Ok(ip.ip().to_string()),
3063            _ => unreachable!(),
3064        }
3065    }
3066
3067    #[pyfunction]
3068    fn gethostbyname_ex(
3069        name: PyUtf8StrRef,
3070        vm: &VirtualMachine,
3071    ) -> Result<(String, PyListRef, PyListRef), IoOrPyException> {
3072        let addr = get_addr(vm, name, c::AF_INET)?;
3073        let (hostname, _) = host_socket::dns::getnameinfo(&addr, 0)
3074            .map_err(|e| convert_socket_error(vm, e, SocketError::HError))?;
3075        Ok((
3076            hostname,
3077            vm.ctx.new_list(vec![]),
3078            vm.ctx
3079                .new_list(vec![vm.ctx.new_str(addr.ip().to_string()).into()]),
3080        ))
3081    }
3082
3083    #[pyfunction]
3084    fn inet_pton(af_inet: i32, ip_string: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
3085        let text = ip_string.as_str().as_bytes();
3086        let packed = match af_inet {
3087            c::AF_INET => inet::pton_v4(text).map(Vec::from),
3088            c::AF_INET6 => inet::pton_v6(text).map(Vec::from),
3089            // What the host would report for an address family it has no
3090            // converter for.
3091            _ => {
3092                let unsupported = rustpython_host_env::errno::errors::EAFNOSUPPORT;
3093                return Err(io::Error::from_raw_os_error(unsupported).into_pyexception(vm));
3094            }
3095        };
3096        packed.ok_or_else(|| vm.new_os_error("illegal IP address string passed to inet_pton"))
3097    }
3098
3099    #[pyfunction]
3100    fn inet_ntop(af_inet: i32, packed_ip: ArgBytesLike, vm: &VirtualMachine) -> PyResult<String> {
3101        let packed_ip = packed_ip.borrow_buf();
3102        let wrong_length = || vm.new_value_error("invalid length of packed IP address string");
3103        match af_inet {
3104            c::AF_INET => {
3105                let packed_ip = <[u8; 4]>::try_from(&*packed_ip).map_err(|_| wrong_length())?;
3106                Ok(inet::ntoa(packed_ip))
3107            }
3108            c::AF_INET6 => {
3109                if packed_ip.len() != 16 {
3110                    return Err(wrong_length());
3111                }
3112                Ok(inet::ntop_v6(&packed_ip))
3113            }
3114            _ => Err(vm.new_value_error(format!("unknown address family {af_inet}"))),
3115        }
3116    }
3117
3118    #[pyfunction]
3119    fn getprotobyname(name: PyStrRef, vm: &VirtualMachine) -> PyResult {
3120        let cstr = name.to_cstring(vm)?;
3121        let proto = unsafe { c::getprotobyname(cstr.as_ptr() as _) };
3122        if proto.is_null() {
3123            return Err(vm.new_os_error("protocol not found"));
3124        }
3125        let num = unsafe { (*proto).p_proto };
3126        Ok(vm.ctx.new_int(num).into())
3127    }
3128
3129    #[pyfunction]
3130    fn getnameinfo(
3131        address: PyTupleRef,
3132        flags: i32,
3133        vm: &VirtualMachine,
3134    ) -> Result<(String, String), IoOrPyException> {
3135        match address.as_slice().len() {
3136            2..=4 => {}
3137            _ => {
3138                return Err(vm.new_type_error("illegal sockaddr argument").into());
3139            }
3140        }
3141        let (addr, flowinfo, scopeid) = Address::from_tuple_ipv6(address.as_slice(), vm)?;
3142        let hints = host_socket::dns::AddrInfoHints {
3143            address: c::AF_UNSPEC,
3144            socktype: c::SOCK_DGRAM,
3145            flags: c::AI_NUMERICHOST,
3146            protocol: 0,
3147        };
3148        let service = addr.port.to_string();
3149        let host_str = addr.host.as_str();
3150        let mut res = host_socket::dns::getaddrinfo(Some(host_str), Some(&service), Some(hints))
3151            .map_err(|e| convert_socket_error(vm, e, SocketError::GaiError))?
3152            .filter_map(Result::ok);
3153        let mut ainfo = res.next().unwrap();
3154        if res.next().is_some() {
3155            return Err(vm
3156                .new_os_error("sockaddr resolved to multiple addresses")
3157                .into());
3158        }
3159        match &mut ainfo.sockaddr {
3160            SocketAddr::V4(_) => {
3161                if address.as_slice().len() != 2 {
3162                    return Err(vm.new_os_error("IPv4 sockaddr must be 2 tuple").into());
3163                }
3164            }
3165            SocketAddr::V6(addr) => {
3166                addr.set_flowinfo(flowinfo);
3167                addr.set_scope_id(scopeid);
3168            }
3169        }
3170        host_socket::dns::getnameinfo(&ainfo.sockaddr, flags)
3171            .map_err(|e| convert_socket_error(vm, e, SocketError::GaiError))
3172    }
3173
3174    #[cfg(unix)]
3175    #[pyfunction]
3176    fn socketpair(
3177        family: OptionalArg<i32>,
3178        socket_kind: OptionalArg<i32>,
3179        proto: OptionalArg<i32>,
3180    ) -> Result<(PySocket, PySocket), IoOrPyException> {
3181        let family = family.unwrap_or(c::AF_UNIX);
3182        let socket_kind = socket_kind.unwrap_or(c::SOCK_STREAM);
3183        let proto = proto.unwrap_or(0);
3184        let (a, b) = Socket::pair(family.into(), socket_kind.into(), Some(proto.into()))?;
3185        let py_a = PySocket::default();
3186        py_a.init_inner(family, socket_kind, proto, a)?;
3187        let py_b = PySocket::default();
3188        py_b.init_inner(family, socket_kind, proto, b)?;
3189        Ok((py_a, py_b))
3190    }
3191
3192    #[cfg(all(unix, not(target_os = "redox")))]
3193    type IfIndex = c::c_uint;
3194    #[cfg(windows)]
3195    type IfIndex = u32; // NET_IFINDEX but windows-sys 0.59 doesn't have it
3196
3197    #[cfg(not(target_os = "redox"))]
3198    #[pyfunction]
3199    fn if_nametoindex(oname: FsPath, vm: &VirtualMachine) -> PyResult<IfIndex> {
3200        #[cfg(windows)]
3201        {
3202            let name = oname.to_cstring(vm)?;
3203            host_socket::if_nametoindex_checked(&name).map_err(|_| vm.new_last_errno_error())
3204        }
3205        #[cfg(not(windows))]
3206        {
3207            let name = oname.to_cstring(vm)?;
3208            // in case 'if_nametoindex' does not set errno
3209            rustpython_host_env::os::set_errno(c::ENODEV);
3210            let ret = unsafe { c::if_nametoindex(name.as_ptr() as _) };
3211            if ret == 0 {
3212                Err(vm.new_last_errno_error())
3213            } else {
3214                Ok(ret)
3215            }
3216        }
3217    }
3218
3219    #[cfg(not(target_os = "redox"))]
3220    #[pyfunction]
3221    fn if_indextoname(if_index: IfIndex, vm: &VirtualMachine) -> PyResult<String> {
3222        #[cfg(windows)]
3223        {
3224            host_socket::if_indextoname_checked(if_index).map_err(|_| vm.new_last_errno_error())
3225        }
3226        #[cfg(not(windows))]
3227        {
3228            let mut buf = [0; c::IF_NAMESIZE + 1];
3229            // in case 'if_indextoname' does not set errno
3230            rustpython_host_env::os::set_errno(c::ENXIO);
3231            let ret = unsafe { c::if_indextoname(if_index, buf.as_mut_ptr()) };
3232            if ret.is_null() {
3233                Err(vm.new_last_errno_error())
3234            } else {
3235                let buf = unsafe { ffi::CStr::from_ptr(buf.as_ptr() as _) };
3236                Ok(buf.to_string_lossy().into_owned())
3237            }
3238        }
3239    }
3240
3241    #[cfg(any(
3242        windows,
3243        target_os = "dragonfly",
3244        target_os = "freebsd",
3245        target_os = "fuchsia",
3246        target_os = "ios",
3247        target_os = "linux",
3248        target_os = "macos",
3249        target_os = "netbsd",
3250        target_os = "openbsd",
3251    ))]
3252    #[pyfunction]
3253    fn if_nameindex(vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> {
3254        #[cfg(not(windows))]
3255        {
3256            let list = host_socket::if_nameindex()
3257                .map_err(|err| err.into_pyexception(vm))?
3258                .into_iter()
3259                .map(|tup| tup.to_pyobject(vm))
3260                .collect();
3261
3262            Ok(list)
3263        }
3264        #[cfg(windows)]
3265        {
3266            let list = host_socket::if_nameindex()
3267                .map_err(|err| err.into_pyexception(vm))?
3268                .into_iter()
3269                .map(|(index, name)| (index, vm.ctx.new_str(name)).to_pyobject(vm))
3270                .collect();
3271            Ok(list)
3272        }
3273    }
3274
3275    fn get_addr(
3276        vm: &VirtualMachine,
3277        pyname: PyUtf8StrRef,
3278        af: i32,
3279    ) -> Result<SocketAddr, IoOrPyException> {
3280        let name = pyname.as_str();
3281        if name.is_empty() {
3282            let hints = host_socket::dns::AddrInfoHints {
3283                address: af,
3284                socktype: c::SOCK_DGRAM,
3285                flags: c::AI_PASSIVE,
3286                protocol: 0,
3287            };
3288            let mut res = host_socket::dns::getaddrinfo(None, Some("0"), Some(hints))
3289                .map_err(|e| convert_socket_error(vm, e, SocketError::GaiError))?;
3290            let ainfo = res.next().unwrap()?;
3291            if res.next().is_some() {
3292                return Err(vm
3293                    .new_os_error("wildcard resolved to multiple address")
3294                    .into());
3295            }
3296            return Ok(ainfo.sockaddr);
3297        }
3298        if name == "255.255.255.255" || name == "<broadcast>" {
3299            match af {
3300                c::AF_INET | c::AF_UNSPEC => {}
3301                _ => {
3302                    return Err(vm.new_os_error("address family mismatched").into());
3303                }
3304            }
3305            return Ok(SocketAddr::V4(net::SocketAddrV4::new(
3306                c::INADDR_BROADCAST.into(),
3307                0,
3308            )));
3309        }
3310        if let c::AF_INET | c::AF_UNSPEC = af
3311            && let Ok(addr) = name.parse::<Ipv4Addr>()
3312        {
3313            return Ok(SocketAddr::V4(net::SocketAddrV4::new(addr, 0)));
3314        }
3315        if matches!(af, c::AF_INET | c::AF_UNSPEC)
3316            && !name.contains('%')
3317            && let Ok(addr) = name.parse::<Ipv6Addr>()
3318        {
3319            return Ok(SocketAddr::V6(net::SocketAddrV6::new(addr, 0, 0, 0)));
3320        }
3321        let hints = host_socket::dns::AddrInfoHints {
3322            address: af,
3323            ..Default::default()
3324        };
3325        let name = vm
3326            .state
3327            .codec_registry
3328            .encode_text(pyname.into_wtf8(), "idna", None, vm)?;
3329        let name = core::str::from_utf8(name.as_bytes())
3330            .map_err(|_| vm.new_runtime_error("idna output is not utf8"))?;
3331        let mut res = host_socket::dns::getaddrinfo(Some(name), None, Some(hints))
3332            .map_err(|e| convert_socket_error(vm, e, SocketError::GaiError))?;
3333        Ok(res.next().unwrap().map(|ainfo| ainfo.sockaddr)?)
3334    }
3335
3336    fn sock_from_raw(fileno: RawSocket, vm: &VirtualMachine) -> PyResult<Socket> {
3337        let invalid = cfg_select! {
3338            windows => fileno == INVALID_SOCKET,
3339            _ => fileno < 0,
3340        };
3341        if invalid {
3342            return Err(vm.new_value_error("negative file descriptor"));
3343        }
3344        Ok(unsafe { sock_from_raw_unchecked(fileno) })
3345    }
3346    /// SAFETY: fileno must not be equal to INVALID_SOCKET
3347    unsafe fn sock_from_raw_unchecked(fileno: RawSocket) -> Socket {
3348        #[cfg(unix)]
3349        {
3350            use std::os::unix::io::FromRawFd;
3351            unsafe { Socket::from_raw_fd(fileno) }
3352        }
3353        #[cfg(windows)]
3354        {
3355            use std::os::windows::io::FromRawSocket;
3356            unsafe { Socket::from_raw_socket(fileno) }
3357        }
3358    }
3359    pub(super) fn sock_fileno(sock: &Socket) -> RawSocket {
3360        #[cfg(unix)]
3361        {
3362            use std::os::unix::io::AsRawFd;
3363            sock.as_raw_fd()
3364        }
3365        #[cfg(windows)]
3366        {
3367            use std::os::windows::io::AsRawSocket;
3368            sock.as_raw_socket()
3369        }
3370    }
3371    fn into_sock_fileno(sock: Socket) -> RawSocket {
3372        #[cfg(unix)]
3373        {
3374            use std::os::unix::io::IntoRawFd;
3375            sock.into_raw_fd()
3376        }
3377        #[cfg(windows)]
3378        {
3379            use std::os::windows::io::IntoRawSocket;
3380            sock.into_raw_socket()
3381        }
3382    }
3383
3384    pub(super) const INVALID_SOCKET: RawSocket = {
3385        #[cfg(unix)]
3386        {
3387            -1
3388        }
3389        #[cfg(windows)]
3390        {
3391            host_socket::INVALID_RAW_SOCKET as RawSocket
3392        }
3393    };
3394
3395    fn convert_socket_error(
3396        vm: &VirtualMachine,
3397        err: host_socket::dns::LookupError,
3398        err_kind: SocketError,
3399    ) -> IoOrPyException {
3400        if let host_socket::dns::LookupErrorKind::System = err.kind() {
3401            return io::Error::from(err).into();
3402        }
3403        let strerr = {
3404            #[cfg(unix)]
3405            {
3406                match err_kind {
3407                    SocketError::GaiError => host_socket::gai_error_string(err.error_num()),
3408                    SocketError::HError => host_socket::h_error_string(err.error_num()),
3409                }
3410            }
3411            #[cfg(windows)]
3412            {
3413                "getaddrinfo failed".to_owned()
3414            }
3415        };
3416        let exception_cls = match err_kind {
3417            SocketError::GaiError => gaierror(vm),
3418            SocketError::HError => herror(vm),
3419        };
3420        vm.new_os_subtype_error(exception_cls, Some(err.error_num()), strerr)
3421            .into()
3422    }
3423
3424    fn timeout_error(vm: &VirtualMachine) -> PyRef<PyOSError> {
3425        timeout_error_msg(vm, "timed out".to_owned())
3426    }
3427    pub(crate) fn timeout_error_msg(vm: &VirtualMachine, msg: String) -> PyRef<PyOSError> {
3428        vm.new_os_subtype_error(timeout(vm), None, msg)
3429    }
3430
3431    #[derive(Copy, Clone)]
3432    pub(crate) struct Deadline {
3433        deadline: Instant,
3434    }
3435
3436    impl Deadline {
3437        fn new(timeout: Duration) -> Self {
3438            Self {
3439                deadline: Instant::now() + timeout,
3440            }
3441        }
3442        fn instant(&self) -> Instant {
3443            self.deadline
3444        }
3445    }
3446
3447    static DEFAULT_TIMEOUT: AtomicCell<f64> = AtomicCell::new(-1.0);
3448
3449    #[pyfunction]
3450    fn getdefaulttimeout() -> Option<f64> {
3451        let timeout = DEFAULT_TIMEOUT.load();
3452        if timeout >= 0.0 { Some(timeout) } else { None }
3453    }
3454
3455    #[pyfunction]
3456    fn setdefaulttimeout(object: Option<ArgIntoFloat>, vm: &VirtualMachine) -> PyResult<()> {
3457        let val = match object {
3458            Some(t) => {
3459                let f = t.into_float();
3460                if f.is_nan() {
3461                    return Err(vm.new_value_error("Invalid value NaN (not a number)"));
3462                }
3463                if f < 0.0 || !f.is_finite() {
3464                    return Err(vm.new_value_error("Timeout value out of range"));
3465                }
3466                f
3467            }
3468            None => -1.0,
3469        };
3470        DEFAULT_TIMEOUT.store(val);
3471        Ok(())
3472    }
3473
3474    #[pyfunction]
3475    fn dup(object: PyObjectRef, vm: &VirtualMachine) -> Result<RawSocket, IoOrPyException> {
3476        let sock = get_raw_sock(&object, vm)?;
3477        let sock = core::mem::ManuallyDrop::new(sock_from_raw(sock, vm)?);
3478        let newsock = sock.try_clone()?;
3479        let fd = into_sock_fileno(newsock);
3480        #[cfg(windows)]
3481        host_socket::set_socket_inheritable(fd as _, false)?;
3482        Ok(fd)
3483    }
3484
3485    #[pyfunction]
3486    fn close(object: PyObjectRef, vm: &VirtualMachine) -> Result<(), IoOrPyException> {
3487        Ok(close_inner(get_raw_sock(&object, vm)?)?)
3488    }
3489
3490    fn close_inner(x: RawSocket) -> io::Result<()> {
3491        host_socket::close_socket_ignore_connreset(x as _)
3492    }
3493
3494    enum SocketError {
3495        HError,
3496        GaiError,
3497    }
3498
3499    #[cfg(all(unix, not(target_os = "redox")))]
3500    #[pyfunction(name = "CMSG_LEN")]
3501    fn cmsg_len(length: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
3502        let length = length.try_index(vm)?.try_to_primitive_in_range(vm)?;
3503        host_socket::checked_cmsg_len(length)
3504            .ok_or_else(|| vm.new_overflow_error("CMSG_LEN() argument out of range"))
3505    }
3506
3507    #[cfg(all(unix, not(target_os = "redox")))]
3508    #[pyfunction(name = "CMSG_SPACE")]
3509    fn cmsg_space(length: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
3510        let length = length.try_index(vm)?.try_to_primitive_in_range(vm)?;
3511        host_socket::checked_cmsg_space(length)
3512            .ok_or_else(|| vm.new_overflow_error("CMSG_SPACE() argument out of range"))
3513    }
3514}