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