• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Socket module */
2 
3 /*
4 
5 This module provides an interface to Berkeley socket IPC.
6 
7 Limitations:
8 
9 - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
10   portable manner, though AF_PACKET, AF_NETLINK, AF_QIPCRTR and AF_TIPC are
11   supported under Linux.
12 - No read/write operations (use sendall/recv or makefile instead).
13 - Additional restrictions apply on some non-Unix platforms (compensated
14   for by socket.py).
15 
16 Module interface:
17 
18 - socket.error: exception raised for socket specific errors, alias for OSError
19 - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
20     a subclass of socket.error
21 - socket.herror: exception raised for gethostby* errors,
22     a subclass of socket.error
23 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
24 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
25 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
26 - socket.getprotobyname(protocolname) --> protocol number
27 - socket.getservbyname(servicename[, protocolname]) --> port number
28 - socket.getservbyport(portnumber[, protocolname]) --> service name
29 - socket.socket([family[, type [, proto, fileno]]]) --> new socket object
30     (fileno specifies a pre-existing socket file descriptor)
31 - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
32 - socket.ntohs(16 bit value) --> new int object
33 - socket.ntohl(32 bit value) --> new int object
34 - socket.htons(16 bit value) --> new int object
35 - socket.htonl(32 bit value) --> new int object
36 - socket.getaddrinfo(host, port [, family, type, proto, flags])
37     --> List of (family, type, proto, canonname, sockaddr)
38 - socket.getnameinfo(sockaddr, flags) --> (host, port)
39 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
40 - socket.has_ipv6: boolean value indicating if IPv6 is supported
41 - socket.inet_aton(IP address) -> 32-bit packed IP representation
42 - socket.inet_ntoa(packed IP) -> IP address string
43 - socket.getdefaulttimeout() -> None | float
44 - socket.setdefaulttimeout(None | float)
45 - socket.if_nameindex() -> list of tuples (if_index, if_name)
46 - socket.if_nametoindex(name) -> corresponding interface index
47 - socket.if_indextoname(index) -> corresponding interface name
48 - an internet socket address is a pair (hostname, port)
49   where hostname can be anything recognized by gethostbyname()
50   (including the dd.dd.dd.dd notation) and port is in host byte order
51 - where a hostname is returned, the dd.dd.dd.dd notation is used
52 - a UNIX domain socket address is a string specifying the pathname
53 - an AF_PACKET socket address is a tuple containing a string
54   specifying the ethernet interface and an integer specifying
55   the Ethernet protocol number to be received. For example:
56   ("eth0",0x1234).  Optional 3rd,4th,5th elements in the tuple
57   specify packet-type and ha-type/addr.
58 - an AF_QIPCRTR socket address is a (node, port) tuple where the
59   node and port are non-negative integers.
60 - an AF_TIPC socket address is expressed as
61  (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
62     TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
63   and scope can be one of:
64     TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
65   The meaning of v1, v2 and v3 depends on the value of addr_type:
66     if addr_type is TIPC_ADDR_NAME:
67         v1 is the server type
68         v2 is the port identifier
69         v3 is ignored
70     if addr_type is TIPC_ADDR_NAMESEQ:
71         v1 is the server type
72         v2 is the lower port number
73         v3 is the upper port number
74     if addr_type is TIPC_ADDR_ID:
75         v1 is the node
76         v2 is the ref
77         v3 is ignored
78 
79 
80 Local naming conventions:
81 
82 - names starting with sock_ are socket object methods
83 - names starting with socket_ are module-level functions
84 - names starting with PySocket are exported through socketmodule.h
85 
86 */
87 
88 #ifndef Py_BUILD_CORE_BUILTIN
89 #  define Py_BUILD_CORE_MODULE 1
90 #endif
91 
92 #ifdef __APPLE__
93 // Issue #35569: Expose RFC 3542 socket options.
94 #define __APPLE_USE_RFC_3542 1
95 #include <AvailabilityMacros.h>
96 /* for getaddrinfo thread safety test on old versions of OS X */
97 #ifndef MAC_OS_X_VERSION_10_5
98 #define MAC_OS_X_VERSION_10_5 1050
99 #endif
100   /*
101    * inet_aton is not available on OSX 10.3, yet we want to use a binary
102    * that was build on 10.4 or later to work on that release, weak linking
103    * comes to the rescue.
104    */
105 # pragma weak inet_aton
106 #endif
107 
108 #include "Python.h"
109 #include "pycore_capsule.h"       // _PyCapsule_SetTraverse()
110 #include "pycore_fileutils.h"     // _Py_set_inheritable()
111 #include "pycore_moduleobject.h"  // _PyModule_GetState
112 #include "pycore_time.h"          // _PyTime_AsMilliseconds()
113 
114 #ifdef _Py_MEMORY_SANITIZER
115 #  include <sanitizer/msan_interface.h>
116 #endif
117 
118 /* Socket object documentation */
119 PyDoc_STRVAR(sock_doc,
120 "socket(family=AF_INET, type=SOCK_STREAM, proto=0) -> socket object\n\
121 socket(family=-1, type=-1, proto=-1, fileno=None) -> socket object\n\
122 \n\
123 Open a socket of the given type.  The family argument specifies the\n\
124 address family; it defaults to AF_INET.  The type argument specifies\n\
125 whether this is a stream (SOCK_STREAM, this is the default)\n\
126 or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,\n\
127 specifying the default protocol.  Keyword arguments are accepted.\n\
128 The socket is created as non-inheritable.\n\
129 \n\
130 When a fileno is passed in, family, type and proto are auto-detected,\n\
131 unless they are explicitly set.\n\
132 \n\
133 A socket object represents one endpoint of a network connection.\n\
134 \n\
135 Methods of socket objects (keyword arguments not allowed):\n\
136 \n\
137 _accept() -- accept connection, returning new socket fd and client address\n\
138 bind(addr) -- bind the socket to a local address\n\
139 close() -- close the socket\n\
140 connect(addr) -- connect the socket to a remote address\n\
141 connect_ex(addr) -- connect, return an error code instead of an exception\n\
142 dup() -- return a new socket fd duplicated from fileno()\n\
143 fileno() -- return underlying file descriptor\n\
144 getpeername() -- return remote address [*]\n\
145 getsockname() -- return local address\n\
146 getsockopt(level, optname[, buflen]) -- get socket options\n\
147 gettimeout() -- return timeout or None\n\
148 listen([n]) -- start listening for incoming connections\n\
149 recv(buflen[, flags]) -- receive data\n\
150 recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
151 recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
152 recvfrom_into(buffer[, nbytes, [, flags])\n\
153   -- receive data and sender\'s address (into a buffer)\n\
154 sendall(data[, flags]) -- send all data\n\
155 send(data[, flags]) -- send data, may not send all of it\n\
156 sendto(data[, flags], addr) -- send data to a given address\n\
157 setblocking(bool) -- set or clear the blocking I/O flag\n\
158 getblocking() -- return True if socket is blocking, False if non-blocking\n\
159 setsockopt(level, optname, value[, optlen]) -- set socket options\n\
160 settimeout(None | float) -- set or clear the timeout\n\
161 shutdown(how) -- shut down traffic in one or both directions\n\
162 \n\
163  [*] not available on all platforms!");
164 
165 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
166    I hope some day someone can clean this up please... */
167 
168 /* Hacks for gethostbyname_r().  On some non-Linux platforms, the configure
169    script doesn't get this right, so we hardcode some platform checks below.
170    On the other hand, not all Linux versions agree, so there the settings
171    computed by the configure script are needed! */
172 
173 #ifndef __linux__
174 # undef HAVE_GETHOSTBYNAME_R_3_ARG
175 # undef HAVE_GETHOSTBYNAME_R_5_ARG
176 # undef HAVE_GETHOSTBYNAME_R_6_ARG
177 #endif
178 
179 #if defined(__OpenBSD__)
180 # include <sys/uio.h>
181 #endif
182 
183 #if defined(__ANDROID__) && __ANDROID_API__ < 23
184 # undef HAVE_GETHOSTBYNAME_R
185 #endif
186 
187 #ifdef HAVE_GETHOSTBYNAME_R
188 # if defined(_AIX) && !defined(_LINUX_SOURCE_COMPAT)
189 #  define HAVE_GETHOSTBYNAME_R_3_ARG
190 # elif defined(__sun) || defined(__sgi)
191 #  define HAVE_GETHOSTBYNAME_R_5_ARG
192 # elif defined(__linux__)
193 /* Rely on the configure script */
194 # elif defined(_LINUX_SOURCE_COMPAT) /* Linux compatibility on AIX */
195 #  define HAVE_GETHOSTBYNAME_R_6_ARG
196 # else
197 #  undef HAVE_GETHOSTBYNAME_R
198 # endif
199 #endif
200 
201 #if !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
202 # define USE_GETHOSTBYNAME_LOCK
203 #endif
204 
205 #if defined(__APPLE__) || defined(__CYGWIN__) || defined(__NetBSD__)
206 #  include <sys/ioctl.h>
207 #endif
208 
209 
210 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
211 /* make sure that the reentrant (gethostbyaddr_r etc)
212    functions are declared correctly if compiling with
213    MIPSPro 7.x in ANSI C mode (default) */
214 
215 /* XXX Using _SGIAPI is the wrong thing,
216    but I don't know what the right thing is. */
217 #undef _SGIAPI /* to avoid warning */
218 #define _SGIAPI 1
219 
220 #undef _XOPEN_SOURCE
221 #include <sys/socket.h>
222 #include <sys/types.h>
223 #include <netinet/in.h>
224 #ifdef _SS_ALIGNSIZE
225 #define HAVE_GETADDRINFO 1
226 #define HAVE_GETNAMEINFO 1
227 #endif
228 
229 #define HAVE_INET_PTON
230 #include <netdb.h>
231 #endif // __sgi
232 
233 /* Solaris fails to define this variable at all. */
234 #if (defined(__sun) && defined(__SVR4)) && !defined(INET_ADDRSTRLEN)
235 #define INET_ADDRSTRLEN 16
236 #endif
237 
238 /* Generic includes */
239 #ifdef HAVE_SYS_TYPES_H
240 #include <sys/types.h>
241 #endif
242 
243 #ifdef HAVE_SYS_SOCKET_H
244 #include <sys/socket.h>
245 #endif
246 
247 #ifdef HAVE_NET_IF_H
248 #include <net/if.h>
249 #endif
250 
251 #ifdef HAVE_NET_ETHERNET_H
252 #include <net/ethernet.h>
253 #endif
254 
255 /* Generic socket object definitions and includes */
256 #define PySocket_BUILDING_SOCKET
257 #include "socketmodule.h"
258 
259 /* Addressing includes */
260 
261 #ifndef MS_WINDOWS
262 
263 /* Non-MS WINDOWS includes */
264 #ifdef HAVE_NETDB_H
265 #  include <netdb.h>
266 #endif
267 #include <unistd.h>               // close()
268 
269 /* Headers needed for inet_ntoa() and inet_addr() */
270 #   include <arpa/inet.h>
271 
272 #  include <fcntl.h>
273 
274 #else /* MS_WINDOWS */
275 
276 /* MS_WINDOWS includes */
277 # ifdef HAVE_FCNTL_H
278 #  include <fcntl.h>
279 # endif
280 
281 /* Helpers needed for AF_HYPERV */
282 # include <Rpc.h>
283 
284 /* Macros based on the IPPROTO enum, see: https://bugs.python.org/issue29515 */
285 #define IPPROTO_ICMP IPPROTO_ICMP
286 #define IPPROTO_IGMP IPPROTO_IGMP
287 #define IPPROTO_GGP IPPROTO_GGP
288 #define IPPROTO_TCP IPPROTO_TCP
289 #define IPPROTO_PUP IPPROTO_PUP
290 #define IPPROTO_UDP IPPROTO_UDP
291 #define IPPROTO_IDP IPPROTO_IDP
292 #define IPPROTO_ND IPPROTO_ND
293 #define IPPROTO_RAW IPPROTO_RAW
294 #define IPPROTO_MAX IPPROTO_MAX
295 #define IPPROTO_HOPOPTS IPPROTO_HOPOPTS
296 #define IPPROTO_IPV4 IPPROTO_IPV4
297 #define IPPROTO_IPV6 IPPROTO_IPV6
298 #define IPPROTO_ROUTING IPPROTO_ROUTING
299 #define IPPROTO_FRAGMENT IPPROTO_FRAGMENT
300 #define IPPROTO_ESP IPPROTO_ESP
301 #define IPPROTO_AH IPPROTO_AH
302 #define IPPROTO_ICMPV6 IPPROTO_ICMPV6
303 #define IPPROTO_NONE IPPROTO_NONE
304 #define IPPROTO_DSTOPTS IPPROTO_DSTOPTS
305 #define IPPROTO_EGP IPPROTO_EGP
306 #define IPPROTO_PIM IPPROTO_PIM
307 #define IPPROTO_ICLFXBM IPPROTO_ICLFXBM  // WinSock2 only
308 #define IPPROTO_ST IPPROTO_ST  // WinSock2 only
309 #define IPPROTO_CBT IPPROTO_CBT  // WinSock2 only
310 #define IPPROTO_IGP IPPROTO_IGP  // WinSock2 only
311 #define IPPROTO_RDP IPPROTO_RDP  // WinSock2 only
312 #define IPPROTO_PGM IPPROTO_PGM  // WinSock2 only
313 #define IPPROTO_L2TP IPPROTO_L2TP  // WinSock2 only
314 #define IPPROTO_SCTP IPPROTO_SCTP  // WinSock2 only
315 
316 /* Provides the IsWindows7SP1OrGreater() function */
317 #include <versionhelpers.h>
318 // For if_nametoindex() and if_indextoname()
319 #include <iphlpapi.h>
320 
321 /* remove some flags on older version Windows during run-time.
322    https://msdn.microsoft.com/en-us/library/windows/desktop/ms738596.aspx */
323 typedef struct {
324     DWORD build_number;  /* available starting with this Win10 BuildNumber */
325     const char flag_name[20];
326 } FlagRuntimeInfo;
327 
328 /* IMPORTANT: make sure the list ordered by descending build_number */
329 static FlagRuntimeInfo win_runtime_flags[] = {
330     /* available starting with Windows 10 1709 */
331     {16299, "TCP_KEEPIDLE"},
332     {16299, "TCP_KEEPINTVL"},
333     /* available starting with Windows 10 1703 */
334     {15063, "TCP_KEEPCNT"},
335     /* available starting with Windows 10 1607 */
336     {14393, "TCP_FASTOPEN"}
337 };
338 
339 /*[clinic input]
340 module _socket
341 class _socket.socket "PySocketSockObject *" "clinic_state()->sock_type"
342 [clinic start generated code]*/
343 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=2db2489bd2219fd8]*/
344 
345 static int
remove_unusable_flags(PyObject * m)346 remove_unusable_flags(PyObject *m)
347 {
348     PyObject *dict;
349     OSVERSIONINFOEX info;
350 
351     dict = PyModule_GetDict(m);
352     if (dict == NULL) {
353         return -1;
354     }
355 #ifndef MS_WINDOWS_DESKTOP
356     info.dwOSVersionInfoSize = sizeof(info);
357     if (!GetVersionEx((OSVERSIONINFO*) &info)) {
358         PyErr_SetFromWindowsErr(0);
359         return -1;
360     }
361 #else
362     /* set to Windows 10, except BuildNumber. */
363     memset(&info, 0, sizeof(info));
364     info.dwOSVersionInfoSize = sizeof(info);
365     info.dwMajorVersion = 10;
366     info.dwMinorVersion = 0;
367 
368     /* set Condition Mask */
369     DWORDLONG dwlConditionMask = 0;
370     VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
371     VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
372     VER_SET_CONDITION(dwlConditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
373 #endif
374 
375     for (int i=0; i<sizeof(win_runtime_flags)/sizeof(FlagRuntimeInfo); i++) {
376 #ifdef MS_WINDOWS_DESKTOP
377         info.dwBuildNumber = win_runtime_flags[i].build_number;
378         /* greater than or equal to the specified version?
379            Compatibility Mode will not cheat VerifyVersionInfo(...) */
380         BOOL isSupported = VerifyVersionInfo(
381             &info,
382             VER_MAJORVERSION|VER_MINORVERSION|VER_BUILDNUMBER,
383             dwlConditionMask);
384 #else
385         /* note in this case 'info' is the actual OS version, whereas above
386            it is the version to compare against. */
387         BOOL isSupported = info.dwMajorVersion > 10 ||
388             (info.dwMajorVersion == 10 && info.dwMinorVersion > 0) ||
389             (info.dwMajorVersion == 10 && info.dwMinorVersion == 0 &&
390             info.dwBuildNumber >= win_runtime_flags[i].build_number);
391 #endif
392         if (isSupported) {
393             break;
394         }
395         else {
396             if (PyDict_PopString(dict, win_runtime_flags[i].flag_name,
397                                  NULL) < 0) {
398                 return -1;
399             }
400         }
401     }
402     return 0;
403 }
404 
405 #endif
406 
407 #include <stddef.h>
408 
409 #ifndef O_NONBLOCK
410 # define O_NONBLOCK O_NDELAY
411 #endif
412 
413 /* include Python's addrinfo.h unless it causes trouble */
414 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
415   /* Do not include addinfo.h on some newer IRIX versions.
416    * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
417    * for example, but not by 6.5.10.
418    */
419 #elif defined(_MSC_VER) && _MSC_VER>1201
420   /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
421    * EAI_* constants are defined in (the already included) ws2tcpip.h.
422    */
423 #else
424 #  include "addrinfo.h"
425 #endif
426 
427 #ifdef __APPLE__
428 /* On OS X, getaddrinfo returns no error indication of lookup
429    failure, so we must use the emulation instead of the libinfo
430    implementation. Unfortunately, performing an autoconf test
431    for this bug would require DNS access for the machine performing
432    the configuration, which is not acceptable. Therefore, we
433    determine the bug just by checking for __APPLE__. If this bug
434    gets ever fixed, perhaps checking for sys/version.h would be
435    appropriate, which is 10/0 on the system with the bug. */
436 #ifndef HAVE_GETNAMEINFO
437 /* This bug seems to be fixed in Jaguar. The easiest way I could
438    Find to check for Jaguar is that it has getnameinfo(), which
439    older releases don't have */
440 #undef HAVE_GETADDRINFO
441 #endif
442 
443 #ifdef HAVE_INET_ATON
444 #define USE_INET_ATON_WEAKLINK
445 #endif
446 
447 #endif
448 
449 /* I know this is a bad practice, but it is the easiest... */
450 #if !defined(HAVE_GETADDRINFO)
451 /* avoid clashes with the C library definition of the symbol. */
452 #define getaddrinfo fake_getaddrinfo
453 #define gai_strerror fake_gai_strerror
454 #define freeaddrinfo fake_freeaddrinfo
455 #include "getaddrinfo.c"
456 #endif
457 
458 #if !defined(HAVE_GETNAMEINFO)
459 #define getnameinfo fake_getnameinfo
460 #include "getnameinfo.c"
461 #endif // HAVE_GETNAMEINFO
462 
463 #ifdef MS_WINDOWS
464 #define SOCKETCLOSE closesocket
465 #endif
466 
467 #ifdef MS_WIN32
468 #  undef EAFNOSUPPORT
469 #  define EAFNOSUPPORT WSAEAFNOSUPPORT
470 #endif
471 
472 #ifndef SOCKETCLOSE
473 #  define SOCKETCLOSE close
474 #endif
475 
476 #if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
477 #define USE_BLUETOOTH 1
478 #if defined(__FreeBSD__)
479 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
480 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
481 #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
482 #define SOL_HCI SOL_HCI_RAW
483 #define HCI_FILTER SO_HCI_RAW_FILTER
484 #define sockaddr_l2 sockaddr_l2cap
485 #define sockaddr_rc sockaddr_rfcomm
486 #define hci_dev hci_node
487 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
488 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
489 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
490 #elif defined(__NetBSD__) || defined(__DragonFly__)
491 #define sockaddr_l2 sockaddr_bt
492 #define sockaddr_rc sockaddr_bt
493 #define sockaddr_hci sockaddr_bt
494 #define sockaddr_sco sockaddr_bt
495 #define SOL_HCI BTPROTO_HCI
496 #define HCI_DATA_DIR SO_HCI_DIRECTION
497 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
498 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
499 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
500 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
501 #else
502 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
503 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
504 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
505 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
506 #endif
507 #endif
508 
509 #ifdef MS_WINDOWS_DESKTOP
510 #define sockaddr_rc SOCKADDR_BTH_REDEF
511 
512 #define USE_BLUETOOTH 1
513 #define AF_BLUETOOTH AF_BTH
514 #define BTPROTO_RFCOMM BTHPROTO_RFCOMM
515 #define _BT_RC_MEMB(sa, memb) ((sa)->memb)
516 #endif /* MS_WINDOWS_DESKTOP */
517 
518 /* Convert "sock_addr_t *" to "struct sockaddr *". */
519 #define SAS2SA(x)       (&((x)->sa))
520 
521 /*
522  * Constants for getnameinfo()
523  */
524 #if !defined(NI_MAXHOST)
525 #define NI_MAXHOST 1025
526 #endif
527 #if !defined(NI_MAXSERV)
528 #define NI_MAXSERV 32
529 #endif
530 
531 #ifndef INVALID_SOCKET /* MS defines this */
532 #define INVALID_SOCKET (-1)
533 #endif
534 
535 #ifndef INADDR_NONE
536 #define INADDR_NONE (-1)
537 #endif
538 
539 typedef struct _socket_state {
540     /* The sock_type variable contains pointers to various functions,
541        some of which call new_sockobject(), which uses sock_type, so
542        there has to be a circular reference. */
543     PyTypeObject *sock_type;
544 
545     /* Global variable holding the exception type for errors detected
546        by this module (but not argument type or memory errors, etc.). */
547     PyObject *socket_herror;
548     PyObject *socket_gaierror;
549 
550     /* Default timeout for new sockets */
551     PyTime_t defaulttimeout;
552 
553 #if defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
554 #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
555     /* accept4() is available on Linux 2.6.28+ and glibc 2.10 */
556     int accept4_works;
557 #endif
558 #endif
559 
560 #ifdef SOCK_CLOEXEC
561     /* socket() and socketpair() fail with EINVAL on Linux kernel older
562      * than 2.6.27 if SOCK_CLOEXEC flag is set in the socket type. */
563     int sock_cloexec_works;
564 #endif
565 } socket_state;
566 
567 static inline socket_state *
get_module_state(PyObject * mod)568 get_module_state(PyObject *mod)
569 {
570     void *state = _PyModule_GetState(mod);
571     assert(state != NULL);
572     return (socket_state *)state;
573 }
574 
575 static struct PyModuleDef socketmodule;
576 
577 static inline socket_state *
find_module_state_by_def(PyTypeObject * type)578 find_module_state_by_def(PyTypeObject *type)
579 {
580     PyObject *mod = PyType_GetModuleByDef(type, &socketmodule);
581     assert(mod != NULL);
582     return get_module_state(mod);
583 }
584 
585 #define clinic_state() (find_module_state_by_def(type))
586 #include "clinic/socketmodule.c.h"
587 #undef clinic_state
588 
589 /* XXX There's a problem here: *static* functions are not supposed to have
590    a Py prefix (or use CapitalizedWords).  Later... */
591 
592 #if defined(HAVE_POLL_H)
593 #include <poll.h>
594 #elif defined(HAVE_SYS_POLL_H)
595 #include <sys/poll.h>
596 #endif
597 
598 /* Largest value to try to store in a socklen_t (used when handling
599    ancillary data).  POSIX requires socklen_t to hold at least
600    (2**31)-1 and recommends against storing larger values, but
601    socklen_t was originally int in the BSD interface, so to be on the
602    safe side we use the smaller of (2**31)-1 and INT_MAX. */
603 #if INT_MAX > 0x7fffffff
604 #define SOCKLEN_T_LIMIT 0x7fffffff
605 #else
606 #define SOCKLEN_T_LIMIT INT_MAX
607 #endif
608 
609 #ifdef HAVE_POLL
610 /* Instead of select(), we'll use poll() since poll() works on any fd. */
611 #define IS_SELECTABLE(s) 1
612 /* Can we call select() with this socket without a buffer overrun? */
613 #else
614 /* If there's no timeout left, we don't have to call select, so it's a safe,
615  * little white lie. */
616 #define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0)
617 #endif
618 
619 static PyObject*
select_error(void)620 select_error(void)
621 {
622     PyErr_SetString(PyExc_OSError, "unable to select on socket");
623     return NULL;
624 }
625 
626 #ifdef MS_WINDOWS
627 #ifndef WSAEAGAIN
628 #define WSAEAGAIN WSAEWOULDBLOCK
629 #endif
630 #define CHECK_ERRNO(expected) \
631     (WSAGetLastError() == WSA ## expected)
632 #else
633 #define CHECK_ERRNO(expected) \
634     (errno == expected)
635 #endif
636 
637 #ifdef MS_WINDOWS
638 #  define GET_SOCK_ERROR WSAGetLastError()
639 #  define SET_SOCK_ERROR(err) WSASetLastError(err)
640 #  define SOCK_TIMEOUT_ERR WSAEWOULDBLOCK
641 #  define SOCK_INPROGRESS_ERR WSAEWOULDBLOCK
642 #else
643 #  define GET_SOCK_ERROR errno
644 #  define SET_SOCK_ERROR(err) do { errno = err; } while (0)
645 #  define SOCK_TIMEOUT_ERR EWOULDBLOCK
646 #  define SOCK_INPROGRESS_ERR EINPROGRESS
647 #endif
648 
649 #ifdef _MSC_VER
650 #  define SUPPRESS_DEPRECATED_CALL __pragma(warning(suppress: 4996))
651 #else
652 #  define SUPPRESS_DEPRECATED_CALL
653 #endif
654 
655 /* Convenience function to raise an error according to errno
656    and return a NULL pointer from a function. */
657 
658 static PyObject *
set_error(void)659 set_error(void)
660 {
661 #ifdef MS_WINDOWS
662     int err_no = WSAGetLastError();
663     /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
664        recognizes the error codes used by both GetLastError() and
665        WSAGetLastError */
666     if (err_no)
667         return PyErr_SetExcFromWindowsErr(PyExc_OSError, err_no);
668 #endif
669 
670     return PyErr_SetFromErrno(PyExc_OSError);
671 }
672 
673 
674 #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME) || defined (HAVE_GETHOSTBYADDR)
675 static PyObject *
set_herror(socket_state * state,int h_error)676 set_herror(socket_state *state, int h_error)
677 {
678     PyObject *v;
679 
680 #ifdef HAVE_HSTRERROR
681     v = Py_BuildValue("(is)", h_error, hstrerror(h_error));
682 #else
683     v = Py_BuildValue("(is)", h_error, "host not found");
684 #endif
685     if (v != NULL) {
686         PyErr_SetObject(state->socket_herror, v);
687         Py_DECREF(v);
688     }
689 
690     return NULL;
691 }
692 #endif
693 
694 
695 #ifdef HAVE_GETADDRINFO
696 static PyObject *
set_gaierror(socket_state * state,int error)697 set_gaierror(socket_state *state, int error)
698 {
699     PyObject *v;
700 
701 #ifdef EAI_SYSTEM
702     /* EAI_SYSTEM is not available on Windows XP. */
703     if (error == EAI_SYSTEM)
704         return set_error();
705 #endif
706 
707 #ifdef HAVE_GAI_STRERROR
708     v = Py_BuildValue("(is)", error, gai_strerror(error));
709 #else
710     v = Py_BuildValue("(is)", error, "getaddrinfo failed");
711 #endif
712     if (v != NULL) {
713         PyErr_SetObject(state->socket_gaierror, v);
714         Py_DECREF(v);
715     }
716 
717     return NULL;
718 }
719 #endif
720 
721 /* Function to perform the setting of socket blocking mode
722    internally. block = (1 | 0). */
723 static int
internal_setblocking(PySocketSockObject * s,int block)724 internal_setblocking(PySocketSockObject *s, int block)
725 {
726     int result = -1;
727 #ifdef MS_WINDOWS
728     u_long arg;
729 #endif
730 #if !defined(MS_WINDOWS) \
731     && !((defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)))
732     int delay_flag, new_delay_flag;
733 #endif
734 
735     Py_BEGIN_ALLOW_THREADS
736 #ifndef MS_WINDOWS
737 #if (defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO))
738     block = !block;
739     if (ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block) == -1)
740         goto done;
741 #else
742     delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
743     if (delay_flag == -1)
744         goto done;
745     if (block)
746         new_delay_flag = delay_flag & (~O_NONBLOCK);
747     else
748         new_delay_flag = delay_flag | O_NONBLOCK;
749     if (new_delay_flag != delay_flag)
750         if (fcntl(s->sock_fd, F_SETFL, new_delay_flag) == -1)
751             goto done;
752 #endif
753 #else /* MS_WINDOWS */
754     arg = !block;
755     if (ioctlsocket(s->sock_fd, FIONBIO, &arg) != 0)
756         goto done;
757 #endif /* MS_WINDOWS */
758 
759     result = 0;
760 
761   done:
762     Py_END_ALLOW_THREADS
763 
764     if (result) {
765 #ifndef MS_WINDOWS
766         PyErr_SetFromErrno(PyExc_OSError);
767 #else
768         PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
769 #endif
770     }
771 
772     return result;
773 }
774 
775 static int
internal_select(PySocketSockObject * s,int writing,PyTime_t interval,int connect)776 internal_select(PySocketSockObject *s, int writing, PyTime_t interval,
777                 int connect)
778 {
779     int n;
780 #ifdef HAVE_POLL
781     struct pollfd pollfd;
782     PyTime_t ms;
783 #else
784     fd_set fds, efds;
785     struct timeval tv, *tvp;
786 #endif
787 
788     /* must be called with the GIL held */
789     assert(PyGILState_Check());
790 
791     /* Error condition is for output only */
792     assert(!(connect && !writing));
793 
794     /* Guard against closed socket */
795     if (s->sock_fd == INVALID_SOCKET)
796         return 0;
797 
798     /* Prefer poll, if available, since you can poll() any fd
799      * which can't be done with select(). */
800 #ifdef HAVE_POLL
801     pollfd.fd = s->sock_fd;
802     pollfd.events = writing ? POLLOUT : POLLIN;
803     if (connect) {
804         /* On Windows, the socket becomes writable on connection success,
805            but a connection failure is notified as an error. On POSIX, the
806            socket becomes writable on connection success or on connection
807            failure. */
808         pollfd.events |= POLLERR;
809     }
810 
811     /* s->sock_timeout is in seconds, timeout in ms */
812     ms = _PyTime_AsMilliseconds(interval, _PyTime_ROUND_CEILING);
813     if (ms > INT_MAX) {
814         ms = INT_MAX;
815     }
816 
817     /* On some OSes, typically BSD-based ones, the timeout parameter of the
818        poll() syscall, when negative, must be exactly INFTIM, where defined,
819        or -1. See issue 37811. */
820     if (ms < 0) {
821 #ifdef INFTIM
822         ms = INFTIM;
823 #else
824         ms = -1;
825 #endif
826     }
827     assert(INT_MIN <= ms && ms <= INT_MAX);
828 
829     Py_BEGIN_ALLOW_THREADS;
830     n = poll(&pollfd, 1, (int)ms);
831     Py_END_ALLOW_THREADS;
832 #else
833     if (interval >= 0) {
834         _PyTime_AsTimeval_clamp(interval, &tv, _PyTime_ROUND_CEILING);
835         tvp = &tv;
836     }
837     else
838         tvp = NULL;
839 
840     FD_ZERO(&fds);
841     FD_SET(s->sock_fd, &fds);
842     FD_ZERO(&efds);
843     if (connect) {
844         /* On Windows, the socket becomes writable on connection success,
845            but a connection failure is notified as an error. On POSIX, the
846            socket becomes writable on connection success or on connection
847            failure. */
848         FD_SET(s->sock_fd, &efds);
849     }
850 
851     /* See if the socket is ready */
852     Py_BEGIN_ALLOW_THREADS;
853     if (writing)
854         n = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
855                    NULL, &fds, &efds, tvp);
856     else
857         n = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
858                    &fds, NULL, &efds, tvp);
859     Py_END_ALLOW_THREADS;
860 #endif
861 
862     if (n < 0)
863         return -1;
864     if (n == 0)
865         return 1;
866     return 0;
867 }
868 
869 /* Call a socket function.
870 
871    On error, raise an exception and return -1 if err is set, or fill err and
872    return -1 otherwise. If a signal was received and the signal handler raised
873    an exception, return -1, and set err to -1 if err is set.
874 
875    On success, return 0, and set err to 0 if err is set.
876 
877    If the socket has a timeout, wait until the socket is ready before calling
878    the function: wait until the socket is writable if writing is nonzero, wait
879    until the socket received data otherwise.
880 
881    If the socket function is interrupted by a signal (failed with EINTR): retry
882    the function, except if the signal handler raised an exception (PEP 475).
883 
884    When the function is retried, recompute the timeout using a monotonic clock.
885 
886    sock_call_ex() must be called with the GIL held. The socket function is
887    called with the GIL released. */
888 static int
sock_call_ex(PySocketSockObject * s,int writing,int (* sock_func)(PySocketSockObject * s,void * data),void * data,int connect,int * err,PyTime_t timeout)889 sock_call_ex(PySocketSockObject *s,
890              int writing,
891              int (*sock_func) (PySocketSockObject *s, void *data),
892              void *data,
893              int connect,
894              int *err,
895              PyTime_t timeout)
896 {
897     int has_timeout = (timeout > 0);
898     PyTime_t deadline = 0;
899     int deadline_initialized = 0;
900     int res;
901 
902     /* sock_call() must be called with the GIL held. */
903     assert(PyGILState_Check());
904 
905     /* outer loop to retry select() when select() is interrupted by a signal
906        or to retry select()+sock_func() on false positive (see above) */
907     while (1) {
908         /* For connect(), poll even for blocking socket. The connection
909            runs asynchronously. */
910         if (has_timeout || connect) {
911             if (has_timeout) {
912                 PyTime_t interval;
913 
914                 if (deadline_initialized) {
915                     /* recompute the timeout */
916                     interval = _PyDeadline_Get(deadline);
917                 }
918                 else {
919                     deadline_initialized = 1;
920                     deadline = _PyDeadline_Init(timeout);
921                     interval = timeout;
922                 }
923 
924                 if (interval >= 0) {
925                     res = internal_select(s, writing, interval, connect);
926                 }
927                 else {
928                     res = 1;
929                 }
930             }
931             else {
932                 res = internal_select(s, writing, timeout, connect);
933             }
934 
935             if (res == -1) {
936                 if (err)
937                     *err = GET_SOCK_ERROR;
938 
939                 if (CHECK_ERRNO(EINTR)) {
940                     /* select() was interrupted by a signal */
941                     if (PyErr_CheckSignals()) {
942                         if (err)
943                             *err = -1;
944                         return -1;
945                     }
946 
947                     /* retry select() */
948                     continue;
949                 }
950 
951                 /* select() failed */
952                 s->errorhandler();
953                 return -1;
954             }
955 
956             if (res == 1) {
957                 if (err)
958                     *err = SOCK_TIMEOUT_ERR;
959                 else
960                     PyErr_SetString(PyExc_TimeoutError, "timed out");
961                 return -1;
962             }
963 
964             /* the socket is ready */
965         }
966 
967         /* inner loop to retry sock_func() when sock_func() is interrupted
968            by a signal */
969         while (1) {
970             Py_BEGIN_ALLOW_THREADS
971             res = sock_func(s, data);
972             Py_END_ALLOW_THREADS
973 
974             if (res) {
975                 /* sock_func() succeeded */
976                 if (err)
977                     *err = 0;
978                 return 0;
979             }
980 
981             if (err)
982                 *err = GET_SOCK_ERROR;
983 
984             if (!CHECK_ERRNO(EINTR))
985                 break;
986 
987             /* sock_func() was interrupted by a signal */
988             if (PyErr_CheckSignals()) {
989                 if (err)
990                     *err = -1;
991                 return -1;
992             }
993 
994             /* retry sock_func() */
995         }
996 
997         if (s->sock_timeout > 0
998             && (CHECK_ERRNO(EWOULDBLOCK) || CHECK_ERRNO(EAGAIN))) {
999             /* False positive: sock_func() failed with EWOULDBLOCK or EAGAIN.
1000 
1001                For example, select() could indicate a socket is ready for
1002                reading, but the data then discarded by the OS because of a
1003                wrong checksum.
1004 
1005                Loop on select() to recheck for socket readiness. */
1006             continue;
1007         }
1008 
1009         /* sock_func() failed */
1010         if (!err)
1011             s->errorhandler();
1012         /* else: err was already set before */
1013         return -1;
1014     }
1015 }
1016 
1017 static int
sock_call(PySocketSockObject * s,int writing,int (* func)(PySocketSockObject * s,void * data),void * data)1018 sock_call(PySocketSockObject *s,
1019           int writing,
1020           int (*func) (PySocketSockObject *s, void *data),
1021           void *data)
1022 {
1023     return sock_call_ex(s, writing, func, data, 0, NULL, s->sock_timeout);
1024 }
1025 
1026 
1027 /* Initialize a new socket object. */
1028 
1029 static int
init_sockobject(socket_state * state,PySocketSockObject * s,SOCKET_T fd,int family,int type,int proto)1030 init_sockobject(socket_state *state, PySocketSockObject *s,
1031                 SOCKET_T fd, int family, int type, int proto)
1032 {
1033     s->sock_fd = fd;
1034     s->sock_family = family;
1035 
1036     s->sock_type = type;
1037 
1038     /* It's possible to pass SOCK_NONBLOCK and SOCK_CLOEXEC bit flags
1039        on some OSes as part of socket.type.  We want to reset them here,
1040        to make socket.type be set to the same value on all platforms.
1041        Otherwise, simple code like 'if sock.type == SOCK_STREAM' is
1042        not portable.
1043     */
1044 #ifdef SOCK_NONBLOCK
1045     s->sock_type = s->sock_type & ~SOCK_NONBLOCK;
1046 #endif
1047 #ifdef SOCK_CLOEXEC
1048     s->sock_type = s->sock_type & ~SOCK_CLOEXEC;
1049 #endif
1050 
1051     s->sock_proto = proto;
1052 
1053     s->errorhandler = &set_error;
1054 #ifdef SOCK_NONBLOCK
1055     if (type & SOCK_NONBLOCK)
1056         s->sock_timeout = 0;
1057     else
1058 #endif
1059     {
1060         s->sock_timeout = _Py_atomic_load_int64_relaxed(&state->defaulttimeout);
1061         if (s->sock_timeout >= 0) {
1062             if (internal_setblocking(s, 0) == -1) {
1063                 return -1;
1064             }
1065         }
1066     }
1067     s->state = state;
1068     return 0;
1069 }
1070 
1071 
1072 #ifdef HAVE_SOCKETPAIR
1073 /* Create a new socket object.
1074    This just creates the object and initializes it.
1075    If the creation fails, return NULL and set an exception (implicit
1076    in NEWOBJ()). */
1077 
1078 static PySocketSockObject *
new_sockobject(socket_state * state,SOCKET_T fd,int family,int type,int proto)1079 new_sockobject(socket_state *state, SOCKET_T fd, int family, int type,
1080                int proto)
1081 {
1082     PyTypeObject *tp = state->sock_type;
1083     PySocketSockObject *s = (PySocketSockObject *)tp->tp_alloc(tp, 0);
1084     if (s == NULL) {
1085         return NULL;
1086     }
1087     if (init_sockobject(state, s, fd, family, type, proto) == -1) {
1088         Py_DECREF(s);
1089         return NULL;
1090     }
1091     return s;
1092 }
1093 #endif
1094 
1095 
1096 /* Lock to allow python interpreter to continue, but only allow one
1097    thread to be in gethostbyname or getaddrinfo */
1098 #if defined(USE_GETHOSTBYNAME_LOCK)
1099 static PyThread_type_lock netdb_lock;
1100 #endif
1101 
1102 
1103 #ifdef HAVE_GETADDRINFO
1104 /* Convert a string specifying a host name or one of a few symbolic
1105    names to a numeric IP address.  This usually calls gethostbyname()
1106    to do the work; the names "" and "<broadcast>" are special.
1107    Return the length (IPv4 should be 4 bytes), or negative if
1108    an error occurred; then an exception is raised. */
1109 
1110 static int
setipaddr(socket_state * state,const char * name,struct sockaddr * addr_ret,size_t addr_ret_size,int af)1111 setipaddr(socket_state *state, const char *name, struct sockaddr *addr_ret,
1112           size_t addr_ret_size, int af)
1113 {
1114     struct addrinfo hints, *res;
1115     int error;
1116 
1117     memset((void *) addr_ret, '\0', sizeof(*addr_ret));
1118     if (name[0] == '\0') {
1119         int siz;
1120         memset(&hints, 0, sizeof(hints));
1121         hints.ai_family = af;
1122         hints.ai_socktype = SOCK_DGRAM;         /*dummy*/
1123         hints.ai_flags = AI_PASSIVE;
1124         Py_BEGIN_ALLOW_THREADS
1125         error = getaddrinfo(NULL, "0", &hints, &res);
1126         Py_END_ALLOW_THREADS
1127         /* We assume that those thread-unsafe getaddrinfo() versions
1128            *are* safe regarding their return value, ie. that a
1129            subsequent call to getaddrinfo() does not destroy the
1130            outcome of the first call. */
1131         if (error) {
1132             res = NULL;  // no-op, remind us that it is invalid; gh-100795
1133             set_gaierror(state, error);
1134             return -1;
1135         }
1136         switch (res->ai_family) {
1137         case AF_INET:
1138             siz = 4;
1139             break;
1140 #ifdef ENABLE_IPV6
1141         case AF_INET6:
1142             siz = 16;
1143             break;
1144 #endif
1145         default:
1146             freeaddrinfo(res);
1147             PyErr_SetString(PyExc_OSError,
1148                 "unsupported address family");
1149             return -1;
1150         }
1151         if (res->ai_next) {
1152             freeaddrinfo(res);
1153             PyErr_SetString(PyExc_OSError,
1154                 "wildcard resolved to multiple address");
1155             return -1;
1156         }
1157         if (res->ai_addrlen < addr_ret_size)
1158             addr_ret_size = res->ai_addrlen;
1159         memcpy(addr_ret, res->ai_addr, addr_ret_size);
1160         freeaddrinfo(res);
1161         return siz;
1162     }
1163     /* special-case broadcast - inet_addr() below can return INADDR_NONE for
1164      * this */
1165     if (strcmp(name, "255.255.255.255") == 0 ||
1166         strcmp(name, "<broadcast>") == 0) {
1167         struct sockaddr_in *sin;
1168         if (af != AF_INET && af != AF_UNSPEC) {
1169             PyErr_SetString(PyExc_OSError,
1170                 "address family mismatched");
1171             return -1;
1172         }
1173         sin = (struct sockaddr_in *)addr_ret;
1174         memset((void *) sin, '\0', sizeof(*sin));
1175         sin->sin_family = AF_INET;
1176 #ifdef HAVE_SOCKADDR_SA_LEN
1177         sin->sin_len = sizeof(*sin);
1178 #endif
1179         sin->sin_addr.s_addr = INADDR_BROADCAST;
1180         return sizeof(sin->sin_addr);
1181     }
1182 
1183     /* avoid a name resolution in case of numeric address */
1184 #ifdef HAVE_INET_PTON
1185     /* check for an IPv4 address */
1186     if (af == AF_UNSPEC || af == AF_INET) {
1187         struct sockaddr_in *sin = (struct sockaddr_in *)addr_ret;
1188         memset(sin, 0, sizeof(*sin));
1189         if (inet_pton(AF_INET, name, &sin->sin_addr) > 0) {
1190             sin->sin_family = AF_INET;
1191 #ifdef HAVE_SOCKADDR_SA_LEN
1192             sin->sin_len = sizeof(*sin);
1193 #endif
1194             return 4;
1195         }
1196     }
1197 #ifdef ENABLE_IPV6
1198     /* check for an IPv6 address - if the address contains a scope ID, we
1199      * fallback to getaddrinfo(), which can handle translation from interface
1200      * name to interface index */
1201     if ((af == AF_UNSPEC || af == AF_INET6) && !strchr(name, '%')) {
1202         struct sockaddr_in6 *sin = (struct sockaddr_in6 *)addr_ret;
1203         memset(sin, 0, sizeof(*sin));
1204         if (inet_pton(AF_INET6, name, &sin->sin6_addr) > 0) {
1205             sin->sin6_family = AF_INET6;
1206 #ifdef HAVE_SOCKADDR_SA_LEN
1207             sin->sin6_len = sizeof(*sin);
1208 #endif
1209             return 16;
1210         }
1211     }
1212 #endif /* ENABLE_IPV6 */
1213 #else /* HAVE_INET_PTON */
1214     /* check for an IPv4 address */
1215     if (af == AF_INET || af == AF_UNSPEC) {
1216         struct sockaddr_in *sin = (struct sockaddr_in *)addr_ret;
1217         memset(sin, 0, sizeof(*sin));
1218         if ((sin->sin_addr.s_addr = inet_addr(name)) != INADDR_NONE) {
1219             sin->sin_family = AF_INET;
1220 #ifdef HAVE_SOCKADDR_SA_LEN
1221             sin->sin_len = sizeof(*sin);
1222 #endif
1223             return 4;
1224         }
1225     }
1226 #endif /* HAVE_INET_PTON */
1227 
1228     /* perform a name resolution */
1229     memset(&hints, 0, sizeof(hints));
1230     hints.ai_family = af;
1231     Py_BEGIN_ALLOW_THREADS
1232     error = getaddrinfo(name, NULL, &hints, &res);
1233 #if defined(__digital__) && defined(__unix__)
1234     if (error == EAI_NONAME && af == AF_UNSPEC) {
1235         /* On Tru64 V5.1, numeric-to-addr conversion fails
1236            if no address family is given. Assume IPv4 for now.*/
1237         hints.ai_family = AF_INET;
1238         error = getaddrinfo(name, NULL, &hints, &res);
1239     }
1240 #endif
1241     Py_END_ALLOW_THREADS
1242     if (error) {
1243         res = NULL;  // no-op, remind us that it is invalid; gh-100795
1244         set_gaierror(state, error);
1245         return -1;
1246     }
1247     if (res->ai_addrlen < addr_ret_size)
1248         addr_ret_size = res->ai_addrlen;
1249     memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
1250     freeaddrinfo(res);
1251     switch (addr_ret->sa_family) {
1252     case AF_INET:
1253         return 4;
1254 #ifdef ENABLE_IPV6
1255     case AF_INET6:
1256         return 16;
1257 #endif
1258     default:
1259         PyErr_SetString(PyExc_OSError, "unknown address family");
1260         return -1;
1261     }
1262 }
1263 #endif // HAVE_GETADDRINFO
1264 
1265 /* Convert IPv4 sockaddr to a Python str. */
1266 
1267 static PyObject *
make_ipv4_addr(const struct sockaddr_in * addr)1268 make_ipv4_addr(const struct sockaddr_in *addr)
1269 {
1270     char buf[INET_ADDRSTRLEN];
1271     if (inet_ntop(AF_INET, &addr->sin_addr, buf, sizeof(buf)) == NULL) {
1272         PyErr_SetFromErrno(PyExc_OSError);
1273         return NULL;
1274     }
1275     return PyUnicode_FromString(buf);
1276 }
1277 
1278 #ifdef ENABLE_IPV6
1279 /* Convert IPv6 sockaddr to a Python str. */
1280 
1281 static PyObject *
make_ipv6_addr(const struct sockaddr_in6 * addr)1282 make_ipv6_addr(const struct sockaddr_in6 *addr)
1283 {
1284     char buf[INET6_ADDRSTRLEN];
1285     if (inet_ntop(AF_INET6, &addr->sin6_addr, buf, sizeof(buf)) == NULL) {
1286         PyErr_SetFromErrno(PyExc_OSError);
1287         return NULL;
1288     }
1289     return PyUnicode_FromString(buf);
1290 }
1291 #endif
1292 
1293 #ifdef USE_BLUETOOTH
1294 /* Convert a string representation of a Bluetooth address into a numeric
1295    address.  Returns the length (6), or raises an exception and returns -1 if
1296    an error occurred. */
1297 
1298 static int
setbdaddr(const char * name,bdaddr_t * bdaddr)1299 setbdaddr(const char *name, bdaddr_t *bdaddr)
1300 {
1301     unsigned int b0, b1, b2, b3, b4, b5;
1302     char ch;
1303     int n;
1304 
1305     n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
1306                &b5, &b4, &b3, &b2, &b1, &b0, &ch);
1307     if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
1308 
1309 #ifdef MS_WINDOWS
1310         *bdaddr = (ULONGLONG)(b0 & 0xFF);
1311         *bdaddr |= ((ULONGLONG)(b1 & 0xFF) << 8);
1312         *bdaddr |= ((ULONGLONG)(b2 & 0xFF) << 16);
1313         *bdaddr |= ((ULONGLONG)(b3 & 0xFF) << 24);
1314         *bdaddr |= ((ULONGLONG)(b4 & 0xFF) << 32);
1315         *bdaddr |= ((ULONGLONG)(b5 & 0xFF) << 40);
1316 #else
1317         bdaddr->b[0] = b0;
1318         bdaddr->b[1] = b1;
1319         bdaddr->b[2] = b2;
1320         bdaddr->b[3] = b3;
1321         bdaddr->b[4] = b4;
1322         bdaddr->b[5] = b5;
1323 #endif
1324 
1325         return 6;
1326     } else {
1327         PyErr_SetString(PyExc_OSError, "bad bluetooth address");
1328         return -1;
1329     }
1330 }
1331 
1332 /* Create a string representation of the Bluetooth address.  This is always a
1333    string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
1334    value (zero padded if necessary). */
1335 
1336 static PyObject *
makebdaddr(bdaddr_t * bdaddr)1337 makebdaddr(bdaddr_t *bdaddr)
1338 {
1339 #ifdef MS_WINDOWS
1340     int i;
1341     unsigned int octets[6];
1342 
1343     for (i = 0; i < 6; ++i) {
1344         octets[i] = ((*bdaddr) >> (8 * i)) & 0xFF;
1345     }
1346 
1347     return PyUnicode_FromFormat("%02X:%02X:%02X:%02X:%02X:%02X",
1348         octets[5], octets[4], octets[3],
1349         octets[2], octets[1], octets[0]);
1350 #else
1351     return PyUnicode_FromFormat("%02X:%02X:%02X:%02X:%02X:%02X",
1352         bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
1353         bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
1354 #endif
1355 }
1356 #endif
1357 
1358 
1359 /* Create an object representing the given socket address,
1360    suitable for passing it back to bind(), connect() etc.
1361    The family field of the sockaddr structure is inspected
1362    to determine what kind of address it really is. */
1363 
1364 /*ARGSUSED*/
1365 static PyObject *
makesockaddr(SOCKET_T sockfd,struct sockaddr * addr,size_t addrlen,int proto)1366 makesockaddr(SOCKET_T sockfd, struct sockaddr *addr, size_t addrlen, int proto)
1367 {
1368     if (addrlen == 0) {
1369         /* No address -- may be recvfrom() from known socket */
1370         Py_RETURN_NONE;
1371     }
1372 
1373     switch (addr->sa_family) {
1374 
1375     case AF_INET:
1376     {
1377         const struct sockaddr_in *a = (const struct sockaddr_in *)addr;
1378         PyObject *addrobj = make_ipv4_addr(a);
1379         PyObject *ret = NULL;
1380         if (addrobj) {
1381             ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
1382             Py_DECREF(addrobj);
1383         }
1384         return ret;
1385     }
1386 
1387 #if defined(AF_UNIX)
1388     case AF_UNIX:
1389     {
1390         struct sockaddr_un *a = (struct sockaddr_un *) addr;
1391 #ifdef __linux__
1392         size_t linuxaddrlen = addrlen - offsetof(struct sockaddr_un, sun_path);
1393         if (linuxaddrlen > 0 && a->sun_path[0] == 0) {  /* Linux abstract namespace */
1394             return PyBytes_FromStringAndSize(a->sun_path, linuxaddrlen);
1395         }
1396         else
1397 #endif /* linux */
1398         {
1399             /* regular NULL-terminated string */
1400             return PyUnicode_DecodeFSDefault(a->sun_path);
1401         }
1402     }
1403 #endif /* AF_UNIX */
1404 
1405 #if defined(AF_NETLINK)
1406        case AF_NETLINK:
1407        {
1408            struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
1409            return Py_BuildValue("II", a->nl_pid, a->nl_groups);
1410        }
1411 #endif /* AF_NETLINK */
1412 
1413 #if defined(AF_QIPCRTR)
1414        case AF_QIPCRTR:
1415        {
1416            struct sockaddr_qrtr *a = (struct sockaddr_qrtr *) addr;
1417            return Py_BuildValue("II", a->sq_node, a->sq_port);
1418        }
1419 #endif /* AF_QIPCRTR */
1420 
1421 #if defined(AF_VSOCK)
1422        case AF_VSOCK:
1423        {
1424            struct sockaddr_vm *a = (struct sockaddr_vm *) addr;
1425            return Py_BuildValue("II", a->svm_cid, a->svm_port);
1426        }
1427 #endif /* AF_VSOCK */
1428 
1429 #ifdef ENABLE_IPV6
1430     case AF_INET6:
1431     {
1432         const struct sockaddr_in6 *a = (const struct sockaddr_in6 *)addr;
1433         PyObject *addrobj = make_ipv6_addr(a);
1434         PyObject *ret = NULL;
1435         if (addrobj) {
1436             ret = Py_BuildValue("OiII",
1437                                 addrobj,
1438                                 ntohs(a->sin6_port),
1439                                 ntohl(a->sin6_flowinfo),
1440                                 a->sin6_scope_id);
1441             Py_DECREF(addrobj);
1442         }
1443         return ret;
1444     }
1445 #endif /* ENABLE_IPV6 */
1446 
1447 #ifdef USE_BLUETOOTH
1448     case AF_BLUETOOTH:
1449         switch (proto) {
1450 
1451 #ifdef BTPROTO_L2CAP
1452         case BTPROTO_L2CAP:
1453         {
1454             struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
1455             PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
1456             PyObject *ret = NULL;
1457             if (addrobj) {
1458                 ret = Py_BuildValue("Oi",
1459                                     addrobj,
1460                                     _BT_L2_MEMB(a, psm));
1461                 Py_DECREF(addrobj);
1462             }
1463             return ret;
1464         }
1465 
1466 #endif /* BTPROTO_L2CAP */
1467 
1468         case BTPROTO_RFCOMM:
1469         {
1470             struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
1471             PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
1472             PyObject *ret = NULL;
1473             if (addrobj) {
1474                 ret = Py_BuildValue("Oi",
1475                                     addrobj,
1476                                     _BT_RC_MEMB(a, channel));
1477                 Py_DECREF(addrobj);
1478             }
1479             return ret;
1480         }
1481 
1482 #ifdef BTPROTO_HCI
1483         case BTPROTO_HCI:
1484         {
1485             struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
1486 #if defined(__NetBSD__) || defined(__DragonFly__)
1487             return makebdaddr(&_BT_HCI_MEMB(a, bdaddr));
1488 #else /* __NetBSD__ || __DragonFly__ */
1489             PyObject *ret = NULL;
1490             ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
1491             return ret;
1492 #endif /* !(__NetBSD__ || __DragonFly__) */
1493         }
1494 
1495 #if !defined(__FreeBSD__)
1496         case BTPROTO_SCO:
1497         {
1498             struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1499             return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1500         }
1501 #endif /* !__FreeBSD__ */
1502 #endif /* BTPROTO_HCI */
1503 
1504         default:
1505             PyErr_SetString(PyExc_ValueError,
1506                             "Unknown Bluetooth protocol");
1507             return NULL;
1508         }
1509 #endif /* USE_BLUETOOTH */
1510 
1511 #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFNAME)
1512     case AF_PACKET:
1513     {
1514         struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1515         const char *ifname = "";
1516         struct ifreq ifr;
1517         /* need to look up interface name give index */
1518         if (a->sll_ifindex) {
1519             ifr.ifr_ifindex = a->sll_ifindex;
1520             if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1521                 ifname = ifr.ifr_name;
1522         }
1523         return Py_BuildValue("shbhy#",
1524                              ifname,
1525                              ntohs(a->sll_protocol),
1526                              a->sll_pkttype,
1527                              a->sll_hatype,
1528                              a->sll_addr,
1529                              (Py_ssize_t)a->sll_halen);
1530     }
1531 #endif /* HAVE_NETPACKET_PACKET_H && SIOCGIFNAME */
1532 
1533 #ifdef HAVE_LINUX_TIPC_H
1534     case AF_TIPC:
1535     {
1536         struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
1537         if (a->addrtype == TIPC_ADDR_NAMESEQ) {
1538             return Py_BuildValue("IIIII",
1539                             a->addrtype,
1540                             a->addr.nameseq.type,
1541                             a->addr.nameseq.lower,
1542                             a->addr.nameseq.upper,
1543                             a->scope);
1544         } else if (a->addrtype == TIPC_ADDR_NAME) {
1545             return Py_BuildValue("IIIII",
1546                             a->addrtype,
1547                             a->addr.name.name.type,
1548                             a->addr.name.name.instance,
1549                             a->addr.name.name.instance,
1550                             a->scope);
1551         } else if (a->addrtype == TIPC_ADDR_ID) {
1552             return Py_BuildValue("IIIII",
1553                             a->addrtype,
1554                             a->addr.id.node,
1555                             a->addr.id.ref,
1556                             0,
1557                             a->scope);
1558         } else {
1559             PyErr_SetString(PyExc_ValueError,
1560                             "Invalid address type");
1561             return NULL;
1562         }
1563     }
1564 #endif /* HAVE_LINUX_TIPC_H */
1565 
1566 #if defined(AF_CAN) && defined(SIOCGIFNAME)
1567     case AF_CAN:
1568     {
1569         struct sockaddr_can *a = (struct sockaddr_can *)addr;
1570         const char *ifname = "";
1571         struct ifreq ifr;
1572         /* need to look up interface name given index */
1573         if (a->can_ifindex) {
1574             ifr.ifr_ifindex = a->can_ifindex;
1575             if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1576                 ifname = ifr.ifr_name;
1577         }
1578 
1579         switch (proto) {
1580 #ifdef CAN_ISOTP
1581           case CAN_ISOTP:
1582           {
1583               return Py_BuildValue("O&kk", PyUnicode_DecodeFSDefault,
1584                                           ifname,
1585                                           a->can_addr.tp.rx_id,
1586                                           a->can_addr.tp.tx_id);
1587           }
1588 #endif /* CAN_ISOTP */
1589 #ifdef CAN_J1939
1590           case CAN_J1939:
1591           {
1592               return Py_BuildValue("O&KIB", PyUnicode_DecodeFSDefault,
1593                                           ifname,
1594                                           (unsigned long long)a->can_addr.j1939.name,
1595                                           (unsigned int)a->can_addr.j1939.pgn,
1596                                           a->can_addr.j1939.addr);
1597           }
1598 #endif /* CAN_J1939 */
1599           default:
1600           {
1601               return Py_BuildValue("(O&)", PyUnicode_DecodeFSDefault,
1602                                         ifname);
1603           }
1604         }
1605     }
1606 #endif /* AF_CAN && SIOCGIFNAME */
1607 
1608 #ifdef PF_SYSTEM
1609     case PF_SYSTEM:
1610         switch(proto) {
1611 #ifdef SYSPROTO_CONTROL
1612         case SYSPROTO_CONTROL:
1613         {
1614             struct sockaddr_ctl *a = (struct sockaddr_ctl *)addr;
1615             return Py_BuildValue("(II)", a->sc_id, a->sc_unit);
1616         }
1617 #endif /* SYSPROTO_CONTROL */
1618         default:
1619             PyErr_SetString(PyExc_ValueError,
1620                             "Invalid address type");
1621             return 0;
1622         }
1623 #endif /* PF_SYSTEM */
1624 
1625 #ifdef HAVE_SOCKADDR_ALG
1626     case AF_ALG:
1627     {
1628         struct sockaddr_alg *a = (struct sockaddr_alg *)addr;
1629         return Py_BuildValue("s#s#HH",
1630             a->salg_type,
1631             strnlen((const char*)a->salg_type,
1632                     sizeof(a->salg_type)),
1633             a->salg_name,
1634             strnlen((const char*)a->salg_name,
1635                     sizeof(a->salg_name)),
1636             a->salg_feat,
1637             a->salg_mask);
1638     }
1639 #endif /* HAVE_SOCKADDR_ALG */
1640 
1641 #ifdef HAVE_AF_HYPERV
1642     case AF_HYPERV:
1643     {
1644         SOCKADDR_HV *a = (SOCKADDR_HV *) addr;
1645 
1646         wchar_t *guidStr;
1647         RPC_STATUS res = UuidToStringW(&a->VmId, &guidStr);
1648         if (res != RPC_S_OK) {
1649             PyErr_SetFromWindowsErr(res);
1650             return 0;
1651         }
1652         PyObject *vmId = PyUnicode_FromWideChar(guidStr, -1);
1653         res = RpcStringFreeW(&guidStr);
1654         assert(res == RPC_S_OK);
1655 
1656         res = UuidToStringW(&a->ServiceId, &guidStr);
1657         if (res != RPC_S_OK) {
1658             Py_DECREF(vmId);
1659             PyErr_SetFromWindowsErr(res);
1660             return 0;
1661         }
1662         PyObject *serviceId = PyUnicode_FromWideChar(guidStr, -1);
1663         res = RpcStringFreeW(&guidStr);
1664         assert(res == RPC_S_OK);
1665 
1666         return Py_BuildValue("NN", vmId, serviceId);
1667     }
1668 #endif /* AF_HYPERV */
1669 
1670     /* More cases here... */
1671 
1672     default:
1673         /* If we don't know the address family, don't raise an
1674            exception -- return it as an (int, bytes) tuple. */
1675         return Py_BuildValue("iy#",
1676                              addr->sa_family,
1677                              addr->sa_data,
1678                              sizeof(addr->sa_data));
1679 
1680     }
1681 }
1682 
1683 #if defined(HAVE_BIND) || defined(HAVE_CONNECTTO) || defined(CMSG_LEN)
1684 /* Helper for getsockaddrarg: bypass IDNA for ASCII-only host names
1685    (in particular, numeric IP addresses). */
1686 struct maybe_idna {
1687     PyObject *obj;
1688     char *buf;
1689 };
1690 
1691 static void
idna_cleanup(struct maybe_idna * data)1692 idna_cleanup(struct maybe_idna *data)
1693 {
1694     Py_CLEAR(data->obj);
1695 }
1696 
1697 static int
idna_converter(PyObject * obj,struct maybe_idna * data)1698 idna_converter(PyObject *obj, struct maybe_idna *data)
1699 {
1700     size_t len;
1701     PyObject *obj2;
1702     if (obj == NULL) {
1703         idna_cleanup(data);
1704         return 1;
1705     }
1706     data->obj = NULL;
1707     len = -1;
1708     if (PyBytes_Check(obj)) {
1709         data->buf = PyBytes_AsString(obj);
1710         len = PyBytes_Size(obj);
1711     }
1712     else if (PyByteArray_Check(obj)) {
1713         data->buf = PyByteArray_AsString(obj);
1714         len = PyByteArray_Size(obj);
1715     }
1716     else if (PyUnicode_Check(obj)) {
1717         if (PyUnicode_IS_COMPACT_ASCII(obj)) {
1718             data->buf = PyUnicode_DATA(obj);
1719             len = PyUnicode_GET_LENGTH(obj);
1720         }
1721         else {
1722             obj2 = PyUnicode_AsEncodedString(obj, "idna", NULL);
1723             if (!obj2) {
1724                 PyErr_SetString(PyExc_TypeError, "encoding of hostname failed");
1725                 return 0;
1726             }
1727             assert(PyBytes_Check(obj2));
1728             data->obj = obj2;
1729             data->buf = PyBytes_AS_STRING(obj2);
1730             len = PyBytes_GET_SIZE(obj2);
1731         }
1732     }
1733     else {
1734         PyErr_Format(PyExc_TypeError, "str, bytes or bytearray expected, not %s",
1735                      Py_TYPE(obj)->tp_name);
1736         return 0;
1737     }
1738     if (strlen(data->buf) != len) {
1739         Py_CLEAR(data->obj);
1740         PyErr_SetString(PyExc_TypeError, "host name must not contain null character");
1741         return 0;
1742     }
1743     return Py_CLEANUP_SUPPORTED;
1744 }
1745 
1746 /* Parse a socket address argument according to the socket object's
1747    address family.  Return 1 if the address was in the proper format,
1748    0 of not.  The address is returned through addr_ret, its length
1749    through len_ret. */
1750 
1751 static int
getsockaddrarg(PySocketSockObject * s,PyObject * args,sock_addr_t * addrbuf,int * len_ret,const char * caller)1752 getsockaddrarg(PySocketSockObject *s, PyObject *args,
1753                sock_addr_t *addrbuf, int *len_ret, const char *caller)
1754 {
1755     switch (s->sock_family) {
1756 
1757 #if defined(AF_UNIX)
1758     case AF_UNIX:
1759     {
1760         Py_buffer path;
1761         int retval = 0;
1762 
1763         /* PEP 383.  Not using PyUnicode_FSConverter since we need to
1764            allow embedded nulls on Linux. */
1765         if (PyUnicode_Check(args)) {
1766             if ((args = PyUnicode_EncodeFSDefault(args)) == NULL)
1767                 return 0;
1768         }
1769         else
1770             Py_INCREF(args);
1771         if (!PyArg_Parse(args, "y*", &path)) {
1772             Py_DECREF(args);
1773             return retval;
1774         }
1775         assert(path.len >= 0);
1776 
1777         struct sockaddr_un* addr = &addrbuf->un;
1778 #ifdef __linux__
1779         if (path.len == 0 || *(const char *)path.buf == 0) {
1780             /* Linux abstract namespace extension:
1781                - Empty address auto-binding to an abstract address
1782                - Address that starts with null byte */
1783             if ((size_t)path.len > sizeof addr->sun_path) {
1784                 PyErr_SetString(PyExc_OSError,
1785                                 "AF_UNIX path too long");
1786                 goto unix_out;
1787             }
1788 
1789             *len_ret = path.len + offsetof(struct sockaddr_un, sun_path);
1790         }
1791         else
1792 #endif /* linux */
1793         {
1794             /* regular NULL-terminated string */
1795             if ((size_t)path.len >= sizeof addr->sun_path) {
1796                 PyErr_SetString(PyExc_OSError,
1797                                 "AF_UNIX path too long");
1798                 goto unix_out;
1799             }
1800             addr->sun_path[path.len] = 0;
1801 
1802             /* including the tailing NUL */
1803             *len_ret = path.len + offsetof(struct sockaddr_un, sun_path) + 1;
1804         }
1805         addr->sun_family = s->sock_family;
1806         memcpy(addr->sun_path, path.buf, path.len);
1807 
1808         retval = 1;
1809     unix_out:
1810         PyBuffer_Release(&path);
1811         Py_DECREF(args);
1812         return retval;
1813     }
1814 #endif /* AF_UNIX */
1815 
1816 #if defined(AF_NETLINK)
1817     case AF_NETLINK:
1818     {
1819         int pid, groups;
1820         struct sockaddr_nl* addr = &addrbuf->nl;
1821         if (!PyTuple_Check(args)) {
1822             PyErr_Format(
1823                 PyExc_TypeError,
1824                 "%s(): AF_NETLINK address must be tuple, not %.500s",
1825                 caller, Py_TYPE(args)->tp_name);
1826             return 0;
1827         }
1828         if (!PyArg_ParseTuple(args,
1829                               "II;AF_NETLINK address must be a pair "
1830                               "(pid, groups)",
1831                               &pid, &groups))
1832         {
1833             return 0;
1834         }
1835         addr->nl_family = AF_NETLINK;
1836         addr->nl_pid = pid;
1837         addr->nl_groups = groups;
1838         *len_ret = sizeof(*addr);
1839         return 1;
1840     }
1841 #endif /* AF_NETLINK */
1842 
1843 #if defined(AF_QIPCRTR)
1844     case AF_QIPCRTR:
1845     {
1846         unsigned int node, port;
1847         struct sockaddr_qrtr* addr = &addrbuf->sq;
1848         if (!PyTuple_Check(args)) {
1849             PyErr_Format(
1850                 PyExc_TypeError,
1851                 "getsockaddrarg: "
1852                 "AF_QIPCRTR address must be tuple, not %.500s",
1853                 Py_TYPE(args)->tp_name);
1854             return 0;
1855         }
1856         if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &node, &port))
1857             return 0;
1858         addr->sq_family = AF_QIPCRTR;
1859         addr->sq_node = node;
1860         addr->sq_port = port;
1861         *len_ret = sizeof(*addr);
1862         return 1;
1863     }
1864 #endif /* AF_QIPCRTR */
1865 
1866 #if defined(AF_VSOCK)
1867     case AF_VSOCK:
1868     {
1869         struct sockaddr_vm* addr = &addrbuf->vm;
1870         int port, cid;
1871         memset(addr, 0, sizeof(struct sockaddr_vm));
1872         if (!PyTuple_Check(args)) {
1873             PyErr_Format(
1874                 PyExc_TypeError,
1875                 "getsockaddrarg: "
1876                 "AF_VSOCK address must be tuple, not %.500s",
1877                 Py_TYPE(args)->tp_name);
1878             return 0;
1879         }
1880         if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &cid, &port))
1881             return 0;
1882         addr->svm_family = s->sock_family;
1883         addr->svm_port = port;
1884         addr->svm_cid = cid;
1885         *len_ret = sizeof(*addr);
1886         return 1;
1887     }
1888 #endif /* AF_VSOCK */
1889 
1890 
1891 #ifdef AF_RDS
1892     case AF_RDS:
1893         /* RDS sockets use sockaddr_in: fall-through */
1894 #endif /* AF_RDS */
1895 
1896 #ifdef AF_DIVERT
1897     case AF_DIVERT:
1898         /* FreeBSD divert(4) sockets use sockaddr_in: fall-through */
1899 #endif /* AF_DIVERT */
1900 
1901     case AF_INET:
1902     {
1903         struct maybe_idna host = {NULL, NULL};
1904         int port, result;
1905         if (!PyTuple_Check(args)) {
1906             PyErr_Format(
1907                 PyExc_TypeError,
1908                 "%s(): AF_INET address must be tuple, not %.500s",
1909                 caller, Py_TYPE(args)->tp_name);
1910             return 0;
1911         }
1912         if (!PyArg_ParseTuple(args,
1913                               "O&i;AF_INET address must be a pair "
1914                               "(host, port)",
1915                               idna_converter, &host, &port))
1916         {
1917             assert(PyErr_Occurred());
1918             if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1919                 PyErr_Format(PyExc_OverflowError,
1920                              "%s(): port must be 0-65535.", caller);
1921             }
1922             return 0;
1923         }
1924         struct sockaddr_in* addr = &addrbuf->in;
1925         result = setipaddr(s->state, host.buf, (struct sockaddr *)addr,
1926                            sizeof(*addr),  AF_INET);
1927         idna_cleanup(&host);
1928         if (result < 0)
1929             return 0;
1930         if (port < 0 || port > 0xffff) {
1931             PyErr_Format(
1932                 PyExc_OverflowError,
1933                 "%s(): port must be 0-65535.", caller);
1934             return 0;
1935         }
1936         addr->sin_family = AF_INET;
1937         addr->sin_port = htons((short)port);
1938         *len_ret = sizeof *addr;
1939         return 1;
1940     }
1941 
1942 #ifdef ENABLE_IPV6
1943     case AF_INET6:
1944     {
1945         struct maybe_idna host = {NULL, NULL};
1946         int port, result;
1947         unsigned int flowinfo, scope_id;
1948         flowinfo = scope_id = 0;
1949         if (!PyTuple_Check(args)) {
1950             PyErr_Format(
1951                 PyExc_TypeError,
1952                 "%s(): AF_INET6 address must be tuple, not %.500s",
1953                 caller, Py_TYPE(args)->tp_name);
1954             return 0;
1955         }
1956         if (!PyArg_ParseTuple(args,
1957                               "O&i|II;AF_INET6 address must be a tuple "
1958                               "(host, port[, flowinfo[, scopeid]])",
1959                               idna_converter, &host, &port, &flowinfo,
1960                               &scope_id))
1961         {
1962             assert(PyErr_Occurred());
1963             if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1964                 PyErr_Format(PyExc_OverflowError,
1965                              "%s(): port must be 0-65535.", caller);
1966             }
1967             return 0;
1968         }
1969         struct sockaddr_in6* addr = &addrbuf->in6;
1970         result = setipaddr(s->state, host.buf, (struct sockaddr *)addr,
1971                            sizeof(*addr), AF_INET6);
1972         idna_cleanup(&host);
1973         if (result < 0)
1974             return 0;
1975         if (port < 0 || port > 0xffff) {
1976             PyErr_Format(
1977                 PyExc_OverflowError,
1978                 "%s(): port must be 0-65535.", caller);
1979             return 0;
1980         }
1981         if (flowinfo > 0xfffff) {
1982             PyErr_Format(
1983                 PyExc_OverflowError,
1984                 "%s(): flowinfo must be 0-1048575.", caller);
1985             return 0;
1986         }
1987         addr->sin6_family = s->sock_family;
1988         addr->sin6_port = htons((short)port);
1989         addr->sin6_flowinfo = htonl(flowinfo);
1990         addr->sin6_scope_id = scope_id;
1991         *len_ret = sizeof *addr;
1992         return 1;
1993     }
1994 #endif /* ENABLE_IPV6 */
1995 
1996 #ifdef USE_BLUETOOTH
1997     case AF_BLUETOOTH:
1998     {
1999         switch (s->sock_proto) {
2000 #ifdef BTPROTO_L2CAP
2001         case BTPROTO_L2CAP:
2002         {
2003             const char *straddr;
2004 
2005             struct sockaddr_l2 *addr = &addrbuf->bt_l2;
2006             memset(addr, 0, sizeof(struct sockaddr_l2));
2007             _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
2008             if (!PyArg_ParseTuple(args, "si", &straddr,
2009                                   &_BT_L2_MEMB(addr, psm))) {
2010                 PyErr_Format(PyExc_OSError,
2011                              "%s(): wrong format", caller);
2012                 return 0;
2013             }
2014             if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
2015                 return 0;
2016 
2017             *len_ret = sizeof *addr;
2018             return 1;
2019         }
2020 #endif /* BTPROTO_L2CAP */
2021         case BTPROTO_RFCOMM:
2022         {
2023             const char *straddr;
2024             struct sockaddr_rc *addr = &addrbuf->bt_rc;
2025             _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
2026             if (!PyArg_ParseTuple(args, "si", &straddr,
2027                                   &_BT_RC_MEMB(addr, channel))) {
2028                 PyErr_Format(PyExc_OSError,
2029                              "%s(): wrong format", caller);
2030                 return 0;
2031             }
2032             if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
2033                 return 0;
2034 
2035             *len_ret = sizeof *addr;
2036             return 1;
2037         }
2038 #ifdef BTPROTO_HCI
2039         case BTPROTO_HCI:
2040         {
2041             struct sockaddr_hci *addr = &addrbuf->bt_hci;
2042 #if defined(__NetBSD__) || defined(__DragonFly__)
2043             const char *straddr;
2044             _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
2045             if (!PyBytes_Check(args)) {
2046                 PyErr_Format(PyExc_OSError, "%s: "
2047                              "wrong format", caller);
2048                 return 0;
2049             }
2050             straddr = PyBytes_AS_STRING(args);
2051             if (setbdaddr(straddr, &_BT_HCI_MEMB(addr, bdaddr)) < 0)
2052                 return 0;
2053 #else  /* __NetBSD__ || __DragonFly__ */
2054             _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
2055             if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
2056                 PyErr_Format(PyExc_OSError,
2057                              "%s(): wrong format", caller);
2058                 return 0;
2059             }
2060 #endif /* !(__NetBSD__ || __DragonFly__) */
2061             *len_ret = sizeof *addr;
2062             return 1;
2063         }
2064 #if !defined(__FreeBSD__)
2065         case BTPROTO_SCO:
2066         {
2067             const char *straddr;
2068 
2069             struct sockaddr_sco *addr = &addrbuf->bt_sco;
2070             _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
2071             if (!PyBytes_Check(args)) {
2072                 PyErr_Format(PyExc_OSError,
2073                              "%s(): wrong format", caller);
2074                 return 0;
2075             }
2076             straddr = PyBytes_AS_STRING(args);
2077             if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
2078                 return 0;
2079 
2080             *len_ret = sizeof *addr;
2081             return 1;
2082         }
2083 #endif /* !__FreeBSD__ */
2084 #endif /* BTPROTO_HCI */
2085         default:
2086             PyErr_Format(PyExc_OSError,
2087                          "%s(): unknown Bluetooth protocol", caller);
2088             return 0;
2089         }
2090     }
2091 #endif /* USE_BLUETOOTH */
2092 
2093 #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFINDEX)
2094     case AF_PACKET:
2095     {
2096         struct ifreq ifr;
2097         const char *interfaceName;
2098         int protoNumber;
2099         int hatype = 0;
2100         int pkttype = PACKET_HOST;
2101         Py_buffer haddr = {NULL, NULL};
2102 
2103         if (!PyTuple_Check(args)) {
2104             PyErr_Format(
2105                 PyExc_TypeError,
2106                 "%s(): AF_PACKET address must be tuple, not %.500s",
2107                 caller, Py_TYPE(args)->tp_name);
2108             return 0;
2109         }
2110         /* XXX: improve the default error message according to the
2111            documentation of AF_PACKET, which would be added as part
2112            of bpo-25041. */
2113         if (!PyArg_ParseTuple(args,
2114                               "si|iiy*;AF_PACKET address must be a tuple of "
2115                               "two to five elements",
2116                               &interfaceName, &protoNumber, &pkttype, &hatype,
2117                               &haddr))
2118         {
2119             assert(PyErr_Occurred());
2120             if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
2121                 PyErr_Format(PyExc_OverflowError,
2122                              "%s(): address argument out of range", caller);
2123             }
2124             return 0;
2125         }
2126         strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
2127         ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
2128         if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
2129             s->errorhandler();
2130             PyBuffer_Release(&haddr);
2131             return 0;
2132         }
2133         if (haddr.buf && haddr.len > 8) {
2134             PyErr_SetString(PyExc_ValueError,
2135                             "Hardware address must be 8 bytes or less");
2136             PyBuffer_Release(&haddr);
2137             return 0;
2138         }
2139         if (protoNumber < 0 || protoNumber > 0xffff) {
2140             PyErr_Format(
2141                 PyExc_OverflowError,
2142                 "%s(): proto must be 0-65535.", caller);
2143             PyBuffer_Release(&haddr);
2144             return 0;
2145         }
2146         struct sockaddr_ll* addr = &addrbuf->ll;
2147         addr->sll_family = AF_PACKET;
2148         addr->sll_protocol = htons((short)protoNumber);
2149         addr->sll_ifindex = ifr.ifr_ifindex;
2150         addr->sll_pkttype = pkttype;
2151         addr->sll_hatype = hatype;
2152         if (haddr.buf) {
2153             memcpy(&addr->sll_addr, haddr.buf, haddr.len);
2154             addr->sll_halen = haddr.len;
2155         }
2156         else
2157             addr->sll_halen = 0;
2158         *len_ret = sizeof *addr;
2159         PyBuffer_Release(&haddr);
2160         return 1;
2161     }
2162 #endif /* HAVE_NETPACKET_PACKET_H && SIOCGIFINDEX */
2163 
2164 #ifdef HAVE_LINUX_TIPC_H
2165     case AF_TIPC:
2166     {
2167         unsigned int atype, v1, v2, v3;
2168         unsigned int scope = TIPC_CLUSTER_SCOPE;
2169 
2170         if (!PyTuple_Check(args)) {
2171             PyErr_Format(
2172                 PyExc_TypeError,
2173                 "%s(): AF_TIPC address must be tuple, not %.500s",
2174                 caller, Py_TYPE(args)->tp_name);
2175             return 0;
2176         }
2177 
2178         if (!PyArg_ParseTuple(args,
2179                               "IIII|I;AF_TIPC address must be a tuple "
2180                               "(addr_type, v1, v2, v3[, scope])",
2181                               &atype, &v1, &v2, &v3, &scope))
2182         {
2183             return 0;
2184         }
2185 
2186         struct sockaddr_tipc *addr = &addrbuf->tipc;
2187         memset(addr, 0, sizeof(struct sockaddr_tipc));
2188 
2189         addr->family = AF_TIPC;
2190         addr->scope = scope;
2191         addr->addrtype = atype;
2192 
2193         if (atype == TIPC_ADDR_NAMESEQ) {
2194             addr->addr.nameseq.type = v1;
2195             addr->addr.nameseq.lower = v2;
2196             addr->addr.nameseq.upper = v3;
2197         } else if (atype == TIPC_ADDR_NAME) {
2198             addr->addr.name.name.type = v1;
2199             addr->addr.name.name.instance = v2;
2200         } else if (atype == TIPC_ADDR_ID) {
2201             addr->addr.id.node = v1;
2202             addr->addr.id.ref = v2;
2203         } else {
2204             /* Shouldn't happen */
2205             PyErr_SetString(PyExc_TypeError, "Invalid address type");
2206             return 0;
2207         }
2208 
2209         *len_ret = sizeof(*addr);
2210 
2211         return 1;
2212     }
2213 #endif /* HAVE_LINUX_TIPC_H */
2214 
2215 #if defined(AF_CAN) && defined(SIOCGIFINDEX)
2216     case AF_CAN:
2217         switch (s->sock_proto) {
2218 #ifdef CAN_RAW
2219         case CAN_RAW:
2220         /* fall-through */
2221 #endif
2222 #ifdef CAN_BCM
2223         case CAN_BCM:
2224 #endif
2225 #if defined(CAN_RAW) || defined(CAN_BCM)
2226         {
2227             PyObject *interfaceName;
2228             struct ifreq ifr;
2229             Py_ssize_t len;
2230             struct sockaddr_can *addr = &addrbuf->can;
2231 
2232             if (!PyTuple_Check(args)) {
2233                 PyErr_Format(PyExc_TypeError,
2234                              "%s(): AF_CAN address must be tuple, not %.500s",
2235                              caller, Py_TYPE(args)->tp_name);
2236                 return 0;
2237             }
2238             if (!PyArg_ParseTuple(args,
2239                                   "O&;AF_CAN address must be a tuple "
2240                                   "(interface, )",
2241                                   PyUnicode_FSConverter, &interfaceName))
2242             {
2243                 return 0;
2244             }
2245 
2246             len = PyBytes_GET_SIZE(interfaceName);
2247 
2248             if (len == 0) {
2249                 ifr.ifr_ifindex = 0;
2250             } else if ((size_t)len < sizeof(ifr.ifr_name)) {
2251                 strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
2252                 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
2253                 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
2254                     s->errorhandler();
2255                     Py_DECREF(interfaceName);
2256                     return 0;
2257                 }
2258             } else {
2259                 PyErr_SetString(PyExc_OSError,
2260                                 "AF_CAN interface name too long");
2261                 Py_DECREF(interfaceName);
2262                 return 0;
2263             }
2264 
2265             addr->can_family = AF_CAN;
2266             addr->can_ifindex = ifr.ifr_ifindex;
2267 
2268             *len_ret = sizeof(*addr);
2269             Py_DECREF(interfaceName);
2270             return 1;
2271         }
2272 #endif /* CAN_RAW || CAN_BCM */
2273 
2274 #ifdef CAN_ISOTP
2275         case CAN_ISOTP:
2276         {
2277             PyObject *interfaceName;
2278             struct ifreq ifr;
2279             Py_ssize_t len;
2280             unsigned long int rx_id, tx_id;
2281 
2282             struct sockaddr_can *addr = &addrbuf->can;
2283 
2284             if (!PyArg_ParseTuple(args, "O&kk", PyUnicode_FSConverter,
2285                                               &interfaceName,
2286                                               &rx_id,
2287                                               &tx_id))
2288                 return 0;
2289 
2290             len = PyBytes_GET_SIZE(interfaceName);
2291 
2292             if (len == 0) {
2293                 ifr.ifr_ifindex = 0;
2294             } else if ((size_t)len < sizeof(ifr.ifr_name)) {
2295                 strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
2296                 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
2297                 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
2298                     s->errorhandler();
2299                     Py_DECREF(interfaceName);
2300                     return 0;
2301                 }
2302             } else {
2303                 PyErr_SetString(PyExc_OSError,
2304                                 "AF_CAN interface name too long");
2305                 Py_DECREF(interfaceName);
2306                 return 0;
2307             }
2308 
2309             addr->can_family = AF_CAN;
2310             addr->can_ifindex = ifr.ifr_ifindex;
2311             addr->can_addr.tp.rx_id = rx_id;
2312             addr->can_addr.tp.tx_id = tx_id;
2313 
2314             *len_ret = sizeof(*addr);
2315             Py_DECREF(interfaceName);
2316             return 1;
2317         }
2318 #endif /* CAN_ISOTP */
2319 #ifdef CAN_J1939
2320         case CAN_J1939:
2321         {
2322             PyObject *interfaceName;
2323             struct ifreq ifr;
2324             Py_ssize_t len;
2325             unsigned long long j1939_name; /* at least 64 bits */
2326             unsigned int j1939_pgn; /* at least 32 bits */
2327             uint8_t j1939_addr;
2328 
2329             struct sockaddr_can *addr = &addrbuf->can;
2330 
2331             if (!PyArg_ParseTuple(args, "O&KIB", PyUnicode_FSConverter,
2332                                               &interfaceName,
2333                                               &j1939_name,
2334                                               &j1939_pgn,
2335                                               &j1939_addr))
2336                 return 0;
2337 
2338             len = PyBytes_GET_SIZE(interfaceName);
2339 
2340             if (len == 0) {
2341                 ifr.ifr_ifindex = 0;
2342             } else if ((size_t)len < sizeof(ifr.ifr_name)) {
2343                 strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
2344                 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
2345                 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
2346                     s->errorhandler();
2347                     Py_DECREF(interfaceName);
2348                     return 0;
2349                 }
2350             } else {
2351                 PyErr_SetString(PyExc_OSError,
2352                                 "AF_CAN interface name too long");
2353                 Py_DECREF(interfaceName);
2354                 return 0;
2355             }
2356 
2357             addr->can_family = AF_CAN;
2358             addr->can_ifindex = ifr.ifr_ifindex;
2359             addr->can_addr.j1939.name = (uint64_t)j1939_name;
2360             addr->can_addr.j1939.pgn = (uint32_t)j1939_pgn;
2361             addr->can_addr.j1939.addr = j1939_addr;
2362 
2363             *len_ret = sizeof(*addr);
2364             Py_DECREF(interfaceName);
2365             return 1;
2366         }
2367 #endif /* CAN_J1939 */
2368         default:
2369             PyErr_Format(PyExc_OSError,
2370                          "%s(): unsupported CAN protocol", caller);
2371             return 0;
2372         }
2373 #endif /* AF_CAN && SIOCGIFINDEX */
2374 
2375 #ifdef PF_SYSTEM
2376     case PF_SYSTEM:
2377         switch (s->sock_proto) {
2378 #ifdef SYSPROTO_CONTROL
2379         case SYSPROTO_CONTROL:
2380         {
2381             struct sockaddr_ctl *addr = &addrbuf->ctl;
2382             addr->sc_family = AF_SYSTEM;
2383             addr->ss_sysaddr = AF_SYS_CONTROL;
2384 
2385             if (PyUnicode_Check(args)) {
2386                 struct ctl_info info;
2387                 PyObject *ctl_name;
2388 
2389                 if (!PyArg_Parse(args, "O&",
2390                                 PyUnicode_FSConverter, &ctl_name)) {
2391                     return 0;
2392                 }
2393 
2394                 if (PyBytes_GET_SIZE(ctl_name) > (Py_ssize_t)sizeof(info.ctl_name)) {
2395                     PyErr_SetString(PyExc_ValueError,
2396                                     "provided string is too long");
2397                     Py_DECREF(ctl_name);
2398                     return 0;
2399                 }
2400                 strncpy(info.ctl_name, PyBytes_AS_STRING(ctl_name),
2401                         sizeof(info.ctl_name));
2402                 Py_DECREF(ctl_name);
2403 
2404                 if (ioctl(s->sock_fd, CTLIOCGINFO, &info)) {
2405                     PyErr_SetString(PyExc_OSError,
2406                           "cannot find kernel control with provided name");
2407                     return 0;
2408                 }
2409 
2410                 addr->sc_id = info.ctl_id;
2411                 addr->sc_unit = 0;
2412             } else if (!PyArg_ParseTuple(args, "II",
2413                                          &(addr->sc_id), &(addr->sc_unit))) {
2414                 PyErr_Format(PyExc_TypeError,
2415                              "%s(): PF_SYSTEM address must be a str or "
2416                              "a pair (id, unit)", caller);
2417                 return 0;
2418             }
2419 
2420             *len_ret = sizeof(*addr);
2421             return 1;
2422         }
2423 #endif /* SYSPROTO_CONTROL */
2424         default:
2425             PyErr_Format(PyExc_OSError,
2426                          "%s(): unsupported PF_SYSTEM protocol", caller);
2427             return 0;
2428         }
2429 #endif /* PF_SYSTEM */
2430 #ifdef HAVE_SOCKADDR_ALG
2431     case AF_ALG:
2432     {
2433         const char *type;
2434         const char *name;
2435         struct sockaddr_alg *sa = &addrbuf->alg;
2436 
2437         memset(sa, 0, sizeof(*sa));
2438         sa->salg_family = AF_ALG;
2439 
2440         if (!PyTuple_Check(args)) {
2441             PyErr_Format(PyExc_TypeError,
2442                          "%s(): AF_ALG address must be tuple, not %.500s",
2443                          caller, Py_TYPE(args)->tp_name);
2444             return 0;
2445         }
2446         if (!PyArg_ParseTuple(args,
2447                               "ss|HH;AF_ALG address must be a tuple "
2448                               "(type, name[, feat[, mask]])",
2449                               &type, &name, &sa->salg_feat, &sa->salg_mask))
2450         {
2451             return 0;
2452         }
2453         /* sockaddr_alg has fixed-sized char arrays for type, and name
2454          * both must be NULL terminated.
2455          */
2456         if (strlen(type) >= sizeof(sa->salg_type)) {
2457             PyErr_SetString(PyExc_ValueError, "AF_ALG type too long.");
2458             return 0;
2459         }
2460         strncpy((char *)sa->salg_type, type, sizeof(sa->salg_type));
2461         if (strlen(name) >= sizeof(sa->salg_name)) {
2462             PyErr_SetString(PyExc_ValueError, "AF_ALG name too long.");
2463             return 0;
2464         }
2465         strncpy((char *)sa->salg_name, name, sizeof(sa->salg_name));
2466 
2467         *len_ret = sizeof(*sa);
2468         return 1;
2469     }
2470 #endif /* HAVE_SOCKADDR_ALG */
2471 #ifdef HAVE_AF_HYPERV
2472     case AF_HYPERV:
2473     {
2474         switch (s->sock_proto) {
2475         case HV_PROTOCOL_RAW:
2476         {
2477             PyObject *vm_id_obj = NULL;
2478             PyObject *service_id_obj = NULL;
2479 
2480             SOCKADDR_HV *addr = &addrbuf->hv;
2481 
2482             memset(addr, 0, sizeof(*addr));
2483             addr->Family = AF_HYPERV;
2484 
2485             if (!PyTuple_Check(args)) {
2486                 PyErr_Format(PyExc_TypeError,
2487                     "%s(): AF_HYPERV address must be tuple, not %.500s",
2488                     caller, Py_TYPE(args)->tp_name);
2489                 return 0;
2490             }
2491             if (!PyArg_ParseTuple(args,
2492                 "UU;AF_HYPERV address must be a str tuple (vm_id, service_id)",
2493                 &vm_id_obj, &service_id_obj))
2494             {
2495                 return 0;
2496             }
2497 
2498             wchar_t *guid_str = PyUnicode_AsWideCharString(vm_id_obj, NULL);
2499             if (guid_str == NULL) {
2500                 PyErr_Format(PyExc_ValueError,
2501                     "%s(): AF_HYPERV address vm_id is not a valid UUID string",
2502                     caller);
2503                 return 0;
2504             }
2505             RPC_STATUS rc = UuidFromStringW(guid_str, &addr->VmId);
2506             PyMem_Free(guid_str);
2507             if (rc != RPC_S_OK) {
2508                 PyErr_Format(PyExc_ValueError,
2509                     "%s(): AF_HYPERV address vm_id is not a valid UUID string",
2510                     caller);
2511                 return 0;
2512             }
2513 
2514             guid_str = PyUnicode_AsWideCharString(service_id_obj, NULL);
2515             if (guid_str == NULL) {
2516                 PyErr_Format(PyExc_ValueError,
2517                     "%s(): AF_HYPERV address service_id is not a valid UUID string",
2518                     caller);
2519                 return 0;
2520             }
2521             rc = UuidFromStringW(guid_str, &addr->ServiceId);
2522             PyMem_Free(guid_str);
2523             if (rc != RPC_S_OK) {
2524                 PyErr_Format(PyExc_ValueError,
2525                     "%s(): AF_HYPERV address service_id is not a valid UUID string",
2526                     caller);
2527                 return 0;
2528             }
2529 
2530             *len_ret = sizeof(*addr);
2531             return 1;
2532         }
2533         default:
2534             PyErr_Format(PyExc_OSError,
2535                 "%s(): unsupported AF_HYPERV protocol: %d",
2536                 caller, s->sock_proto);
2537             return 0;
2538         }
2539     }
2540 #endif /* HAVE_AF_HYPERV */
2541 
2542     /* More cases here... */
2543 
2544     default:
2545         PyErr_Format(PyExc_OSError, "%s(): bad family", caller);
2546         return 0;
2547 
2548     }
2549 }
2550 #endif // defined(HAVE_BIND) || defined(HAVE_CONNECTTO) || defined(CMSG_LEN)
2551 
2552 
2553 /* Get the address length according to the socket object's address family.
2554    Return 1 if the family is known, 0 otherwise.  The length is returned
2555    through len_ret. */
2556 
2557 static int
getsockaddrlen(PySocketSockObject * s,socklen_t * len_ret)2558 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
2559 {
2560     switch (s->sock_family) {
2561 
2562 #if defined(AF_UNIX)
2563     case AF_UNIX:
2564     {
2565         *len_ret = sizeof (struct sockaddr_un);
2566         return 1;
2567     }
2568 #endif /* AF_UNIX */
2569 
2570 #if defined(AF_NETLINK)
2571     case AF_NETLINK:
2572     {
2573         *len_ret = sizeof (struct sockaddr_nl);
2574         return 1;
2575     }
2576 #endif /* AF_NETLINK */
2577 
2578 #if defined(AF_QIPCRTR)
2579     case AF_QIPCRTR:
2580     {
2581         *len_ret = sizeof (struct sockaddr_qrtr);
2582         return 1;
2583     }
2584 #endif /* AF_QIPCRTR */
2585 
2586 #if defined(AF_VSOCK)
2587        case AF_VSOCK:
2588        {
2589            *len_ret = sizeof (struct sockaddr_vm);
2590            return 1;
2591        }
2592 #endif /* AF_VSOCK */
2593 
2594 #ifdef AF_RDS
2595     case AF_RDS:
2596         /* RDS sockets use sockaddr_in: fall-through */
2597 #endif /* AF_RDS */
2598 
2599     case AF_INET:
2600     {
2601         *len_ret = sizeof (struct sockaddr_in);
2602         return 1;
2603     }
2604 
2605 #ifdef ENABLE_IPV6
2606     case AF_INET6:
2607     {
2608         *len_ret = sizeof (struct sockaddr_in6);
2609         return 1;
2610     }
2611 #endif /* ENABLE_IPV6 */
2612 
2613 #ifdef USE_BLUETOOTH
2614     case AF_BLUETOOTH:
2615     {
2616         switch(s->sock_proto)
2617         {
2618 
2619 #ifdef BTPROTO_L2CAP
2620         case BTPROTO_L2CAP:
2621             *len_ret = sizeof (struct sockaddr_l2);
2622             return 1;
2623 #endif /* BTPROTO_L2CAP */
2624         case BTPROTO_RFCOMM:
2625             *len_ret = sizeof (struct sockaddr_rc);
2626             return 1;
2627 #ifdef BTPROTO_HCI
2628         case BTPROTO_HCI:
2629             *len_ret = sizeof (struct sockaddr_hci);
2630             return 1;
2631 #if !defined(__FreeBSD__)
2632         case BTPROTO_SCO:
2633             *len_ret = sizeof (struct sockaddr_sco);
2634             return 1;
2635 #endif /* !__FreeBSD__ */
2636 #endif /* BTPROTO_HCI */
2637         default:
2638             PyErr_SetString(PyExc_OSError, "getsockaddrlen: "
2639                             "unknown BT protocol");
2640             return 0;
2641 
2642         }
2643     }
2644 #endif /* USE_BLUETOOTH */
2645 
2646 #ifdef HAVE_NETPACKET_PACKET_H
2647     case AF_PACKET:
2648     {
2649         *len_ret = sizeof (struct sockaddr_ll);
2650         return 1;
2651     }
2652 #endif /* HAVE_NETPACKET_PACKET_H */
2653 
2654 #ifdef HAVE_LINUX_TIPC_H
2655     case AF_TIPC:
2656     {
2657         *len_ret = sizeof (struct sockaddr_tipc);
2658         return 1;
2659     }
2660 #endif /* HAVE_LINUX_TIPC_H */
2661 
2662 #ifdef AF_CAN
2663     case AF_CAN:
2664     {
2665         *len_ret = sizeof (struct sockaddr_can);
2666         return 1;
2667     }
2668 #endif /* AF_CAN */
2669 
2670 #ifdef PF_SYSTEM
2671     case PF_SYSTEM:
2672         switch(s->sock_proto) {
2673 #ifdef SYSPROTO_CONTROL
2674         case SYSPROTO_CONTROL:
2675             *len_ret = sizeof (struct sockaddr_ctl);
2676             return 1;
2677 #endif /* SYSPROTO_CONTROL */
2678         default:
2679             PyErr_SetString(PyExc_OSError, "getsockaddrlen: "
2680                             "unknown PF_SYSTEM protocol");
2681             return 0;
2682         }
2683 #endif /* PF_SYSTEM */
2684 #ifdef HAVE_SOCKADDR_ALG
2685     case AF_ALG:
2686     {
2687         *len_ret = sizeof (struct sockaddr_alg);
2688         return 1;
2689     }
2690 #endif /* HAVE_SOCKADDR_ALG */
2691 #ifdef HAVE_AF_HYPERV
2692     case AF_HYPERV:
2693     {
2694         *len_ret = sizeof (SOCKADDR_HV);
2695         return 1;
2696     }
2697 #endif /* HAVE_AF_HYPERV */
2698 
2699     /* More cases here... */
2700 
2701     default:
2702         PyErr_SetString(PyExc_OSError, "getsockaddrlen: bad family");
2703         return 0;
2704 
2705     }
2706 }
2707 
2708 
2709 /* Support functions for the sendmsg() and recvmsg[_into]() methods.
2710    Currently, these methods are only compiled if the RFC 2292/3542
2711    CMSG_LEN() macro is available.  Older systems seem to have used
2712    sizeof(struct cmsghdr) + (length) where CMSG_LEN() is used now, so
2713    it may be possible to define CMSG_LEN() that way if it's not
2714    provided.  Some architectures might need extra padding after the
2715    cmsghdr, however, and CMSG_LEN() would have to take account of
2716    this. */
2717 #ifdef CMSG_LEN
2718 /* If length is in range, set *result to CMSG_LEN(length) and return
2719    true; otherwise, return false. */
2720 static int
get_CMSG_LEN(size_t length,size_t * result)2721 get_CMSG_LEN(size_t length, size_t *result)
2722 {
2723     size_t tmp;
2724 
2725     if (length > (SOCKLEN_T_LIMIT - CMSG_LEN(0)))
2726         return 0;
2727     tmp = CMSG_LEN(length);
2728     if (tmp > SOCKLEN_T_LIMIT || tmp < length)
2729         return 0;
2730     *result = tmp;
2731     return 1;
2732 }
2733 
2734 #ifdef CMSG_SPACE
2735 /* If length is in range, set *result to CMSG_SPACE(length) and return
2736    true; otherwise, return false. */
2737 static int
get_CMSG_SPACE(size_t length,size_t * result)2738 get_CMSG_SPACE(size_t length, size_t *result)
2739 {
2740     size_t tmp;
2741 
2742     /* Use CMSG_SPACE(1) here in order to take account of the padding
2743        necessary before *and* after the data. */
2744     if (length > (SOCKLEN_T_LIMIT - CMSG_SPACE(1)))
2745         return 0;
2746     tmp = CMSG_SPACE(length);
2747     if (tmp > SOCKLEN_T_LIMIT || tmp < length)
2748         return 0;
2749     *result = tmp;
2750     return 1;
2751 }
2752 #endif
2753 
2754 /* Return true iff msg->msg_controllen is valid, cmsgh is a valid
2755    pointer in msg->msg_control with at least "space" bytes after it,
2756    and its cmsg_len member inside the buffer. */
2757 static int
cmsg_min_space(struct msghdr * msg,struct cmsghdr * cmsgh,size_t space)2758 cmsg_min_space(struct msghdr *msg, struct cmsghdr *cmsgh, size_t space)
2759 {
2760     size_t cmsg_offset;
2761     static const size_t cmsg_len_end = (offsetof(struct cmsghdr, cmsg_len) +
2762                                         sizeof(cmsgh->cmsg_len));
2763 
2764     /* Note that POSIX allows msg_controllen to be of signed type. */
2765     if (cmsgh == NULL || msg->msg_control == NULL)
2766         return 0;
2767     /* Note that POSIX allows msg_controllen to be of a signed type. This is
2768        annoying under OS X as it's unsigned there and so it triggers a
2769        tautological comparison warning under Clang when compared against 0.
2770        Since the check is valid on other platforms, silence the warning under
2771        Clang. */
2772     #ifdef __clang__
2773     #pragma clang diagnostic push
2774     #pragma clang diagnostic ignored "-Wtautological-compare"
2775     #endif
2776     #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
2777     #pragma GCC diagnostic push
2778     #pragma GCC diagnostic ignored "-Wtype-limits"
2779     #endif
2780     if (msg->msg_controllen < 0)
2781         return 0;
2782     #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
2783     #pragma GCC diagnostic pop
2784     #endif
2785     #ifdef __clang__
2786     #pragma clang diagnostic pop
2787     #endif
2788     if (space < cmsg_len_end)
2789         space = cmsg_len_end;
2790     cmsg_offset = (char *)cmsgh - (char *)msg->msg_control;
2791     return (cmsg_offset <= (size_t)-1 - space &&
2792             cmsg_offset + space <= msg->msg_controllen);
2793 }
2794 
2795 /* If pointer CMSG_DATA(cmsgh) is in buffer msg->msg_control, set
2796    *space to number of bytes following it in the buffer and return
2797    true; otherwise, return false.  Assumes cmsgh, msg->msg_control and
2798    msg->msg_controllen are valid. */
2799 static int
get_cmsg_data_space(struct msghdr * msg,struct cmsghdr * cmsgh,size_t * space)2800 get_cmsg_data_space(struct msghdr *msg, struct cmsghdr *cmsgh, size_t *space)
2801 {
2802     size_t data_offset;
2803     char *data_ptr;
2804 
2805     if ((data_ptr = (char *)CMSG_DATA(cmsgh)) == NULL)
2806         return 0;
2807     data_offset = data_ptr - (char *)msg->msg_control;
2808     if (data_offset > msg->msg_controllen)
2809         return 0;
2810     *space = msg->msg_controllen - data_offset;
2811     return 1;
2812 }
2813 
2814 /* If cmsgh is invalid or not contained in the buffer pointed to by
2815    msg->msg_control, return -1.  If cmsgh is valid and its associated
2816    data is entirely contained in the buffer, set *data_len to the
2817    length of the associated data and return 0.  If only part of the
2818    associated data is contained in the buffer but cmsgh is otherwise
2819    valid, set *data_len to the length contained in the buffer and
2820    return 1. */
2821 static int
get_cmsg_data_len(struct msghdr * msg,struct cmsghdr * cmsgh,size_t * data_len)2822 get_cmsg_data_len(struct msghdr *msg, struct cmsghdr *cmsgh, size_t *data_len)
2823 {
2824     size_t space, cmsg_data_len;
2825 
2826     if (!cmsg_min_space(msg, cmsgh, CMSG_LEN(0)) ||
2827         cmsgh->cmsg_len < CMSG_LEN(0))
2828         return -1;
2829     cmsg_data_len = cmsgh->cmsg_len - CMSG_LEN(0);
2830     if (!get_cmsg_data_space(msg, cmsgh, &space))
2831         return -1;
2832     if (space >= cmsg_data_len) {
2833         *data_len = cmsg_data_len;
2834         return 0;
2835     }
2836     *data_len = space;
2837     return 1;
2838 }
2839 #endif    /* CMSG_LEN */
2840 
2841 
2842 struct sock_accept {
2843     socklen_t *addrlen;
2844     sock_addr_t *addrbuf;
2845     SOCKET_T result;
2846 };
2847 
2848 #if defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
2849 
2850 static int
sock_accept_impl(PySocketSockObject * s,void * data)2851 sock_accept_impl(PySocketSockObject *s, void *data)
2852 {
2853     struct sock_accept *ctx = data;
2854     struct sockaddr *addr = SAS2SA(ctx->addrbuf);
2855     socklen_t *paddrlen = ctx->addrlen;
2856 #ifdef HAVE_SOCKADDR_ALG
2857     /* AF_ALG does not support accept() with addr and raises
2858      * ECONNABORTED instead. */
2859     if (s->sock_family == AF_ALG) {
2860         addr = NULL;
2861         paddrlen = NULL;
2862         *ctx->addrlen = 0;
2863     }
2864 #endif
2865 
2866 #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
2867     socket_state *state = s->state;
2868     if (state->accept4_works != 0) {
2869         ctx->result = accept4(s->sock_fd, addr, paddrlen,
2870                               SOCK_CLOEXEC);
2871         if (ctx->result == INVALID_SOCKET && state->accept4_works == -1) {
2872             /* On Linux older than 2.6.28, accept4() fails with ENOSYS */
2873             state->accept4_works = (errno != ENOSYS);
2874         }
2875     }
2876     if (state->accept4_works == 0)
2877         ctx->result = accept(s->sock_fd, addr, paddrlen);
2878 #else
2879     ctx->result = accept(s->sock_fd, addr, paddrlen);
2880 #endif
2881 
2882 #ifdef MS_WINDOWS
2883     return (ctx->result != INVALID_SOCKET);
2884 #else
2885     return (ctx->result >= 0);
2886 #endif
2887 }
2888 
2889 /* s._accept() -> (fd, address) */
2890 
2891 static PyObject *
sock_accept(PySocketSockObject * s,PyObject * Py_UNUSED (ignored))2892 sock_accept(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
2893 {
2894     sock_addr_t addrbuf;
2895     SOCKET_T newfd;
2896     socklen_t addrlen;
2897     PyObject *sock = NULL;
2898     PyObject *addr = NULL;
2899     PyObject *res = NULL;
2900     struct sock_accept ctx;
2901 
2902     if (!getsockaddrlen(s, &addrlen))
2903         return NULL;
2904     memset(&addrbuf, 0, addrlen);
2905 
2906     if (!IS_SELECTABLE(s))
2907         return select_error();
2908 
2909     ctx.addrlen = &addrlen;
2910     ctx.addrbuf = &addrbuf;
2911     if (sock_call(s, 0, sock_accept_impl, &ctx) < 0)
2912         return NULL;
2913     newfd = ctx.result;
2914 
2915 #ifdef MS_WINDOWS
2916 #if defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
2917 #ifndef HANDLE_FLAG_INHERIT
2918 #define HANDLE_FLAG_INHERIT 0x00000001
2919 #endif
2920     if (!SetHandleInformation((HANDLE)newfd, HANDLE_FLAG_INHERIT, 0)) {
2921         PyErr_SetFromWindowsErr(0);
2922         SOCKETCLOSE(newfd);
2923         goto finally;
2924     }
2925 #endif
2926 #else
2927 
2928 #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
2929     socket_state *state = s->state;
2930     if (!state->accept4_works)
2931 #endif
2932     {
2933         if (_Py_set_inheritable(newfd, 0, NULL) < 0) {
2934             SOCKETCLOSE(newfd);
2935             goto finally;
2936         }
2937     }
2938 #endif
2939 
2940     sock = PyLong_FromSocket_t(newfd);
2941     if (sock == NULL) {
2942         SOCKETCLOSE(newfd);
2943         goto finally;
2944     }
2945 
2946     addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
2947                         addrlen, s->sock_proto);
2948     if (addr == NULL)
2949         goto finally;
2950 
2951     res = PyTuple_Pack(2, sock, addr);
2952 
2953 finally:
2954     Py_XDECREF(sock);
2955     Py_XDECREF(addr);
2956     return res;
2957 }
2958 
2959 PyDoc_STRVAR(accept_doc,
2960 "_accept() -> (integer, address info)\n\
2961 \n\
2962 Wait for an incoming connection.  Return a new socket file descriptor\n\
2963 representing the connection, and the address of the client.\n\
2964 For IP sockets, the address info is a pair (hostaddr, port).");
2965 #endif // defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
2966 
2967 
2968 /* s.setblocking(flag) method.  Argument:
2969    False -- non-blocking mode; same as settimeout(0)
2970    True -- blocking mode; same as settimeout(None)
2971 */
2972 
2973 static PyObject *
sock_setblocking(PySocketSockObject * s,PyObject * arg)2974 sock_setblocking(PySocketSockObject *s, PyObject *arg)
2975 {
2976     long block;
2977 
2978     block = PyObject_IsTrue(arg);
2979     if (block < 0)
2980         return NULL;
2981 
2982     s->sock_timeout = _PyTime_FromSeconds(block ? -1 : 0);
2983     if (internal_setblocking(s, block) == -1) {
2984         return NULL;
2985     }
2986     Py_RETURN_NONE;
2987 }
2988 
2989 PyDoc_STRVAR(setblocking_doc,
2990 "setblocking(flag)\n\
2991 \n\
2992 Set the socket to blocking (flag is true) or non-blocking (false).\n\
2993 setblocking(True) is equivalent to settimeout(None);\n\
2994 setblocking(False) is equivalent to settimeout(0.0).");
2995 
2996 /* s.getblocking() method.
2997    Returns True if socket is in blocking mode,
2998    False if it is in non-blocking mode.
2999 */
3000 static PyObject *
sock_getblocking(PySocketSockObject * s,PyObject * Py_UNUSED (ignored))3001 sock_getblocking(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3002 {
3003     if (s->sock_timeout) {
3004         Py_RETURN_TRUE;
3005     }
3006     else {
3007         Py_RETURN_FALSE;
3008     }
3009 }
3010 
3011 PyDoc_STRVAR(getblocking_doc,
3012 "getblocking()\n\
3013 \n\
3014 Returns True if socket is in blocking mode, or False if it\n\
3015 is in non-blocking mode.");
3016 
3017 static int
socket_parse_timeout(PyTime_t * timeout,PyObject * timeout_obj)3018 socket_parse_timeout(PyTime_t *timeout, PyObject *timeout_obj)
3019 {
3020 #ifdef MS_WINDOWS
3021     struct timeval tv;
3022 #endif
3023 #ifndef HAVE_POLL
3024     PyTime_t ms;
3025 #endif
3026     int overflow = 0;
3027 
3028     if (timeout_obj == Py_None) {
3029         *timeout = _PyTime_FromSeconds(-1);
3030         return 0;
3031     }
3032 
3033     if (_PyTime_FromSecondsObject(timeout,
3034                                   timeout_obj, _PyTime_ROUND_TIMEOUT) < 0)
3035         return -1;
3036 
3037     if (*timeout < 0) {
3038         PyErr_SetString(PyExc_ValueError, "Timeout value out of range");
3039         return -1;
3040     }
3041 
3042 #ifdef MS_WINDOWS
3043     overflow |= (_PyTime_AsTimeval(*timeout, &tv, _PyTime_ROUND_TIMEOUT) < 0);
3044 #endif
3045 #ifndef HAVE_POLL
3046     ms = _PyTime_AsMilliseconds(*timeout, _PyTime_ROUND_TIMEOUT);
3047     overflow |= (ms > INT_MAX);
3048 #endif
3049     if (overflow) {
3050         PyErr_SetString(PyExc_OverflowError,
3051                         "timeout doesn't fit into C timeval");
3052         return -1;
3053     }
3054 
3055     return 0;
3056 }
3057 
3058 /* s.settimeout(timeout) method.  Argument:
3059    None -- no timeout, blocking mode; same as setblocking(True)
3060    0.0  -- non-blocking mode; same as setblocking(False)
3061    > 0  -- timeout mode; operations time out after timeout seconds
3062    < 0  -- illegal; raises an exception
3063 */
3064 static PyObject *
sock_settimeout(PySocketSockObject * s,PyObject * arg)3065 sock_settimeout(PySocketSockObject *s, PyObject *arg)
3066 {
3067     PyTime_t timeout;
3068 
3069     if (socket_parse_timeout(&timeout, arg) < 0)
3070         return NULL;
3071 
3072     s->sock_timeout = timeout;
3073 
3074     int block = timeout < 0;
3075     /* Blocking mode for a Python socket object means that operations
3076        like :meth:`recv` or :meth:`sendall` will block the execution of
3077        the current thread until they are complete or aborted with a
3078        `TimeoutError` or `socket.error` errors.  When timeout is `None`,
3079        the underlying FD is in a blocking mode.  When timeout is a positive
3080        number, the FD is in a non-blocking mode, and socket ops are
3081        implemented with a `select()` call.
3082 
3083        When timeout is 0.0, the FD is in a non-blocking mode.
3084 
3085        This table summarizes all states in which the socket object and
3086        its underlying FD can be:
3087 
3088        ==================== ===================== ==============
3089         `gettimeout()`       `getblocking()`       FD
3090        ==================== ===================== ==============
3091         ``None``             ``True``              blocking
3092         ``0.0``              ``False``             non-blocking
3093         ``> 0``              ``True``              non-blocking
3094     */
3095 
3096     if (internal_setblocking(s, block) == -1) {
3097         return NULL;
3098     }
3099     Py_RETURN_NONE;
3100 }
3101 
3102 PyDoc_STRVAR(settimeout_doc,
3103 "settimeout(timeout)\n\
3104 \n\
3105 Set a timeout on socket operations.  'timeout' can be a float,\n\
3106 giving in seconds, or None.  Setting a timeout of None disables\n\
3107 the timeout feature and is equivalent to setblocking(1).\n\
3108 Setting a timeout of zero is the same as setblocking(0).");
3109 
3110 /* s.gettimeout() method.
3111    Returns the timeout associated with a socket. */
3112 static PyObject *
sock_gettimeout(PySocketSockObject * s,PyObject * Py_UNUSED (ignored))3113 sock_gettimeout(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3114 {
3115     if (s->sock_timeout < 0) {
3116         Py_RETURN_NONE;
3117     }
3118     else {
3119         double seconds = PyTime_AsSecondsDouble(s->sock_timeout);
3120         return PyFloat_FromDouble(seconds);
3121     }
3122 }
3123 
3124 PyDoc_STRVAR(gettimeout_doc,
3125 "gettimeout() -> timeout\n\
3126 \n\
3127 Returns the timeout in seconds (float) associated with socket\n\
3128 operations. A timeout of None indicates that timeouts on socket\n\
3129 operations are disabled.");
3130 
3131 #ifdef HAVE_SETSOCKOPT
3132 /* s.setsockopt() method.
3133    With an integer third argument, sets an integer optval with optlen=4.
3134    With None as third argument and an integer fourth argument, set
3135    optval=NULL with unsigned int as optlen.
3136    With a string third argument, sets an option from a buffer;
3137    use optional built-in module 'struct' to encode the string.
3138 */
3139 
3140 static PyObject *
sock_setsockopt(PySocketSockObject * s,PyObject * args)3141 sock_setsockopt(PySocketSockObject *s, PyObject *args)
3142 {
3143     int level;
3144     int optname;
3145     int res;
3146     Py_buffer optval;
3147     int flag;
3148     unsigned int optlen;
3149     PyObject *none;
3150 
3151 #ifdef AF_VSOCK
3152     if (s->sock_family == AF_VSOCK) {
3153         uint64_t vflag; // Must be set width of 64 bits
3154         /* setsockopt(level, opt, flag) */
3155         if (PyArg_ParseTuple(args, "iiK:setsockopt",
3156                          &level, &optname, &vflag)) {
3157             // level should always be set to AF_VSOCK
3158             res = setsockopt(s->sock_fd, level, optname,
3159                          (void*)&vflag, sizeof vflag);
3160             goto done;
3161         }
3162         return NULL;
3163     }
3164 #endif
3165 
3166     /* setsockopt(level, opt, flag) */
3167     if (PyArg_ParseTuple(args, "iii:setsockopt",
3168                          &level, &optname, &flag)) {
3169         res = setsockopt(s->sock_fd, level, optname,
3170                          (char*)&flag, sizeof flag);
3171         goto done;
3172     }
3173 
3174     PyErr_Clear();
3175     /* setsockopt(level, opt, None, flag) */
3176     if (PyArg_ParseTuple(args, "iiO!I:setsockopt",
3177                          &level, &optname, Py_TYPE(Py_None), &none, &optlen)) {
3178         assert(sizeof(socklen_t) >= sizeof(unsigned int));
3179         res = setsockopt(s->sock_fd, level, optname,
3180                          NULL, (socklen_t)optlen);
3181         goto done;
3182     }
3183 
3184     PyErr_Clear();
3185     /* setsockopt(level, opt, buffer) */
3186     if (!PyArg_ParseTuple(args, "iiy*:setsockopt",
3187                             &level, &optname, &optval))
3188         return NULL;
3189 
3190 #ifdef MS_WINDOWS
3191     if (optval.len > INT_MAX) {
3192         PyBuffer_Release(&optval);
3193         PyErr_Format(PyExc_OverflowError,
3194                         "socket option is larger than %i bytes",
3195                         INT_MAX);
3196         return NULL;
3197     }
3198     res = setsockopt(s->sock_fd, level, optname,
3199                         optval.buf, (int)optval.len);
3200 #else
3201     res = setsockopt(s->sock_fd, level, optname, optval.buf, optval.len);
3202 #endif
3203     PyBuffer_Release(&optval);
3204 
3205 done:
3206     if (res < 0) {
3207         return s->errorhandler();
3208     }
3209 
3210     Py_RETURN_NONE;
3211 }
3212 
3213 PyDoc_STRVAR(setsockopt_doc,
3214 "setsockopt(level, option, value: int)\n\
3215 setsockopt(level, option, value: buffer)\n\
3216 setsockopt(level, option, None, optlen: int)\n\
3217 \n\
3218 Set a socket option.  See the Unix manual for level and option.\n\
3219 The value argument can either be an integer, a string buffer, or\n\
3220 None, optlen.");
3221 #endif
3222 
3223 /* s.getsockopt() method.
3224    With two arguments, retrieves an integer option.
3225    With a third integer argument, retrieves a string buffer of that size;
3226    use optional built-in module 'struct' to decode the string. */
3227 
3228 static PyObject *
sock_getsockopt(PySocketSockObject * s,PyObject * args)3229 sock_getsockopt(PySocketSockObject *s, PyObject *args)
3230 {
3231     int level;
3232     int optname;
3233     int res;
3234     PyObject *buf;
3235     socklen_t buflen = 0;
3236     int flag = 0;
3237     socklen_t flagsize;
3238 
3239     if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
3240                           &level, &optname, &buflen))
3241         return NULL;
3242 
3243     if (buflen == 0) {
3244 #ifdef AF_VSOCK
3245         if (s->sock_family == AF_VSOCK) {
3246             uint64_t vflag = 0; // Must be set width of 64 bits
3247             flagsize = sizeof vflag;
3248             res = getsockopt(s->sock_fd, level, optname,
3249                          (void *)&vflag, &flagsize);
3250             if (res < 0)
3251                 return s->errorhandler();
3252             return PyLong_FromUnsignedLong(vflag);
3253         }
3254 #endif
3255         flagsize = sizeof flag;
3256         res = getsockopt(s->sock_fd, level, optname,
3257                          (void *)&flag, &flagsize);
3258         if (res < 0)
3259             return s->errorhandler();
3260         return PyLong_FromLong(flag);
3261     }
3262 #ifdef AF_VSOCK
3263     if (s->sock_family == AF_VSOCK) {
3264         PyErr_SetString(PyExc_OSError,
3265                         "getsockopt string buffer not allowed");
3266         return NULL;
3267         }
3268 #endif
3269     if (buflen <= 0 || buflen > 1024) {
3270         PyErr_SetString(PyExc_OSError,
3271                         "getsockopt buflen out of range");
3272         return NULL;
3273     }
3274     buf = PyBytes_FromStringAndSize((char *)NULL, buflen);
3275     if (buf == NULL)
3276         return NULL;
3277     res = getsockopt(s->sock_fd, level, optname,
3278                      (void *)PyBytes_AS_STRING(buf), &buflen);
3279     if (res < 0) {
3280         Py_DECREF(buf);
3281         return s->errorhandler();
3282     }
3283     _PyBytes_Resize(&buf, buflen);
3284     return buf;
3285 }
3286 
3287 PyDoc_STRVAR(getsockopt_doc,
3288 "getsockopt(level, option[, buffersize]) -> value\n\
3289 \n\
3290 Get a socket option.  See the Unix manual for level and option.\n\
3291 If a nonzero buffersize argument is given, the return value is a\n\
3292 string of that length; otherwise it is an integer.");
3293 
3294 
3295 #ifdef HAVE_BIND
3296 /* s.bind(sockaddr) method */
3297 
3298 static PyObject *
sock_bind(PySocketSockObject * s,PyObject * addro)3299 sock_bind(PySocketSockObject *s, PyObject *addro)
3300 {
3301     sock_addr_t addrbuf;
3302     int addrlen;
3303     int res;
3304 
3305     if (!getsockaddrarg(s, addro, &addrbuf, &addrlen, "bind")) {
3306         return NULL;
3307     }
3308 
3309     if (PySys_Audit("socket.bind", "OO", s, addro) < 0) {
3310         return NULL;
3311     }
3312 
3313     Py_BEGIN_ALLOW_THREADS
3314     res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
3315     Py_END_ALLOW_THREADS
3316     if (res < 0)
3317         return s->errorhandler();
3318     Py_RETURN_NONE;
3319 }
3320 
3321 PyDoc_STRVAR(bind_doc,
3322 "bind(address)\n\
3323 \n\
3324 Bind the socket to a local address.  For IP sockets, the address is a\n\
3325 pair (host, port); the host must refer to the local host. For raw packet\n\
3326 sockets the address is a tuple (ifname, proto [,pkttype [,hatype [,addr]]])");
3327 #endif
3328 
3329 
3330 /* s.close() method.
3331    Set the file descriptor to -1 so operations tried subsequently
3332    will surely fail. */
3333 
3334 static PyObject *
sock_close(PySocketSockObject * s,PyObject * Py_UNUSED (ignored))3335 sock_close(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3336 {
3337     SOCKET_T fd;
3338     int res;
3339 
3340     fd = s->sock_fd;
3341     if (fd != INVALID_SOCKET) {
3342         s->sock_fd = INVALID_SOCKET;
3343 
3344         /* We do not want to retry upon EINTR: see
3345            http://lwn.net/Articles/576478/ and
3346            http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
3347            for more details. */
3348         Py_BEGIN_ALLOW_THREADS
3349         res = SOCKETCLOSE(fd);
3350         Py_END_ALLOW_THREADS
3351         /* bpo-30319: The peer can already have closed the connection.
3352            Python ignores ECONNRESET on close(). */
3353         if (res < 0 && errno != ECONNRESET) {
3354             return s->errorhandler();
3355         }
3356     }
3357     Py_RETURN_NONE;
3358 }
3359 
3360 PyDoc_STRVAR(sock_close_doc,
3361 "close()\n\
3362 \n\
3363 Close the socket.  It cannot be used after this call.");
3364 
3365 static PyObject *
sock_detach(PySocketSockObject * s,PyObject * Py_UNUSED (ignored))3366 sock_detach(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3367 {
3368     SOCKET_T fd = s->sock_fd;
3369     s->sock_fd = INVALID_SOCKET;
3370     return PyLong_FromSocket_t(fd);
3371 }
3372 
3373 PyDoc_STRVAR(detach_doc,
3374 "detach()\n\
3375 \n\
3376 Close the socket object without closing the underlying file descriptor.\n\
3377 The object cannot be used after this call, but the file descriptor\n\
3378 can be reused for other purposes.  The file descriptor is returned.");
3379 
3380 #ifdef HAVE_CONNECT
3381 static int
sock_connect_impl(PySocketSockObject * s,void * Py_UNUSED (data))3382 sock_connect_impl(PySocketSockObject *s, void* Py_UNUSED(data))
3383 {
3384     int err;
3385     socklen_t size = sizeof err;
3386 
3387     if (getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR, (void *)&err, &size)) {
3388         /* getsockopt() failed */
3389         return 0;
3390     }
3391 
3392     if (err == EISCONN)
3393         return 1;
3394     if (err != 0) {
3395         /* sock_call_ex() uses GET_SOCK_ERROR() to get the error code */
3396         SET_SOCK_ERROR(err);
3397         return 0;
3398     }
3399     return 1;
3400 }
3401 
3402 static int
internal_connect(PySocketSockObject * s,struct sockaddr * addr,int addrlen,int raise)3403 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
3404                  int raise)
3405 {
3406     int res, err, wait_connect;
3407 
3408     Py_BEGIN_ALLOW_THREADS
3409     res = connect(s->sock_fd, addr, addrlen);
3410     Py_END_ALLOW_THREADS
3411 
3412     if (!res) {
3413         /* connect() succeeded, the socket is connected */
3414         return 0;
3415     }
3416 
3417     /* connect() failed */
3418 
3419     /* save error, PyErr_CheckSignals() can replace it */
3420     err = GET_SOCK_ERROR;
3421     if (CHECK_ERRNO(EINTR)) {
3422         if (PyErr_CheckSignals())
3423             return -1;
3424 
3425         /* Issue #23618: when connect() fails with EINTR, the connection is
3426            running asynchronously.
3427 
3428            If the socket is blocking or has a timeout, wait until the
3429            connection completes, fails or timed out using select(), and then
3430            get the connection status using getsockopt(SO_ERROR).
3431 
3432            If the socket is non-blocking, raise InterruptedError. The caller is
3433            responsible to wait until the connection completes, fails or timed
3434            out (it's the case in asyncio for example). */
3435         wait_connect = (s->sock_timeout != 0 && IS_SELECTABLE(s));
3436     }
3437     else {
3438         wait_connect = (s->sock_timeout > 0 && err == SOCK_INPROGRESS_ERR
3439                         && IS_SELECTABLE(s));
3440     }
3441 
3442     if (!wait_connect) {
3443         if (raise) {
3444             /* restore error, maybe replaced by PyErr_CheckSignals() */
3445             SET_SOCK_ERROR(err);
3446             s->errorhandler();
3447             return -1;
3448         }
3449         else
3450             return err;
3451     }
3452 
3453     if (raise) {
3454         /* socket.connect() raises an exception on error */
3455         if (sock_call_ex(s, 1, sock_connect_impl, NULL,
3456                          1, NULL, s->sock_timeout) < 0)
3457             return -1;
3458     }
3459     else {
3460         /* socket.connect_ex() returns the error code on error */
3461         if (sock_call_ex(s, 1, sock_connect_impl, NULL,
3462                          1, &err, s->sock_timeout) < 0)
3463             return err;
3464     }
3465     return 0;
3466 }
3467 
3468 /* s.connect(sockaddr) method */
3469 
3470 static PyObject *
sock_connect(PySocketSockObject * s,PyObject * addro)3471 sock_connect(PySocketSockObject *s, PyObject *addro)
3472 {
3473     sock_addr_t addrbuf;
3474     int addrlen;
3475     int res;
3476 
3477     if (!getsockaddrarg(s, addro, &addrbuf, &addrlen, "connect")) {
3478         return NULL;
3479     }
3480 
3481     if (PySys_Audit("socket.connect", "OO", s, addro) < 0) {
3482         return NULL;
3483     }
3484 
3485     res = internal_connect(s, SAS2SA(&addrbuf), addrlen, 1);
3486     if (res < 0)
3487         return NULL;
3488 
3489     Py_RETURN_NONE;
3490 }
3491 
3492 PyDoc_STRVAR(connect_doc,
3493 "connect(address)\n\
3494 \n\
3495 Connect the socket to a remote address.  For IP sockets, the address\n\
3496 is a pair (host, port).");
3497 
3498 
3499 /* s.connect_ex(sockaddr) method */
3500 
3501 static PyObject *
sock_connect_ex(PySocketSockObject * s,PyObject * addro)3502 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
3503 {
3504     sock_addr_t addrbuf;
3505     int addrlen;
3506     int res;
3507 
3508     if (!getsockaddrarg(s, addro, &addrbuf, &addrlen, "connect_ex")) {
3509         return NULL;
3510     }
3511 
3512     if (PySys_Audit("socket.connect", "OO", s, addro) < 0) {
3513         return NULL;
3514     }
3515 
3516     res = internal_connect(s, SAS2SA(&addrbuf), addrlen, 0);
3517     if (res < 0)
3518         return NULL;
3519 
3520     return PyLong_FromLong((long) res);
3521 }
3522 
3523 PyDoc_STRVAR(connect_ex_doc,
3524 "connect_ex(address) -> errno\n\
3525 \n\
3526 This is like connect(address), but returns an error code (the errno value)\n\
3527 instead of raising an exception when an error occurs.");
3528 #endif // HAVE_CONNECT
3529 
3530 
3531 /* s.fileno() method */
3532 
3533 static PyObject *
sock_fileno(PySocketSockObject * s,PyObject * Py_UNUSED (ignored))3534 sock_fileno(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3535 {
3536     return PyLong_FromSocket_t(s->sock_fd);
3537 }
3538 
3539 PyDoc_STRVAR(fileno_doc,
3540 "fileno() -> integer\n\
3541 \n\
3542 Return the integer file descriptor of the socket.");
3543 
3544 
3545 #ifdef HAVE_GETSOCKNAME
3546 /* s.getsockname() method */
3547 
3548 static PyObject *
sock_getsockname(PySocketSockObject * s,PyObject * Py_UNUSED (ignored))3549 sock_getsockname(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3550 {
3551     sock_addr_t addrbuf;
3552     int res;
3553     socklen_t addrlen;
3554 
3555     if (!getsockaddrlen(s, &addrlen))
3556         return NULL;
3557     memset(&addrbuf, 0, addrlen);
3558     Py_BEGIN_ALLOW_THREADS
3559     res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
3560     Py_END_ALLOW_THREADS
3561     if (res < 0)
3562         return s->errorhandler();
3563     return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
3564                         s->sock_proto);
3565 }
3566 
3567 PyDoc_STRVAR(getsockname_doc,
3568 "getsockname() -> address info\n\
3569 \n\
3570 Return the address of the local endpoint. The format depends on the\n\
3571 address family. For IPv4 sockets, the address info is a pair\n\
3572 (hostaddr, port). For IPv6 sockets, the address info is a 4-tuple\n\
3573 (hostaddr, port, flowinfo, scope_id).");
3574 #endif
3575 
3576 
3577 #ifdef HAVE_GETPEERNAME         /* Cray APP doesn't have this :-( */
3578 /* s.getpeername() method */
3579 
3580 static PyObject *
sock_getpeername(PySocketSockObject * s,PyObject * Py_UNUSED (ignored))3581 sock_getpeername(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3582 {
3583     sock_addr_t addrbuf;
3584     int res;
3585     socklen_t addrlen;
3586 
3587     if (!getsockaddrlen(s, &addrlen))
3588         return NULL;
3589     memset(&addrbuf, 0, addrlen);
3590     Py_BEGIN_ALLOW_THREADS
3591     res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
3592     Py_END_ALLOW_THREADS
3593     if (res < 0)
3594         return s->errorhandler();
3595     return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
3596                         s->sock_proto);
3597 }
3598 
3599 PyDoc_STRVAR(getpeername_doc,
3600 "getpeername() -> address info\n\
3601 \n\
3602 Return the address of the remote endpoint.  For IP sockets, the address\n\
3603 info is a pair (hostaddr, port).");
3604 
3605 #endif /* HAVE_GETPEERNAME */
3606 
3607 
3608 #ifdef HAVE_LISTEN
3609 /* s.listen(n) method */
3610 
3611 static PyObject *
sock_listen(PySocketSockObject * s,PyObject * args)3612 sock_listen(PySocketSockObject *s, PyObject *args)
3613 {
3614     /* We try to choose a default backlog high enough to avoid connection drops
3615      * for common workloads, yet not too high to limit resource usage. */
3616     int backlog = Py_MIN(SOMAXCONN, 128);
3617     int res;
3618 
3619     if (!PyArg_ParseTuple(args, "|i:listen", &backlog))
3620         return NULL;
3621 
3622     Py_BEGIN_ALLOW_THREADS
3623     /* To avoid problems on systems that don't allow a negative backlog
3624      * (which doesn't make sense anyway) we force a minimum value of 0. */
3625     if (backlog < 0)
3626         backlog = 0;
3627     res = listen(s->sock_fd, backlog);
3628     Py_END_ALLOW_THREADS
3629     if (res < 0)
3630         return s->errorhandler();
3631     Py_RETURN_NONE;
3632 }
3633 
3634 PyDoc_STRVAR(listen_doc,
3635 "listen([backlog])\n\
3636 \n\
3637 Enable a server to accept connections.  If backlog is specified, it must be\n\
3638 at least 0 (if it is lower, it is set to 0); it specifies the number of\n\
3639 unaccepted connections that the system will allow before refusing new\n\
3640 connections. If not specified, a default reasonable value is chosen.");
3641 #endif
3642 
3643 struct sock_recv {
3644     char *cbuf;
3645     Py_ssize_t len;
3646     int flags;
3647     Py_ssize_t result;
3648 };
3649 
3650 static int
sock_recv_impl(PySocketSockObject * s,void * data)3651 sock_recv_impl(PySocketSockObject *s, void *data)
3652 {
3653     struct sock_recv *ctx = data;
3654 
3655 #ifdef MS_WINDOWS
3656     if (ctx->len > INT_MAX)
3657         ctx->len = INT_MAX;
3658     ctx->result = recv(s->sock_fd, ctx->cbuf, (int)ctx->len, ctx->flags);
3659 #else
3660     ctx->result = recv(s->sock_fd, ctx->cbuf, ctx->len, ctx->flags);
3661 #endif
3662     return (ctx->result >= 0);
3663 }
3664 
3665 
3666 /*
3667  * This is the guts of the recv() and recv_into() methods, which reads into a
3668  * char buffer.  If you have any inc/dec ref to do to the objects that contain
3669  * the buffer, do it in the caller.  This function returns the number of bytes
3670  * successfully read.  If there was an error, it returns -1.  Note that it is
3671  * also possible that we return a number of bytes smaller than the request
3672  * bytes.
3673  */
3674 
3675 static Py_ssize_t
sock_recv_guts(PySocketSockObject * s,char * cbuf,Py_ssize_t len,int flags)3676 sock_recv_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags)
3677 {
3678     struct sock_recv ctx;
3679 
3680     if (!IS_SELECTABLE(s)) {
3681         select_error();
3682         return -1;
3683     }
3684     if (len == 0) {
3685         /* If 0 bytes were requested, do nothing. */
3686         return 0;
3687     }
3688 
3689     ctx.cbuf = cbuf;
3690     ctx.len = len;
3691     ctx.flags = flags;
3692     if (sock_call(s, 0, sock_recv_impl, &ctx) < 0)
3693         return -1;
3694 
3695     return ctx.result;
3696 }
3697 
3698 
3699 /* s.recv(nbytes [,flags]) method */
3700 
3701 static PyObject *
sock_recv(PySocketSockObject * s,PyObject * args)3702 sock_recv(PySocketSockObject *s, PyObject *args)
3703 {
3704     Py_ssize_t recvlen, outlen;
3705     int flags = 0;
3706     PyObject *buf;
3707 
3708     if (!PyArg_ParseTuple(args, "n|i:recv", &recvlen, &flags))
3709         return NULL;
3710 
3711     if (recvlen < 0) {
3712         PyErr_SetString(PyExc_ValueError,
3713                         "negative buffersize in recv");
3714         return NULL;
3715     }
3716 
3717     /* Allocate a new string. */
3718     buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
3719     if (buf == NULL)
3720         return NULL;
3721 
3722     /* Call the guts */
3723     outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags);
3724     if (outlen < 0) {
3725         /* An error occurred, release the string and return an
3726            error. */
3727         Py_DECREF(buf);
3728         return NULL;
3729     }
3730     if (outlen != recvlen) {
3731         /* We did not read as many bytes as we anticipated, resize the
3732            string if possible and be successful. */
3733         _PyBytes_Resize(&buf, outlen);
3734     }
3735 
3736     return buf;
3737 }
3738 
3739 PyDoc_STRVAR(recv_doc,
3740 "recv(buffersize[, flags]) -> data\n\
3741 \n\
3742 Receive up to buffersize bytes from the socket.  For the optional flags\n\
3743 argument, see the Unix manual.  When no data is available, block until\n\
3744 at least one byte is available or until the remote end is closed.  When\n\
3745 the remote end is closed and all data is read, return the empty string.");
3746 
3747 
3748 /* s.recv_into(buffer, [nbytes [,flags]]) method */
3749 
3750 static PyObject*
sock_recv_into(PySocketSockObject * s,PyObject * args,PyObject * kwds)3751 sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
3752 {
3753     static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
3754 
3755     int flags = 0;
3756     Py_buffer pbuf;
3757     char *buf;
3758     Py_ssize_t buflen, readlen, recvlen = 0;
3759 
3760     /* Get the buffer's memory */
3761     if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ni:recv_into", kwlist,
3762                                      &pbuf, &recvlen, &flags))
3763         return NULL;
3764     buf = pbuf.buf;
3765     buflen = pbuf.len;
3766 
3767     if (recvlen < 0) {
3768         PyBuffer_Release(&pbuf);
3769         PyErr_SetString(PyExc_ValueError,
3770                         "negative buffersize in recv_into");
3771         return NULL;
3772     }
3773     if (recvlen == 0) {
3774         /* If nbytes was not specified, use the buffer's length */
3775         recvlen = buflen;
3776     }
3777 
3778     /* Check if the buffer is large enough */
3779     if (buflen < recvlen) {
3780         PyBuffer_Release(&pbuf);
3781         PyErr_SetString(PyExc_ValueError,
3782                         "buffer too small for requested bytes");
3783         return NULL;
3784     }
3785 
3786     /* Call the guts */
3787     readlen = sock_recv_guts(s, buf, recvlen, flags);
3788     if (readlen < 0) {
3789         /* Return an error. */
3790         PyBuffer_Release(&pbuf);
3791         return NULL;
3792     }
3793 
3794     PyBuffer_Release(&pbuf);
3795     /* Return the number of bytes read.  Note that we do not do anything
3796        special here in the case that readlen < recvlen. */
3797     return PyLong_FromSsize_t(readlen);
3798 }
3799 
3800 PyDoc_STRVAR(recv_into_doc,
3801 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
3802 \n\
3803 A version of recv() that stores its data into a buffer rather than creating\n\
3804 a new string.  Receive up to buffersize bytes from the socket.  If buffersize\n\
3805 is not specified (or 0), receive up to the size available in the given buffer.\n\
3806 \n\
3807 See recv() for documentation about the flags.");
3808 
3809 struct sock_recvfrom {
3810     char* cbuf;
3811     Py_ssize_t len;
3812     int flags;
3813     socklen_t *addrlen;
3814     sock_addr_t *addrbuf;
3815     Py_ssize_t result;
3816 };
3817 
3818 #ifdef HAVE_RECVFROM
3819 static int
sock_recvfrom_impl(PySocketSockObject * s,void * data)3820 sock_recvfrom_impl(PySocketSockObject *s, void *data)
3821 {
3822     struct sock_recvfrom *ctx = data;
3823 
3824     memset(ctx->addrbuf, 0, *ctx->addrlen);
3825 
3826 #ifdef MS_WINDOWS
3827     if (ctx->len > INT_MAX)
3828         ctx->len = INT_MAX;
3829     ctx->result = recvfrom(s->sock_fd, ctx->cbuf, (int)ctx->len, ctx->flags,
3830                            SAS2SA(ctx->addrbuf), ctx->addrlen);
3831 #else
3832     ctx->result = recvfrom(s->sock_fd, ctx->cbuf, ctx->len, ctx->flags,
3833                            SAS2SA(ctx->addrbuf), ctx->addrlen);
3834 #endif
3835     return (ctx->result >= 0);
3836 }
3837 
3838 
3839 /*
3840  * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
3841  * into a char buffer.  If you have any inc/def ref to do to the objects that
3842  * contain the buffer, do it in the caller.  This function returns the number
3843  * of bytes successfully read.  If there was an error, it returns -1.  Note
3844  * that it is also possible that we return a number of bytes smaller than the
3845  * request bytes.
3846  *
3847  * 'addr' is a return value for the address object.  Note that you must decref
3848  * it yourself.
3849  */
3850 static Py_ssize_t
sock_recvfrom_guts(PySocketSockObject * s,char * cbuf,Py_ssize_t len,int flags,PyObject ** addr)3851 sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags,
3852                    PyObject** addr)
3853 {
3854     sock_addr_t addrbuf;
3855     socklen_t addrlen;
3856     struct sock_recvfrom ctx;
3857 
3858     *addr = NULL;
3859 
3860     if (!getsockaddrlen(s, &addrlen))
3861         return -1;
3862 
3863     if (!IS_SELECTABLE(s)) {
3864         select_error();
3865         return -1;
3866     }
3867 
3868     ctx.cbuf = cbuf;
3869     ctx.len = len;
3870     ctx.flags = flags;
3871     ctx.addrbuf = &addrbuf;
3872     ctx.addrlen = &addrlen;
3873     if (sock_call(s, 0, sock_recvfrom_impl, &ctx) < 0)
3874         return -1;
3875 
3876     *addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
3877                          s->sock_proto);
3878     if (*addr == NULL)
3879         return -1;
3880 
3881     return ctx.result;
3882 }
3883 
3884 /* s.recvfrom(nbytes [,flags]) method */
3885 
3886 static PyObject *
sock_recvfrom(PySocketSockObject * s,PyObject * args)3887 sock_recvfrom(PySocketSockObject *s, PyObject *args)
3888 {
3889     PyObject *buf = NULL;
3890     PyObject *addr = NULL;
3891     PyObject *ret = NULL;
3892     int flags = 0;
3893     Py_ssize_t recvlen, outlen;
3894 
3895     if (!PyArg_ParseTuple(args, "n|i:recvfrom", &recvlen, &flags))
3896         return NULL;
3897 
3898     if (recvlen < 0) {
3899         PyErr_SetString(PyExc_ValueError,
3900                         "negative buffersize in recvfrom");
3901         return NULL;
3902     }
3903 
3904     buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
3905     if (buf == NULL)
3906         return NULL;
3907 
3908     outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf),
3909                                 recvlen, flags, &addr);
3910     if (outlen < 0) {
3911         goto finally;
3912     }
3913 
3914     if (outlen != recvlen) {
3915         /* We did not read as many bytes as we anticipated, resize the
3916            string if possible and be successful. */
3917         if (_PyBytes_Resize(&buf, outlen) < 0)
3918             /* Oopsy, not so successful after all. */
3919             goto finally;
3920     }
3921 
3922     ret = PyTuple_Pack(2, buf, addr);
3923 
3924 finally:
3925     Py_XDECREF(buf);
3926     Py_XDECREF(addr);
3927     return ret;
3928 }
3929 
3930 PyDoc_STRVAR(recvfrom_doc,
3931 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
3932 \n\
3933 Like recv(buffersize, flags) but also return the sender's address info.");
3934 
3935 
3936 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
3937 
3938 static PyObject *
sock_recvfrom_into(PySocketSockObject * s,PyObject * args,PyObject * kwds)3939 sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
3940 {
3941     static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
3942 
3943     int flags = 0;
3944     Py_buffer pbuf;
3945     char *buf;
3946     Py_ssize_t readlen, buflen, recvlen = 0;
3947 
3948     PyObject *addr = NULL;
3949 
3950     if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ni:recvfrom_into",
3951                                      kwlist, &pbuf,
3952                                      &recvlen, &flags))
3953         return NULL;
3954     buf = pbuf.buf;
3955     buflen = pbuf.len;
3956 
3957     if (recvlen < 0) {
3958         PyBuffer_Release(&pbuf);
3959         PyErr_SetString(PyExc_ValueError,
3960                         "negative buffersize in recvfrom_into");
3961         return NULL;
3962     }
3963     if (recvlen == 0) {
3964         /* If nbytes was not specified, use the buffer's length */
3965         recvlen = buflen;
3966     } else if (recvlen > buflen) {
3967         PyBuffer_Release(&pbuf);
3968         PyErr_SetString(PyExc_ValueError,
3969                         "nbytes is greater than the length of the buffer");
3970         return NULL;
3971     }
3972 
3973     readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
3974     if (readlen < 0) {
3975         PyBuffer_Release(&pbuf);
3976         /* Return an error */
3977         Py_XDECREF(addr);
3978         return NULL;
3979     }
3980 
3981     PyBuffer_Release(&pbuf);
3982     /* Return the number of bytes read and the address.  Note that we do
3983        not do anything special here in the case that readlen < recvlen. */
3984     return Py_BuildValue("nN", readlen, addr);
3985 }
3986 
3987 PyDoc_STRVAR(recvfrom_into_doc,
3988 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
3989 \n\
3990 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
3991 #endif
3992 
3993 /* The sendmsg() and recvmsg[_into]() methods require a working
3994    CMSG_LEN().  See the comment near get_CMSG_LEN(). */
3995 #ifdef CMSG_LEN
3996 struct sock_recvmsg {
3997     struct msghdr *msg;
3998     int flags;
3999     ssize_t result;
4000 };
4001 
4002 static int
sock_recvmsg_impl(PySocketSockObject * s,void * data)4003 sock_recvmsg_impl(PySocketSockObject *s, void *data)
4004 {
4005     struct sock_recvmsg *ctx = data;
4006 
4007     ctx->result = recvmsg(s->sock_fd, ctx->msg, ctx->flags);
4008     return  (ctx->result >= 0);
4009 }
4010 
4011 /*
4012  * Call recvmsg() with the supplied iovec structures, flags, and
4013  * ancillary data buffer size (controllen).  Returns the tuple return
4014  * value for recvmsg() or recvmsg_into(), with the first item provided
4015  * by the supplied makeval() function.  makeval() will be called with
4016  * the length read and makeval_data as arguments, and must return a
4017  * new reference (which will be decrefed if there is a subsequent
4018  * error).  On error, closes any file descriptors received via
4019  * SCM_RIGHTS.
4020  */
4021 static PyObject *
sock_recvmsg_guts(PySocketSockObject * s,struct iovec * iov,int iovlen,int flags,Py_ssize_t controllen,PyObject * (* makeval)(ssize_t,void *),void * makeval_data)4022 sock_recvmsg_guts(PySocketSockObject *s, struct iovec *iov, int iovlen,
4023                   int flags, Py_ssize_t controllen,
4024                   PyObject *(*makeval)(ssize_t, void *), void *makeval_data)
4025 {
4026     sock_addr_t addrbuf;
4027     socklen_t addrbuflen;
4028     struct msghdr msg = {0};
4029     PyObject *cmsg_list = NULL, *retval = NULL;
4030     void *controlbuf = NULL;
4031     struct cmsghdr *cmsgh;
4032     size_t cmsgdatalen = 0;
4033     int cmsg_status;
4034     struct sock_recvmsg ctx;
4035 
4036     /* XXX: POSIX says that msg_name and msg_namelen "shall be
4037        ignored" when the socket is connected (Linux fills them in
4038        anyway for AF_UNIX sockets at least).  Normally msg_namelen
4039        seems to be set to 0 if there's no address, but try to
4040        initialize msg_name to something that won't be mistaken for a
4041        real address if that doesn't happen. */
4042     if (!getsockaddrlen(s, &addrbuflen))
4043         return NULL;
4044     memset(&addrbuf, 0, addrbuflen);
4045     SAS2SA(&addrbuf)->sa_family = AF_UNSPEC;
4046 
4047     if (controllen < 0 || controllen > SOCKLEN_T_LIMIT) {
4048         PyErr_SetString(PyExc_ValueError,
4049                         "invalid ancillary data buffer length");
4050         return NULL;
4051     }
4052     if (controllen > 0 && (controlbuf = PyMem_Malloc(controllen)) == NULL)
4053         return PyErr_NoMemory();
4054 
4055     /* Make the system call. */
4056     if (!IS_SELECTABLE(s)) {
4057         select_error();
4058         goto finally;
4059     }
4060 
4061     msg.msg_name = SAS2SA(&addrbuf);
4062     msg.msg_namelen = addrbuflen;
4063     msg.msg_iov = iov;
4064     msg.msg_iovlen = iovlen;
4065     msg.msg_control = controlbuf;
4066     msg.msg_controllen = controllen;
4067 
4068     ctx.msg = &msg;
4069     ctx.flags = flags;
4070     if (sock_call(s, 0, sock_recvmsg_impl, &ctx) < 0)
4071         goto finally;
4072 
4073     /* Make list of (level, type, data) tuples from control messages. */
4074     if ((cmsg_list = PyList_New(0)) == NULL)
4075         goto err_closefds;
4076     /* Check for empty ancillary data as old CMSG_FIRSTHDR()
4077        implementations didn't do so. */
4078     for (cmsgh = ((msg.msg_controllen > 0) ? CMSG_FIRSTHDR(&msg) : NULL);
4079          cmsgh != NULL; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
4080         PyObject *bytes, *tuple;
4081         int tmp;
4082 
4083         cmsg_status = get_cmsg_data_len(&msg, cmsgh, &cmsgdatalen);
4084         if (cmsg_status != 0) {
4085             if (PyErr_WarnEx(PyExc_RuntimeWarning,
4086                              "received malformed or improperly-truncated "
4087                              "ancillary data", 1) == -1)
4088                 goto err_closefds;
4089         }
4090         if (cmsg_status < 0)
4091             break;
4092         if (cmsgdatalen > PY_SSIZE_T_MAX) {
4093             PyErr_SetString(PyExc_OSError, "control message too long");
4094             goto err_closefds;
4095         }
4096 
4097         bytes = PyBytes_FromStringAndSize((char *)CMSG_DATA(cmsgh),
4098                                           cmsgdatalen);
4099         tuple = Py_BuildValue("iiN", (int)cmsgh->cmsg_level,
4100                               (int)cmsgh->cmsg_type, bytes);
4101         if (tuple == NULL)
4102             goto err_closefds;
4103         tmp = PyList_Append(cmsg_list, tuple);
4104         Py_DECREF(tuple);
4105         if (tmp != 0)
4106             goto err_closefds;
4107 
4108         if (cmsg_status != 0)
4109             break;
4110     }
4111 
4112     retval = Py_BuildValue("NOiN",
4113                            (*makeval)(ctx.result, makeval_data),
4114                            cmsg_list,
4115                            (int)msg.msg_flags,
4116                            makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
4117                                         ((msg.msg_namelen > addrbuflen) ?
4118                                          addrbuflen : msg.msg_namelen),
4119                                         s->sock_proto));
4120     if (retval == NULL)
4121         goto err_closefds;
4122 
4123 finally:
4124     Py_XDECREF(cmsg_list);
4125     PyMem_Free(controlbuf);
4126     return retval;
4127 
4128 err_closefds:
4129 #ifdef SCM_RIGHTS
4130     /* Close all descriptors coming from SCM_RIGHTS, so they don't leak. */
4131     for (cmsgh = ((msg.msg_controllen > 0) ? CMSG_FIRSTHDR(&msg) : NULL);
4132          cmsgh != NULL; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
4133         cmsg_status = get_cmsg_data_len(&msg, cmsgh, &cmsgdatalen);
4134         if (cmsg_status < 0)
4135             break;
4136         if (cmsgh->cmsg_level == SOL_SOCKET &&
4137             cmsgh->cmsg_type == SCM_RIGHTS) {
4138             size_t numfds;
4139             int *fdp;
4140 
4141             numfds = cmsgdatalen / sizeof(int);
4142             fdp = (int *)CMSG_DATA(cmsgh);
4143             while (numfds-- > 0)
4144                 close(*fdp++);
4145         }
4146         if (cmsg_status != 0)
4147             break;
4148     }
4149 #endif /* SCM_RIGHTS */
4150     goto finally;
4151 }
4152 
4153 
4154 static PyObject *
makeval_recvmsg(ssize_t received,void * data)4155 makeval_recvmsg(ssize_t received, void *data)
4156 {
4157     PyObject **buf = data;
4158 
4159     if (received < PyBytes_GET_SIZE(*buf))
4160         _PyBytes_Resize(buf, received);
4161     return Py_XNewRef(*buf);
4162 }
4163 
4164 /* s.recvmsg(bufsize[, ancbufsize[, flags]]) method */
4165 
4166 static PyObject *
sock_recvmsg(PySocketSockObject * s,PyObject * args)4167 sock_recvmsg(PySocketSockObject *s, PyObject *args)
4168 {
4169     Py_ssize_t bufsize, ancbufsize = 0;
4170     int flags = 0;
4171     struct iovec iov;
4172     PyObject *buf = NULL, *retval = NULL;
4173 
4174     if (!PyArg_ParseTuple(args, "n|ni:recvmsg", &bufsize, &ancbufsize, &flags))
4175         return NULL;
4176 
4177     if (bufsize < 0) {
4178         PyErr_SetString(PyExc_ValueError, "negative buffer size in recvmsg()");
4179         return NULL;
4180     }
4181     if ((buf = PyBytes_FromStringAndSize(NULL, bufsize)) == NULL)
4182         return NULL;
4183     iov.iov_base = PyBytes_AS_STRING(buf);
4184     iov.iov_len = bufsize;
4185 
4186     /* Note that we're passing a pointer to *our pointer* to the bytes
4187        object here (&buf); makeval_recvmsg() may incref the object, or
4188        deallocate it and set our pointer to NULL. */
4189     retval = sock_recvmsg_guts(s, &iov, 1, flags, ancbufsize,
4190                                &makeval_recvmsg, &buf);
4191     Py_XDECREF(buf);
4192     return retval;
4193 }
4194 
4195 PyDoc_STRVAR(recvmsg_doc,
4196 "recvmsg(bufsize[, ancbufsize[, flags]]) -> (data, ancdata, msg_flags, address)\n\
4197 \n\
4198 Receive normal data (up to bufsize bytes) and ancillary data from the\n\
4199 socket.  The ancbufsize argument sets the size in bytes of the\n\
4200 internal buffer used to receive the ancillary data; it defaults to 0,\n\
4201 meaning that no ancillary data will be received.  Appropriate buffer\n\
4202 sizes for ancillary data can be calculated using CMSG_SPACE() or\n\
4203 CMSG_LEN(), and items which do not fit into the buffer might be\n\
4204 truncated or discarded.  The flags argument defaults to 0 and has the\n\
4205 same meaning as for recv().\n\
4206 \n\
4207 The return value is a 4-tuple: (data, ancdata, msg_flags, address).\n\
4208 The data item is a bytes object holding the non-ancillary data\n\
4209 received.  The ancdata item is a list of zero or more tuples\n\
4210 (cmsg_level, cmsg_type, cmsg_data) representing the ancillary data\n\
4211 (control messages) received: cmsg_level and cmsg_type are integers\n\
4212 specifying the protocol level and protocol-specific type respectively,\n\
4213 and cmsg_data is a bytes object holding the associated data.  The\n\
4214 msg_flags item is the bitwise OR of various flags indicating\n\
4215 conditions on the received message; see your system documentation for\n\
4216 details.  If the receiving socket is unconnected, address is the\n\
4217 address of the sending socket, if available; otherwise, its value is\n\
4218 unspecified.\n\
4219 \n\
4220 If recvmsg() raises an exception after the system call returns, it\n\
4221 will first attempt to close any file descriptors received via the\n\
4222 SCM_RIGHTS mechanism.");
4223 
4224 
4225 static PyObject *
makeval_recvmsg_into(ssize_t received,void * data)4226 makeval_recvmsg_into(ssize_t received, void *data)
4227 {
4228     return PyLong_FromSsize_t(received);
4229 }
4230 
4231 /* s.recvmsg_into(buffers[, ancbufsize[, flags]]) method */
4232 
4233 static PyObject *
sock_recvmsg_into(PySocketSockObject * s,PyObject * args)4234 sock_recvmsg_into(PySocketSockObject *s, PyObject *args)
4235 {
4236     Py_ssize_t ancbufsize = 0;
4237     int flags = 0;
4238     struct iovec *iovs = NULL;
4239     Py_ssize_t i, nitems, nbufs = 0;
4240     Py_buffer *bufs = NULL;
4241     PyObject *buffers_arg, *fast, *retval = NULL;
4242 
4243     if (!PyArg_ParseTuple(args, "O|ni:recvmsg_into",
4244                           &buffers_arg, &ancbufsize, &flags))
4245         return NULL;
4246 
4247     if ((fast = PySequence_Fast(buffers_arg,
4248                                 "recvmsg_into() argument 1 must be an "
4249                                 "iterable")) == NULL)
4250         return NULL;
4251     nitems = PySequence_Fast_GET_SIZE(fast);
4252     if (nitems > INT_MAX) {
4253         PyErr_SetString(PyExc_OSError, "recvmsg_into() argument 1 is too long");
4254         goto finally;
4255     }
4256 
4257     /* Fill in an iovec for each item, and save the Py_buffer
4258        structs to release afterwards. */
4259     if (nitems > 0 && ((iovs = PyMem_New(struct iovec, nitems)) == NULL ||
4260                        (bufs = PyMem_New(Py_buffer, nitems)) == NULL)) {
4261         PyErr_NoMemory();
4262         goto finally;
4263     }
4264     for (; nbufs < nitems; nbufs++) {
4265         if (!PyArg_Parse(PySequence_Fast_GET_ITEM(fast, nbufs),
4266                          "w*;recvmsg_into() argument 1 must be an iterable "
4267                          "of single-segment read-write buffers",
4268                          &bufs[nbufs]))
4269             goto finally;
4270         iovs[nbufs].iov_base = bufs[nbufs].buf;
4271         iovs[nbufs].iov_len = bufs[nbufs].len;
4272     }
4273 
4274     retval = sock_recvmsg_guts(s, iovs, nitems, flags, ancbufsize,
4275                                &makeval_recvmsg_into, NULL);
4276 finally:
4277     for (i = 0; i < nbufs; i++)
4278         PyBuffer_Release(&bufs[i]);
4279     PyMem_Free(bufs);
4280     PyMem_Free(iovs);
4281     Py_DECREF(fast);
4282     return retval;
4283 }
4284 
4285 PyDoc_STRVAR(recvmsg_into_doc,
4286 "recvmsg_into(buffers[, ancbufsize[, flags]]) -> (nbytes, ancdata, msg_flags, address)\n\
4287 \n\
4288 Receive normal data and ancillary data from the socket, scattering the\n\
4289 non-ancillary data into a series of buffers.  The buffers argument\n\
4290 must be an iterable of objects that export writable buffers\n\
4291 (e.g. bytearray objects); these will be filled with successive chunks\n\
4292 of the non-ancillary data until it has all been written or there are\n\
4293 no more buffers.  The ancbufsize argument sets the size in bytes of\n\
4294 the internal buffer used to receive the ancillary data; it defaults to\n\
4295 0, meaning that no ancillary data will be received.  Appropriate\n\
4296 buffer sizes for ancillary data can be calculated using CMSG_SPACE()\n\
4297 or CMSG_LEN(), and items which do not fit into the buffer might be\n\
4298 truncated or discarded.  The flags argument defaults to 0 and has the\n\
4299 same meaning as for recv().\n\
4300 \n\
4301 The return value is a 4-tuple: (nbytes, ancdata, msg_flags, address).\n\
4302 The nbytes item is the total number of bytes of non-ancillary data\n\
4303 written into the buffers.  The ancdata item is a list of zero or more\n\
4304 tuples (cmsg_level, cmsg_type, cmsg_data) representing the ancillary\n\
4305 data (control messages) received: cmsg_level and cmsg_type are\n\
4306 integers specifying the protocol level and protocol-specific type\n\
4307 respectively, and cmsg_data is a bytes object holding the associated\n\
4308 data.  The msg_flags item is the bitwise OR of various flags\n\
4309 indicating conditions on the received message; see your system\n\
4310 documentation for details.  If the receiving socket is unconnected,\n\
4311 address is the address of the sending socket, if available; otherwise,\n\
4312 its value is unspecified.\n\
4313 \n\
4314 If recvmsg_into() raises an exception after the system call returns,\n\
4315 it will first attempt to close any file descriptors received via the\n\
4316 SCM_RIGHTS mechanism.");
4317 #endif    /* CMSG_LEN */
4318 
4319 
4320 struct sock_send {
4321     char *buf;
4322     Py_ssize_t len;
4323     int flags;
4324     Py_ssize_t result;
4325 };
4326 
4327 static int
sock_send_impl(PySocketSockObject * s,void * data)4328 sock_send_impl(PySocketSockObject *s, void *data)
4329 {
4330     struct sock_send *ctx = data;
4331 
4332 #ifdef MS_WINDOWS
4333     if (ctx->len > INT_MAX)
4334         ctx->len = INT_MAX;
4335     ctx->result = send(s->sock_fd, ctx->buf, (int)ctx->len, ctx->flags);
4336 #else
4337     ctx->result = send(s->sock_fd, ctx->buf, ctx->len, ctx->flags);
4338 #endif
4339     return (ctx->result >= 0);
4340 }
4341 
4342 /* s.send(data [,flags]) method */
4343 
4344 static PyObject *
sock_send(PySocketSockObject * s,PyObject * args)4345 sock_send(PySocketSockObject *s, PyObject *args)
4346 {
4347     int flags = 0;
4348     Py_buffer pbuf;
4349     struct sock_send ctx;
4350 
4351     if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags))
4352         return NULL;
4353 
4354     if (!IS_SELECTABLE(s)) {
4355         PyBuffer_Release(&pbuf);
4356         return select_error();
4357     }
4358     ctx.buf = pbuf.buf;
4359     ctx.len = pbuf.len;
4360     ctx.flags = flags;
4361     if (sock_call(s, 1, sock_send_impl, &ctx) < 0) {
4362         PyBuffer_Release(&pbuf);
4363         return NULL;
4364     }
4365     PyBuffer_Release(&pbuf);
4366 
4367     return PyLong_FromSsize_t(ctx.result);
4368 }
4369 
4370 PyDoc_STRVAR(send_doc,
4371 "send(data[, flags]) -> count\n\
4372 \n\
4373 Send a data string to the socket.  For the optional flags\n\
4374 argument, see the Unix manual.  Return the number of bytes\n\
4375 sent; this may be less than len(data) if the network is busy.");
4376 
4377 
4378 /* s.sendall(data [,flags]) method */
4379 
4380 static PyObject *
sock_sendall(PySocketSockObject * s,PyObject * args)4381 sock_sendall(PySocketSockObject *s, PyObject *args)
4382 {
4383     char *buf;
4384     Py_ssize_t len, n;
4385     int flags = 0;
4386     Py_buffer pbuf;
4387     struct sock_send ctx;
4388     int has_timeout = (s->sock_timeout > 0);
4389     PyTime_t timeout = s->sock_timeout;
4390     PyTime_t deadline = 0;
4391     int deadline_initialized = 0;
4392     PyObject *res = NULL;
4393 
4394     if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags))
4395         return NULL;
4396     buf = pbuf.buf;
4397     len = pbuf.len;
4398 
4399     if (!IS_SELECTABLE(s)) {
4400         PyBuffer_Release(&pbuf);
4401         return select_error();
4402     }
4403 
4404     do {
4405         if (has_timeout) {
4406             if (deadline_initialized) {
4407                 /* recompute the timeout */
4408                 timeout = _PyDeadline_Get(deadline);
4409             }
4410             else {
4411                 deadline_initialized = 1;
4412                 deadline = _PyDeadline_Init(timeout);
4413             }
4414 
4415             if (timeout <= 0) {
4416                 PyErr_SetString(PyExc_TimeoutError, "timed out");
4417                 goto done;
4418             }
4419         }
4420 
4421         ctx.buf = buf;
4422         ctx.len = len;
4423         ctx.flags = flags;
4424         if (sock_call_ex(s, 1, sock_send_impl, &ctx, 0, NULL, timeout) < 0)
4425             goto done;
4426         n = ctx.result;
4427         assert(n >= 0);
4428 
4429         buf += n;
4430         len -= n;
4431 
4432         /* We must run our signal handlers before looping again.
4433            send() can return a successful partial write when it is
4434            interrupted, so we can't restrict ourselves to EINTR. */
4435         if (PyErr_CheckSignals())
4436             goto done;
4437     } while (len > 0);
4438     PyBuffer_Release(&pbuf);
4439 
4440     res = Py_NewRef(Py_None);
4441 
4442 done:
4443     PyBuffer_Release(&pbuf);
4444     return res;
4445 }
4446 
4447 PyDoc_STRVAR(sendall_doc,
4448 "sendall(data[, flags])\n\
4449 \n\
4450 Send a data string to the socket.  For the optional flags\n\
4451 argument, see the Unix manual.  This calls send() repeatedly\n\
4452 until all data is sent.  If an error occurs, it's impossible\n\
4453 to tell how much data has been sent.");
4454 
4455 
4456 #ifdef HAVE_SENDTO
4457 struct sock_sendto {
4458     char *buf;
4459     Py_ssize_t len;
4460     int flags;
4461     int addrlen;
4462     sock_addr_t *addrbuf;
4463     Py_ssize_t result;
4464 };
4465 
4466 static int
sock_sendto_impl(PySocketSockObject * s,void * data)4467 sock_sendto_impl(PySocketSockObject *s, void *data)
4468 {
4469     struct sock_sendto *ctx = data;
4470 
4471 #ifdef MS_WINDOWS
4472     if (ctx->len > INT_MAX)
4473         ctx->len = INT_MAX;
4474     ctx->result = sendto(s->sock_fd, ctx->buf, (int)ctx->len, ctx->flags,
4475                          SAS2SA(ctx->addrbuf), ctx->addrlen);
4476 #else
4477     ctx->result = sendto(s->sock_fd, ctx->buf, ctx->len, ctx->flags,
4478                          SAS2SA(ctx->addrbuf), ctx->addrlen);
4479 #endif
4480     return (ctx->result >= 0);
4481 }
4482 
4483 /* s.sendto(data, [flags,] sockaddr) method */
4484 
4485 static PyObject *
sock_sendto(PySocketSockObject * s,PyObject * args)4486 sock_sendto(PySocketSockObject *s, PyObject *args)
4487 {
4488     Py_buffer pbuf;
4489     PyObject *addro;
4490     Py_ssize_t arglen;
4491     sock_addr_t addrbuf;
4492     int addrlen, flags;
4493     struct sock_sendto ctx;
4494 
4495     flags = 0;
4496     arglen = PyTuple_Size(args);
4497     switch (arglen) {
4498         case 2:
4499             if (!PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro)) {
4500                 return NULL;
4501             }
4502             break;
4503         case 3:
4504             if (!PyArg_ParseTuple(args, "y*iO:sendto",
4505                                   &pbuf, &flags, &addro)) {
4506                 return NULL;
4507             }
4508             break;
4509         default:
4510             PyErr_Format(PyExc_TypeError,
4511                          "sendto() takes 2 or 3 arguments (%zd given)",
4512                          arglen);
4513             return NULL;
4514     }
4515 
4516     if (!IS_SELECTABLE(s)) {
4517         PyBuffer_Release(&pbuf);
4518         return select_error();
4519     }
4520 
4521     if (!getsockaddrarg(s, addro, &addrbuf, &addrlen, "sendto")) {
4522         PyBuffer_Release(&pbuf);
4523         return NULL;
4524     }
4525 
4526     if (PySys_Audit("socket.sendto", "OO", s, addro) < 0) {
4527         return NULL;
4528     }
4529 
4530     ctx.buf = pbuf.buf;
4531     ctx.len = pbuf.len;
4532     ctx.flags = flags;
4533     ctx.addrlen = addrlen;
4534     ctx.addrbuf = &addrbuf;
4535     if (sock_call(s, 1, sock_sendto_impl, &ctx) < 0) {
4536         PyBuffer_Release(&pbuf);
4537         return NULL;
4538     }
4539     PyBuffer_Release(&pbuf);
4540 
4541     return PyLong_FromSsize_t(ctx.result);
4542 }
4543 
4544 PyDoc_STRVAR(sendto_doc,
4545 "sendto(data[, flags], address) -> count\n\
4546 \n\
4547 Like send(data, flags) but allows specifying the destination address.\n\
4548 For IP sockets, the address is a pair (hostaddr, port).");
4549 #endif
4550 
4551 
4552 /* The sendmsg() and recvmsg[_into]() methods require a working
4553    CMSG_LEN().  See the comment near get_CMSG_LEN(). */
4554 #ifdef CMSG_LEN
4555 struct sock_sendmsg {
4556     struct msghdr *msg;
4557     int flags;
4558     ssize_t result;
4559 };
4560 
4561 static int
sock_sendmsg_iovec(PySocketSockObject * s,PyObject * data_arg,struct msghdr * msg,Py_buffer ** databufsout,Py_ssize_t * ndatabufsout)4562 sock_sendmsg_iovec(PySocketSockObject *s, PyObject *data_arg,
4563                    struct msghdr *msg,
4564                    Py_buffer **databufsout, Py_ssize_t *ndatabufsout) {
4565     Py_ssize_t ndataparts, ndatabufs = 0;
4566     int result = -1;
4567     struct iovec *iovs = NULL;
4568     PyObject *data_fast = NULL;
4569     Py_buffer *databufs = NULL;
4570 
4571     /* Fill in an iovec for each message part, and save the Py_buffer
4572        structs to release afterwards. */
4573     data_fast = PySequence_Fast(data_arg,
4574                                 "sendmsg() argument 1 must be an "
4575                                 "iterable");
4576     if (data_fast == NULL) {
4577         goto finally;
4578     }
4579 
4580     ndataparts = PySequence_Fast_GET_SIZE(data_fast);
4581     if (ndataparts > INT_MAX) {
4582         PyErr_SetString(PyExc_OSError, "sendmsg() argument 1 is too long");
4583         goto finally;
4584     }
4585 
4586     msg->msg_iovlen = ndataparts;
4587     if (ndataparts > 0) {
4588         iovs = PyMem_New(struct iovec, ndataparts);
4589         if (iovs == NULL) {
4590             PyErr_NoMemory();
4591             goto finally;
4592         }
4593         msg->msg_iov = iovs;
4594 
4595         databufs = PyMem_New(Py_buffer, ndataparts);
4596         if (databufs == NULL) {
4597             PyErr_NoMemory();
4598             goto finally;
4599         }
4600     }
4601     for (; ndatabufs < ndataparts; ndatabufs++) {
4602         if (!PyArg_Parse(PySequence_Fast_GET_ITEM(data_fast, ndatabufs),
4603                          "y*;sendmsg() argument 1 must be an iterable of "
4604                          "bytes-like objects",
4605                          &databufs[ndatabufs]))
4606             goto finally;
4607         iovs[ndatabufs].iov_base = databufs[ndatabufs].buf;
4608         iovs[ndatabufs].iov_len = databufs[ndatabufs].len;
4609     }
4610     result = 0;
4611   finally:
4612     *databufsout = databufs;
4613     *ndatabufsout = ndatabufs;
4614     Py_XDECREF(data_fast);
4615     return result;
4616 }
4617 
4618 static int
sock_sendmsg_impl(PySocketSockObject * s,void * data)4619 sock_sendmsg_impl(PySocketSockObject *s, void *data)
4620 {
4621     struct sock_sendmsg *ctx = data;
4622 
4623     ctx->result = sendmsg(s->sock_fd, ctx->msg, ctx->flags);
4624     return (ctx->result >= 0);
4625 }
4626 
4627 /* s.sendmsg(buffers[, ancdata[, flags[, address]]]) method */
4628 
4629 static PyObject *
sock_sendmsg(PySocketSockObject * s,PyObject * args)4630 sock_sendmsg(PySocketSockObject *s, PyObject *args)
4631 {
4632     Py_ssize_t i, ndatabufs = 0, ncmsgs, ncmsgbufs = 0;
4633     Py_buffer *databufs = NULL;
4634     sock_addr_t addrbuf;
4635     struct msghdr msg;
4636     struct cmsginfo {
4637         int level;
4638         int type;
4639         Py_buffer data;
4640     } *cmsgs = NULL;
4641     void *controlbuf = NULL;
4642     size_t controllen, controllen_last;
4643     int addrlen, flags = 0;
4644     PyObject *data_arg, *cmsg_arg = NULL, *addr_arg = NULL,
4645         *cmsg_fast = NULL, *retval = NULL;
4646     struct sock_sendmsg ctx;
4647 
4648     if (!PyArg_ParseTuple(args, "O|OiO:sendmsg",
4649                           &data_arg, &cmsg_arg, &flags, &addr_arg)) {
4650         return NULL;
4651     }
4652 
4653     memset(&msg, 0, sizeof(msg));
4654 
4655     /* Parse destination address. */
4656     if (addr_arg != NULL && addr_arg != Py_None) {
4657         if (!getsockaddrarg(s, addr_arg, &addrbuf, &addrlen,
4658                             "sendmsg"))
4659         {
4660             goto finally;
4661         }
4662         if (PySys_Audit("socket.sendmsg", "OO", s, addr_arg) < 0) {
4663             return NULL;
4664         }
4665         msg.msg_name = &addrbuf;
4666         msg.msg_namelen = addrlen;
4667     } else {
4668         if (PySys_Audit("socket.sendmsg", "OO", s, Py_None) < 0) {
4669             return NULL;
4670         }
4671     }
4672 
4673     /* Fill in an iovec for each message part, and save the Py_buffer
4674        structs to release afterwards. */
4675     if (sock_sendmsg_iovec(s, data_arg, &msg, &databufs, &ndatabufs) == -1) {
4676         goto finally;
4677     }
4678 
4679     if (cmsg_arg == NULL)
4680         ncmsgs = 0;
4681     else {
4682         if ((cmsg_fast = PySequence_Fast(cmsg_arg,
4683                                          "sendmsg() argument 2 must be an "
4684                                          "iterable")) == NULL)
4685             goto finally;
4686         ncmsgs = PySequence_Fast_GET_SIZE(cmsg_fast);
4687     }
4688 
4689 #ifndef CMSG_SPACE
4690     if (ncmsgs > 1) {
4691         PyErr_SetString(PyExc_OSError,
4692                         "sending multiple control messages is not supported "
4693                         "on this system");
4694         goto finally;
4695     }
4696 #endif
4697     /* Save level, type and Py_buffer for each control message,
4698        and calculate total size. */
4699     if (ncmsgs > 0 && (cmsgs = PyMem_New(struct cmsginfo, ncmsgs)) == NULL) {
4700         PyErr_NoMemory();
4701         goto finally;
4702     }
4703     controllen = controllen_last = 0;
4704     while (ncmsgbufs < ncmsgs) {
4705         size_t bufsize, space;
4706 
4707         if (!PyArg_Parse(PySequence_Fast_GET_ITEM(cmsg_fast, ncmsgbufs),
4708                          "(iiy*):[sendmsg() ancillary data items]",
4709                          &cmsgs[ncmsgbufs].level,
4710                          &cmsgs[ncmsgbufs].type,
4711                          &cmsgs[ncmsgbufs].data))
4712             goto finally;
4713         bufsize = cmsgs[ncmsgbufs++].data.len;
4714 
4715 #ifdef CMSG_SPACE
4716         if (!get_CMSG_SPACE(bufsize, &space)) {
4717 #else
4718         if (!get_CMSG_LEN(bufsize, &space)) {
4719 #endif
4720             PyErr_SetString(PyExc_OSError, "ancillary data item too large");
4721             goto finally;
4722         }
4723         controllen += space;
4724         if (controllen > SOCKLEN_T_LIMIT || controllen < controllen_last) {
4725             PyErr_SetString(PyExc_OSError, "too much ancillary data");
4726             goto finally;
4727         }
4728         controllen_last = controllen;
4729     }
4730 
4731     /* Construct ancillary data block from control message info. */
4732     if (ncmsgbufs > 0) {
4733         struct cmsghdr *cmsgh = NULL;
4734 
4735         controlbuf = PyMem_Malloc(controllen);
4736         if (controlbuf == NULL) {
4737             PyErr_NoMemory();
4738             goto finally;
4739         }
4740         msg.msg_control = controlbuf;
4741 
4742         msg.msg_controllen = controllen;
4743 
4744         /* Need to zero out the buffer as a workaround for glibc's
4745            CMSG_NXTHDR() implementation.  After getting the pointer to
4746            the next header, it checks its (uninitialized) cmsg_len
4747            member to see if the "message" fits in the buffer, and
4748            returns NULL if it doesn't.  Zero-filling the buffer
4749            ensures that this doesn't happen. */
4750         memset(controlbuf, 0, controllen);
4751 
4752         for (i = 0; i < ncmsgbufs; i++) {
4753             size_t msg_len, data_len = cmsgs[i].data.len;
4754             int enough_space = 0;
4755 
4756             cmsgh = (i == 0) ? CMSG_FIRSTHDR(&msg) : CMSG_NXTHDR(&msg, cmsgh);
4757             if (cmsgh == NULL) {
4758                 PyErr_Format(PyExc_RuntimeError,
4759                              "unexpected NULL result from %s()",
4760                              (i == 0) ? "CMSG_FIRSTHDR" : "CMSG_NXTHDR");
4761                 goto finally;
4762             }
4763             if (!get_CMSG_LEN(data_len, &msg_len)) {
4764                 PyErr_SetString(PyExc_RuntimeError,
4765                                 "item size out of range for CMSG_LEN()");
4766                 goto finally;
4767             }
4768             if (cmsg_min_space(&msg, cmsgh, msg_len)) {
4769                 size_t space;
4770 
4771                 cmsgh->cmsg_len = msg_len;
4772                 if (get_cmsg_data_space(&msg, cmsgh, &space))
4773                     enough_space = (space >= data_len);
4774             }
4775             if (!enough_space) {
4776                 PyErr_SetString(PyExc_RuntimeError,
4777                                 "ancillary data does not fit in calculated "
4778                                 "space");
4779                 goto finally;
4780             }
4781             cmsgh->cmsg_level = cmsgs[i].level;
4782             cmsgh->cmsg_type = cmsgs[i].type;
4783             memcpy(CMSG_DATA(cmsgh), cmsgs[i].data.buf, data_len);
4784         }
4785     }
4786 
4787     /* Make the system call. */
4788     if (!IS_SELECTABLE(s)) {
4789         select_error();
4790         goto finally;
4791     }
4792 
4793     ctx.msg = &msg;
4794     ctx.flags = flags;
4795     if (sock_call(s, 1, sock_sendmsg_impl, &ctx) < 0)
4796         goto finally;
4797 
4798     retval = PyLong_FromSsize_t(ctx.result);
4799 
4800 finally:
4801     PyMem_Free(controlbuf);
4802     for (i = 0; i < ncmsgbufs; i++)
4803         PyBuffer_Release(&cmsgs[i].data);
4804     PyMem_Free(cmsgs);
4805     Py_XDECREF(cmsg_fast);
4806     PyMem_Free(msg.msg_iov);
4807     for (i = 0; i < ndatabufs; i++) {
4808         PyBuffer_Release(&databufs[i]);
4809     }
4810     PyMem_Free(databufs);
4811     return retval;
4812 }
4813 
4814 PyDoc_STRVAR(sendmsg_doc,
4815 "sendmsg(buffers[, ancdata[, flags[, address]]]) -> count\n\
4816 \n\
4817 Send normal and ancillary data to the socket, gathering the\n\
4818 non-ancillary data from a series of buffers and concatenating it into\n\
4819 a single message.  The buffers argument specifies the non-ancillary\n\
4820 data as an iterable of bytes-like objects (e.g. bytes objects).\n\
4821 The ancdata argument specifies the ancillary data (control messages)\n\
4822 as an iterable of zero or more tuples (cmsg_level, cmsg_type,\n\
4823 cmsg_data), where cmsg_level and cmsg_type are integers specifying the\n\
4824 protocol level and protocol-specific type respectively, and cmsg_data\n\
4825 is a bytes-like object holding the associated data.  The flags\n\
4826 argument defaults to 0 and has the same meaning as for send().  If\n\
4827 address is supplied and not None, it sets a destination address for\n\
4828 the message.  The return value is the number of bytes of non-ancillary\n\
4829 data sent.");
4830 #endif    /* CMSG_LEN */
4831 
4832 #ifdef HAVE_SOCKADDR_ALG
4833 static PyObject*
4834 sock_sendmsg_afalg(PySocketSockObject *self, PyObject *args, PyObject *kwds)
4835 {
4836     PyObject *retval = NULL;
4837 
4838     Py_ssize_t i, ndatabufs = 0;
4839     Py_buffer *databufs = NULL;
4840     PyObject *data_arg = NULL;
4841 
4842     Py_buffer iv = {NULL, NULL};
4843 
4844     PyObject *opobj = NULL;
4845     int op = -1;
4846 
4847     PyObject *assoclenobj = NULL;
4848     int assoclen = -1;
4849 
4850     unsigned int *uiptr;
4851     int flags = 0;
4852 
4853     struct msghdr msg;
4854     struct cmsghdr *header = NULL;
4855     struct af_alg_iv *alg_iv = NULL;
4856     struct sock_sendmsg ctx;
4857     Py_ssize_t controllen;
4858     void *controlbuf = NULL;
4859     static char *keywords[] = {"msg", "op", "iv", "assoclen", "flags", 0};
4860 
4861     if (self->sock_family != AF_ALG) {
4862         PyErr_SetString(PyExc_OSError,
4863                         "algset is only supported for AF_ALG");
4864         return NULL;
4865     }
4866 
4867     if (!PyArg_ParseTupleAndKeywords(args, kwds,
4868                                      "|O$O!y*O!i:sendmsg_afalg", keywords,
4869                                      &data_arg,
4870                                      &PyLong_Type, &opobj, &iv,
4871                                      &PyLong_Type, &assoclenobj, &flags)) {
4872         return NULL;
4873     }
4874 
4875     memset(&msg, 0, sizeof(msg));
4876 
4877     /* op is a required, keyword-only argument >= 0 */
4878     if (opobj != NULL) {
4879         op = PyLong_AsInt(opobj);
4880     }
4881     if (op < 0) {
4882         /* override exception from PyLong_AsInt() */
4883         PyErr_SetString(PyExc_TypeError,
4884                         "Invalid or missing argument 'op'");
4885         goto finally;
4886     }
4887     /* assoclen is optional but must be >= 0 */
4888     if (assoclenobj != NULL) {
4889         assoclen = PyLong_AsInt(assoclenobj);
4890         if (assoclen == -1 && PyErr_Occurred()) {
4891             goto finally;
4892         }
4893         if (assoclen < 0) {
4894             PyErr_SetString(PyExc_TypeError,
4895                             "assoclen must be positive");
4896             goto finally;
4897         }
4898     }
4899 
4900     controllen = CMSG_SPACE(4);
4901     if (iv.buf != NULL) {
4902         controllen += CMSG_SPACE(sizeof(*alg_iv) + iv.len);
4903     }
4904     if (assoclen >= 0) {
4905         controllen += CMSG_SPACE(4);
4906     }
4907 
4908     controlbuf = PyMem_Malloc(controllen);
4909     if (controlbuf == NULL) {
4910         PyErr_NoMemory();
4911         goto finally;
4912     }
4913     memset(controlbuf, 0, controllen);
4914 
4915     msg.msg_controllen = controllen;
4916     msg.msg_control = controlbuf;
4917 
4918     /* Fill in an iovec for each message part, and save the Py_buffer
4919        structs to release afterwards. */
4920     if (data_arg != NULL) {
4921         if (sock_sendmsg_iovec(self, data_arg, &msg, &databufs, &ndatabufs) == -1) {
4922             goto finally;
4923         }
4924     }
4925 
4926     /* set operation to encrypt or decrypt */
4927     header = CMSG_FIRSTHDR(&msg);
4928     if (header == NULL) {
4929         PyErr_SetString(PyExc_RuntimeError,
4930                         "unexpected NULL result from CMSG_FIRSTHDR");
4931         goto finally;
4932     }
4933     header->cmsg_level = SOL_ALG;
4934     header->cmsg_type = ALG_SET_OP;
4935     header->cmsg_len = CMSG_LEN(4);
4936     uiptr = (void*)CMSG_DATA(header);
4937     *uiptr = (unsigned int)op;
4938 
4939     /* set initialization vector */
4940     if (iv.buf != NULL) {
4941         header = CMSG_NXTHDR(&msg, header);
4942         if (header == NULL) {
4943             PyErr_SetString(PyExc_RuntimeError,
4944                             "unexpected NULL result from CMSG_NXTHDR(iv)");
4945             goto finally;
4946         }
4947         header->cmsg_level = SOL_ALG;
4948         header->cmsg_type = ALG_SET_IV;
4949         header->cmsg_len = CMSG_SPACE(sizeof(*alg_iv) + iv.len);
4950         alg_iv = (void*)CMSG_DATA(header);
4951         alg_iv->ivlen = iv.len;
4952         memcpy(alg_iv->iv, iv.buf, iv.len);
4953     }
4954 
4955     /* set length of associated data for AEAD */
4956     if (assoclen >= 0) {
4957         header = CMSG_NXTHDR(&msg, header);
4958         if (header == NULL) {
4959             PyErr_SetString(PyExc_RuntimeError,
4960                             "unexpected NULL result from CMSG_NXTHDR(assoc)");
4961             goto finally;
4962         }
4963         header->cmsg_level = SOL_ALG;
4964         header->cmsg_type = ALG_SET_AEAD_ASSOCLEN;
4965         header->cmsg_len = CMSG_LEN(4);
4966         uiptr = (void*)CMSG_DATA(header);
4967         *uiptr = (unsigned int)assoclen;
4968     }
4969 
4970     ctx.msg = &msg;
4971     ctx.flags = flags;
4972     if (sock_call(self, 1, sock_sendmsg_impl, &ctx) < 0) {
4973         goto finally;
4974     }
4975 
4976     retval = PyLong_FromSsize_t(ctx.result);
4977 
4978   finally:
4979     PyMem_Free(controlbuf);
4980     if (iv.buf != NULL) {
4981         PyBuffer_Release(&iv);
4982     }
4983     PyMem_Free(msg.msg_iov);
4984     for (i = 0; i < ndatabufs; i++) {
4985         PyBuffer_Release(&databufs[i]);
4986     }
4987     PyMem_Free(databufs);
4988     return retval;
4989 }
4990 
4991 PyDoc_STRVAR(sendmsg_afalg_doc,
4992 "sendmsg_afalg([msg], *, op[, iv[, assoclen[, flags=MSG_MORE]]])\n\
4993 \n\
4994 Set operation mode, IV and length of associated data for an AF_ALG\n\
4995 operation socket.");
4996 #endif
4997 
4998 #ifdef HAVE_SHUTDOWN
4999 /* s.shutdown(how) method */
5000 
5001 static PyObject *
5002 sock_shutdown(PySocketSockObject *s, PyObject *arg)
5003 {
5004     int how;
5005     int res;
5006 
5007     how = PyLong_AsInt(arg);
5008     if (how == -1 && PyErr_Occurred())
5009         return NULL;
5010     Py_BEGIN_ALLOW_THREADS
5011     res = shutdown(s->sock_fd, how);
5012     Py_END_ALLOW_THREADS
5013     if (res < 0)
5014         return s->errorhandler();
5015     Py_RETURN_NONE;
5016 }
5017 
5018 PyDoc_STRVAR(shutdown_doc,
5019 "shutdown(flag)\n\
5020 \n\
5021 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
5022 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
5023 #endif
5024 
5025 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
5026 static PyObject*
5027 sock_ioctl(PySocketSockObject *s, PyObject *arg)
5028 {
5029     unsigned long cmd = SIO_RCVALL;
5030     PyObject *argO;
5031     DWORD recv;
5032 
5033     if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
5034         return NULL;
5035 
5036     switch (cmd) {
5037     case SIO_RCVALL: {
5038         unsigned int option = RCVALL_ON;
5039         if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
5040             return NULL;
5041         if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
5042                          NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
5043             return set_error();
5044         }
5045         return PyLong_FromUnsignedLong(recv); }
5046     case SIO_KEEPALIVE_VALS: {
5047         struct tcp_keepalive ka;
5048         if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
5049                         &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
5050             return NULL;
5051         if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
5052                          NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
5053             return set_error();
5054         }
5055         return PyLong_FromUnsignedLong(recv); }
5056 #if defined(SIO_LOOPBACK_FAST_PATH)
5057     case SIO_LOOPBACK_FAST_PATH: {
5058         unsigned int option;
5059         if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
5060             return NULL;
5061         if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
5062                          NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
5063             return set_error();
5064         }
5065         return PyLong_FromUnsignedLong(recv); }
5066 #endif
5067     default:
5068         PyErr_Format(PyExc_ValueError, "invalid ioctl command %lu", cmd);
5069         return NULL;
5070     }
5071 }
5072 PyDoc_STRVAR(sock_ioctl_doc,
5073 "ioctl(cmd, option) -> long\n\
5074 \n\
5075 Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
5076 SIO_RCVALL:  'option' must be one of the socket.RCVALL_* constants.\n\
5077 SIO_KEEPALIVE_VALS:  'option' is a tuple of (onoff, timeout, interval).\n\
5078 SIO_LOOPBACK_FAST_PATH: 'option' is a boolean value, and is disabled by default");
5079 #endif
5080 
5081 #if defined(MS_WINDOWS)
5082 static PyObject*
5083 sock_share(PySocketSockObject *s, PyObject *arg)
5084 {
5085     WSAPROTOCOL_INFOW info;
5086     DWORD processId;
5087     int result;
5088 
5089     if (!PyArg_ParseTuple(arg, "I", &processId))
5090         return NULL;
5091 
5092     Py_BEGIN_ALLOW_THREADS
5093     result = WSADuplicateSocketW(s->sock_fd, processId, &info);
5094     Py_END_ALLOW_THREADS
5095     if (result == SOCKET_ERROR)
5096         return set_error();
5097     return PyBytes_FromStringAndSize((const char*)&info, sizeof(info));
5098 }
5099 PyDoc_STRVAR(sock_share_doc,
5100 "share(process_id) -> bytes\n\
5101 \n\
5102 Share the socket with another process.  The target process id\n\
5103 must be provided and the resulting bytes object passed to the target\n\
5104 process.  There the shared socket can be instantiated by calling\n\
5105 socket.fromshare().");
5106 
5107 
5108 #endif
5109 
5110 /* List of methods for socket objects */
5111 
5112 static PyMethodDef sock_methods[] = {
5113 #if defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
5114     {"_accept",           (PyCFunction)sock_accept, METH_NOARGS,
5115                       accept_doc},
5116 #endif
5117 #ifdef HAVE_BIND
5118     {"bind",              (PyCFunction)sock_bind, METH_O,
5119                       bind_doc},
5120 #endif
5121     {"close",             (PyCFunction)sock_close, METH_NOARGS,
5122                       sock_close_doc},
5123 #ifdef HAVE_CONNECT
5124     {"connect",           (PyCFunction)sock_connect, METH_O,
5125                       connect_doc},
5126     {"connect_ex",        (PyCFunction)sock_connect_ex, METH_O,
5127                       connect_ex_doc},
5128 #endif
5129     {"detach",            (PyCFunction)sock_detach, METH_NOARGS,
5130                       detach_doc},
5131     {"fileno",            (PyCFunction)sock_fileno, METH_NOARGS,
5132                       fileno_doc},
5133 #ifdef HAVE_GETPEERNAME
5134     {"getpeername",       (PyCFunction)sock_getpeername,
5135                       METH_NOARGS, getpeername_doc},
5136 #endif
5137 #ifdef HAVE_GETSOCKNAME
5138     {"getsockname",       (PyCFunction)sock_getsockname,
5139                       METH_NOARGS, getsockname_doc},
5140 #endif
5141     {"getsockopt",        (PyCFunction)sock_getsockopt, METH_VARARGS,
5142                       getsockopt_doc},
5143 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
5144     {"ioctl",             (PyCFunction)sock_ioctl, METH_VARARGS,
5145                       sock_ioctl_doc},
5146 #endif
5147 #if defined(MS_WINDOWS)
5148     {"share",         (PyCFunction)sock_share, METH_VARARGS,
5149                       sock_share_doc},
5150 #endif
5151 #ifdef HAVE_LISTEN
5152     {"listen",            (PyCFunction)sock_listen, METH_VARARGS,
5153                       listen_doc},
5154 #endif
5155     {"recv",              (PyCFunction)sock_recv, METH_VARARGS,
5156                       recv_doc},
5157     {"recv_into",         _PyCFunction_CAST(sock_recv_into), METH_VARARGS | METH_KEYWORDS,
5158                       recv_into_doc},
5159 #ifdef HAVE_RECVFROM
5160     {"recvfrom",          (PyCFunction)sock_recvfrom, METH_VARARGS,
5161                       recvfrom_doc},
5162     {"recvfrom_into",  _PyCFunction_CAST(sock_recvfrom_into), METH_VARARGS | METH_KEYWORDS,
5163                       recvfrom_into_doc},
5164 #endif
5165     {"send",              (PyCFunction)sock_send, METH_VARARGS,
5166                       send_doc},
5167     {"sendall",           (PyCFunction)sock_sendall, METH_VARARGS,
5168                       sendall_doc},
5169 #ifdef HAVE_SENDTO
5170     {"sendto",            (PyCFunction)sock_sendto, METH_VARARGS,
5171                       sendto_doc},
5172 #endif
5173     {"setblocking",       (PyCFunction)sock_setblocking, METH_O,
5174                       setblocking_doc},
5175     {"getblocking",   (PyCFunction)sock_getblocking, METH_NOARGS,
5176                       getblocking_doc},
5177     {"settimeout",    (PyCFunction)sock_settimeout, METH_O,
5178                       settimeout_doc},
5179     {"gettimeout",    (PyCFunction)sock_gettimeout, METH_NOARGS,
5180                       gettimeout_doc},
5181 #ifdef HAVE_SETSOCKOPT
5182     {"setsockopt",        (PyCFunction)sock_setsockopt, METH_VARARGS,
5183                       setsockopt_doc},
5184 #endif
5185 #ifdef HAVE_SHUTDOWN
5186     {"shutdown",          (PyCFunction)sock_shutdown, METH_O,
5187                       shutdown_doc},
5188 #endif
5189 #ifdef CMSG_LEN
5190     {"recvmsg",           (PyCFunction)sock_recvmsg, METH_VARARGS,
5191                       recvmsg_doc},
5192     {"recvmsg_into",      (PyCFunction)sock_recvmsg_into, METH_VARARGS,
5193                       recvmsg_into_doc,},
5194     {"sendmsg",           (PyCFunction)sock_sendmsg, METH_VARARGS,
5195                       sendmsg_doc},
5196 #endif
5197 #ifdef HAVE_SOCKADDR_ALG
5198     {"sendmsg_afalg",     _PyCFunction_CAST(sock_sendmsg_afalg), METH_VARARGS | METH_KEYWORDS,
5199                       sendmsg_afalg_doc},
5200 #endif
5201     {NULL,                      NULL}           /* sentinel */
5202 };
5203 
5204 /* SockObject members */
5205 static PyMemberDef sock_memberlist[] = {
5206        {"family", Py_T_INT, offsetof(PySocketSockObject, sock_family), Py_READONLY, "the socket family"},
5207        {"type", Py_T_INT, offsetof(PySocketSockObject, sock_type), Py_READONLY, "the socket type"},
5208        {"proto", Py_T_INT, offsetof(PySocketSockObject, sock_proto), Py_READONLY, "the socket protocol"},
5209        {0},
5210 };
5211 
5212 static PyGetSetDef sock_getsetlist[] = {
5213     {"timeout", (getter)sock_gettimeout, NULL, PyDoc_STR("the socket timeout")},
5214     {NULL} /* sentinel */
5215 };
5216 
5217 /* Deallocate a socket object in response to the last Py_DECREF().
5218    First close the file description. */
5219 
5220 static void
5221 sock_finalize(PySocketSockObject *s)
5222 {
5223     SOCKET_T fd;
5224 
5225     /* Save the current exception, if any. */
5226     PyObject *exc = PyErr_GetRaisedException();
5227 
5228     if (s->sock_fd != INVALID_SOCKET) {
5229         if (PyErr_ResourceWarning((PyObject *)s, 1, "unclosed %R", s)) {
5230             /* Spurious errors can appear at shutdown */
5231             if (PyErr_ExceptionMatches(PyExc_Warning)) {
5232                 PyErr_WriteUnraisable((PyObject *)s);
5233             }
5234         }
5235 
5236         /* Only close the socket *after* logging the ResourceWarning warning
5237            to allow the logger to call socket methods like
5238            socket.getsockname(). If the socket is closed before, socket
5239            methods fails with the EBADF error. */
5240         fd = s->sock_fd;
5241         s->sock_fd = INVALID_SOCKET;
5242 
5243         /* We do not want to retry upon EINTR: see sock_close() */
5244         Py_BEGIN_ALLOW_THREADS
5245         (void) SOCKETCLOSE(fd);
5246         Py_END_ALLOW_THREADS
5247     }
5248 
5249     /* Restore the saved exception. */
5250     PyErr_SetRaisedException(exc);
5251 }
5252 
5253 static int
5254 sock_traverse(PySocketSockObject *s, visitproc visit, void *arg)
5255 {
5256     Py_VISIT(Py_TYPE(s));
5257     return 0;
5258 }
5259 
5260 static void
5261 sock_dealloc(PySocketSockObject *s)
5262 {
5263     if (PyObject_CallFinalizerFromDealloc((PyObject *)s) < 0) {
5264         return;
5265     }
5266     PyTypeObject *tp = Py_TYPE(s);
5267     PyObject_GC_UnTrack(s);
5268     tp->tp_free((PyObject *)s);
5269     Py_DECREF(tp);
5270 }
5271 
5272 
5273 static PyObject *
5274 sock_repr(PySocketSockObject *s)
5275 {
5276     long sock_fd;
5277     /* On Windows, this test is needed because SOCKET_T is unsigned */
5278     if (s->sock_fd == INVALID_SOCKET) {
5279         sock_fd = -1;
5280     }
5281 #if SIZEOF_SOCKET_T > SIZEOF_LONG
5282     else if (s->sock_fd > LONG_MAX) {
5283         /* this can occur on Win64, and actually there is a special
5284            ugly printf formatter for decimal pointer length integer
5285            printing, only bother if necessary*/
5286         PyErr_SetString(PyExc_OverflowError,
5287                         "no printf formatter to display "
5288                         "the socket descriptor in decimal");
5289         return NULL;
5290     }
5291 #endif
5292     else
5293         sock_fd = (long)s->sock_fd;
5294     return PyUnicode_FromFormat(
5295         "<socket object, fd=%ld, family=%d, type=%d, proto=%d>",
5296         sock_fd, s->sock_family,
5297         s->sock_type,
5298         s->sock_proto);
5299 }
5300 
5301 
5302 /* Create a new, uninitialized socket object. */
5303 
5304 static PyObject *
5305 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5306 {
5307     PyObject *new;
5308 
5309     new = type->tp_alloc(type, 0);
5310     if (new != NULL) {
5311         ((PySocketSockObject *)new)->sock_fd = INVALID_SOCKET;
5312         ((PySocketSockObject *)new)->sock_timeout = _PyTime_FromSeconds(-1);
5313         ((PySocketSockObject *)new)->errorhandler = &set_error;
5314     }
5315     return new;
5316 }
5317 
5318 
5319 /* Initialize a new socket object. */
5320 
5321 /*ARGSUSED*/
5322 
5323 #ifndef HAVE_SOCKET
5324 #define socket stub_socket
5325 static int
5326 socket(int domain, int type, int protocol)
5327 {
5328     errno = ENOTSUP;
5329     return INVALID_SOCKET;
5330 }
5331 #endif
5332 
5333 /*[clinic input]
5334 _socket.socket.__init__ as sock_initobj
5335     family: int = -1
5336     type: int = -1
5337     proto: int = -1
5338     fileno as fdobj: object = NULL
5339 [clinic start generated code]*/
5340 
5341 static int
5342 sock_initobj_impl(PySocketSockObject *self, int family, int type, int proto,
5343                   PyObject *fdobj)
5344 /*[clinic end generated code: output=d114d026b9a9a810 input=04cfc32953f5cc25]*/
5345 {
5346 
5347     SOCKET_T fd = INVALID_SOCKET;
5348     socket_state *state = find_module_state_by_def(Py_TYPE(self));
5349 
5350 #ifndef MS_WINDOWS
5351 #ifdef SOCK_CLOEXEC
5352     int *atomic_flag_works = &state->sock_cloexec_works;
5353 #else
5354     int *atomic_flag_works = NULL;
5355 #endif
5356 #endif
5357 
5358 #ifdef MS_WINDOWS
5359     /* In this case, we don't use the family, type and proto args */
5360     if (fdobj == NULL || fdobj == Py_None)
5361 #endif
5362     {
5363         if (PySys_Audit("socket.__new__", "Oiii",
5364                         self, family, type, proto) < 0) {
5365             return -1;
5366         }
5367     }
5368 
5369     if (fdobj != NULL && fdobj != Py_None) {
5370 #ifdef MS_WINDOWS
5371         /* recreate a socket that was duplicated */
5372         if (PyBytes_Check(fdobj)) {
5373             WSAPROTOCOL_INFOW info;
5374             if (PyBytes_GET_SIZE(fdobj) != sizeof(info)) {
5375                 PyErr_Format(PyExc_ValueError,
5376                     "socket descriptor string has wrong size, "
5377                     "should be %zu bytes.", sizeof(info));
5378                 return -1;
5379             }
5380             memcpy(&info, PyBytes_AS_STRING(fdobj), sizeof(info));
5381 
5382             if (PySys_Audit("socket.__new__", "Oiii", self,
5383                             info.iAddressFamily, info.iSocketType,
5384                             info.iProtocol) < 0) {
5385                 return -1;
5386             }
5387 
5388             Py_BEGIN_ALLOW_THREADS
5389             fd = WSASocketW(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
5390                      FROM_PROTOCOL_INFO, &info, 0, WSA_FLAG_OVERLAPPED);
5391             Py_END_ALLOW_THREADS
5392             if (fd == INVALID_SOCKET) {
5393                 set_error();
5394                 return -1;
5395             }
5396 
5397             if (!SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0)) {
5398                 PyErr_SetFromWindowsErr(0);
5399                 closesocket(fd);
5400                 return -1;
5401             }
5402 
5403             family = info.iAddressFamily;
5404             type = info.iSocketType;
5405             proto = info.iProtocol;
5406         }
5407         else
5408 #endif
5409         {
5410             fd = PyLong_AsSocket_t(fdobj);
5411             if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
5412                 return -1;
5413 #ifdef MS_WINDOWS
5414             if (fd == INVALID_SOCKET) {
5415 #else
5416             if (fd < 0) {
5417 #endif
5418                 PyErr_SetString(PyExc_ValueError, "negative file descriptor");
5419                 return -1;
5420             }
5421 
5422             /* validate that passed file descriptor is valid and a socket. */
5423             sock_addr_t addrbuf;
5424             socklen_t addrlen = sizeof(sock_addr_t);
5425 
5426             memset(&addrbuf, 0, addrlen);
5427 #ifdef HAVE_GETSOCKNAME
5428             if (getsockname(fd, SAS2SA(&addrbuf), &addrlen) == 0) {
5429                 if (family == -1) {
5430                     family = SAS2SA(&addrbuf)->sa_family;
5431                 }
5432             } else {
5433 #ifdef MS_WINDOWS
5434                 /* getsockname() on an unbound socket is an error on Windows.
5435                    Invalid descriptor and not a socket is same error code.
5436                    Error out if family must be resolved, or bad descriptor. */
5437                 if (family == -1 || CHECK_ERRNO(ENOTSOCK)) {
5438 #else
5439                 /* getsockname() is not supported for SOL_ALG on Linux. */
5440                 if (family == -1 || CHECK_ERRNO(EBADF) || CHECK_ERRNO(ENOTSOCK)) {
5441 #endif
5442                     set_error();
5443                     return -1;
5444                 }
5445             }
5446 #endif // HAVE_GETSOCKNAME
5447 #ifdef SO_TYPE
5448             if (type == -1) {
5449                 int tmp;
5450                 socklen_t slen = sizeof(tmp);
5451                 if (getsockopt(fd, SOL_SOCKET, SO_TYPE,
5452                                (void *)&tmp, &slen) == 0)
5453                 {
5454                     type = tmp;
5455                 } else {
5456                     set_error();
5457                     return -1;
5458                 }
5459             }
5460 #else
5461             type = SOCK_STREAM;
5462 #endif
5463 #ifdef SO_PROTOCOL
5464             if (proto == -1) {
5465                 int tmp;
5466                 socklen_t slen = sizeof(tmp);
5467                 if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL,
5468                                (void *)&tmp, &slen) == 0)
5469                 {
5470                     proto = tmp;
5471                 } else {
5472                     set_error();
5473                     return -1;
5474                 }
5475             }
5476 #else
5477             proto = 0;
5478 #endif
5479         }
5480     }
5481     else {
5482         /* No fd, default to AF_INET and SOCK_STREAM */
5483         if (family == -1) {
5484             family = AF_INET;
5485         }
5486         if (type == -1) {
5487             type = SOCK_STREAM;
5488         }
5489         if (proto == -1) {
5490             proto = 0;
5491         }
5492 #ifdef MS_WINDOWS
5493         Py_BEGIN_ALLOW_THREADS
5494         fd = WSASocketW(family, type, proto,
5495                         NULL, 0,
5496                         WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT);
5497         Py_END_ALLOW_THREADS
5498 
5499         if (fd == INVALID_SOCKET) {
5500             set_error();
5501             return -1;
5502         }
5503 #else
5504         /* UNIX */
5505         Py_BEGIN_ALLOW_THREADS
5506 #ifdef SOCK_CLOEXEC
5507         if (state->sock_cloexec_works != 0) {
5508             fd = socket(family, type | SOCK_CLOEXEC, proto);
5509             if (state->sock_cloexec_works == -1) {
5510                 if (fd >= 0) {
5511                     state->sock_cloexec_works = 1;
5512                 }
5513                 else if (errno == EINVAL) {
5514                     /* Linux older than 2.6.27 does not support SOCK_CLOEXEC */
5515                     state->sock_cloexec_works = 0;
5516                     fd = socket(family, type, proto);
5517                 }
5518             }
5519         }
5520         else
5521 #endif
5522         {
5523             fd = socket(family, type, proto);
5524         }
5525         Py_END_ALLOW_THREADS
5526 
5527         if (fd == INVALID_SOCKET) {
5528             set_error();
5529             return -1;
5530         }
5531 
5532         if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
5533             SOCKETCLOSE(fd);
5534             return -1;
5535         }
5536 #endif
5537     }
5538     if (init_sockobject(state, self, fd, family, type, proto) == -1) {
5539         SOCKETCLOSE(fd);
5540         return -1;
5541     }
5542 
5543     return 0;
5544 
5545 }
5546 
5547 
5548 /* Type object for socket objects. */
5549 
5550 static PyType_Slot sock_slots[] = {
5551     {Py_tp_dealloc, sock_dealloc},
5552     {Py_tp_traverse, sock_traverse},
5553     {Py_tp_repr, sock_repr},
5554     {Py_tp_doc, (void *)sock_doc},
5555     {Py_tp_methods, sock_methods},
5556     {Py_tp_members, sock_memberlist},
5557     {Py_tp_getset, sock_getsetlist},
5558     {Py_tp_init, sock_initobj},
5559     {Py_tp_new, sock_new},
5560     {Py_tp_finalize, sock_finalize},
5561     {0, NULL},
5562 };
5563 
5564 static PyType_Spec sock_spec = {
5565     .name = "_socket.socket",
5566     .basicsize = sizeof(PySocketSockObject),
5567     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
5568               Py_TPFLAGS_IMMUTABLETYPE),
5569     .slots = sock_slots,
5570 };
5571 
5572 
5573 #ifdef HAVE_GETHOSTNAME
5574 /* Python interface to gethostname(). */
5575 
5576 /*ARGSUSED*/
5577 static PyObject *
5578 socket_gethostname(PyObject *self, PyObject *unused)
5579 {
5580     if (PySys_Audit("socket.gethostname", NULL) < 0) {
5581         return NULL;
5582     }
5583 
5584 #ifdef MS_WINDOWS
5585     /* Don't use winsock's gethostname, as this returns the ANSI
5586        version of the hostname, whereas we need a Unicode string.
5587        Otherwise, gethostname apparently also returns the DNS name. */
5588     wchar_t buf[MAX_COMPUTERNAME_LENGTH + 1];
5589     DWORD size = Py_ARRAY_LENGTH(buf);
5590     wchar_t *name;
5591     PyObject *result;
5592 
5593     if (GetComputerNameExW(ComputerNamePhysicalDnsHostname, buf, &size))
5594         return PyUnicode_FromWideChar(buf, size);
5595 
5596     if (GetLastError() != ERROR_MORE_DATA)
5597         return PyErr_SetFromWindowsErr(0);
5598 
5599     if (size == 0)
5600         return PyUnicode_New(0, 0);
5601 
5602     /* MSDN says ERROR_MORE_DATA may occur because DNS allows longer
5603        names */
5604     name = PyMem_New(wchar_t, size);
5605     if (!name) {
5606         PyErr_NoMemory();
5607         return NULL;
5608     }
5609     if (!GetComputerNameExW(ComputerNamePhysicalDnsHostname,
5610                            name,
5611                            &size))
5612     {
5613         PyErr_SetFromWindowsErr(0);
5614         PyMem_Free(name);
5615         return NULL;
5616     }
5617 
5618     result = PyUnicode_FromWideChar(name, size);
5619     PyMem_Free(name);
5620     return result;
5621 #else
5622     char buf[1024];
5623     int res;
5624     Py_BEGIN_ALLOW_THREADS
5625     res = gethostname(buf, (int) sizeof buf - 1);
5626     Py_END_ALLOW_THREADS
5627     if (res < 0)
5628         return set_error();
5629     buf[sizeof buf - 1] = '\0';
5630     return PyUnicode_DecodeFSDefault(buf);
5631 #endif
5632 }
5633 
5634 PyDoc_STRVAR(gethostname_doc,
5635 "gethostname() -> string\n\
5636 \n\
5637 Return the current host name.");
5638 #endif
5639 
5640 #ifdef HAVE_SETHOSTNAME
5641 PyDoc_STRVAR(sethostname_doc,
5642 "sethostname(name)\n\n\
5643 Sets the hostname to name.");
5644 
5645 static PyObject *
5646 socket_sethostname(PyObject *self, PyObject *args)
5647 {
5648     PyObject *hnobj;
5649     Py_buffer buf;
5650     int res, flag = 0;
5651 
5652 #if defined(_AIX) || (defined(__sun) && defined(__SVR4) && Py_SUNOS_VERSION <= 510)
5653 /* issue #18259, sethostname is not declared in any useful header file on AIX
5654  * the same is true for Solaris 10 */
5655 extern int sethostname(const char *, size_t);
5656 #endif
5657 
5658     if (!PyArg_ParseTuple(args, "S:sethostname", &hnobj)) {
5659         PyErr_Clear();
5660         if (!PyArg_ParseTuple(args, "O&:sethostname",
5661                 PyUnicode_FSConverter, &hnobj))
5662             return NULL;
5663         flag = 1;
5664     }
5665 
5666     if (PySys_Audit("socket.sethostname", "(O)", hnobj) < 0) {
5667         return NULL;
5668     }
5669 
5670     res = PyObject_GetBuffer(hnobj, &buf, PyBUF_SIMPLE);
5671     if (!res) {
5672         res = sethostname(buf.buf, buf.len);
5673         PyBuffer_Release(&buf);
5674     }
5675     if (flag)
5676         Py_DECREF(hnobj);
5677     if (res)
5678         return set_error();
5679     Py_RETURN_NONE;
5680 }
5681 #endif
5682 
5683 #ifdef HAVE_GETADDRINFO
5684 /* Python interface to gethostbyname(name). */
5685 
5686 /*ARGSUSED*/
5687 static PyObject *
5688 socket_gethostbyname(PyObject *self, PyObject *args)
5689 {
5690     char *name;
5691     struct sockaddr_in addrbuf;
5692     PyObject *ret = NULL;
5693 
5694     if (!PyArg_ParseTuple(args, "et:gethostbyname", "idna", &name))
5695         return NULL;
5696     if (PySys_Audit("socket.gethostbyname", "O", args) < 0) {
5697         goto finally;
5698     }
5699     socket_state *state = get_module_state(self);
5700     int rc = setipaddr(state, name, (struct sockaddr *)&addrbuf,
5701                        sizeof(addrbuf), AF_INET);
5702     if (rc < 0) {
5703         goto finally;
5704     }
5705     ret = make_ipv4_addr(&addrbuf);
5706 finally:
5707     PyMem_Free(name);
5708     return ret;
5709 }
5710 
5711 PyDoc_STRVAR(gethostbyname_doc,
5712 "gethostbyname(host) -> address\n\
5713 \n\
5714 Return the IP address (a string of the form '255.255.255.255') for a host.");
5715 #endif
5716 
5717 
5718 #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME) || defined (HAVE_GETHOSTBYADDR)
5719 static PyObject*
5720 sock_decode_hostname(const char *name)
5721 {
5722 #ifdef MS_WINDOWS
5723     /* Issue #26227: gethostbyaddr() returns a string encoded
5724      * to the ANSI code page */
5725     return PyUnicode_DecodeMBCS(name, strlen(name), "surrogatepass");
5726 #else
5727     /* Decode from UTF-8 */
5728     return PyUnicode_FromString(name);
5729 #endif
5730 }
5731 
5732 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
5733 
5734 static PyObject *
5735 gethost_common(socket_state *state, struct hostent *h, struct sockaddr *addr,
5736                size_t alen, int af)
5737 {
5738     char **pch;
5739     PyObject *rtn_tuple = (PyObject *)NULL;
5740     PyObject *name_list = (PyObject *)NULL;
5741     PyObject *addr_list = (PyObject *)NULL;
5742     PyObject *tmp;
5743     PyObject *name;
5744 
5745     if (h == NULL) {
5746         /* Let's get real error message to return */
5747         set_herror(state, h_errno);
5748         return NULL;
5749     }
5750 
5751     if (h->h_addrtype != af) {
5752         /* Let's get real error message to return */
5753         errno = EAFNOSUPPORT;
5754         PyErr_SetFromErrno(PyExc_OSError);
5755         return NULL;
5756     }
5757 
5758     switch (af) {
5759 
5760     case AF_INET:
5761         if (alen < sizeof(struct sockaddr_in))
5762             return NULL;
5763         break;
5764 
5765 #ifdef ENABLE_IPV6
5766     case AF_INET6:
5767         if (alen < sizeof(struct sockaddr_in6))
5768             return NULL;
5769         break;
5770 #endif
5771 
5772     }
5773 
5774     if ((name_list = PyList_New(0)) == NULL)
5775         goto err;
5776 
5777     if ((addr_list = PyList_New(0)) == NULL)
5778         goto err;
5779 
5780     /* SF #1511317: h_aliases can be NULL */
5781     if (h->h_aliases) {
5782         for (pch = h->h_aliases; ; pch++) {
5783             int status;
5784             char *host_alias;
5785             // pch can be misaligned
5786             memcpy(&host_alias, pch, sizeof(host_alias));
5787             if (host_alias == NULL) {
5788                 break;
5789             }
5790             tmp = PyUnicode_FromString(host_alias);
5791             if (tmp == NULL)
5792                 goto err;
5793 
5794             status = PyList_Append(name_list, tmp);
5795             Py_DECREF(tmp);
5796 
5797             if (status)
5798                 goto err;
5799         }
5800     }
5801 
5802     for (pch = h->h_addr_list; ; pch++) {
5803         int status;
5804         char *host_address;
5805         // pch can be misaligned
5806         memcpy(&host_address, pch, sizeof(host_address));
5807         if (host_address == NULL) {
5808             break;
5809         }
5810 
5811         switch (af) {
5812 
5813         case AF_INET:
5814             {
5815             struct sockaddr_in sin;
5816             memset(&sin, 0, sizeof(sin));
5817             sin.sin_family = af;
5818 #ifdef HAVE_SOCKADDR_SA_LEN
5819             sin.sin_len = sizeof(sin);
5820 #endif
5821             memcpy(&sin.sin_addr, host_address, sizeof(sin.sin_addr));
5822             tmp = make_ipv4_addr(&sin);
5823 
5824             if (pch == h->h_addr_list && alen >= sizeof(sin))
5825                 memcpy((char *) addr, &sin, sizeof(sin));
5826             break;
5827             }
5828 
5829 #ifdef ENABLE_IPV6
5830         case AF_INET6:
5831             {
5832             struct sockaddr_in6 sin6;
5833             memset(&sin6, 0, sizeof(sin6));
5834             sin6.sin6_family = af;
5835 #ifdef HAVE_SOCKADDR_SA_LEN
5836             sin6.sin6_len = sizeof(sin6);
5837 #endif
5838             memcpy(&sin6.sin6_addr, host_address, sizeof(sin6.sin6_addr));
5839             tmp = make_ipv6_addr(&sin6);
5840 
5841             if (pch == h->h_addr_list && alen >= sizeof(sin6))
5842                 memcpy((char *) addr, &sin6, sizeof(sin6));
5843             break;
5844             }
5845 #endif
5846 
5847         default:                /* can't happen */
5848             PyErr_SetString(PyExc_OSError,
5849                             "unsupported address family");
5850             return NULL;
5851         }
5852 
5853         if (tmp == NULL)
5854             goto err;
5855 
5856         status = PyList_Append(addr_list, tmp);
5857         Py_DECREF(tmp);
5858 
5859         if (status)
5860             goto err;
5861     }
5862 
5863     name = sock_decode_hostname(h->h_name);
5864     if (name == NULL)
5865         goto err;
5866     rtn_tuple = Py_BuildValue("NOO", name, name_list, addr_list);
5867 
5868  err:
5869     Py_XDECREF(name_list);
5870     Py_XDECREF(addr_list);
5871     return rtn_tuple;
5872 }
5873 #endif
5874 
5875 #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME)
5876 /* Python interface to gethostbyname_ex(name). */
5877 
5878 /*ARGSUSED*/
5879 static PyObject *
5880 socket_gethostbyname_ex(PyObject *self, PyObject *args)
5881 {
5882     char *name;
5883     struct hostent *h;
5884     sock_addr_t addr;
5885     struct sockaddr *sa;
5886     PyObject *ret = NULL;
5887 #ifdef HAVE_GETHOSTBYNAME_R
5888     struct hostent hp_allocated;
5889 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
5890     struct hostent_data data;
5891 #else
5892     char buf[16384];
5893     int buf_len = (sizeof buf) - 1;
5894     int errnop;
5895 #endif
5896 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
5897     int result;
5898 #endif
5899 #endif /* HAVE_GETHOSTBYNAME_R */
5900 
5901     if (!PyArg_ParseTuple(args, "et:gethostbyname_ex", "idna", &name))
5902         return NULL;
5903     if (PySys_Audit("socket.gethostbyname", "O", args) < 0) {
5904         goto finally;
5905     }
5906     socket_state *state = get_module_state(self);
5907     if (setipaddr(state, name, SAS2SA(&addr), sizeof(addr), AF_INET) < 0) {
5908         goto finally;
5909     }
5910     Py_BEGIN_ALLOW_THREADS
5911 #ifdef HAVE_GETHOSTBYNAME_R
5912 #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
5913     gethostbyname_r(name, &hp_allocated, buf, buf_len,
5914                              &h, &errnop);
5915 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
5916     h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
5917 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
5918     memset((void *) &data, '\0', sizeof(data));
5919     result = gethostbyname_r(name, &hp_allocated, &data);
5920     h = (result != 0) ? NULL : &hp_allocated;
5921 #endif
5922 #else /* not HAVE_GETHOSTBYNAME_R */
5923 #ifdef USE_GETHOSTBYNAME_LOCK
5924     PyThread_acquire_lock(netdb_lock, 1);
5925 #endif
5926     SUPPRESS_DEPRECATED_CALL
5927     h = gethostbyname(name);
5928 #endif /* HAVE_GETHOSTBYNAME_R */
5929     Py_END_ALLOW_THREADS
5930     /* Some C libraries would require addr.__ss_family instead of
5931        addr.ss_family.
5932        Therefore, we cast the sockaddr_storage into sockaddr to
5933        access sa_family. */
5934     sa = SAS2SA(&addr);
5935     ret = gethost_common(state, h, SAS2SA(&addr), sizeof(addr),
5936                          sa->sa_family);
5937 #ifdef USE_GETHOSTBYNAME_LOCK
5938     PyThread_release_lock(netdb_lock);
5939 #endif
5940 finally:
5941     PyMem_Free(name);
5942     return ret;
5943 }
5944 
5945 PyDoc_STRVAR(ghbn_ex_doc,
5946 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
5947 \n\
5948 Return the true host name, a list of aliases, and a list of IP addresses,\n\
5949 for a host.  The host argument is a string giving a host name or IP number.");
5950 #endif
5951 
5952 #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYADDR)
5953 /* Python interface to gethostbyaddr(IP). */
5954 
5955 /*ARGSUSED*/
5956 static PyObject *
5957 socket_gethostbyaddr(PyObject *self, PyObject *args)
5958 {
5959     sock_addr_t addr;
5960     struct sockaddr *sa = SAS2SA(&addr);
5961     char *ip_num;
5962     struct hostent *h;
5963     PyObject *ret = NULL;
5964 #ifdef HAVE_GETHOSTBYNAME_R
5965     struct hostent hp_allocated;
5966 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
5967     struct hostent_data data;
5968 #else
5969     /* glibcs up to 2.10 assume that the buf argument to
5970        gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
5971        does not ensure. The attribute below instructs the compiler
5972        to maintain this alignment. */
5973     char buf[16384] Py_ALIGNED(8);
5974     int buf_len = (sizeof buf) - 1;
5975     int errnop;
5976 #endif
5977 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
5978     int result;
5979 #endif
5980 #endif /* HAVE_GETHOSTBYNAME_R */
5981     const char *ap;
5982     int al;
5983     int af;
5984 
5985     if (!PyArg_ParseTuple(args, "et:gethostbyaddr", "idna", &ip_num))
5986         return NULL;
5987     if (PySys_Audit("socket.gethostbyaddr", "O", args) < 0) {
5988         goto finally;
5989     }
5990     af = AF_UNSPEC;
5991     socket_state *state = get_module_state(self);
5992     if (setipaddr(state, ip_num, sa, sizeof(addr), af) < 0) {
5993         goto finally;
5994     }
5995     af = sa->sa_family;
5996     ap = NULL;
5997     /* al = 0; */
5998     switch (af) {
5999     case AF_INET:
6000         ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
6001         al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
6002         break;
6003 #ifdef ENABLE_IPV6
6004     case AF_INET6:
6005         ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
6006         al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
6007         break;
6008 #endif
6009     default:
6010         PyErr_SetString(PyExc_OSError, "unsupported address family");
6011         goto finally;
6012     }
6013     Py_BEGIN_ALLOW_THREADS
6014 #ifdef HAVE_GETHOSTBYNAME_R
6015 #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
6016     gethostbyaddr_r(ap, al, af,
6017         &hp_allocated, buf, buf_len,
6018         &h, &errnop);
6019 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
6020     h = gethostbyaddr_r(ap, al, af,
6021                         &hp_allocated, buf, buf_len, &errnop);
6022 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
6023     memset((void *) &data, '\0', sizeof(data));
6024     result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
6025     h = (result != 0) ? NULL : &hp_allocated;
6026 #endif
6027 #else /* not HAVE_GETHOSTBYNAME_R */
6028 #ifdef USE_GETHOSTBYNAME_LOCK
6029     PyThread_acquire_lock(netdb_lock, 1);
6030 #endif
6031     SUPPRESS_DEPRECATED_CALL
6032     h = gethostbyaddr(ap, al, af);
6033 #endif /* HAVE_GETHOSTBYNAME_R */
6034     Py_END_ALLOW_THREADS
6035     ret = gethost_common(state, h, SAS2SA(&addr), sizeof(addr), af);
6036 #ifdef USE_GETHOSTBYNAME_LOCK
6037     PyThread_release_lock(netdb_lock);
6038 #endif
6039 finally:
6040     PyMem_Free(ip_num);
6041     return ret;
6042 }
6043 
6044 PyDoc_STRVAR(gethostbyaddr_doc,
6045 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
6046 \n\
6047 Return the true host name, a list of aliases, and a list of IP addresses,\n\
6048 for a host.  The host argument is a string giving a host name or IP number.");
6049 #endif
6050 
6051 #ifdef HAVE_GETSERVBYNAME
6052 /* Python interface to getservbyname(name).
6053    This only returns the port number, since the other info is already
6054    known or not useful (like the list of aliases). */
6055 
6056 /*ARGSUSED*/
6057 static PyObject *
6058 socket_getservbyname(PyObject *self, PyObject *args)
6059 {
6060     const char *name, *proto=NULL;
6061     struct servent *sp;
6062     if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
6063         return NULL;
6064 
6065     if (PySys_Audit("socket.getservbyname", "ss", name, proto) < 0) {
6066         return NULL;
6067     }
6068 
6069     Py_BEGIN_ALLOW_THREADS
6070     sp = getservbyname(name, proto);
6071     Py_END_ALLOW_THREADS
6072     if (sp == NULL) {
6073         PyErr_SetString(PyExc_OSError, "service/proto not found");
6074         return NULL;
6075     }
6076     return PyLong_FromLong((long) ntohs(sp->s_port));
6077 }
6078 
6079 PyDoc_STRVAR(getservbyname_doc,
6080 "getservbyname(servicename[, protocolname]) -> integer\n\
6081 \n\
6082 Return a port number from a service name and protocol name.\n\
6083 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
6084 otherwise any protocol will match.");
6085 #endif
6086 
6087 #ifdef HAVE_GETSERVBYPORT
6088 /* Python interface to getservbyport(port).
6089    This only returns the service name, since the other info is already
6090    known or not useful (like the list of aliases). */
6091 
6092 /*ARGSUSED*/
6093 static PyObject *
6094 socket_getservbyport(PyObject *self, PyObject *args)
6095 {
6096     int port;
6097     const char *proto=NULL;
6098     struct servent *sp;
6099     if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
6100         return NULL;
6101     if (port < 0 || port > 0xffff) {
6102         PyErr_SetString(
6103             PyExc_OverflowError,
6104             "getservbyport: port must be 0-65535.");
6105         return NULL;
6106     }
6107 
6108     if (PySys_Audit("socket.getservbyport", "is", port, proto) < 0) {
6109         return NULL;
6110     }
6111 
6112     Py_BEGIN_ALLOW_THREADS
6113     sp = getservbyport(htons((short)port), proto);
6114     Py_END_ALLOW_THREADS
6115     if (sp == NULL) {
6116         PyErr_SetString(PyExc_OSError, "port/proto not found");
6117         return NULL;
6118     }
6119     return PyUnicode_FromString(sp->s_name);
6120 }
6121 
6122 PyDoc_STRVAR(getservbyport_doc,
6123 "getservbyport(port[, protocolname]) -> string\n\
6124 \n\
6125 Return the service name from a port number and protocol name.\n\
6126 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
6127 otherwise any protocol will match.");
6128 #endif
6129 
6130 #ifdef HAVE_GETPROTOBYNAME
6131 /* Python interface to getprotobyname(name).
6132    This only returns the protocol number, since the other info is
6133    already known or not useful (like the list of aliases). */
6134 
6135 /*ARGSUSED*/
6136 static PyObject *
6137 socket_getprotobyname(PyObject *self, PyObject *args)
6138 {
6139     const char *name;
6140     struct protoent *sp;
6141     if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
6142         return NULL;
6143     Py_BEGIN_ALLOW_THREADS
6144     sp = getprotobyname(name);
6145     Py_END_ALLOW_THREADS
6146     if (sp == NULL) {
6147         PyErr_SetString(PyExc_OSError, "protocol not found");
6148         return NULL;
6149     }
6150     return PyLong_FromLong((long) sp->p_proto);
6151 }
6152 
6153 PyDoc_STRVAR(getprotobyname_doc,
6154 "getprotobyname(name) -> integer\n\
6155 \n\
6156 Return the protocol number for the named protocol.  (Rarely used.)");
6157 #endif
6158 
6159 static PyObject *
6160 socket_close(PyObject *self, PyObject *fdobj)
6161 {
6162     SOCKET_T fd;
6163     int res;
6164 
6165     fd = PyLong_AsSocket_t(fdobj);
6166     if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
6167         return NULL;
6168     Py_BEGIN_ALLOW_THREADS
6169     res = SOCKETCLOSE(fd);
6170     Py_END_ALLOW_THREADS
6171     /* bpo-30319: The peer can already have closed the connection.
6172        Python ignores ECONNRESET on close(). */
6173     if (res < 0 && !CHECK_ERRNO(ECONNRESET)) {
6174         return set_error();
6175     }
6176     Py_RETURN_NONE;
6177 }
6178 
6179 PyDoc_STRVAR(close_doc,
6180 "close(integer) -> None\n\
6181 \n\
6182 Close an integer socket file descriptor.  This is like os.close(), but for\n\
6183 sockets; on some platforms os.close() won't work for socket file descriptors.");
6184 
6185 #ifndef NO_DUP
6186 /* dup() function for socket fds */
6187 
6188 static PyObject *
6189 socket_dup(PyObject *self, PyObject *fdobj)
6190 {
6191     SOCKET_T fd, newfd;
6192     PyObject *newfdobj;
6193 #ifdef MS_WINDOWS
6194     WSAPROTOCOL_INFOW info;
6195 #endif
6196 
6197     fd = PyLong_AsSocket_t(fdobj);
6198     if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) {
6199         return NULL;
6200     }
6201 
6202 #ifdef MS_WINDOWS
6203     if (WSADuplicateSocketW(fd, GetCurrentProcessId(), &info))
6204         return set_error();
6205 
6206     newfd = WSASocketW(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
6207                       FROM_PROTOCOL_INFO,
6208                       &info, 0, WSA_FLAG_OVERLAPPED);
6209     if (newfd == INVALID_SOCKET) {
6210         return set_error();
6211     }
6212 
6213     if (!SetHandleInformation((HANDLE)newfd, HANDLE_FLAG_INHERIT, 0)) {
6214         PyErr_SetFromWindowsErr(0);
6215         closesocket(newfd);
6216         return NULL;
6217     }
6218 #else
6219     /* On UNIX, dup can be used to duplicate the file descriptor of a socket */
6220     newfd = _Py_dup(fd);
6221     if (newfd == INVALID_SOCKET) {
6222         return NULL;
6223     }
6224 #endif
6225 
6226     newfdobj = PyLong_FromSocket_t(newfd);
6227     if (newfdobj == NULL) {
6228         SOCKETCLOSE(newfd);
6229     }
6230     return newfdobj;
6231 }
6232 
6233 PyDoc_STRVAR(dup_doc,
6234 "dup(integer) -> integer\n\
6235 \n\
6236 Duplicate an integer socket file descriptor.  This is like os.dup(), but for\n\
6237 sockets; on some platforms os.dup() won't work for socket file descriptors.");
6238 #endif
6239 
6240 
6241 #ifdef HAVE_SOCKETPAIR
6242 /* Create a pair of sockets using the socketpair() function.
6243    Arguments as for socket() except the default family is AF_UNIX if
6244    defined on the platform; otherwise, the default is AF_INET. */
6245 
6246 /*ARGSUSED*/
6247 static PyObject *
6248 socket_socketpair(PyObject *self, PyObject *args)
6249 {
6250     PySocketSockObject *s0 = NULL, *s1 = NULL;
6251     SOCKET_T sv[2];
6252     int family, type = SOCK_STREAM, proto = 0;
6253     PyObject *res = NULL;
6254     socket_state *state = get_module_state(self);
6255 #ifdef SOCK_CLOEXEC
6256     int *atomic_flag_works = &state->sock_cloexec_works;
6257 #else
6258     int *atomic_flag_works = NULL;
6259 #endif
6260     int ret;
6261 
6262 #if defined(AF_UNIX)
6263     family = AF_UNIX;
6264 #else
6265     family = AF_INET;
6266 #endif
6267     if (!PyArg_ParseTuple(args, "|iii:socketpair",
6268                           &family, &type, &proto))
6269         return NULL;
6270 
6271     /* Create a pair of socket fds */
6272     Py_BEGIN_ALLOW_THREADS
6273 #ifdef SOCK_CLOEXEC
6274     if (state->sock_cloexec_works != 0) {
6275         ret = socketpair(family, type | SOCK_CLOEXEC, proto, sv);
6276         if (state->sock_cloexec_works == -1) {
6277             if (ret >= 0) {
6278                 state->sock_cloexec_works = 1;
6279             }
6280             else if (errno == EINVAL) {
6281                 /* Linux older than 2.6.27 does not support SOCK_CLOEXEC */
6282                 state->sock_cloexec_works = 0;
6283                 ret = socketpair(family, type, proto, sv);
6284             }
6285         }
6286     }
6287     else
6288 #endif
6289     {
6290         ret = socketpair(family, type, proto, sv);
6291     }
6292     Py_END_ALLOW_THREADS
6293 
6294     if (ret < 0)
6295         return set_error();
6296 
6297     if (_Py_set_inheritable(sv[0], 0, atomic_flag_works) < 0)
6298         goto finally;
6299     if (_Py_set_inheritable(sv[1], 0, atomic_flag_works) < 0)
6300         goto finally;
6301 
6302     s0 = new_sockobject(state, sv[0], family, type, proto);
6303     if (s0 == NULL)
6304         goto finally;
6305     s1 = new_sockobject(state, sv[1], family, type, proto);
6306     if (s1 == NULL)
6307         goto finally;
6308     res = PyTuple_Pack(2, s0, s1);
6309 
6310 finally:
6311     if (res == NULL) {
6312         if (s0 == NULL)
6313             SOCKETCLOSE(sv[0]);
6314         if (s1 == NULL)
6315             SOCKETCLOSE(sv[1]);
6316     }
6317     Py_XDECREF(s0);
6318     Py_XDECREF(s1);
6319     return res;
6320 }
6321 
6322 PyDoc_STRVAR(socketpair_doc,
6323 "socketpair([family[, type [, proto]]]) -> (socket object, socket object)\n\
6324 \n\
6325 Create a pair of socket objects from the sockets returned by the platform\n\
6326 socketpair() function.\n\
6327 The arguments are the same as for socket() except the default family is\n\
6328 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
6329 
6330 #endif /* HAVE_SOCKETPAIR */
6331 
6332 
6333 /*[clinic input]
6334 _socket.socket.ntohs
6335     x: int
6336     /
6337 
6338 Convert a 16-bit unsigned integer from network to host byte order.
6339 [clinic start generated code]*/
6340 
6341 static PyObject *
6342 _socket_socket_ntohs_impl(PySocketSockObject *self, int x)
6343 /*[clinic end generated code: output=a828a61a9fb205b2 input=9a79cb3a71652147]*/
6344 {
6345     if (x < 0) {
6346         PyErr_SetString(PyExc_OverflowError,
6347                         "ntohs: can't convert negative Python int to C "
6348                         "16-bit unsigned integer");
6349         return NULL;
6350     }
6351     if (x > 0xffff) {
6352         PyErr_SetString(PyExc_OverflowError,
6353                         "ntohs: Python int too large to convert to C "
6354                         "16-bit unsigned integer");
6355         return NULL;
6356     }
6357     return PyLong_FromUnsignedLong(ntohs((unsigned short)x));
6358 }
6359 
6360 
6361 static PyObject *
6362 socket_ntohl(PyObject *self, PyObject *arg)
6363 {
6364     unsigned long x;
6365 
6366     if (PyLong_Check(arg)) {
6367         x = PyLong_AsUnsignedLong(arg);
6368         if (x == (unsigned long) -1 && PyErr_Occurred())
6369             return NULL;
6370 #if SIZEOF_LONG > 4
6371         {
6372             unsigned long y;
6373             /* only want the trailing 32 bits */
6374             y = x & 0xFFFFFFFFUL;
6375             if (y ^ x)
6376                 return PyErr_Format(PyExc_OverflowError,
6377                             "int larger than 32 bits");
6378             x = y;
6379         }
6380 #endif
6381     }
6382     else
6383         return PyErr_Format(PyExc_TypeError,
6384                             "expected int, %s found",
6385                             Py_TYPE(arg)->tp_name);
6386     return PyLong_FromUnsignedLong(ntohl(x));
6387 }
6388 
6389 PyDoc_STRVAR(ntohl_doc,
6390 "ntohl(integer) -> integer\n\
6391 \n\
6392 Convert a 32-bit integer from network to host byte order.");
6393 
6394 
6395 /*[clinic input]
6396 _socket.socket.htons
6397     x: int
6398     /
6399 
6400 Convert a 16-bit unsigned integer from host to network byte order.
6401 [clinic start generated code]*/
6402 
6403 static PyObject *
6404 _socket_socket_htons_impl(PySocketSockObject *self, int x)
6405 /*[clinic end generated code: output=d785ee692312da47 input=053252d8416f4337]*/
6406 {
6407     if (x < 0) {
6408         PyErr_SetString(PyExc_OverflowError,
6409                         "htons: can't convert negative Python int to C "
6410                         "16-bit unsigned integer");
6411         return NULL;
6412     }
6413     if (x > 0xffff) {
6414         PyErr_SetString(PyExc_OverflowError,
6415                         "htons: Python int too large to convert to C "
6416                         "16-bit unsigned integer");
6417         return NULL;
6418     }
6419     return PyLong_FromUnsignedLong(htons((unsigned short)x));
6420 }
6421 
6422 
6423 static PyObject *
6424 socket_htonl(PyObject *self, PyObject *arg)
6425 {
6426     unsigned long x;
6427 
6428     if (PyLong_Check(arg)) {
6429         x = PyLong_AsUnsignedLong(arg);
6430         if (x == (unsigned long) -1 && PyErr_Occurred())
6431             return NULL;
6432 #if SIZEOF_LONG > 4
6433         {
6434             unsigned long y;
6435             /* only want the trailing 32 bits */
6436             y = x & 0xFFFFFFFFUL;
6437             if (y ^ x)
6438                 return PyErr_Format(PyExc_OverflowError,
6439                             "int larger than 32 bits");
6440             x = y;
6441         }
6442 #endif
6443     }
6444     else
6445         return PyErr_Format(PyExc_TypeError,
6446                             "expected int, %s found",
6447                             Py_TYPE(arg)->tp_name);
6448     return PyLong_FromUnsignedLong(htonl((unsigned long)x));
6449 }
6450 
6451 PyDoc_STRVAR(htonl_doc,
6452 "htonl(integer) -> integer\n\
6453 \n\
6454 Convert a 32-bit integer from host to network byte order.");
6455 
6456 /* socket.inet_aton() and socket.inet_ntoa() functions. */
6457 
6458 /*[clinic input]
6459 _socket.socket.inet_aton
6460     ip_addr: str
6461     /
6462 
6463 Convert an IP address in string format (123.45.67.89) to the 32-bit packed binary format used in low-level network functions.
6464 [clinic start generated code]*/
6465 
6466 static PyObject *
6467 _socket_socket_inet_aton_impl(PySocketSockObject *self, const char *ip_addr)
6468 /*[clinic end generated code: output=5bfe11a255423d8c input=a120e20cb52b9488]*/
6469 {
6470 #ifdef HAVE_INET_ATON
6471     struct in_addr buf;
6472 #endif
6473 
6474 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
6475 #if (SIZEOF_INT != 4)
6476 #error "Not sure if in_addr_t exists and int is not 32-bits."
6477 #endif
6478     /* Have to use inet_addr() instead */
6479     unsigned int packed_addr;
6480 #endif
6481 
6482 #ifdef HAVE_INET_ATON
6483 
6484 #ifdef USE_INET_ATON_WEAKLINK
6485     if (inet_aton != NULL) {
6486 #endif
6487     if (inet_aton(ip_addr, &buf))
6488         return PyBytes_FromStringAndSize((char *)(&buf),
6489                                           sizeof(buf));
6490 
6491     PyErr_SetString(PyExc_OSError,
6492                     "illegal IP address string passed to inet_aton");
6493     return NULL;
6494 
6495 #ifdef USE_INET_ATON_WEAKLINK
6496    } else {
6497 #endif
6498 
6499 #endif
6500 
6501 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
6502 
6503     /* special-case this address as inet_addr might return INADDR_NONE
6504      * for this */
6505     if (strcmp(ip_addr, "255.255.255.255") == 0) {
6506         packed_addr = INADDR_BROADCAST;
6507     } else {
6508 
6509         SUPPRESS_DEPRECATED_CALL
6510         packed_addr = inet_addr(ip_addr);
6511 
6512         if (packed_addr == INADDR_NONE) {               /* invalid address */
6513             PyErr_SetString(PyExc_OSError,
6514                 "illegal IP address string passed to inet_aton");
6515             return NULL;
6516         }
6517     }
6518     return PyBytes_FromStringAndSize((char *) &packed_addr,
6519                                       sizeof(packed_addr));
6520 
6521 #ifdef USE_INET_ATON_WEAKLINK
6522    }
6523 #endif
6524 
6525 #endif
6526 }
6527 
6528 #ifdef HAVE_INET_NTOA
6529 /*[clinic input]
6530 _socket.socket.inet_ntoa
6531     packed_ip: Py_buffer
6532     /
6533 
6534 Convert an IP address from 32-bit packed binary format to string format.
6535 [clinic start generated code]*/
6536 
6537 static PyObject *
6538 _socket_socket_inet_ntoa_impl(PySocketSockObject *self, Py_buffer *packed_ip)
6539 /*[clinic end generated code: output=b671880a3f62461b input=95c2c4a1b2ee957c]*/
6540 {
6541     struct in_addr packed_addr;
6542 
6543     if (packed_ip->len != sizeof(packed_addr)) {
6544         PyErr_SetString(PyExc_OSError,
6545             "packed IP wrong length for inet_ntoa");
6546         PyBuffer_Release(packed_ip);
6547         return NULL;
6548     }
6549 
6550     memcpy(&packed_addr, packed_ip->buf, packed_ip->len);
6551     PyBuffer_Release(packed_ip);
6552 
6553     SUPPRESS_DEPRECATED_CALL
6554     return PyUnicode_FromString(inet_ntoa(packed_addr));
6555 }
6556 #endif // HAVE_INET_NTOA
6557 
6558 #ifdef HAVE_INET_PTON
6559 
6560 PyDoc_STRVAR(inet_pton_doc,
6561 "inet_pton(af, ip) -> packed IP address string\n\
6562 \n\
6563 Convert an IP address from string format to a packed string suitable\n\
6564 for use with low-level network functions.");
6565 
6566 static PyObject *
6567 socket_inet_pton(PyObject *self, PyObject *args)
6568 {
6569     int af;
6570     const char* ip;
6571     int retval;
6572 #ifdef ENABLE_IPV6
6573     char packed[Py_MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
6574 #else
6575     char packed[sizeof(struct in_addr)];
6576 #endif
6577     if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
6578         return NULL;
6579     }
6580 
6581 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
6582     if(af == AF_INET6) {
6583         PyErr_SetString(PyExc_OSError,
6584                         "can't use AF_INET6, IPv6 is disabled");
6585         return NULL;
6586     }
6587 #endif
6588 
6589     retval = inet_pton(af, ip, packed);
6590     if (retval < 0) {
6591         PyErr_SetFromErrno(PyExc_OSError);
6592         return NULL;
6593     } else if (retval == 0) {
6594         PyErr_SetString(PyExc_OSError,
6595             "illegal IP address string passed to inet_pton");
6596         return NULL;
6597     } else if (af == AF_INET) {
6598         return PyBytes_FromStringAndSize(packed,
6599                                           sizeof(struct in_addr));
6600 #ifdef ENABLE_IPV6
6601     } else if (af == AF_INET6) {
6602         return PyBytes_FromStringAndSize(packed,
6603                                           sizeof(struct in6_addr));
6604 #endif
6605     } else {
6606         PyErr_SetString(PyExc_OSError, "unknown address family");
6607         return NULL;
6608     }
6609 }
6610 
6611 PyDoc_STRVAR(inet_ntop_doc,
6612 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
6613 \n\
6614 Convert a packed IP address of the given family to string format.");
6615 
6616 static PyObject *
6617 socket_inet_ntop(PyObject *self, PyObject *args)
6618 {
6619     int af;
6620     Py_buffer packed_ip;
6621     const char* retval;
6622 #ifdef ENABLE_IPV6
6623     char ip[Py_MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN)];
6624 #else
6625     char ip[INET_ADDRSTRLEN];
6626 #endif
6627 
6628     if (!PyArg_ParseTuple(args, "iy*:inet_ntop", &af, &packed_ip)) {
6629         return NULL;
6630     }
6631 
6632     if (af == AF_INET) {
6633         if (packed_ip.len != sizeof(struct in_addr)) {
6634             PyErr_SetString(PyExc_ValueError,
6635                 "invalid length of packed IP address string");
6636             PyBuffer_Release(&packed_ip);
6637             return NULL;
6638         }
6639 #ifdef ENABLE_IPV6
6640     } else if (af == AF_INET6) {
6641         if (packed_ip.len != sizeof(struct in6_addr)) {
6642             PyErr_SetString(PyExc_ValueError,
6643                 "invalid length of packed IP address string");
6644             PyBuffer_Release(&packed_ip);
6645             return NULL;
6646         }
6647 #endif
6648     } else {
6649         PyErr_Format(PyExc_ValueError,
6650             "unknown address family %d", af);
6651         PyBuffer_Release(&packed_ip);
6652         return NULL;
6653     }
6654 
6655     /* inet_ntop guarantee NUL-termination of resulting string. */
6656     retval = inet_ntop(af, packed_ip.buf, ip, sizeof(ip));
6657     if (!retval) {
6658         PyErr_SetFromErrno(PyExc_OSError);
6659         PyBuffer_Release(&packed_ip);
6660         return NULL;
6661     } else {
6662         PyBuffer_Release(&packed_ip);
6663         return PyUnicode_FromString(retval);
6664     }
6665 }
6666 
6667 #endif /* HAVE_INET_PTON */
6668 
6669 #ifdef HAVE_GETADDRINFO
6670 /* Python interface to getaddrinfo(host, port). */
6671 
6672 /*ARGSUSED*/
6673 static PyObject *
6674 socket_getaddrinfo(PyObject *self, PyObject *args, PyObject* kwargs)
6675 {
6676     static char* kwnames[] = {"host", "port", "family", "type", "proto",
6677                               "flags", 0};
6678     struct addrinfo hints, *res;
6679     struct addrinfo *res0 = NULL;
6680     PyObject *hobj = NULL;
6681     PyObject *pobj = (PyObject *)NULL;
6682     PyObject *pstr = NULL;
6683     const char *hptr, *pptr;
6684     int family, socktype, protocol, flags;
6685     int error;
6686     PyObject *all = (PyObject *)NULL;
6687     PyObject *idna = NULL;
6688 
6689     socktype = protocol = flags = 0;
6690     family = AF_UNSPEC;
6691     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|iiii:getaddrinfo",
6692                           kwnames, &hobj, &pobj, &family, &socktype,
6693                           &protocol, &flags)) {
6694         return NULL;
6695     }
6696     if (hobj == Py_None) {
6697         hptr = NULL;
6698     } else if (PyUnicode_Check(hobj)) {
6699         idna = PyUnicode_AsEncodedString(hobj, "idna", NULL);
6700         if (!idna)
6701             return NULL;
6702         assert(PyBytes_Check(idna));
6703         hptr = PyBytes_AS_STRING(idna);
6704     } else if (PyBytes_Check(hobj)) {
6705         hptr = PyBytes_AsString(hobj);
6706     } else {
6707         PyErr_SetString(PyExc_TypeError,
6708                         "getaddrinfo() argument 1 must be string or None");
6709         return NULL;
6710     }
6711     if (PyLong_CheckExact(pobj)) {
6712         pstr = PyObject_Str(pobj);
6713         if (pstr == NULL)
6714             goto err;
6715         assert(PyUnicode_Check(pstr));
6716         pptr = PyUnicode_AsUTF8(pstr);
6717         if (pptr == NULL)
6718             goto err;
6719     } else if (PyUnicode_Check(pobj)) {
6720         pptr = PyUnicode_AsUTF8(pobj);
6721         if (pptr == NULL)
6722             goto err;
6723     } else if (PyBytes_Check(pobj)) {
6724         pptr = PyBytes_AS_STRING(pobj);
6725     } else if (pobj == Py_None) {
6726         pptr = (char *)NULL;
6727     } else {
6728         PyErr_SetString(PyExc_OSError, "Int or String expected");
6729         goto err;
6730     }
6731 #if defined(__APPLE__) && defined(AI_NUMERICSERV)
6732     if ((flags & AI_NUMERICSERV) && (pptr == NULL || (pptr[0] == '0' && pptr[1] == 0))) {
6733         /* On OSX up to at least OSX 10.8 getaddrinfo crashes
6734          * if AI_NUMERICSERV is set and the servname is NULL or "0".
6735          * This workaround avoids a segfault in libsystem.
6736          */
6737         pptr = "00";
6738     }
6739 #endif
6740 
6741     if (PySys_Audit("socket.getaddrinfo", "OOiii",
6742                     hobj, pobj, family, socktype, protocol) < 0) {
6743         return NULL;
6744     }
6745 
6746     memset(&hints, 0, sizeof(hints));
6747     hints.ai_family = family;
6748     hints.ai_socktype = socktype;
6749     hints.ai_protocol = protocol;
6750     hints.ai_flags = flags;
6751     Py_BEGIN_ALLOW_THREADS
6752     error = getaddrinfo(hptr, pptr, &hints, &res0);
6753     Py_END_ALLOW_THREADS
6754     if (error) {
6755         res0 = NULL;  // gh-100795
6756         socket_state *state = get_module_state(self);
6757         set_gaierror(state, error);
6758         goto err;
6759     }
6760 
6761     all = PyList_New(0);
6762     if (all == NULL)
6763         goto err;
6764     for (res = res0; res; res = res->ai_next) {
6765         PyObject *single;
6766         PyObject *addr =
6767             makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
6768         if (addr == NULL)
6769             goto err;
6770         single = Py_BuildValue("iiisO", res->ai_family,
6771             res->ai_socktype, res->ai_protocol,
6772             res->ai_canonname ? res->ai_canonname : "",
6773             addr);
6774         Py_DECREF(addr);
6775         if (single == NULL)
6776             goto err;
6777 
6778         if (PyList_Append(all, single)) {
6779             Py_DECREF(single);
6780             goto err;
6781         }
6782         Py_DECREF(single);
6783     }
6784     Py_XDECREF(idna);
6785     Py_XDECREF(pstr);
6786     if (res0)
6787         freeaddrinfo(res0);
6788     return all;
6789  err:
6790     Py_XDECREF(all);
6791     Py_XDECREF(idna);
6792     Py_XDECREF(pstr);
6793     if (res0)
6794         freeaddrinfo(res0);
6795     return (PyObject *)NULL;
6796 }
6797 
6798 PyDoc_STRVAR(getaddrinfo_doc,
6799 "getaddrinfo(host, port [, family, type, proto, flags])\n\
6800     -> list of (family, type, proto, canonname, sockaddr)\n\
6801 \n\
6802 Resolve host and port into addrinfo struct.");
6803 #endif // HAVE_GETADDRINFO
6804 
6805 #ifdef HAVE_GETNAMEINFO
6806 /* Python interface to getnameinfo(sa, flags). */
6807 
6808 /*ARGSUSED*/
6809 static PyObject *
6810 socket_getnameinfo(PyObject *self, PyObject *args)
6811 {
6812     PyObject *sa = (PyObject *)NULL;
6813     int flags;
6814     const char *hostp;
6815     int port;
6816     unsigned int flowinfo, scope_id;
6817     char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
6818     struct addrinfo hints, *res = NULL;
6819     int error;
6820     PyObject *ret = (PyObject *)NULL;
6821     PyObject *name;
6822 
6823     flags = flowinfo = scope_id = 0;
6824     if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
6825         return NULL;
6826     if (!PyTuple_Check(sa)) {
6827         PyErr_SetString(PyExc_TypeError,
6828                         "getnameinfo() argument 1 must be a tuple");
6829         return NULL;
6830     }
6831     if (!PyArg_ParseTuple(sa, "si|II;getnameinfo(): illegal sockaddr argument",
6832                           &hostp, &port, &flowinfo, &scope_id))
6833     {
6834         return NULL;
6835     }
6836     if (flowinfo > 0xfffff) {
6837         PyErr_SetString(PyExc_OverflowError,
6838                         "getnameinfo(): flowinfo must be 0-1048575.");
6839         return NULL;
6840     }
6841 
6842     if (PySys_Audit("socket.getnameinfo", "(O)", sa) < 0) {
6843         return NULL;
6844     }
6845 
6846     PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
6847     memset(&hints, 0, sizeof(hints));
6848     hints.ai_family = AF_UNSPEC;
6849     hints.ai_socktype = SOCK_DGRAM;     /* make numeric port happy */
6850     hints.ai_flags = AI_NUMERICHOST;    /* don't do any name resolution */
6851     Py_BEGIN_ALLOW_THREADS
6852     error = getaddrinfo(hostp, pbuf, &hints, &res);
6853     Py_END_ALLOW_THREADS
6854     if (error) {
6855         res = NULL;  // gh-100795
6856         socket_state *state = get_module_state(self);
6857         set_gaierror(state, error);
6858         goto fail;
6859     }
6860     if (res->ai_next) {
6861         PyErr_SetString(PyExc_OSError,
6862             "sockaddr resolved to multiple addresses");
6863         goto fail;
6864     }
6865     switch (res->ai_family) {
6866     case AF_INET:
6867         {
6868         if (PyTuple_GET_SIZE(sa) != 2) {
6869             PyErr_SetString(PyExc_OSError,
6870                 "IPv4 sockaddr must be 2 tuple");
6871             goto fail;
6872         }
6873         break;
6874         }
6875 #ifdef ENABLE_IPV6
6876     case AF_INET6:
6877         {
6878         struct sockaddr_in6 *sin6;
6879         sin6 = (struct sockaddr_in6 *)res->ai_addr;
6880         sin6->sin6_flowinfo = htonl(flowinfo);
6881         sin6->sin6_scope_id = scope_id;
6882         break;
6883         }
6884 #endif
6885     }
6886     Py_BEGIN_ALLOW_THREADS
6887     error = getnameinfo(res->ai_addr, (socklen_t) res->ai_addrlen,
6888                     hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
6889     Py_END_ALLOW_THREADS
6890     if (error) {
6891         socket_state *state = get_module_state(self);
6892         set_gaierror(state, error);
6893         goto fail;
6894     }
6895 
6896     name = sock_decode_hostname(hbuf);
6897     if (name == NULL)
6898         goto fail;
6899     ret = Py_BuildValue("Ns", name, pbuf);
6900 
6901 fail:
6902     if (res)
6903         freeaddrinfo(res);
6904     return ret;
6905 }
6906 
6907 PyDoc_STRVAR(getnameinfo_doc,
6908 "getnameinfo(sockaddr, flags) --> (host, port)\n\
6909 \n\
6910 Get host and port for a sockaddr.");
6911 #endif // HAVE_GETNAMEINFO
6912 
6913 /* Python API to getting and setting the default timeout value. */
6914 
6915 static PyObject *
6916 socket_getdefaulttimeout(PyObject *self, PyObject *Py_UNUSED(ignored))
6917 {
6918     socket_state *state = get_module_state(self);
6919     PyTime_t timeout = _Py_atomic_load_int64_relaxed(&state->defaulttimeout);
6920     if (timeout < 0) {
6921         Py_RETURN_NONE;
6922     }
6923     else {
6924         double seconds = PyTime_AsSecondsDouble(timeout);
6925         return PyFloat_FromDouble(seconds);
6926     }
6927 }
6928 
6929 PyDoc_STRVAR(getdefaulttimeout_doc,
6930 "getdefaulttimeout() -> timeout\n\
6931 \n\
6932 Returns the default timeout in seconds (float) for new socket objects.\n\
6933 A value of None indicates that new socket objects have no timeout.\n\
6934 When the socket module is first imported, the default is None.");
6935 
6936 static PyObject *
6937 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
6938 {
6939     PyTime_t timeout;
6940 
6941     if (socket_parse_timeout(&timeout, arg) < 0)
6942         return NULL;
6943 
6944     socket_state *state = get_module_state(self);
6945     _Py_atomic_store_int64_relaxed(&state->defaulttimeout, timeout);
6946 
6947     Py_RETURN_NONE;
6948 }
6949 
6950 PyDoc_STRVAR(setdefaulttimeout_doc,
6951 "setdefaulttimeout(timeout)\n\
6952 \n\
6953 Set the default timeout in seconds (float) for new socket objects.\n\
6954 A value of None indicates that new socket objects have no timeout.\n\
6955 When the socket module is first imported, the default is None.");
6956 
6957 #if defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
6958 /* Python API for getting interface indices and names */
6959 
6960 static PyObject *
6961 socket_if_nameindex(PyObject *self, PyObject *arg)
6962 {
6963     PyObject *list = PyList_New(0);
6964     if (list == NULL) {
6965         return NULL;
6966     }
6967 #ifdef MS_WINDOWS
6968     PMIB_IF_TABLE2 tbl;
6969     int ret;
6970     if ((ret = GetIfTable2Ex(MibIfTableRaw, &tbl)) != NO_ERROR) {
6971         Py_DECREF(list);
6972         // ret is used instead of GetLastError()
6973         return PyErr_SetFromWindowsErr(ret);
6974     }
6975     for (ULONG i = 0; i < tbl->NumEntries; ++i) {
6976         MIB_IF_ROW2 r = tbl->Table[i];
6977         WCHAR buf[NDIS_IF_MAX_STRING_SIZE + 1];
6978         if ((ret = ConvertInterfaceLuidToNameW(&r.InterfaceLuid, buf,
6979                                                Py_ARRAY_LENGTH(buf)))) {
6980             Py_DECREF(list);
6981             FreeMibTable(tbl);
6982             // ret is used instead of GetLastError()
6983             return PyErr_SetFromWindowsErr(ret);
6984         }
6985         PyObject *tuple = Py_BuildValue("Iu", r.InterfaceIndex, buf);
6986         if (tuple == NULL || PyList_Append(list, tuple) == -1) {
6987             Py_XDECREF(tuple);
6988             Py_DECREF(list);
6989             FreeMibTable(tbl);
6990             return NULL;
6991         }
6992         Py_DECREF(tuple);
6993     }
6994     FreeMibTable(tbl);
6995     return list;
6996 #else
6997     int i;
6998     struct if_nameindex *ni;
6999 
7000     ni = if_nameindex();
7001     if (ni == NULL) {
7002         PyErr_SetFromErrno(PyExc_OSError);
7003         Py_DECREF(list);
7004         return NULL;
7005     }
7006 
7007 #ifdef _Py_MEMORY_SANITIZER
7008     __msan_unpoison(ni, sizeof(ni));
7009     __msan_unpoison(&ni[0], sizeof(ni[0]));
7010 #endif
7011     for (i = 0; ni[i].if_index != 0 && i < INT_MAX; i++) {
7012 #ifdef _Py_MEMORY_SANITIZER
7013         /* This one isn't the end sentinel, the next one must exist. */
7014         __msan_unpoison(&ni[i+1], sizeof(ni[0]));
7015         /* Otherwise Py_BuildValue internals are flagged by MSan when
7016            they access the not-msan-tracked if_name string data. */
7017         {
7018             char *to_sanitize = ni[i].if_name;
7019             do {
7020                 __msan_unpoison(to_sanitize, 1);
7021             } while (*to_sanitize++ != '\0');
7022         }
7023 #endif
7024         PyObject *ni_tuple = Py_BuildValue("IO&",
7025                 ni[i].if_index, PyUnicode_DecodeFSDefault, ni[i].if_name);
7026 
7027         if (ni_tuple == NULL || PyList_Append(list, ni_tuple) == -1) {
7028             Py_XDECREF(ni_tuple);
7029             Py_DECREF(list);
7030             if_freenameindex(ni);
7031             return NULL;
7032         }
7033         Py_DECREF(ni_tuple);
7034     }
7035 
7036     if_freenameindex(ni);
7037     return list;
7038 #endif
7039 }
7040 
7041 PyDoc_STRVAR(if_nameindex_doc,
7042 "if_nameindex()\n\
7043 \n\
7044 Returns a list of network interface information (index, name) tuples.");
7045 
7046 /*[clinic input]
7047 _socket.socket.if_nametoindex
7048     oname: object(converter="PyUnicode_FSConverter")
7049     /
7050 
7051 Returns the interface index corresponding to the interface name if_name.
7052 [clinic start generated code]*/
7053 
7054 static PyObject *
7055 _socket_socket_if_nametoindex_impl(PySocketSockObject *self, PyObject *oname)
7056 /*[clinic end generated code: output=f7fc00511a309a8e input=662688054482cd46]*/
7057 {
7058 #ifdef MS_WINDOWS
7059     NET_IFINDEX index;
7060 #else
7061     unsigned long index;
7062 #endif
7063 
7064     index = if_nametoindex(PyBytes_AS_STRING(oname));
7065     Py_DECREF(oname);
7066     if (index == 0) {
7067         /* if_nametoindex() doesn't set errno */
7068         PyErr_SetString(PyExc_OSError, "no interface with this name");
7069         return NULL;
7070     }
7071 
7072     return PyLong_FromUnsignedLong(index);
7073 }
7074 
7075 
7076 static PyObject *
7077 socket_if_indextoname(PyObject *self, PyObject *arg)
7078 {
7079     unsigned long index_long = PyLong_AsUnsignedLong(arg);
7080     if (index_long == (unsigned long) -1 && PyErr_Occurred()) {
7081         return NULL;
7082     }
7083 
7084 #ifdef MS_WINDOWS
7085     NET_IFINDEX index = (NET_IFINDEX)index_long;
7086 #else
7087     unsigned int index = (unsigned int)index_long;
7088 #endif
7089 
7090     if ((unsigned long)index != index_long) {
7091         PyErr_SetString(PyExc_OverflowError, "index is too large");
7092         return NULL;
7093     }
7094 
7095     char name[IF_NAMESIZE + 1];
7096     if (if_indextoname(index, name) == NULL) {
7097         PyErr_SetFromErrno(PyExc_OSError);
7098         return NULL;
7099     }
7100 
7101     return PyUnicode_DecodeFSDefault(name);
7102 }
7103 
7104 PyDoc_STRVAR(if_indextoname_doc,
7105 "if_indextoname(if_index)\n\
7106 \n\
7107 Returns the interface name corresponding to the interface index if_index.");
7108 
7109 #endif // defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
7110 
7111 
7112 #ifdef CMSG_LEN
7113 /* Python interface to CMSG_LEN(length). */
7114 
7115 static PyObject *
7116 socket_CMSG_LEN(PyObject *self, PyObject *args)
7117 {
7118     Py_ssize_t length;
7119     size_t result;
7120 
7121     if (!PyArg_ParseTuple(args, "n:CMSG_LEN", &length))
7122         return NULL;
7123     if (length < 0 || !get_CMSG_LEN(length, &result)) {
7124         PyErr_Format(PyExc_OverflowError, "CMSG_LEN() argument out of range");
7125         return NULL;
7126     }
7127     return PyLong_FromSize_t(result);
7128 }
7129 
7130 PyDoc_STRVAR(CMSG_LEN_doc,
7131 "CMSG_LEN(length) -> control message length\n\
7132 \n\
7133 Return the total length, without trailing padding, of an ancillary\n\
7134 data item with associated data of the given length.  This value can\n\
7135 often be used as the buffer size for recvmsg() to receive a single\n\
7136 item of ancillary data, but RFC 3542 requires portable applications to\n\
7137 use CMSG_SPACE() and thus include space for padding, even when the\n\
7138 item will be the last in the buffer.  Raises OverflowError if length\n\
7139 is outside the permissible range of values.");
7140 
7141 
7142 #ifdef CMSG_SPACE
7143 /* Python interface to CMSG_SPACE(length). */
7144 
7145 static PyObject *
7146 socket_CMSG_SPACE(PyObject *self, PyObject *args)
7147 {
7148     Py_ssize_t length;
7149     size_t result;
7150 
7151     if (!PyArg_ParseTuple(args, "n:CMSG_SPACE", &length))
7152         return NULL;
7153     if (length < 0 || !get_CMSG_SPACE(length, &result)) {
7154         PyErr_SetString(PyExc_OverflowError,
7155                         "CMSG_SPACE() argument out of range");
7156         return NULL;
7157     }
7158     return PyLong_FromSize_t(result);
7159 }
7160 
7161 PyDoc_STRVAR(CMSG_SPACE_doc,
7162 "CMSG_SPACE(length) -> buffer size\n\
7163 \n\
7164 Return the buffer size needed for recvmsg() to receive an ancillary\n\
7165 data item with associated data of the given length, along with any\n\
7166 trailing padding.  The buffer space needed to receive multiple items\n\
7167 is the sum of the CMSG_SPACE() values for their associated data\n\
7168 lengths.  Raises OverflowError if length is outside the permissible\n\
7169 range of values.");
7170 #endif    /* CMSG_SPACE */
7171 #endif    /* CMSG_LEN */
7172 
7173 
7174 /* List of functions exported by this module. */
7175 
7176 static PyMethodDef socket_methods[] = {
7177 #ifdef HAVE_GETADDRINFO
7178     {"gethostbyname",           socket_gethostbyname,
7179      METH_VARARGS, gethostbyname_doc},
7180 #endif
7181 #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME)
7182     {"gethostbyname_ex",        socket_gethostbyname_ex,
7183      METH_VARARGS, ghbn_ex_doc},
7184 #endif
7185 #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYADDR)
7186     {"gethostbyaddr",           socket_gethostbyaddr,
7187      METH_VARARGS, gethostbyaddr_doc},
7188 #endif
7189 #ifdef HAVE_GETHOSTNAME
7190     {"gethostname",             socket_gethostname,
7191      METH_NOARGS,  gethostname_doc},
7192 #endif
7193 #ifdef HAVE_SETHOSTNAME
7194     {"sethostname",             socket_sethostname,
7195      METH_VARARGS,  sethostname_doc},
7196 #endif
7197 #ifdef HAVE_GETSERVBYNAME
7198     {"getservbyname",           socket_getservbyname,
7199      METH_VARARGS, getservbyname_doc},
7200 #endif
7201 #ifdef HAVE_GETSERVBYPORT
7202     {"getservbyport",           socket_getservbyport,
7203      METH_VARARGS, getservbyport_doc},
7204 #endif
7205 #ifdef HAVE_GETPROTOBYNAME
7206     {"getprotobyname",          socket_getprotobyname,
7207      METH_VARARGS, getprotobyname_doc},
7208 #endif
7209     {"close",                   socket_close,
7210      METH_O, close_doc},
7211 #ifndef NO_DUP
7212     {"dup",                     socket_dup,
7213      METH_O, dup_doc},
7214 #endif
7215 #ifdef HAVE_SOCKETPAIR
7216     {"socketpair",              socket_socketpair,
7217      METH_VARARGS, socketpair_doc},
7218 #endif
7219     _SOCKET_SOCKET_NTOHS_METHODDEF
7220     {"ntohl",                   socket_ntohl,
7221      METH_O, ntohl_doc},
7222     _SOCKET_SOCKET_HTONS_METHODDEF
7223     {"htonl",                   socket_htonl,
7224      METH_O, htonl_doc},
7225     _SOCKET_SOCKET_INET_ATON_METHODDEF
7226 #ifdef HAVE_INET_NTOA
7227     _SOCKET_SOCKET_INET_NTOA_METHODDEF
7228 #endif
7229 #ifdef HAVE_INET_PTON
7230     {"inet_pton",               socket_inet_pton,
7231      METH_VARARGS, inet_pton_doc},
7232     {"inet_ntop",               socket_inet_ntop,
7233      METH_VARARGS, inet_ntop_doc},
7234 #endif
7235 #ifdef HAVE_GETADDRINFO
7236     {"getaddrinfo",             _PyCFunction_CAST(socket_getaddrinfo),
7237      METH_VARARGS | METH_KEYWORDS, getaddrinfo_doc},
7238 #endif
7239 #ifdef HAVE_GETNAMEINFO
7240     {"getnameinfo",             socket_getnameinfo,
7241      METH_VARARGS, getnameinfo_doc},
7242 #endif
7243     {"getdefaulttimeout",       socket_getdefaulttimeout,
7244      METH_NOARGS, getdefaulttimeout_doc},
7245     {"setdefaulttimeout",       socket_setdefaulttimeout,
7246      METH_O, setdefaulttimeout_doc},
7247 #if defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
7248     {"if_nameindex", socket_if_nameindex,
7249      METH_NOARGS, if_nameindex_doc},
7250     _SOCKET_SOCKET_IF_NAMETOINDEX_METHODDEF
7251     {"if_indextoname", socket_if_indextoname,
7252      METH_O, if_indextoname_doc},
7253 #endif
7254 #ifdef CMSG_LEN
7255     {"CMSG_LEN",                socket_CMSG_LEN,
7256      METH_VARARGS, CMSG_LEN_doc},
7257 #ifdef CMSG_SPACE
7258     {"CMSG_SPACE",              socket_CMSG_SPACE,
7259      METH_VARARGS, CMSG_SPACE_doc},
7260 #endif
7261 #endif
7262     {NULL,                      NULL}            /* Sentinel */
7263 };
7264 
7265 
7266 #ifdef MS_WINDOWS
7267 #define OS_INIT_DEFINED
7268 
7269 /* Additional initialization and cleanup for Windows */
7270 
7271 static void
7272 os_cleanup(void)
7273 {
7274     WSACleanup();
7275 }
7276 
7277 static int
7278 os_init(void)
7279 {
7280     WSADATA WSAData;
7281     int ret;
7282     ret = WSAStartup(0x0101, &WSAData);
7283     switch (ret) {
7284     case 0:     /* No error */
7285         Py_AtExit(os_cleanup);
7286         return 1; /* Success */
7287     case WSASYSNOTREADY:
7288         PyErr_SetString(PyExc_ImportError,
7289                         "WSAStartup failed: network not ready");
7290         break;
7291     case WSAVERNOTSUPPORTED:
7292     case WSAEINVAL:
7293         PyErr_SetString(
7294             PyExc_ImportError,
7295             "WSAStartup failed: requested version not supported");
7296         break;
7297     default:
7298         PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret);
7299         break;
7300     }
7301     return 0; /* Failure */
7302 }
7303 
7304 #endif /* MS_WINDOWS */
7305 
7306 
7307 
7308 #ifndef OS_INIT_DEFINED
7309 static int
7310 os_init(void)
7311 {
7312     return 1; /* Success */
7313 }
7314 #endif
7315 
7316 static int
7317 sock_capi_traverse(PyObject *capsule, visitproc visit, void *arg)
7318 {
7319     PySocketModule_APIObject *capi = PyCapsule_GetPointer(capsule, PySocket_CAPSULE_NAME);
7320     assert(capi != NULL);
7321     Py_VISIT(capi->Sock_Type);
7322     return 0;
7323 }
7324 
7325 static int
7326 sock_capi_clear(PyObject *capsule)
7327 {
7328     PySocketModule_APIObject *capi = PyCapsule_GetPointer(capsule, PySocket_CAPSULE_NAME);
7329     assert(capi != NULL);
7330     Py_CLEAR(capi->Sock_Type);
7331     return 0;
7332 }
7333 
7334 static void
7335 sock_capi_free(PySocketModule_APIObject *capi)
7336 {
7337     Py_XDECREF(capi->Sock_Type);  // sock_capi_free() can clear it
7338     Py_DECREF(capi->error);
7339     Py_DECREF(capi->timeout_error);
7340     PyMem_Free(capi);
7341 }
7342 
7343 static void
7344 sock_capi_destroy(PyObject *capsule)
7345 {
7346     void *capi = PyCapsule_GetPointer(capsule, PySocket_CAPSULE_NAME);
7347     assert(capi != NULL);
7348     sock_capi_free(capi);
7349 }
7350 
7351 static PySocketModule_APIObject *
7352 sock_get_api(socket_state *state)
7353 {
7354     PySocketModule_APIObject *capi = PyMem_Malloc(sizeof(PySocketModule_APIObject));
7355     if (capi == NULL) {
7356         PyErr_NoMemory();
7357         return NULL;
7358     }
7359 
7360     capi->Sock_Type = (PyTypeObject *)Py_NewRef(state->sock_type);
7361     capi->error = Py_NewRef(PyExc_OSError);
7362     capi->timeout_error = Py_NewRef(PyExc_TimeoutError);
7363     return capi;
7364 }
7365 
7366 
7367 /* Initialize the _socket module.
7368 
7369    This module is actually called "_socket", and there's a wrapper
7370    "socket.py" which implements some additional functionality.
7371    The import of "_socket" may fail with an ImportError exception if
7372    os-specific initialization fails.  On Windows, this does WINSOCK
7373    initialization.  When WINSOCK is initialized successfully, a call to
7374    WSACleanup() is scheduled to be made at exit time.
7375 */
7376 
7377 PyDoc_STRVAR(socket_doc,
7378 "Implementation module for socket operations.\n\
7379 \n\
7380 See the socket module for documentation.");
7381 
7382 static int
7383 socket_exec(PyObject *m)
7384 {
7385     if (!os_init()) {
7386         goto error;
7387     }
7388 
7389     socket_state *state = get_module_state(m);
7390     state->defaulttimeout = _PYTIME_FROMSECONDS(-1);
7391 
7392 #if defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
7393 #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
7394     state->accept4_works = -1;
7395 #endif
7396 #endif
7397 
7398 #ifdef SOCK_CLOEXEC
7399     state->sock_cloexec_works = -1;
7400 #endif
7401 
7402 #define ADD_EXC(MOD, NAME, VAR, BASE) do {                  \
7403     VAR = PyErr_NewException("socket." NAME, BASE, NULL);   \
7404     if (VAR == NULL) {                                      \
7405         goto error;                                         \
7406     }                                                       \
7407     if (PyModule_AddObjectRef(MOD, NAME, VAR) < 0) {        \
7408         goto error;                                         \
7409     }                                                       \
7410 } while (0)
7411 
7412     ADD_EXC(m, "herror", state->socket_herror, PyExc_OSError);
7413     ADD_EXC(m, "gaierror", state->socket_gaierror, PyExc_OSError);
7414 
7415 #undef ADD_EXC
7416 
7417     if (PyModule_AddObjectRef(m, "error", PyExc_OSError) < 0) {
7418         goto error;
7419     }
7420     if (PyModule_AddObjectRef(m, "timeout", PyExc_TimeoutError) < 0) {
7421         goto error;
7422     }
7423 
7424     PyObject *sock_type = PyType_FromMetaclass(NULL, m, &sock_spec, NULL);
7425     if (sock_type == NULL) {
7426         goto error;
7427     }
7428     state->sock_type = (PyTypeObject *)sock_type;
7429     if (PyModule_AddObjectRef(m, "SocketType", sock_type) < 0) {
7430         goto error;
7431     }
7432     if (PyModule_AddType(m, state->sock_type) < 0) {
7433         goto error;
7434     }
7435 
7436     PyObject *has_ipv6;
7437 #ifdef ENABLE_IPV6
7438     has_ipv6 = Py_True;
7439 #else
7440     has_ipv6 = Py_False;
7441 #endif
7442     if (PyModule_AddObjectRef(m, "has_ipv6", has_ipv6) < 0) {
7443         goto error;
7444     }
7445 
7446     /* Export C API */
7447     PySocketModule_APIObject *capi = sock_get_api(state);
7448     if (capi == NULL) {
7449         goto error;
7450     }
7451     PyObject *capsule = PyCapsule_New(capi,
7452                                       PySocket_CAPSULE_NAME,
7453                                       sock_capi_destroy);
7454     if (capsule == NULL) {
7455         sock_capi_free(capi);
7456         goto error;
7457     }
7458     if (_PyCapsule_SetTraverse(capsule,
7459                                sock_capi_traverse, sock_capi_clear) < 0) {
7460         sock_capi_free(capi);
7461         goto error;
7462     }
7463 
7464     if (PyModule_Add(m, PySocket_CAPI_NAME, capsule) < 0) {
7465         goto error;
7466     }
7467 
7468 #define ADD_INT_MACRO(MOD, INT) do {                    \
7469     if (PyModule_AddIntConstant(MOD, #INT, INT) < 0) {  \
7470         goto error;                                     \
7471     }                                                   \
7472 } while (0)
7473 
7474 #define ADD_INT_CONST(MOD, NAME, INT) do {              \
7475     if (PyModule_AddIntConstant(MOD, NAME, INT) < 0) {  \
7476         goto error;                                     \
7477     }                                                   \
7478 } while (0)
7479 
7480 #define ADD_STR_CONST(MOD, NAME, STR) do {                  \
7481     if (PyModule_AddStringConstant(MOD, NAME, STR) < 0) {   \
7482         goto error;                                         \
7483     }                                                       \
7484 } while (0)
7485 
7486     /* Address families (we only support AF_INET and AF_UNIX) */
7487 #ifdef AF_UNSPEC
7488     ADD_INT_MACRO(m, AF_UNSPEC);
7489 #endif
7490     ADD_INT_MACRO(m, AF_INET);
7491 #if defined(AF_UNIX)
7492     ADD_INT_MACRO(m, AF_UNIX);
7493 #endif /* AF_UNIX */
7494 #ifdef AF_AX25
7495     /* Amateur Radio AX.25 */
7496     ADD_INT_MACRO(m, AF_AX25);
7497 #endif
7498 #ifdef AF_IPX
7499     ADD_INT_MACRO(m, AF_IPX); /* Novell IPX */
7500 #endif
7501 #ifdef AF_APPLETALK
7502     /* Appletalk DDP */
7503     ADD_INT_MACRO(m, AF_APPLETALK);
7504 #endif
7505 #ifdef AF_NETROM
7506     /* Amateur radio NetROM */
7507     ADD_INT_MACRO(m, AF_NETROM);
7508 #endif
7509 #ifdef AF_BRIDGE
7510     /* Multiprotocol bridge */
7511     ADD_INT_MACRO(m, AF_BRIDGE);
7512 #endif
7513 #ifdef AF_ATMPVC
7514     /* ATM PVCs */
7515     ADD_INT_MACRO(m, AF_ATMPVC);
7516 #endif
7517 #ifdef AF_AAL5
7518     /* Reserved for Werner's ATM */
7519     ADD_INT_MACRO(m, AF_AAL5);
7520 #endif
7521 #ifdef HAVE_SOCKADDR_ALG
7522     ADD_INT_MACRO(m, AF_ALG); /* Linux crypto */
7523 #endif
7524 #ifdef AF_X25
7525     /* Reserved for X.25 project */
7526     ADD_INT_MACRO(m, AF_X25);
7527 #endif
7528 #ifdef AF_INET6
7529     ADD_INT_MACRO(m, AF_INET6); /* IP version 6 */
7530 #endif
7531 #ifdef AF_ROSE
7532     /* Amateur Radio X.25 PLP */
7533     ADD_INT_MACRO(m, AF_ROSE);
7534 #endif
7535 #ifdef AF_DECnet
7536     /* Reserved for DECnet project */
7537     ADD_INT_MACRO(m, AF_DECnet);
7538 #endif
7539 #ifdef AF_NETBEUI
7540     /* Reserved for 802.2LLC project */
7541     ADD_INT_MACRO(m, AF_NETBEUI);
7542 #endif
7543 #ifdef AF_SECURITY
7544     /* Security callback pseudo AF */
7545     ADD_INT_MACRO(m, AF_SECURITY);
7546 #endif
7547 #ifdef AF_KEY
7548     /* PF_KEY key management API */
7549     ADD_INT_MACRO(m, AF_KEY);
7550 #endif
7551 #ifdef AF_NETLINK
7552     /*  */
7553     ADD_INT_MACRO(m, AF_NETLINK);
7554     ADD_INT_MACRO(m, NETLINK_ROUTE);
7555 #ifdef NETLINK_SKIP
7556     ADD_INT_MACRO(m, NETLINK_SKIP);
7557 #endif
7558 #ifdef NETLINK_W1
7559     ADD_INT_MACRO(m, NETLINK_W1);
7560 #endif
7561     ADD_INT_MACRO(m, NETLINK_USERSOCK);
7562     ADD_INT_MACRO(m, NETLINK_FIREWALL);
7563 #ifdef NETLINK_TCPDIAG
7564     ADD_INT_MACRO(m, NETLINK_TCPDIAG);
7565 #endif
7566 #ifdef NETLINK_NFLOG
7567     ADD_INT_MACRO(m, NETLINK_NFLOG);
7568 #endif
7569 #ifdef NETLINK_XFRM
7570     ADD_INT_MACRO(m, NETLINK_XFRM);
7571 #endif
7572 #ifdef NETLINK_ARPD
7573     ADD_INT_MACRO(m, NETLINK_ARPD);
7574 #endif
7575 #ifdef NETLINK_ROUTE6
7576     ADD_INT_MACRO(m, NETLINK_ROUTE6);
7577 #endif
7578     ADD_INT_MACRO(m, NETLINK_IP6_FW);
7579 #ifdef NETLINK_DNRTMSG
7580     ADD_INT_MACRO(m, NETLINK_DNRTMSG);
7581 #endif
7582 #ifdef NETLINK_TAPBASE
7583     ADD_INT_MACRO(m, NETLINK_TAPBASE);
7584 #endif
7585 #ifdef NETLINK_CRYPTO
7586     ADD_INT_MACRO(m, NETLINK_CRYPTO);
7587 #endif
7588 #endif /* AF_NETLINK */
7589 
7590 #ifdef AF_QIPCRTR
7591     /* Qualcomm IPCROUTER */
7592     ADD_INT_MACRO(m, AF_QIPCRTR);
7593 #endif
7594 
7595 #ifdef AF_VSOCK
7596     ADD_INT_CONST(m, "AF_VSOCK", AF_VSOCK);
7597     ADD_INT_CONST(m, "SO_VM_SOCKETS_BUFFER_SIZE", 0);
7598     ADD_INT_CONST(m, "SO_VM_SOCKETS_BUFFER_MIN_SIZE", 1);
7599     ADD_INT_CONST(m, "SO_VM_SOCKETS_BUFFER_MAX_SIZE", 2);
7600     ADD_INT_CONST(m, "VMADDR_CID_ANY", 0xffffffff);
7601     ADD_INT_CONST(m, "VMADDR_PORT_ANY", 0xffffffff);
7602     ADD_INT_CONST(m, "VMADDR_CID_HOST", 2);
7603     ADD_INT_CONST(m, "VM_SOCKETS_INVALID_VERSION", 0xffffffff);
7604     ADD_INT_CONST(m, "IOCTL_VM_SOCKETS_GET_LOCAL_CID",  _IO(7, 0xb9));
7605 #endif
7606 
7607 #ifdef AF_ROUTE
7608     /* Alias to emulate 4.4BSD */
7609     ADD_INT_MACRO(m, AF_ROUTE);
7610 #endif
7611 #ifdef AF_LINK
7612     ADD_INT_MACRO(m, AF_LINK);
7613 #endif
7614 #ifdef AF_ASH
7615     /* Ash */
7616     ADD_INT_MACRO(m, AF_ASH);
7617 #endif
7618 #ifdef AF_ECONET
7619     /* Acorn Econet */
7620     ADD_INT_MACRO(m, AF_ECONET);
7621 #endif
7622 #ifdef AF_ATMSVC
7623     /* ATM SVCs */
7624     ADD_INT_MACRO(m, AF_ATMSVC);
7625 #endif
7626 #ifdef AF_SNA
7627     /* Linux SNA Project (nutters!) */
7628     ADD_INT_MACRO(m, AF_SNA);
7629 #endif
7630 #ifdef AF_IRDA
7631     /* IRDA sockets */
7632     ADD_INT_MACRO(m, AF_IRDA);
7633 #endif
7634 #ifdef AF_PPPOX
7635     /* PPPoX sockets */
7636     ADD_INT_MACRO(m, AF_PPPOX);
7637 #endif
7638 #ifdef AF_WANPIPE
7639     /* Wanpipe API Sockets */
7640     ADD_INT_MACRO(m, AF_WANPIPE);
7641 #endif
7642 #ifdef AF_LLC
7643     /* Linux LLC */
7644     ADD_INT_MACRO(m, AF_LLC);
7645 #endif
7646 #ifdef HAVE_AF_HYPERV
7647     /* Hyper-V sockets */
7648     ADD_INT_MACRO(m, AF_HYPERV);
7649 
7650     /* for proto */
7651     ADD_INT_MACRO(m, HV_PROTOCOL_RAW);
7652 
7653     /* for setsockopt() */
7654     ADD_INT_MACRO(m, HVSOCKET_CONNECT_TIMEOUT);
7655     ADD_INT_MACRO(m, HVSOCKET_CONNECT_TIMEOUT_MAX);
7656     ADD_INT_MACRO(m, HVSOCKET_CONNECTED_SUSPEND);
7657     ADD_INT_MACRO(m, HVSOCKET_ADDRESS_FLAG_PASSTHRU);
7658 
7659     /* for bind() or connect() */
7660     ADD_STR_CONST(m, "HV_GUID_ZERO", "00000000-0000-0000-0000-000000000000");
7661     ADD_STR_CONST(m, "HV_GUID_WILDCARD", "00000000-0000-0000-0000-000000000000");
7662     ADD_STR_CONST(m, "HV_GUID_BROADCAST", "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF");
7663     ADD_STR_CONST(m, "HV_GUID_CHILDREN", "90DB8B89-0D35-4F79-8CE9-49EA0AC8B7CD");
7664     ADD_STR_CONST(m, "HV_GUID_LOOPBACK", "E0E16197-DD56-4A10-9195-5EE7A155A838");
7665     ADD_STR_CONST(m, "HV_GUID_PARENT", "A42E7CDA-D03F-480C-9CC2-A4DE20ABB878");
7666 #endif /* HAVE_AF_HYPERV */
7667 
7668 #ifdef USE_BLUETOOTH
7669     ADD_INT_MACRO(m, AF_BLUETOOTH);
7670 #ifdef BTPROTO_L2CAP
7671     ADD_INT_MACRO(m, BTPROTO_L2CAP);
7672 #endif /* BTPROTO_L2CAP */
7673 #ifdef BTPROTO_HCI
7674     ADD_INT_MACRO(m, BTPROTO_HCI);
7675     ADD_INT_MACRO(m, SOL_HCI);
7676 #if !defined(__NetBSD__) && !defined(__DragonFly__)
7677     ADD_INT_MACRO(m, HCI_FILTER);
7678 #if !defined(__FreeBSD__)
7679     ADD_INT_MACRO(m, HCI_TIME_STAMP);
7680     ADD_INT_MACRO(m, HCI_DATA_DIR);
7681 #endif /* !__FreeBSD__ */
7682 #endif /* !__NetBSD__ && !__DragonFly__ */
7683 #endif /* BTPROTO_HCI */
7684 #ifdef BTPROTO_RFCOMM
7685     ADD_INT_MACRO(m, BTPROTO_RFCOMM);
7686 #endif /* BTPROTO_RFCOMM */
7687     ADD_STR_CONST(m, "BDADDR_ANY", "00:00:00:00:00:00");
7688     ADD_STR_CONST(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
7689 #ifdef BTPROTO_SCO
7690     ADD_INT_MACRO(m, BTPROTO_SCO);
7691 #endif /* BTPROTO_SCO */
7692 #endif /* USE_BLUETOOTH */
7693 
7694 #ifdef AF_CAN
7695     /* Controller Area Network */
7696     ADD_INT_MACRO(m, AF_CAN);
7697 #endif
7698 #ifdef PF_CAN
7699     /* Controller Area Network */
7700     ADD_INT_MACRO(m, PF_CAN);
7701 #endif
7702 
7703 /* Reliable Datagram Sockets */
7704 #ifdef AF_RDS
7705     ADD_INT_MACRO(m, AF_RDS);
7706 #endif
7707 #ifdef PF_RDS
7708     ADD_INT_MACRO(m, PF_RDS);
7709 #endif
7710 
7711 /* Kernel event messages */
7712 #ifdef PF_SYSTEM
7713     ADD_INT_MACRO(m, PF_SYSTEM);
7714 #endif
7715 #ifdef AF_SYSTEM
7716     ADD_INT_MACRO(m, AF_SYSTEM);
7717 #endif
7718 
7719 /* FreeBSD divert(4) */
7720 #ifdef PF_DIVERT
7721     ADD_INT_MACRO(m, PF_DIVERT);
7722 #endif
7723 #ifdef AF_DIVERT
7724     ADD_INT_MACRO(m, AF_DIVERT);
7725 #endif
7726 
7727 #ifdef AF_PACKET
7728     ADD_INT_MACRO(m, AF_PACKET);
7729 #endif
7730 #ifdef PF_PACKET
7731     ADD_INT_MACRO(m, PF_PACKET);
7732 #endif
7733 #ifdef PACKET_HOST
7734     ADD_INT_MACRO(m, PACKET_HOST);
7735 #endif
7736 #ifdef PACKET_BROADCAST
7737     ADD_INT_MACRO(m, PACKET_BROADCAST);
7738 #endif
7739 #ifdef PACKET_MULTICAST
7740     ADD_INT_MACRO(m, PACKET_MULTICAST);
7741 #endif
7742 #ifdef PACKET_OTHERHOST
7743     ADD_INT_MACRO(m, PACKET_OTHERHOST);
7744 #endif
7745 #ifdef PACKET_OUTGOING
7746     ADD_INT_MACRO(m, PACKET_OUTGOING);
7747 #endif
7748 #ifdef PACKET_LOOPBACK
7749     ADD_INT_MACRO(m, PACKET_LOOPBACK);
7750 #endif
7751 #ifdef PACKET_FASTROUTE
7752     ADD_INT_MACRO(m, PACKET_FASTROUTE);
7753 #endif
7754 
7755 #ifdef HAVE_LINUX_TIPC_H
7756     ADD_INT_MACRO(m, AF_TIPC);
7757 
7758     /* for addresses */
7759     ADD_INT_MACRO(m, TIPC_ADDR_NAMESEQ);
7760     ADD_INT_MACRO(m, TIPC_ADDR_NAME);
7761     ADD_INT_MACRO(m, TIPC_ADDR_ID);
7762 
7763     ADD_INT_MACRO(m, TIPC_ZONE_SCOPE);
7764     ADD_INT_MACRO(m, TIPC_CLUSTER_SCOPE);
7765     ADD_INT_MACRO(m, TIPC_NODE_SCOPE);
7766 
7767     /* for setsockopt() */
7768     ADD_INT_MACRO(m, SOL_TIPC);
7769     ADD_INT_MACRO(m, TIPC_IMPORTANCE);
7770     ADD_INT_MACRO(m, TIPC_SRC_DROPPABLE);
7771     ADD_INT_MACRO(m, TIPC_DEST_DROPPABLE);
7772     ADD_INT_MACRO(m, TIPC_CONN_TIMEOUT);
7773 
7774     ADD_INT_MACRO(m, TIPC_LOW_IMPORTANCE);
7775     ADD_INT_MACRO(m, TIPC_MEDIUM_IMPORTANCE);
7776     ADD_INT_MACRO(m, TIPC_HIGH_IMPORTANCE);
7777     ADD_INT_MACRO(m, TIPC_CRITICAL_IMPORTANCE);
7778 
7779     /* for subscriptions */
7780     ADD_INT_MACRO(m, TIPC_SUB_PORTS);
7781     ADD_INT_MACRO(m, TIPC_SUB_SERVICE);
7782 #ifdef TIPC_SUB_CANCEL
7783     /* doesn't seem to be available everywhere */
7784     ADD_INT_MACRO(m, TIPC_SUB_CANCEL);
7785 #endif
7786     ADD_INT_MACRO(m, TIPC_WAIT_FOREVER);
7787     ADD_INT_MACRO(m, TIPC_PUBLISHED);
7788     ADD_INT_MACRO(m, TIPC_WITHDRAWN);
7789     ADD_INT_MACRO(m, TIPC_SUBSCR_TIMEOUT);
7790     ADD_INT_MACRO(m, TIPC_CFG_SRV);
7791     ADD_INT_MACRO(m, TIPC_TOP_SRV);
7792 #endif
7793 
7794 #ifdef HAVE_SOCKADDR_ALG
7795     /* Socket options */
7796     ADD_INT_MACRO(m, ALG_SET_KEY);
7797     ADD_INT_MACRO(m, ALG_SET_IV);
7798     ADD_INT_MACRO(m, ALG_SET_OP);
7799     ADD_INT_MACRO(m, ALG_SET_AEAD_ASSOCLEN);
7800     ADD_INT_MACRO(m, ALG_SET_AEAD_AUTHSIZE);
7801     ADD_INT_MACRO(m, ALG_SET_PUBKEY);
7802 
7803     /* Operations */
7804     ADD_INT_MACRO(m, ALG_OP_DECRYPT);
7805     ADD_INT_MACRO(m, ALG_OP_ENCRYPT);
7806     ADD_INT_MACRO(m, ALG_OP_SIGN);
7807     ADD_INT_MACRO(m, ALG_OP_VERIFY);
7808 #endif
7809 
7810 /* IEEE 802.3 protocol numbers required for a standard TCP/IP network stack */
7811 #ifdef ETHERTYPE_ARP
7812     ADD_INT_MACRO(m, ETHERTYPE_ARP);
7813 #endif
7814 #ifdef ETHERTYPE_IP
7815     ADD_INT_MACRO(m, ETHERTYPE_IP);
7816 #endif
7817 #ifdef ETHERTYPE_IPV6
7818     ADD_INT_MACRO(m, ETHERTYPE_IPV6);
7819 #endif
7820 #ifdef ETHERTYPE_VLAN
7821     ADD_INT_MACRO(m, ETHERTYPE_VLAN);
7822 #endif
7823 
7824 /* Linux pseudo-protocol for sniffing every packet */
7825 #ifdef ETH_P_ALL
7826     ADD_INT_MACRO(m, ETH_P_ALL);
7827 #endif
7828 
7829     /* Socket types */
7830     ADD_INT_MACRO(m, SOCK_STREAM);
7831     ADD_INT_MACRO(m, SOCK_DGRAM);
7832 /* We have incomplete socket support. */
7833 #ifdef SOCK_RAW
7834     /* SOCK_RAW is marked as optional in the POSIX specification */
7835     ADD_INT_MACRO(m, SOCK_RAW);
7836 #endif
7837 #ifdef SOCK_SEQPACKET
7838     ADD_INT_MACRO(m, SOCK_SEQPACKET);
7839 #endif
7840 #if defined(SOCK_RDM)
7841     ADD_INT_MACRO(m, SOCK_RDM);
7842 #endif
7843 #ifdef SOCK_CLOEXEC
7844     ADD_INT_MACRO(m, SOCK_CLOEXEC);
7845 #endif
7846 #ifdef SOCK_NONBLOCK
7847     ADD_INT_MACRO(m, SOCK_NONBLOCK);
7848 #endif
7849 
7850 #ifdef  SO_DEBUG
7851     ADD_INT_MACRO(m, SO_DEBUG);
7852 #endif
7853 #ifdef  SO_ACCEPTCONN
7854     ADD_INT_MACRO(m, SO_ACCEPTCONN);
7855 #endif
7856 #ifdef  SO_REUSEADDR
7857     ADD_INT_MACRO(m, SO_REUSEADDR);
7858 #endif
7859 #ifdef SO_EXCLUSIVEADDRUSE
7860     ADD_INT_MACRO(m, SO_EXCLUSIVEADDRUSE);
7861 #endif
7862 #ifdef SO_INCOMING_CPU
7863     ADD_INT_MACRO(m, SO_INCOMING_CPU);
7864 #endif
7865 
7866 #ifdef  SO_KEEPALIVE
7867     ADD_INT_MACRO(m, SO_KEEPALIVE);
7868 #endif
7869 #ifdef  SO_DONTROUTE
7870     ADD_INT_MACRO(m, SO_DONTROUTE);
7871 #endif
7872 #ifdef  SO_BROADCAST
7873     ADD_INT_MACRO(m, SO_BROADCAST);
7874 #endif
7875 #ifdef  SO_USELOOPBACK
7876     ADD_INT_MACRO(m, SO_USELOOPBACK);
7877 #endif
7878 #ifdef  SO_LINGER
7879     ADD_INT_MACRO(m, SO_LINGER);
7880 #endif
7881 #ifdef  SO_OOBINLINE
7882     ADD_INT_MACRO(m, SO_OOBINLINE);
7883 #endif
7884 #ifndef __GNU__
7885 #ifdef  SO_REUSEPORT
7886     ADD_INT_MACRO(m, SO_REUSEPORT);
7887 #endif
7888 #endif
7889 #ifdef  SO_SNDBUF
7890     ADD_INT_MACRO(m, SO_SNDBUF);
7891 #endif
7892 #ifdef  SO_RCVBUF
7893     ADD_INT_MACRO(m, SO_RCVBUF);
7894 #endif
7895 #ifdef  SO_SNDLOWAT
7896     ADD_INT_MACRO(m, SO_SNDLOWAT);
7897 #endif
7898 #ifdef  SO_RCVLOWAT
7899     ADD_INT_MACRO(m, SO_RCVLOWAT);
7900 #endif
7901 #ifdef  SO_SNDTIMEO
7902     ADD_INT_MACRO(m, SO_SNDTIMEO);
7903 #endif
7904 #ifdef  SO_RCVTIMEO
7905     ADD_INT_MACRO(m, SO_RCVTIMEO);
7906 #endif
7907 #ifdef  SO_ERROR
7908     ADD_INT_MACRO(m, SO_ERROR);
7909 #endif
7910 #ifdef  SO_TYPE
7911     ADD_INT_MACRO(m, SO_TYPE);
7912 #endif
7913 #ifdef  SO_SETFIB
7914     ADD_INT_MACRO(m, SO_SETFIB);
7915 #endif
7916 #ifdef  SO_PASSCRED
7917     ADD_INT_MACRO(m, SO_PASSCRED);
7918 #endif
7919 #ifdef  SO_PEERCRED
7920     ADD_INT_MACRO(m, SO_PEERCRED);
7921 #endif
7922 #ifdef  LOCAL_PEERCRED
7923     ADD_INT_MACRO(m, LOCAL_PEERCRED);
7924 #endif
7925 #ifdef  SO_PASSSEC
7926     ADD_INT_MACRO(m, SO_PASSSEC);
7927 #endif
7928 #ifdef  SO_PEERSEC
7929     ADD_INT_MACRO(m, SO_PEERSEC);
7930 #endif
7931 #ifdef  SO_BINDTODEVICE
7932     ADD_INT_MACRO(m, SO_BINDTODEVICE);
7933 #endif
7934 #ifdef  SO_BINDTOIFINDEX
7935     ADD_INT_MACRO(m, SO_BINDTOIFINDEX);
7936 #endif
7937 #ifdef  SO_PRIORITY
7938     ADD_INT_MACRO(m, SO_PRIORITY);
7939 #endif
7940 #ifdef  SO_MARK
7941     ADD_INT_MACRO(m, SO_MARK);
7942 #endif
7943 #ifdef  SO_USER_COOKIE
7944     ADD_INT_MACRO(m, SO_USER_COOKIE);
7945 #endif
7946 #ifdef  SO_RTABLE
7947     ADD_INT_MACRO(m, SO_RTABLE);
7948 #endif
7949 #ifdef SO_DOMAIN
7950     ADD_INT_MACRO(m, SO_DOMAIN);
7951 #endif
7952 #ifdef SO_PROTOCOL
7953     ADD_INT_MACRO(m, SO_PROTOCOL);
7954 #endif
7955 #ifdef LOCAL_CREDS
7956     ADD_INT_MACRO(m, LOCAL_CREDS);
7957 #endif
7958 #ifdef LOCAL_CREDS_PERSISTENT
7959     ADD_INT_MACRO(m, LOCAL_CREDS_PERSISTENT);
7960 #endif
7961 
7962     /* Maximum number of connections for "listen" */
7963 #ifdef  SOMAXCONN
7964     ADD_INT_MACRO(m, SOMAXCONN);
7965 #else
7966     ADD_INT_CONST(m, "SOMAXCONN", 5); /* Common value */
7967 #endif
7968 
7969     /* Ancillary message types */
7970 #ifdef  SCM_RIGHTS
7971     ADD_INT_MACRO(m, SCM_RIGHTS);
7972 #endif
7973 #ifdef  SCM_CREDENTIALS
7974     ADD_INT_MACRO(m, SCM_CREDENTIALS);
7975 #endif
7976 #ifdef  SCM_CREDS
7977     ADD_INT_MACRO(m, SCM_CREDS);
7978 #endif
7979 #ifdef  SCM_CREDS2
7980     ADD_INT_MACRO(m, SCM_CREDS2);
7981 #endif
7982 
7983     /* Flags for send, recv */
7984 #ifdef  MSG_OOB
7985     ADD_INT_MACRO(m, MSG_OOB);
7986 #endif
7987 #ifdef  MSG_PEEK
7988     ADD_INT_MACRO(m, MSG_PEEK);
7989 #endif
7990 #ifdef  MSG_DONTROUTE
7991     ADD_INT_MACRO(m, MSG_DONTROUTE);
7992 #endif
7993 #ifdef  MSG_DONTWAIT
7994     ADD_INT_MACRO(m, MSG_DONTWAIT);
7995 #endif
7996 #ifdef  MSG_EOR
7997     ADD_INT_MACRO(m, MSG_EOR);
7998 #endif
7999 #ifdef  MSG_TRUNC
8000     // workaround for https://github.com/WebAssembly/wasi-libc/issues/305
8001     #if defined(__wasi__) && !defined(__WASI_RIFLAGS_RECV_DATA_TRUNCATED)
8002     #  define __WASI_RIFLAGS_RECV_DATA_TRUNCATED 2
8003     #endif
8004     ADD_INT_MACRO(m, MSG_TRUNC);
8005 #endif
8006 #ifdef  MSG_CTRUNC
8007     ADD_INT_MACRO(m, MSG_CTRUNC);
8008 #endif
8009 #ifdef  MSG_WAITALL
8010     ADD_INT_MACRO(m, MSG_WAITALL);
8011 #endif
8012 #ifdef  MSG_BTAG
8013     ADD_INT_MACRO(m, MSG_BTAG);
8014 #endif
8015 #ifdef  MSG_ETAG
8016     ADD_INT_MACRO(m, MSG_ETAG);
8017 #endif
8018 #ifdef  MSG_NOSIGNAL
8019     ADD_INT_MACRO(m, MSG_NOSIGNAL);
8020 #endif
8021 #ifdef  MSG_NOTIFICATION
8022     ADD_INT_MACRO(m, MSG_NOTIFICATION);
8023 #endif
8024 #ifdef  MSG_CMSG_CLOEXEC
8025     ADD_INT_MACRO(m, MSG_CMSG_CLOEXEC);
8026 #endif
8027 #ifdef  MSG_ERRQUEUE
8028     ADD_INT_MACRO(m, MSG_ERRQUEUE);
8029 #endif
8030 #ifdef  MSG_CONFIRM
8031     ADD_INT_MACRO(m, MSG_CONFIRM);
8032 #endif
8033 #ifdef  MSG_MORE
8034     ADD_INT_MACRO(m, MSG_MORE);
8035 #endif
8036 #ifdef  MSG_EOF
8037     ADD_INT_MACRO(m, MSG_EOF);
8038 #endif
8039 #ifdef  MSG_BCAST
8040     ADD_INT_MACRO(m, MSG_BCAST);
8041 #endif
8042 #ifdef  MSG_MCAST
8043     ADD_INT_MACRO(m, MSG_MCAST);
8044 #endif
8045 #ifdef MSG_FASTOPEN
8046     ADD_INT_MACRO(m, MSG_FASTOPEN);
8047 #endif
8048 
8049     /* Protocol level and numbers, usable for [gs]etsockopt */
8050 #ifdef  SOL_SOCKET
8051     ADD_INT_MACRO(m, SOL_SOCKET);
8052 #endif
8053 #ifdef  SOL_IP
8054     ADD_INT_MACRO(m, SOL_IP);
8055 #else
8056     ADD_INT_CONST(m, "SOL_IP", 0);
8057 #endif
8058 #ifdef  SOL_IPX
8059     ADD_INT_MACRO(m, SOL_IPX);
8060 #endif
8061 #ifdef  SOL_AX25
8062     ADD_INT_MACRO(m, SOL_AX25);
8063 #endif
8064 #ifdef  SOL_ATALK
8065     ADD_INT_MACRO(m, SOL_ATALK);
8066 #endif
8067 #ifdef  SOL_NETROM
8068     ADD_INT_MACRO(m, SOL_NETROM);
8069 #endif
8070 #ifdef  SOL_ROSE
8071     ADD_INT_MACRO(m, SOL_ROSE);
8072 #endif
8073 #ifdef  SOL_TCP
8074     ADD_INT_MACRO(m, SOL_TCP);
8075 #else
8076     ADD_INT_CONST(m, "SOL_TCP", 6);
8077 #endif
8078 #ifdef  SOL_UDP
8079     ADD_INT_MACRO(m, SOL_UDP);
8080 #else
8081     ADD_INT_CONST(m, "SOL_UDP", 17);
8082 #endif
8083 #ifdef SOL_CAN_BASE
8084     ADD_INT_MACRO(m, SOL_CAN_BASE);
8085 #endif
8086 #ifdef SOL_CAN_RAW
8087     ADD_INT_MACRO(m, SOL_CAN_RAW);
8088     ADD_INT_MACRO(m, CAN_RAW);
8089 #endif
8090 #if defined(HAVE_LINUX_CAN_H) || defined(HAVE_NETCAN_CAN_H)
8091     ADD_INT_MACRO(m, CAN_EFF_FLAG);
8092     ADD_INT_MACRO(m, CAN_RTR_FLAG);
8093     ADD_INT_MACRO(m, CAN_ERR_FLAG);
8094 
8095     ADD_INT_MACRO(m, CAN_SFF_MASK);
8096     ADD_INT_MACRO(m, CAN_EFF_MASK);
8097     ADD_INT_MACRO(m, CAN_ERR_MASK);
8098 #ifdef CAN_ISOTP
8099     ADD_INT_MACRO(m, CAN_ISOTP);
8100 #endif
8101 #ifdef CAN_J1939
8102     ADD_INT_MACRO(m, CAN_J1939);
8103 #endif
8104 #endif
8105 #if defined(HAVE_LINUX_CAN_RAW_H) || defined(HAVE_NETCAN_CAN_H)
8106     ADD_INT_MACRO(m, CAN_RAW_FILTER);
8107 #ifdef CAN_RAW_ERR_FILTER
8108     ADD_INT_MACRO(m, CAN_RAW_ERR_FILTER);
8109 #endif
8110     ADD_INT_MACRO(m, CAN_RAW_LOOPBACK);
8111     ADD_INT_MACRO(m, CAN_RAW_RECV_OWN_MSGS);
8112 #endif
8113 #ifdef HAVE_LINUX_CAN_RAW_FD_FRAMES
8114     ADD_INT_MACRO(m, CAN_RAW_FD_FRAMES);
8115 #endif
8116 #ifdef HAVE_LINUX_CAN_RAW_JOIN_FILTERS
8117     ADD_INT_MACRO(m, CAN_RAW_JOIN_FILTERS);
8118 #endif
8119 #ifdef HAVE_LINUX_CAN_BCM_H
8120     ADD_INT_MACRO(m, CAN_BCM);
8121 
8122     /* BCM opcodes */
8123     ADD_INT_CONST(m, "CAN_BCM_TX_SETUP", TX_SETUP);
8124     ADD_INT_CONST(m, "CAN_BCM_TX_DELETE", TX_DELETE);
8125     ADD_INT_CONST(m, "CAN_BCM_TX_READ", TX_READ);
8126     ADD_INT_CONST(m, "CAN_BCM_TX_SEND", TX_SEND);
8127     ADD_INT_CONST(m, "CAN_BCM_RX_SETUP", RX_SETUP);
8128     ADD_INT_CONST(m, "CAN_BCM_RX_DELETE", RX_DELETE);
8129     ADD_INT_CONST(m, "CAN_BCM_RX_READ", RX_READ);
8130     ADD_INT_CONST(m, "CAN_BCM_TX_STATUS", TX_STATUS);
8131     ADD_INT_CONST(m, "CAN_BCM_TX_EXPIRED", TX_EXPIRED);
8132     ADD_INT_CONST(m, "CAN_BCM_RX_STATUS", RX_STATUS);
8133     ADD_INT_CONST(m, "CAN_BCM_RX_TIMEOUT", RX_TIMEOUT);
8134     ADD_INT_CONST(m, "CAN_BCM_RX_CHANGED", RX_CHANGED);
8135 
8136     /* BCM flags */
8137     ADD_INT_CONST(m, "CAN_BCM_SETTIMER", SETTIMER);
8138     ADD_INT_CONST(m, "CAN_BCM_STARTTIMER", STARTTIMER);
8139     ADD_INT_CONST(m, "CAN_BCM_TX_COUNTEVT", TX_COUNTEVT);
8140     ADD_INT_CONST(m, "CAN_BCM_TX_ANNOUNCE", TX_ANNOUNCE);
8141     ADD_INT_CONST(m, "CAN_BCM_TX_CP_CAN_ID", TX_CP_CAN_ID);
8142     ADD_INT_CONST(m, "CAN_BCM_RX_FILTER_ID", RX_FILTER_ID);
8143     ADD_INT_CONST(m, "CAN_BCM_RX_CHECK_DLC", RX_CHECK_DLC);
8144     ADD_INT_CONST(m, "CAN_BCM_RX_NO_AUTOTIMER", RX_NO_AUTOTIMER);
8145     ADD_INT_CONST(m, "CAN_BCM_RX_ANNOUNCE_RESUME", RX_ANNOUNCE_RESUME);
8146     ADD_INT_CONST(m, "CAN_BCM_TX_RESET_MULTI_IDX", TX_RESET_MULTI_IDX);
8147     ADD_INT_CONST(m, "CAN_BCM_RX_RTR_FRAME", RX_RTR_FRAME);
8148 #ifdef CAN_FD_FRAME
8149     /* CAN_FD_FRAME was only introduced in the 4.8.x kernel series */
8150     ADD_INT_CONST(m, "CAN_BCM_CAN_FD_FRAME", CAN_FD_FRAME);
8151 #endif
8152 #endif
8153 #ifdef HAVE_LINUX_CAN_J1939_H
8154     ADD_INT_MACRO(m, J1939_MAX_UNICAST_ADDR);
8155     ADD_INT_MACRO(m, J1939_IDLE_ADDR);
8156     ADD_INT_MACRO(m, J1939_NO_ADDR);
8157     ADD_INT_MACRO(m, J1939_NO_NAME);
8158     ADD_INT_MACRO(m, J1939_PGN_REQUEST);
8159     ADD_INT_MACRO(m, J1939_PGN_ADDRESS_CLAIMED);
8160     ADD_INT_MACRO(m, J1939_PGN_ADDRESS_COMMANDED);
8161     ADD_INT_MACRO(m, J1939_PGN_PDU1_MAX);
8162     ADD_INT_MACRO(m, J1939_PGN_MAX);
8163     ADD_INT_MACRO(m, J1939_NO_PGN);
8164 
8165     /* J1939 socket options */
8166     ADD_INT_MACRO(m, SO_J1939_FILTER);
8167     ADD_INT_MACRO(m, SO_J1939_PROMISC);
8168     ADD_INT_MACRO(m, SO_J1939_SEND_PRIO);
8169     ADD_INT_MACRO(m, SO_J1939_ERRQUEUE);
8170 
8171     ADD_INT_MACRO(m, SCM_J1939_DEST_ADDR);
8172     ADD_INT_MACRO(m, SCM_J1939_DEST_NAME);
8173     ADD_INT_MACRO(m, SCM_J1939_PRIO);
8174     ADD_INT_MACRO(m, SCM_J1939_ERRQUEUE);
8175 
8176     ADD_INT_MACRO(m, J1939_NLA_PAD);
8177     ADD_INT_MACRO(m, J1939_NLA_BYTES_ACKED);
8178 
8179     ADD_INT_MACRO(m, J1939_EE_INFO_NONE);
8180     ADD_INT_MACRO(m, J1939_EE_INFO_TX_ABORT);
8181 
8182     ADD_INT_MACRO(m, J1939_FILTER_MAX);
8183 #endif
8184 #ifdef SOL_RDS
8185     ADD_INT_MACRO(m, SOL_RDS);
8186 #endif
8187 #ifdef HAVE_SOCKADDR_ALG
8188     ADD_INT_MACRO(m, SOL_ALG);
8189 #endif
8190 #ifdef RDS_CANCEL_SENT_TO
8191     ADD_INT_MACRO(m, RDS_CANCEL_SENT_TO);
8192 #endif
8193 #ifdef RDS_GET_MR
8194     ADD_INT_MACRO(m, RDS_GET_MR);
8195 #endif
8196 #ifdef RDS_FREE_MR
8197     ADD_INT_MACRO(m, RDS_FREE_MR);
8198 #endif
8199 #ifdef RDS_RECVERR
8200     ADD_INT_MACRO(m, RDS_RECVERR);
8201 #endif
8202 #ifdef RDS_CONG_MONITOR
8203     ADD_INT_MACRO(m, RDS_CONG_MONITOR);
8204 #endif
8205 #ifdef RDS_GET_MR_FOR_DEST
8206     ADD_INT_MACRO(m, RDS_GET_MR_FOR_DEST);
8207 #endif
8208 #ifdef  IPPROTO_IP
8209     ADD_INT_MACRO(m, IPPROTO_IP);
8210 #else
8211     ADD_INT_CONST(m, "IPPROTO_IP", 0);
8212 #endif
8213 #ifdef  IPPROTO_HOPOPTS
8214     ADD_INT_MACRO(m, IPPROTO_HOPOPTS);
8215 #endif
8216 #ifdef  IPPROTO_ICMP
8217     ADD_INT_MACRO(m, IPPROTO_ICMP);
8218 #else
8219     ADD_INT_CONST(m, "IPPROTO_ICMP", 1);
8220 #endif
8221 #ifdef  IPPROTO_IGMP
8222     ADD_INT_MACRO(m, IPPROTO_IGMP);
8223 #endif
8224 #ifdef  IPPROTO_GGP
8225     ADD_INT_MACRO(m, IPPROTO_GGP);
8226 #endif
8227 #ifdef  IPPROTO_IPV4
8228     ADD_INT_MACRO(m, IPPROTO_IPV4);
8229 #endif
8230 #ifdef  IPPROTO_IPV6
8231     ADD_INT_MACRO(m, IPPROTO_IPV6);
8232 #endif
8233 #ifdef  IPPROTO_IPIP
8234     ADD_INT_MACRO(m, IPPROTO_IPIP);
8235 #endif
8236 #ifdef  IPPROTO_TCP
8237     ADD_INT_MACRO(m, IPPROTO_TCP);
8238 #else
8239     ADD_INT_CONST(m, "IPPROTO_TCP", 6);
8240 #endif
8241 #ifdef  IPPROTO_EGP
8242     ADD_INT_MACRO(m, IPPROTO_EGP);
8243 #endif
8244 #ifdef  IPPROTO_PUP
8245     ADD_INT_MACRO(m, IPPROTO_PUP);
8246 #endif
8247 #ifdef  IPPROTO_UDP
8248     ADD_INT_MACRO(m, IPPROTO_UDP);
8249 #else
8250     ADD_INT_CONST(m, "IPPROTO_UDP", 17);
8251 #endif
8252 #ifdef  IPPROTO_UDPLITE
8253     ADD_INT_MACRO(m, IPPROTO_UDPLITE);
8254     #ifndef UDPLITE_SEND_CSCOV
8255         #define UDPLITE_SEND_CSCOV 10
8256     #endif
8257     ADD_INT_MACRO(m, UDPLITE_SEND_CSCOV);
8258     #ifndef UDPLITE_RECV_CSCOV
8259         #define UDPLITE_RECV_CSCOV 11
8260     #endif
8261     ADD_INT_MACRO(m, UDPLITE_RECV_CSCOV);
8262 #endif
8263 #ifdef  IPPROTO_IDP
8264     ADD_INT_MACRO(m, IPPROTO_IDP);
8265 #endif
8266 #ifdef  IPPROTO_HELLO
8267     ADD_INT_MACRO(m, IPPROTO_HELLO);
8268 #endif
8269 #ifdef  IPPROTO_ND
8270     ADD_INT_MACRO(m, IPPROTO_ND);
8271 #endif
8272 #ifdef  IPPROTO_TP
8273     ADD_INT_MACRO(m, IPPROTO_TP);
8274 #endif
8275 #ifdef  IPPROTO_ROUTING
8276     ADD_INT_MACRO(m, IPPROTO_ROUTING);
8277 #endif
8278 #ifdef  IPPROTO_FRAGMENT
8279     ADD_INT_MACRO(m, IPPROTO_FRAGMENT);
8280 #endif
8281 #ifdef  IPPROTO_RSVP
8282     ADD_INT_MACRO(m, IPPROTO_RSVP);
8283 #endif
8284 #ifdef  IPPROTO_GRE
8285     ADD_INT_MACRO(m, IPPROTO_GRE);
8286 #endif
8287 #ifdef  IPPROTO_ESP
8288     ADD_INT_MACRO(m, IPPROTO_ESP);
8289 #endif
8290 #ifdef  IPPROTO_AH
8291     ADD_INT_MACRO(m, IPPROTO_AH);
8292 #endif
8293 #ifdef  IPPROTO_MOBILE
8294     ADD_INT_MACRO(m, IPPROTO_MOBILE);
8295 #endif
8296 #ifdef  IPPROTO_ICMPV6
8297     ADD_INT_MACRO(m, IPPROTO_ICMPV6);
8298 #endif
8299 #ifdef  IPPROTO_NONE
8300     ADD_INT_MACRO(m, IPPROTO_NONE);
8301 #endif
8302 #ifdef  IPPROTO_DSTOPTS
8303     ADD_INT_MACRO(m, IPPROTO_DSTOPTS);
8304 #endif
8305 #ifdef  IPPROTO_XTP
8306     ADD_INT_MACRO(m, IPPROTO_XTP);
8307 #endif
8308 #ifdef  IPPROTO_EON
8309     ADD_INT_MACRO(m, IPPROTO_EON);
8310 #endif
8311 #ifdef  IPPROTO_PIM
8312     ADD_INT_MACRO(m, IPPROTO_PIM);
8313 #endif
8314 #ifdef  IPPROTO_IPCOMP
8315     ADD_INT_MACRO(m, IPPROTO_IPCOMP);
8316 #endif
8317 #ifdef  IPPROTO_VRRP
8318     ADD_INT_MACRO(m, IPPROTO_VRRP);
8319 #endif
8320 #ifdef  IPPROTO_SCTP
8321     ADD_INT_MACRO(m, IPPROTO_SCTP);
8322 #endif
8323 #ifdef  IPPROTO_BIP
8324     ADD_INT_MACRO(m, IPPROTO_BIP);
8325 #endif
8326 #ifdef  IPPROTO_MPTCP
8327     ADD_INT_MACRO(m, IPPROTO_MPTCP);
8328 #endif
8329 /**/
8330 #ifdef  IPPROTO_RAW
8331     ADD_INT_MACRO(m, IPPROTO_RAW);
8332 #else
8333     ADD_INT_CONST(m, "IPPROTO_RAW", 255);
8334 #endif
8335 #ifdef  IPPROTO_MAX
8336     ADD_INT_MACRO(m, IPPROTO_MAX);
8337 #endif
8338 
8339 #ifdef  MS_WINDOWS
8340     ADD_INT_MACRO(m, IPPROTO_ICLFXBM);
8341     ADD_INT_MACRO(m, IPPROTO_ST);
8342     ADD_INT_MACRO(m, IPPROTO_CBT);
8343     ADD_INT_MACRO(m, IPPROTO_IGP);
8344     ADD_INT_MACRO(m, IPPROTO_RDP);
8345     ADD_INT_MACRO(m, IPPROTO_PGM);
8346     ADD_INT_MACRO(m, IPPROTO_L2TP);
8347     ADD_INT_MACRO(m, IPPROTO_SCTP);
8348 #endif
8349 
8350 #ifdef  SYSPROTO_CONTROL
8351     ADD_INT_MACRO(m, SYSPROTO_CONTROL);
8352 #endif
8353 
8354     /* Some port configuration */
8355 #ifdef  IPPORT_RESERVED
8356     ADD_INT_MACRO(m, IPPORT_RESERVED);
8357 #else
8358     ADD_INT_CONST(m, "IPPORT_RESERVED", 1024);
8359 #endif
8360 #ifdef  IPPORT_USERRESERVED
8361     ADD_INT_MACRO(m, IPPORT_USERRESERVED);
8362 #else
8363     ADD_INT_CONST(m, "IPPORT_USERRESERVED", 5000);
8364 #endif
8365 
8366     /* Some reserved IP v.4 addresses */
8367 #ifdef  INADDR_ANY
8368     ADD_INT_MACRO(m, INADDR_ANY);
8369 #else
8370     ADD_INT_CONST(m, "INADDR_ANY", 0x00000000);
8371 #endif
8372 #ifdef  INADDR_BROADCAST
8373     ADD_INT_MACRO(m, INADDR_BROADCAST);
8374 #else
8375     ADD_INT_CONST(m, "INADDR_BROADCAST", 0xffffffff);
8376 #endif
8377 #ifdef  INADDR_LOOPBACK
8378     ADD_INT_MACRO(m, INADDR_LOOPBACK);
8379 #else
8380     ADD_INT_CONST(m, "INADDR_LOOPBACK", 0x7F000001);
8381 #endif
8382 #ifdef  INADDR_UNSPEC_GROUP
8383     ADD_INT_MACRO(m, INADDR_UNSPEC_GROUP);
8384 #else
8385     ADD_INT_CONST(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
8386 #endif
8387 #ifdef  INADDR_ALLHOSTS_GROUP
8388     ADD_INT_CONST(m, "INADDR_ALLHOSTS_GROUP",
8389                             INADDR_ALLHOSTS_GROUP);
8390 #else
8391     ADD_INT_CONST(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
8392 #endif
8393 #ifdef  INADDR_MAX_LOCAL_GROUP
8394     ADD_INT_MACRO(m, INADDR_MAX_LOCAL_GROUP);
8395 #else
8396     ADD_INT_CONST(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
8397 #endif
8398 #ifdef  INADDR_NONE
8399     ADD_INT_MACRO(m, INADDR_NONE);
8400 #else
8401     ADD_INT_CONST(m, "INADDR_NONE", 0xffffffff);
8402 #endif
8403 
8404     /* IPv4 [gs]etsockopt options */
8405 #ifdef  IP_OPTIONS
8406     ADD_INT_MACRO(m, IP_OPTIONS);
8407 #endif
8408 #ifdef  IP_HDRINCL
8409     ADD_INT_MACRO(m, IP_HDRINCL);
8410 #endif
8411 #ifdef  IP_TOS
8412     ADD_INT_MACRO(m, IP_TOS);
8413 #endif
8414 #ifdef  IP_TTL
8415     ADD_INT_MACRO(m, IP_TTL);
8416 #endif
8417 #ifdef  IP_RECVOPTS
8418     ADD_INT_MACRO(m, IP_RECVOPTS);
8419 #endif
8420 #ifdef  IP_RECVRETOPTS
8421     ADD_INT_MACRO(m, IP_RECVRETOPTS);
8422 #endif
8423 #ifdef  IP_RECVTOS
8424     ADD_INT_MACRO(m, IP_RECVTOS);
8425 #endif
8426 #ifdef  IP_RECVDSTADDR
8427     ADD_INT_MACRO(m, IP_RECVDSTADDR);
8428 #endif
8429 #ifdef  IP_RETOPTS
8430     ADD_INT_MACRO(m, IP_RETOPTS);
8431 #endif
8432 #ifdef  IP_MULTICAST_IF
8433     ADD_INT_MACRO(m, IP_MULTICAST_IF);
8434 #endif
8435 #ifdef  IP_MULTICAST_TTL
8436     ADD_INT_MACRO(m, IP_MULTICAST_TTL);
8437 #endif
8438 #ifdef  IP_MULTICAST_LOOP
8439     ADD_INT_MACRO(m, IP_MULTICAST_LOOP);
8440 #endif
8441 #ifdef  IP_ADD_MEMBERSHIP
8442     ADD_INT_MACRO(m, IP_ADD_MEMBERSHIP);
8443 #endif
8444 #ifdef  IP_DROP_MEMBERSHIP
8445     ADD_INT_MACRO(m, IP_DROP_MEMBERSHIP);
8446 #endif
8447 #ifdef  IP_DEFAULT_MULTICAST_TTL
8448     ADD_INT_MACRO(m, IP_DEFAULT_MULTICAST_TTL);
8449 #endif
8450 #ifdef  IP_DEFAULT_MULTICAST_LOOP
8451     ADD_INT_MACRO(m, IP_DEFAULT_MULTICAST_LOOP);
8452 #endif
8453 #ifdef  IP_MAX_MEMBERSHIPS
8454     ADD_INT_MACRO(m, IP_MAX_MEMBERSHIPS);
8455 #endif
8456 #ifdef  IP_TRANSPARENT
8457     ADD_INT_MACRO(m, IP_TRANSPARENT);
8458 #endif
8459 #ifdef  IP_PKTINFO
8460     ADD_INT_MACRO(m, IP_PKTINFO);
8461 #endif
8462 #ifdef IP_BIND_ADDRESS_NO_PORT
8463     ADD_INT_MACRO(m, IP_BIND_ADDRESS_NO_PORT);
8464 #endif
8465 #ifdef IP_UNBLOCK_SOURCE
8466     ADD_INT_MACRO(m, IP_UNBLOCK_SOURCE);
8467 #endif
8468 #ifdef IP_BLOCK_SOURCE
8469     ADD_INT_MACRO(m, IP_BLOCK_SOURCE);
8470 #endif
8471 #ifdef IP_ADD_SOURCE_MEMBERSHIP
8472     ADD_INT_MACRO(m, IP_ADD_SOURCE_MEMBERSHIP);
8473 #endif
8474 #ifdef IP_DROP_SOURCE_MEMBERSHIP
8475     ADD_INT_MACRO(m, IP_DROP_SOURCE_MEMBERSHIP);
8476 #endif
8477 
8478     /* IPv6 [gs]etsockopt options, defined in RFC2553 */
8479 #ifdef  IPV6_JOIN_GROUP
8480     ADD_INT_MACRO(m, IPV6_JOIN_GROUP);
8481 #endif
8482 #ifdef  IPV6_LEAVE_GROUP
8483     ADD_INT_MACRO(m, IPV6_LEAVE_GROUP);
8484 #endif
8485 #ifdef  IPV6_MULTICAST_HOPS
8486     ADD_INT_MACRO(m, IPV6_MULTICAST_HOPS);
8487 #endif
8488 #ifdef  IPV6_MULTICAST_IF
8489     ADD_INT_MACRO(m, IPV6_MULTICAST_IF);
8490 #endif
8491 #ifdef  IPV6_MULTICAST_LOOP
8492     ADD_INT_MACRO(m, IPV6_MULTICAST_LOOP);
8493 #endif
8494 #ifdef  IPV6_UNICAST_HOPS
8495     ADD_INT_MACRO(m, IPV6_UNICAST_HOPS);
8496 #endif
8497     /* Additional IPV6 socket options, defined in RFC 3493 */
8498 #ifdef IPV6_V6ONLY
8499     ADD_INT_MACRO(m, IPV6_V6ONLY);
8500 #endif
8501     /* Advanced IPV6 socket options, from RFC 3542 */
8502 #ifdef IPV6_CHECKSUM
8503     ADD_INT_MACRO(m, IPV6_CHECKSUM);
8504 #endif
8505 #ifdef IPV6_DONTFRAG
8506     ADD_INT_MACRO(m, IPV6_DONTFRAG);
8507 #endif
8508 #ifdef IPV6_DSTOPTS
8509     ADD_INT_MACRO(m, IPV6_DSTOPTS);
8510 #endif
8511 #ifdef IPV6_HOPLIMIT
8512     ADD_INT_MACRO(m, IPV6_HOPLIMIT);
8513 #endif
8514 #ifdef IPV6_HOPOPTS
8515     ADD_INT_MACRO(m, IPV6_HOPOPTS);
8516 #endif
8517 #ifdef IPV6_NEXTHOP
8518     ADD_INT_MACRO(m, IPV6_NEXTHOP);
8519 #endif
8520 #ifdef IPV6_PATHMTU
8521     ADD_INT_MACRO(m, IPV6_PATHMTU);
8522 #endif
8523 #ifdef IPV6_PKTINFO
8524     ADD_INT_MACRO(m, IPV6_PKTINFO);
8525 #endif
8526 #ifdef IPV6_RECVDSTOPTS
8527     ADD_INT_MACRO(m, IPV6_RECVDSTOPTS);
8528 #endif
8529 #ifdef IPV6_RECVHOPLIMIT
8530     ADD_INT_MACRO(m, IPV6_RECVHOPLIMIT);
8531 #endif
8532 #ifdef IPV6_RECVHOPOPTS
8533     ADD_INT_MACRO(m, IPV6_RECVHOPOPTS);
8534 #endif
8535 #ifdef IPV6_RECVPKTINFO
8536     ADD_INT_MACRO(m, IPV6_RECVPKTINFO);
8537 #endif
8538 #ifdef IPV6_RECVRTHDR
8539     ADD_INT_MACRO(m, IPV6_RECVRTHDR);
8540 #endif
8541 #ifdef IPV6_RECVTCLASS
8542     ADD_INT_MACRO(m, IPV6_RECVTCLASS);
8543 #endif
8544 #ifdef IPV6_RTHDR
8545     ADD_INT_MACRO(m, IPV6_RTHDR);
8546 #endif
8547 #ifdef IPV6_RTHDRDSTOPTS
8548     ADD_INT_MACRO(m, IPV6_RTHDRDSTOPTS);
8549 #endif
8550 #ifdef IPV6_RTHDR_TYPE_0
8551     ADD_INT_MACRO(m, IPV6_RTHDR_TYPE_0);
8552 #endif
8553 #ifdef IPV6_RECVPATHMTU
8554     ADD_INT_MACRO(m, IPV6_RECVPATHMTU);
8555 #endif
8556 #ifdef IPV6_TCLASS
8557     ADD_INT_MACRO(m, IPV6_TCLASS);
8558 #endif
8559 #ifdef IPV6_USE_MIN_MTU
8560     ADD_INT_MACRO(m, IPV6_USE_MIN_MTU);
8561 #endif
8562 
8563     /* TCP options */
8564 #ifdef  TCP_NODELAY
8565     ADD_INT_MACRO(m, TCP_NODELAY);
8566 #endif
8567 #ifdef  TCP_MAXSEG
8568     ADD_INT_MACRO(m, TCP_MAXSEG);
8569 #endif
8570 #ifdef  TCP_CORK
8571     ADD_INT_MACRO(m, TCP_CORK);
8572 #endif
8573 #ifdef  TCP_KEEPIDLE
8574     ADD_INT_MACRO(m, TCP_KEEPIDLE);
8575 #endif
8576     /* TCP_KEEPALIVE is OSX's TCP_KEEPIDLE equivalent */
8577 #if defined(__APPLE__) && defined(TCP_KEEPALIVE)
8578     ADD_INT_MACRO(m, TCP_KEEPALIVE);
8579 #endif
8580 #ifdef  TCP_KEEPINTVL
8581     ADD_INT_MACRO(m, TCP_KEEPINTVL);
8582 #endif
8583 #ifdef  TCP_KEEPCNT
8584     ADD_INT_MACRO(m, TCP_KEEPCNT);
8585 #endif
8586 #ifdef  TCP_SYNCNT
8587     ADD_INT_MACRO(m, TCP_SYNCNT);
8588 #endif
8589 #ifdef  TCP_LINGER2
8590     ADD_INT_MACRO(m, TCP_LINGER2);
8591 #endif
8592 #ifdef  TCP_DEFER_ACCEPT
8593     ADD_INT_MACRO(m, TCP_DEFER_ACCEPT);
8594 #endif
8595 #ifdef  TCP_WINDOW_CLAMP
8596     ADD_INT_MACRO(m, TCP_WINDOW_CLAMP);
8597 #endif
8598 #ifdef  TCP_INFO
8599     ADD_INT_MACRO(m, TCP_INFO);
8600 #endif
8601 #ifdef  TCP_CONNECTION_INFO
8602     ADD_INT_MACRO(m, TCP_CONNECTION_INFO);
8603 #endif
8604 #ifdef  TCP_QUICKACK
8605     ADD_INT_MACRO(m, TCP_QUICKACK);
8606 #endif
8607 #ifdef  TCP_CONGESTION
8608     ADD_INT_MACRO(m, TCP_CONGESTION);
8609 #endif
8610 #ifdef  TCP_MD5SIG
8611     ADD_INT_MACRO(m, TCP_MD5SIG);
8612 #endif
8613 #ifdef  TCP_THIN_LINEAR_TIMEOUTS
8614     ADD_INT_MACRO(m, TCP_THIN_LINEAR_TIMEOUTS);
8615 #endif
8616 #ifdef  TCP_THIN_DUPACK
8617     ADD_INT_MACRO(m, TCP_THIN_DUPACK);
8618 #endif
8619 #ifdef  TCP_USER_TIMEOUT
8620     ADD_INT_MACRO(m, TCP_USER_TIMEOUT);
8621 #endif
8622 #ifdef  TCP_REPAIR
8623     ADD_INT_MACRO(m, TCP_REPAIR);
8624 #endif
8625 #ifdef  TCP_REPAIR_QUEUE
8626     ADD_INT_MACRO(m, TCP_REPAIR_QUEUE);
8627 #endif
8628 #ifdef  TCP_QUEUE_SEQ
8629     ADD_INT_MACRO(m, TCP_QUEUE_SEQ);
8630 #endif
8631 #ifdef  TCP_REPAIR_OPTIONS
8632     ADD_INT_MACRO(m, TCP_REPAIR_OPTIONS);
8633 #endif
8634 #ifdef  TCP_FASTOPEN
8635     ADD_INT_MACRO(m, TCP_FASTOPEN);
8636 #endif
8637 #ifdef  TCP_TIMESTAMP
8638     ADD_INT_MACRO(m, TCP_TIMESTAMP);
8639 #endif
8640 #ifdef  TCP_NOTSENT_LOWAT
8641     ADD_INT_MACRO(m, TCP_NOTSENT_LOWAT);
8642 #endif
8643 #ifdef  TCP_CC_INFO
8644     ADD_INT_MACRO(m, TCP_CC_INFO);
8645 #endif
8646 #ifdef  TCP_SAVE_SYN
8647     ADD_INT_MACRO(m, TCP_SAVE_SYN);
8648 #endif
8649 #ifdef  TCP_SAVED_SYN
8650     ADD_INT_MACRO(m, TCP_SAVED_SYN);
8651 #endif
8652 #ifdef  TCP_REPAIR_WINDOW
8653     ADD_INT_MACRO(m, TCP_REPAIR_WINDOW);
8654 #endif
8655 #ifdef  TCP_FASTOPEN_CONNECT
8656     ADD_INT_MACRO(m, TCP_FASTOPEN_CONNECT);
8657 #endif
8658 #ifdef  TCP_ULP
8659     ADD_INT_MACRO(m, TCP_ULP);
8660 #endif
8661 #ifdef  TCP_MD5SIG_EXT
8662     ADD_INT_MACRO(m, TCP_MD5SIG_EXT);
8663 #endif
8664 #ifdef  TCP_FASTOPEN_KEY
8665     ADD_INT_MACRO(m, TCP_FASTOPEN_KEY);
8666 #endif
8667 #ifdef  TCP_FASTOPEN_NO_COOKIE
8668     ADD_INT_MACRO(m, TCP_FASTOPEN_NO_COOKIE);
8669 #endif
8670 #ifdef  TCP_ZEROCOPY_RECEIVE
8671     ADD_INT_MACRO(m, TCP_ZEROCOPY_RECEIVE);
8672 #endif
8673 #ifdef  TCP_INQ
8674     ADD_INT_MACRO(m, TCP_INQ);
8675 #endif
8676 #ifdef  TCP_TX_DELAY
8677     ADD_INT_MACRO(m, TCP_TX_DELAY);
8678 #endif
8679 
8680     /* IPX options */
8681 #ifdef  IPX_TYPE
8682     ADD_INT_MACRO(m, IPX_TYPE);
8683 #endif
8684 
8685 /* Reliable Datagram Sockets */
8686 #ifdef RDS_CMSG_RDMA_ARGS
8687     ADD_INT_MACRO(m, RDS_CMSG_RDMA_ARGS);
8688 #endif
8689 #ifdef RDS_CMSG_RDMA_DEST
8690     ADD_INT_MACRO(m, RDS_CMSG_RDMA_DEST);
8691 #endif
8692 #ifdef RDS_CMSG_RDMA_MAP
8693     ADD_INT_MACRO(m, RDS_CMSG_RDMA_MAP);
8694 #endif
8695 #ifdef RDS_CMSG_RDMA_STATUS
8696     ADD_INT_MACRO(m, RDS_CMSG_RDMA_STATUS);
8697 #endif
8698 #ifdef RDS_CMSG_RDMA_UPDATE
8699     ADD_INT_MACRO(m, RDS_CMSG_RDMA_UPDATE);
8700 #endif
8701 #ifdef RDS_RDMA_READWRITE
8702     ADD_INT_MACRO(m, RDS_RDMA_READWRITE);
8703 #endif
8704 #ifdef RDS_RDMA_FENCE
8705     ADD_INT_MACRO(m, RDS_RDMA_FENCE);
8706 #endif
8707 #ifdef RDS_RDMA_INVALIDATE
8708     ADD_INT_MACRO(m, RDS_RDMA_INVALIDATE);
8709 #endif
8710 #ifdef RDS_RDMA_USE_ONCE
8711     ADD_INT_MACRO(m, RDS_RDMA_USE_ONCE);
8712 #endif
8713 #ifdef RDS_RDMA_DONTWAIT
8714     ADD_INT_MACRO(m, RDS_RDMA_DONTWAIT);
8715 #endif
8716 #ifdef RDS_RDMA_NOTIFY_ME
8717     ADD_INT_MACRO(m, RDS_RDMA_NOTIFY_ME);
8718 #endif
8719 #ifdef RDS_RDMA_SILENT
8720     ADD_INT_MACRO(m, RDS_RDMA_SILENT);
8721 #endif
8722 
8723     /* get{addr,name}info parameters */
8724 #ifdef EAI_ADDRFAMILY
8725     ADD_INT_MACRO(m, EAI_ADDRFAMILY);
8726 #endif
8727 #ifdef EAI_AGAIN
8728     ADD_INT_MACRO(m, EAI_AGAIN);
8729 #endif
8730 #ifdef EAI_BADFLAGS
8731     ADD_INT_MACRO(m, EAI_BADFLAGS);
8732 #endif
8733 #ifdef EAI_FAIL
8734     ADD_INT_MACRO(m, EAI_FAIL);
8735 #endif
8736 #ifdef EAI_FAMILY
8737     ADD_INT_MACRO(m, EAI_FAMILY);
8738 #endif
8739 #ifdef EAI_MEMORY
8740     ADD_INT_MACRO(m, EAI_MEMORY);
8741 #endif
8742 #ifdef EAI_NODATA
8743     ADD_INT_MACRO(m, EAI_NODATA);
8744 #endif
8745 #ifdef EAI_NONAME
8746     ADD_INT_MACRO(m, EAI_NONAME);
8747 #endif
8748 #ifdef EAI_OVERFLOW
8749     ADD_INT_MACRO(m, EAI_OVERFLOW);
8750 #endif
8751 #ifdef EAI_SERVICE
8752     ADD_INT_MACRO(m, EAI_SERVICE);
8753 #endif
8754 #ifdef EAI_SOCKTYPE
8755     ADD_INT_MACRO(m, EAI_SOCKTYPE);
8756 #endif
8757 #ifdef EAI_SYSTEM
8758     ADD_INT_MACRO(m, EAI_SYSTEM);
8759 #endif
8760 #ifdef EAI_BADHINTS
8761     ADD_INT_MACRO(m, EAI_BADHINTS);
8762 #endif
8763 #ifdef EAI_PROTOCOL
8764     ADD_INT_MACRO(m, EAI_PROTOCOL);
8765 #endif
8766 #ifdef EAI_MAX
8767     ADD_INT_MACRO(m, EAI_MAX);
8768 #endif
8769 #ifdef AI_PASSIVE
8770     ADD_INT_MACRO(m, AI_PASSIVE);
8771 #endif
8772 #ifdef AI_CANONNAME
8773     ADD_INT_MACRO(m, AI_CANONNAME);
8774 #endif
8775 #ifdef AI_NUMERICHOST
8776     ADD_INT_MACRO(m, AI_NUMERICHOST);
8777 #endif
8778 #ifdef AI_NUMERICSERV
8779     ADD_INT_MACRO(m, AI_NUMERICSERV);
8780 #endif
8781 #ifdef AI_MASK
8782     ADD_INT_MACRO(m, AI_MASK);
8783 #endif
8784 #ifdef AI_ALL
8785     ADD_INT_MACRO(m, AI_ALL);
8786 #endif
8787 #ifdef AI_V4MAPPED_CFG
8788     ADD_INT_MACRO(m, AI_V4MAPPED_CFG);
8789 #endif
8790 #ifdef AI_ADDRCONFIG
8791     ADD_INT_MACRO(m, AI_ADDRCONFIG);
8792 #endif
8793 #ifdef AI_V4MAPPED
8794     ADD_INT_MACRO(m, AI_V4MAPPED);
8795 #endif
8796 #ifdef AI_DEFAULT
8797     ADD_INT_MACRO(m, AI_DEFAULT);
8798 #endif
8799 #ifdef NI_MAXHOST
8800     ADD_INT_MACRO(m, NI_MAXHOST);
8801 #endif
8802 #ifdef NI_MAXSERV
8803     ADD_INT_MACRO(m, NI_MAXSERV);
8804 #endif
8805 #ifdef NI_NOFQDN
8806     ADD_INT_MACRO(m, NI_NOFQDN);
8807 #endif
8808 #ifdef NI_NUMERICHOST
8809     ADD_INT_MACRO(m, NI_NUMERICHOST);
8810 #endif
8811 #ifdef NI_NAMEREQD
8812     ADD_INT_MACRO(m, NI_NAMEREQD);
8813 #endif
8814 #ifdef NI_NUMERICSERV
8815     ADD_INT_MACRO(m, NI_NUMERICSERV);
8816 #endif
8817 #ifdef NI_DGRAM
8818     ADD_INT_MACRO(m, NI_DGRAM);
8819 #endif
8820 #ifdef NI_IDN
8821     ADD_INT_MACRO(m, NI_IDN);
8822 #endif
8823 
8824     /* shutdown() parameters */
8825 #ifdef SHUT_RD
8826     ADD_INT_MACRO(m, SHUT_RD);
8827 #elif defined(SD_RECEIVE)
8828     ADD_INT_CONST(m, "SHUT_RD", SD_RECEIVE);
8829 #else
8830     ADD_INT_CONST(m, "SHUT_RD", 0);
8831 #endif
8832 #ifdef SHUT_WR
8833     ADD_INT_MACRO(m, SHUT_WR);
8834 #elif defined(SD_SEND)
8835     ADD_INT_CONST(m, "SHUT_WR", SD_SEND);
8836 #else
8837     ADD_INT_CONST(m, "SHUT_WR", 1);
8838 #endif
8839 #ifdef SHUT_RDWR
8840     ADD_INT_MACRO(m, SHUT_RDWR);
8841 #elif defined(SD_BOTH)
8842     ADD_INT_CONST(m, "SHUT_RDWR", SD_BOTH);
8843 #else
8844     ADD_INT_CONST(m, "SHUT_RDWR", 2);
8845 #endif
8846 
8847 #ifdef SIO_RCVALL
8848     {
8849         DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS,
8850 #if defined(SIO_LOOPBACK_FAST_PATH)
8851             SIO_LOOPBACK_FAST_PATH
8852 #endif
8853         };
8854         const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS",
8855 #if defined(SIO_LOOPBACK_FAST_PATH)
8856             "SIO_LOOPBACK_FAST_PATH"
8857 #endif
8858         };
8859         int i;
8860         for (i = 0; i < Py_ARRAY_LENGTH(codes); ++i) {
8861             if (PyModule_Add(m, names[i], PyLong_FromUnsignedLong(codes[i])) < 0) {
8862                 goto error;
8863             }
8864         }
8865     }
8866     ADD_INT_MACRO(m, RCVALL_OFF);
8867     ADD_INT_MACRO(m, RCVALL_ON);
8868     ADD_INT_MACRO(m, RCVALL_SOCKETLEVELONLY);
8869 #ifdef RCVALL_IPLEVEL
8870     ADD_INT_MACRO(m, RCVALL_IPLEVEL);
8871 #endif
8872 #ifdef RCVALL_MAX
8873     ADD_INT_MACRO(m, RCVALL_MAX);
8874 #endif
8875 #endif /* _MSTCPIP_ */
8876 
8877     /* Initialize gethostbyname lock */
8878 #if defined(USE_GETHOSTBYNAME_LOCK)
8879     netdb_lock = PyThread_allocate_lock();
8880 #endif
8881 
8882 #ifdef MS_WINDOWS
8883     /* remove some flags on older version Windows during run-time */
8884     if (remove_unusable_flags(m) < 0) {
8885         goto error;
8886     }
8887 #endif
8888 
8889 #undef ADD_INT_MACRO
8890 #undef ADD_INT_CONST
8891 #undef ADD_STR_CONST
8892 
8893     return 0;
8894 
8895 error:
8896     return -1;
8897 }
8898 
8899 static struct PyModuleDef_Slot socket_slots[] = {
8900     {Py_mod_exec, socket_exec},
8901     {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
8902     {Py_mod_gil, Py_MOD_GIL_NOT_USED},
8903     {0, NULL},
8904 };
8905 
8906 static int
8907 socket_traverse(PyObject *mod, visitproc visit, void *arg)
8908 {
8909     socket_state *state = get_module_state(mod);
8910     Py_VISIT(state->sock_type);
8911     Py_VISIT(state->socket_herror);
8912     Py_VISIT(state->socket_gaierror);
8913     return 0;
8914 }
8915 
8916 static int
8917 socket_clear(PyObject *mod)
8918 {
8919     socket_state *state = get_module_state(mod);
8920     Py_CLEAR(state->sock_type);
8921     Py_CLEAR(state->socket_herror);
8922     Py_CLEAR(state->socket_gaierror);
8923     return 0;
8924 }
8925 
8926 static void
8927 socket_free(void *mod)
8928 {
8929     (void)socket_clear((PyObject *)mod);
8930 }
8931 
8932 static struct PyModuleDef socketmodule = {
8933     .m_base = PyModuleDef_HEAD_INIT,
8934     .m_name = PySocket_MODULE_NAME,
8935     .m_doc = socket_doc,
8936     .m_size = sizeof(socket_state),
8937     .m_methods = socket_methods,
8938     .m_slots = socket_slots,
8939     .m_traverse = socket_traverse,
8940     .m_clear = socket_clear,
8941     .m_free = socket_free,
8942 };
8943 
8944 PyMODINIT_FUNC
8945 PyInit__socket(void)
8946 {
8947     return PyModuleDef_Init(&socketmodule);
8948 }
8949