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