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. The format depends on the\n\
3328 address family. For IPv4 sockets, the address info is a pair\n\
3329 (hostaddr, port).");
3330 
3331 
3332 #ifdef HAVE_GETPEERNAME         /* Cray APP doesn't have this :-( */
3333 /* s.getpeername() method */
3334 
3335 static PyObject *
sock_getpeername(PySocketSockObject * s,PyObject * Py_UNUSED (ignored))3336 sock_getpeername(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3337 {
3338     sock_addr_t addrbuf;
3339     int res;
3340     socklen_t addrlen;
3341 
3342     if (!getsockaddrlen(s, &addrlen))
3343         return NULL;
3344     memset(&addrbuf, 0, addrlen);
3345     Py_BEGIN_ALLOW_THREADS
3346     res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
3347     Py_END_ALLOW_THREADS
3348     if (res < 0)
3349         return s->errorhandler();
3350     return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
3351                         s->sock_proto);
3352 }
3353 
3354 PyDoc_STRVAR(getpeername_doc,
3355 "getpeername() -> address info\n\
3356 \n\
3357 Return the address of the remote endpoint.  For IP sockets, the address\n\
3358 info is a pair (hostaddr, port).");
3359 
3360 #endif /* HAVE_GETPEERNAME */
3361 
3362 
3363 /* s.listen(n) method */
3364 
3365 static PyObject *
sock_listen(PySocketSockObject * s,PyObject * args)3366 sock_listen(PySocketSockObject *s, PyObject *args)
3367 {
3368     /* We try to choose a default backlog high enough to avoid connection drops
3369      * for common workloads, yet not too high to limit resource usage. */
3370     int backlog = Py_MIN(SOMAXCONN, 128);
3371     int res;
3372 
3373     if (!PyArg_ParseTuple(args, "|i:listen", &backlog))
3374         return NULL;
3375 
3376     Py_BEGIN_ALLOW_THREADS
3377     /* To avoid problems on systems that don't allow a negative backlog
3378      * (which doesn't make sense anyway) we force a minimum value of 0. */
3379     if (backlog < 0)
3380         backlog = 0;
3381     res = listen(s->sock_fd, backlog);
3382     Py_END_ALLOW_THREADS
3383     if (res < 0)
3384         return s->errorhandler();
3385     Py_RETURN_NONE;
3386 }
3387 
3388 PyDoc_STRVAR(listen_doc,
3389 "listen([backlog])\n\
3390 \n\
3391 Enable a server to accept connections.  If backlog is specified, it must be\n\
3392 at least 0 (if it is lower, it is set to 0); it specifies the number of\n\
3393 unaccepted connections that the system will allow before refusing new\n\
3394 connections. If not specified, a default reasonable value is chosen.");
3395 
3396 struct sock_recv {
3397     char *cbuf;
3398     Py_ssize_t len;
3399     int flags;
3400     Py_ssize_t result;
3401 };
3402 
3403 static int
sock_recv_impl(PySocketSockObject * s,void * data)3404 sock_recv_impl(PySocketSockObject *s, void *data)
3405 {
3406     struct sock_recv *ctx = data;
3407 
3408 #ifdef MS_WINDOWS
3409     if (ctx->len > INT_MAX)
3410         ctx->len = INT_MAX;
3411     ctx->result = recv(s->sock_fd, ctx->cbuf, (int)ctx->len, ctx->flags);
3412 #else
3413     ctx->result = recv(s->sock_fd, ctx->cbuf, ctx->len, ctx->flags);
3414 #endif
3415     return (ctx->result >= 0);
3416 }
3417 
3418 
3419 /*
3420  * This is the guts of the recv() and recv_into() methods, which reads into a
3421  * char buffer.  If you have any inc/dec ref to do to the objects that contain
3422  * the buffer, do it in the caller.  This function returns the number of bytes
3423  * successfully read.  If there was an error, it returns -1.  Note that it is
3424  * also possible that we return a number of bytes smaller than the request
3425  * bytes.
3426  */
3427 
3428 static Py_ssize_t
sock_recv_guts(PySocketSockObject * s,char * cbuf,Py_ssize_t len,int flags)3429 sock_recv_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags)
3430 {
3431     struct sock_recv ctx;
3432 
3433     if (!IS_SELECTABLE(s)) {
3434         select_error();
3435         return -1;
3436     }
3437     if (len == 0) {
3438         /* If 0 bytes were requested, do nothing. */
3439         return 0;
3440     }
3441 
3442     ctx.cbuf = cbuf;
3443     ctx.len = len;
3444     ctx.flags = flags;
3445     if (sock_call(s, 0, sock_recv_impl, &ctx) < 0)
3446         return -1;
3447 
3448     return ctx.result;
3449 }
3450 
3451 
3452 /* s.recv(nbytes [,flags]) method */
3453 
3454 static PyObject *
sock_recv(PySocketSockObject * s,PyObject * args)3455 sock_recv(PySocketSockObject *s, PyObject *args)
3456 {
3457     Py_ssize_t recvlen, outlen;
3458     int flags = 0;
3459     PyObject *buf;
3460 
3461     if (!PyArg_ParseTuple(args, "n|i:recv", &recvlen, &flags))
3462         return NULL;
3463 
3464     if (recvlen < 0) {
3465         PyErr_SetString(PyExc_ValueError,
3466                         "negative buffersize in recv");
3467         return NULL;
3468     }
3469 
3470     /* Allocate a new string. */
3471     buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
3472     if (buf == NULL)
3473         return NULL;
3474 
3475     /* Call the guts */
3476     outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags);
3477     if (outlen < 0) {
3478         /* An error occurred, release the string and return an
3479            error. */
3480         Py_DECREF(buf);
3481         return NULL;
3482     }
3483     if (outlen != recvlen) {
3484         /* We did not read as many bytes as we anticipated, resize the
3485            string if possible and be successful. */
3486         _PyBytes_Resize(&buf, outlen);
3487     }
3488 
3489     return buf;
3490 }
3491 
3492 PyDoc_STRVAR(recv_doc,
3493 "recv(buffersize[, flags]) -> data\n\
3494 \n\
3495 Receive up to buffersize bytes from the socket.  For the optional flags\n\
3496 argument, see the Unix manual.  When no data is available, block until\n\
3497 at least one byte is available or until the remote end is closed.  When\n\
3498 the remote end is closed and all data is read, return the empty string.");
3499 
3500 
3501 /* s.recv_into(buffer, [nbytes [,flags]]) method */
3502 
3503 static PyObject*
sock_recv_into(PySocketSockObject * s,PyObject * args,PyObject * kwds)3504 sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
3505 {
3506     static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
3507 
3508     int flags = 0;
3509     Py_buffer pbuf;
3510     char *buf;
3511     Py_ssize_t buflen, readlen, recvlen = 0;
3512 
3513     /* Get the buffer's memory */
3514     if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ni:recv_into", kwlist,
3515                                      &pbuf, &recvlen, &flags))
3516         return NULL;
3517     buf = pbuf.buf;
3518     buflen = pbuf.len;
3519 
3520     if (recvlen < 0) {
3521         PyBuffer_Release(&pbuf);
3522         PyErr_SetString(PyExc_ValueError,
3523                         "negative buffersize in recv_into");
3524         return NULL;
3525     }
3526     if (recvlen == 0) {
3527         /* If nbytes was not specified, use the buffer's length */
3528         recvlen = buflen;
3529     }
3530 
3531     /* Check if the buffer is large enough */
3532     if (buflen < recvlen) {
3533         PyBuffer_Release(&pbuf);
3534         PyErr_SetString(PyExc_ValueError,
3535                         "buffer too small for requested bytes");
3536         return NULL;
3537     }
3538 
3539     /* Call the guts */
3540     readlen = sock_recv_guts(s, buf, recvlen, flags);
3541     if (readlen < 0) {
3542         /* Return an error. */
3543         PyBuffer_Release(&pbuf);
3544         return NULL;
3545     }
3546 
3547     PyBuffer_Release(&pbuf);
3548     /* Return the number of bytes read.  Note that we do not do anything
3549        special here in the case that readlen < recvlen. */
3550     return PyLong_FromSsize_t(readlen);
3551 }
3552 
3553 PyDoc_STRVAR(recv_into_doc,
3554 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
3555 \n\
3556 A version of recv() that stores its data into a buffer rather than creating\n\
3557 a new string.  Receive up to buffersize bytes from the socket.  If buffersize\n\
3558 is not specified (or 0), receive up to the size available in the given buffer.\n\
3559 \n\
3560 See recv() for documentation about the flags.");
3561 
3562 struct sock_recvfrom {
3563     char* cbuf;
3564     Py_ssize_t len;
3565     int flags;
3566     socklen_t *addrlen;
3567     sock_addr_t *addrbuf;
3568     Py_ssize_t result;
3569 };
3570 
3571 static int
sock_recvfrom_impl(PySocketSockObject * s,void * data)3572 sock_recvfrom_impl(PySocketSockObject *s, void *data)
3573 {
3574     struct sock_recvfrom *ctx = data;
3575 
3576     memset(ctx->addrbuf, 0, *ctx->addrlen);
3577 
3578 #ifdef MS_WINDOWS
3579     if (ctx->len > INT_MAX)
3580         ctx->len = INT_MAX;
3581     ctx->result = recvfrom(s->sock_fd, ctx->cbuf, (int)ctx->len, ctx->flags,
3582                            SAS2SA(ctx->addrbuf), ctx->addrlen);
3583 #else
3584     ctx->result = recvfrom(s->sock_fd, ctx->cbuf, ctx->len, ctx->flags,
3585                            SAS2SA(ctx->addrbuf), ctx->addrlen);
3586 #endif
3587     return (ctx->result >= 0);
3588 }
3589 
3590 
3591 /*
3592  * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
3593  * into a char buffer.  If you have any inc/def ref to do to the objects that
3594  * contain the buffer, do it in the caller.  This function returns the number
3595  * of bytes successfully read.  If there was an error, it returns -1.  Note
3596  * that it is also possible that we return a number of bytes smaller than the
3597  * request bytes.
3598  *
3599  * 'addr' is a return value for the address object.  Note that you must decref
3600  * it yourself.
3601  */
3602 static Py_ssize_t
sock_recvfrom_guts(PySocketSockObject * s,char * cbuf,Py_ssize_t len,int flags,PyObject ** addr)3603 sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags,
3604                    PyObject** addr)
3605 {
3606     sock_addr_t addrbuf;
3607     socklen_t addrlen;
3608     struct sock_recvfrom ctx;
3609 
3610     *addr = NULL;
3611 
3612     if (!getsockaddrlen(s, &addrlen))
3613         return -1;
3614 
3615     if (!IS_SELECTABLE(s)) {
3616         select_error();
3617         return -1;
3618     }
3619 
3620     ctx.cbuf = cbuf;
3621     ctx.len = len;
3622     ctx.flags = flags;
3623     ctx.addrbuf = &addrbuf;
3624     ctx.addrlen = &addrlen;
3625     if (sock_call(s, 0, sock_recvfrom_impl, &ctx) < 0)
3626         return -1;
3627 
3628     *addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
3629                          s->sock_proto);
3630     if (*addr == NULL)
3631         return -1;
3632 
3633     return ctx.result;
3634 }
3635 
3636 /* s.recvfrom(nbytes [,flags]) method */
3637 
3638 static PyObject *
sock_recvfrom(PySocketSockObject * s,PyObject * args)3639 sock_recvfrom(PySocketSockObject *s, PyObject *args)
3640 {
3641     PyObject *buf = NULL;
3642     PyObject *addr = NULL;
3643     PyObject *ret = NULL;
3644     int flags = 0;
3645     Py_ssize_t recvlen, outlen;
3646 
3647     if (!PyArg_ParseTuple(args, "n|i:recvfrom", &recvlen, &flags))
3648         return NULL;
3649 
3650     if (recvlen < 0) {
3651         PyErr_SetString(PyExc_ValueError,
3652                         "negative buffersize in recvfrom");
3653         return NULL;
3654     }
3655 
3656     buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
3657     if (buf == NULL)
3658         return NULL;
3659 
3660     outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf),
3661                                 recvlen, flags, &addr);
3662     if (outlen < 0) {
3663         goto finally;
3664     }
3665 
3666     if (outlen != recvlen) {
3667         /* We did not read as many bytes as we anticipated, resize the
3668            string if possible and be successful. */
3669         if (_PyBytes_Resize(&buf, outlen) < 0)
3670             /* Oopsy, not so successful after all. */
3671             goto finally;
3672     }
3673 
3674     ret = PyTuple_Pack(2, buf, addr);
3675 
3676 finally:
3677     Py_XDECREF(buf);
3678     Py_XDECREF(addr);
3679     return ret;
3680 }
3681 
3682 PyDoc_STRVAR(recvfrom_doc,
3683 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
3684 \n\
3685 Like recv(buffersize, flags) but also return the sender's address info.");
3686 
3687 
3688 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
3689 
3690 static PyObject *
sock_recvfrom_into(PySocketSockObject * s,PyObject * args,PyObject * kwds)3691 sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
3692 {
3693     static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
3694 
3695     int flags = 0;
3696     Py_buffer pbuf;
3697     char *buf;
3698     Py_ssize_t readlen, buflen, recvlen = 0;
3699 
3700     PyObject *addr = NULL;
3701 
3702     if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ni:recvfrom_into",
3703                                      kwlist, &pbuf,
3704                                      &recvlen, &flags))
3705         return NULL;
3706     buf = pbuf.buf;
3707     buflen = pbuf.len;
3708 
3709     if (recvlen < 0) {
3710         PyBuffer_Release(&pbuf);
3711         PyErr_SetString(PyExc_ValueError,
3712                         "negative buffersize in recvfrom_into");
3713         return NULL;
3714     }
3715     if (recvlen == 0) {
3716         /* If nbytes was not specified, use the buffer's length */
3717         recvlen = buflen;
3718     } else if (recvlen > buflen) {
3719         PyBuffer_Release(&pbuf);
3720         PyErr_SetString(PyExc_ValueError,
3721                         "nbytes is greater than the length of the buffer");
3722         return NULL;
3723     }
3724 
3725     readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
3726     if (readlen < 0) {
3727         PyBuffer_Release(&pbuf);
3728         /* Return an error */
3729         Py_XDECREF(addr);
3730         return NULL;
3731     }
3732 
3733     PyBuffer_Release(&pbuf);
3734     /* Return the number of bytes read and the address.  Note that we do
3735        not do anything special here in the case that readlen < recvlen. */
3736     return Py_BuildValue("nN", readlen, addr);
3737 }
3738 
3739 PyDoc_STRVAR(recvfrom_into_doc,
3740 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
3741 \n\
3742 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
3743 
3744 /* The sendmsg() and recvmsg[_into]() methods require a working
3745    CMSG_LEN().  See the comment near get_CMSG_LEN(). */
3746 #ifdef CMSG_LEN
3747 struct sock_recvmsg {
3748     struct msghdr *msg;
3749     int flags;
3750     ssize_t result;
3751 };
3752 
3753 static int
sock_recvmsg_impl(PySocketSockObject * s,void * data)3754 sock_recvmsg_impl(PySocketSockObject *s, void *data)
3755 {
3756     struct sock_recvmsg *ctx = data;
3757 
3758     ctx->result = recvmsg(s->sock_fd, ctx->msg, ctx->flags);
3759     return  (ctx->result >= 0);
3760 }
3761 
3762 /*
3763  * Call recvmsg() with the supplied iovec structures, flags, and
3764  * ancillary data buffer size (controllen).  Returns the tuple return
3765  * value for recvmsg() or recvmsg_into(), with the first item provided
3766  * by the supplied makeval() function.  makeval() will be called with
3767  * the length read and makeval_data as arguments, and must return a
3768  * new reference (which will be decrefed if there is a subsequent
3769  * error).  On error, closes any file descriptors received via
3770  * SCM_RIGHTS.
3771  */
3772 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)3773 sock_recvmsg_guts(PySocketSockObject *s, struct iovec *iov, int iovlen,
3774                   int flags, Py_ssize_t controllen,
3775                   PyObject *(*makeval)(ssize_t, void *), void *makeval_data)
3776 {
3777     sock_addr_t addrbuf;
3778     socklen_t addrbuflen;
3779     struct msghdr msg = {0};
3780     PyObject *cmsg_list = NULL, *retval = NULL;
3781     void *controlbuf = NULL;
3782     struct cmsghdr *cmsgh;
3783     size_t cmsgdatalen = 0;
3784     int cmsg_status;
3785     struct sock_recvmsg ctx;
3786 
3787     /* XXX: POSIX says that msg_name and msg_namelen "shall be
3788        ignored" when the socket is connected (Linux fills them in
3789        anyway for AF_UNIX sockets at least).  Normally msg_namelen
3790        seems to be set to 0 if there's no address, but try to
3791        initialize msg_name to something that won't be mistaken for a
3792        real address if that doesn't happen. */
3793     if (!getsockaddrlen(s, &addrbuflen))
3794         return NULL;
3795     memset(&addrbuf, 0, addrbuflen);
3796     SAS2SA(&addrbuf)->sa_family = AF_UNSPEC;
3797 
3798     if (controllen < 0 || controllen > SOCKLEN_T_LIMIT) {
3799         PyErr_SetString(PyExc_ValueError,
3800                         "invalid ancillary data buffer length");
3801         return NULL;
3802     }
3803     if (controllen > 0 && (controlbuf = PyMem_Malloc(controllen)) == NULL)
3804         return PyErr_NoMemory();
3805 
3806     /* Make the system call. */
3807     if (!IS_SELECTABLE(s)) {
3808         select_error();
3809         goto finally;
3810     }
3811 
3812     msg.msg_name = SAS2SA(&addrbuf);
3813     msg.msg_namelen = addrbuflen;
3814     msg.msg_iov = iov;
3815     msg.msg_iovlen = iovlen;
3816     msg.msg_control = controlbuf;
3817     msg.msg_controllen = controllen;
3818 
3819     ctx.msg = &msg;
3820     ctx.flags = flags;
3821     if (sock_call(s, 0, sock_recvmsg_impl, &ctx) < 0)
3822         goto finally;
3823 
3824     /* Make list of (level, type, data) tuples from control messages. */
3825     if ((cmsg_list = PyList_New(0)) == NULL)
3826         goto err_closefds;
3827     /* Check for empty ancillary data as old CMSG_FIRSTHDR()
3828        implementations didn't do so. */
3829     for (cmsgh = ((msg.msg_controllen > 0) ? CMSG_FIRSTHDR(&msg) : NULL);
3830          cmsgh != NULL; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
3831         PyObject *bytes, *tuple;
3832         int tmp;
3833 
3834         cmsg_status = get_cmsg_data_len(&msg, cmsgh, &cmsgdatalen);
3835         if (cmsg_status != 0) {
3836             if (PyErr_WarnEx(PyExc_RuntimeWarning,
3837                              "received malformed or improperly-truncated "
3838                              "ancillary data", 1) == -1)
3839                 goto err_closefds;
3840         }
3841         if (cmsg_status < 0)
3842             break;
3843         if (cmsgdatalen > PY_SSIZE_T_MAX) {
3844             PyErr_SetString(PyExc_OSError, "control message too long");
3845             goto err_closefds;
3846         }
3847 
3848         bytes = PyBytes_FromStringAndSize((char *)CMSG_DATA(cmsgh),
3849                                           cmsgdatalen);
3850         tuple = Py_BuildValue("iiN", (int)cmsgh->cmsg_level,
3851                               (int)cmsgh->cmsg_type, bytes);
3852         if (tuple == NULL)
3853             goto err_closefds;
3854         tmp = PyList_Append(cmsg_list, tuple);
3855         Py_DECREF(tuple);
3856         if (tmp != 0)
3857             goto err_closefds;
3858 
3859         if (cmsg_status != 0)
3860             break;
3861     }
3862 
3863     retval = Py_BuildValue("NOiN",
3864                            (*makeval)(ctx.result, makeval_data),
3865                            cmsg_list,
3866                            (int)msg.msg_flags,
3867                            makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
3868                                         ((msg.msg_namelen > addrbuflen) ?
3869                                          addrbuflen : msg.msg_namelen),
3870                                         s->sock_proto));
3871     if (retval == NULL)
3872         goto err_closefds;
3873 
3874 finally:
3875     Py_XDECREF(cmsg_list);
3876     PyMem_Free(controlbuf);
3877     return retval;
3878 
3879 err_closefds:
3880 #ifdef SCM_RIGHTS
3881     /* Close all descriptors coming from SCM_RIGHTS, so they don't leak. */
3882     for (cmsgh = ((msg.msg_controllen > 0) ? CMSG_FIRSTHDR(&msg) : NULL);
3883          cmsgh != NULL; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
3884         cmsg_status = get_cmsg_data_len(&msg, cmsgh, &cmsgdatalen);
3885         if (cmsg_status < 0)
3886             break;
3887         if (cmsgh->cmsg_level == SOL_SOCKET &&
3888             cmsgh->cmsg_type == SCM_RIGHTS) {
3889             size_t numfds;
3890             int *fdp;
3891 
3892             numfds = cmsgdatalen / sizeof(int);
3893             fdp = (int *)CMSG_DATA(cmsgh);
3894             while (numfds-- > 0)
3895                 close(*fdp++);
3896         }
3897         if (cmsg_status != 0)
3898             break;
3899     }
3900 #endif /* SCM_RIGHTS */
3901     goto finally;
3902 }
3903 
3904 
3905 static PyObject *
makeval_recvmsg(ssize_t received,void * data)3906 makeval_recvmsg(ssize_t received, void *data)
3907 {
3908     PyObject **buf = data;
3909 
3910     if (received < PyBytes_GET_SIZE(*buf))
3911         _PyBytes_Resize(buf, received);
3912     Py_XINCREF(*buf);
3913     return *buf;
3914 }
3915 
3916 /* s.recvmsg(bufsize[, ancbufsize[, flags]]) method */
3917 
3918 static PyObject *
sock_recvmsg(PySocketSockObject * s,PyObject * args)3919 sock_recvmsg(PySocketSockObject *s, PyObject *args)
3920 {
3921     Py_ssize_t bufsize, ancbufsize = 0;
3922     int flags = 0;
3923     struct iovec iov;
3924     PyObject *buf = NULL, *retval = NULL;
3925 
3926     if (!PyArg_ParseTuple(args, "n|ni:recvmsg", &bufsize, &ancbufsize, &flags))
3927         return NULL;
3928 
3929     if (bufsize < 0) {
3930         PyErr_SetString(PyExc_ValueError, "negative buffer size in recvmsg()");
3931         return NULL;
3932     }
3933     if ((buf = PyBytes_FromStringAndSize(NULL, bufsize)) == NULL)
3934         return NULL;
3935     iov.iov_base = PyBytes_AS_STRING(buf);
3936     iov.iov_len = bufsize;
3937 
3938     /* Note that we're passing a pointer to *our pointer* to the bytes
3939        object here (&buf); makeval_recvmsg() may incref the object, or
3940        deallocate it and set our pointer to NULL. */
3941     retval = sock_recvmsg_guts(s, &iov, 1, flags, ancbufsize,
3942                                &makeval_recvmsg, &buf);
3943     Py_XDECREF(buf);
3944     return retval;
3945 }
3946 
3947 PyDoc_STRVAR(recvmsg_doc,
3948 "recvmsg(bufsize[, ancbufsize[, flags]]) -> (data, ancdata, msg_flags, address)\n\
3949 \n\
3950 Receive normal data (up to bufsize bytes) and ancillary data from the\n\
3951 socket.  The ancbufsize argument sets the size in bytes of the\n\
3952 internal buffer used to receive the ancillary data; it defaults to 0,\n\
3953 meaning that no ancillary data will be received.  Appropriate buffer\n\
3954 sizes for ancillary data can be calculated using CMSG_SPACE() or\n\
3955 CMSG_LEN(), and items which do not fit into the buffer might be\n\
3956 truncated or discarded.  The flags argument defaults to 0 and has the\n\
3957 same meaning as for recv().\n\
3958 \n\
3959 The return value is a 4-tuple: (data, ancdata, msg_flags, address).\n\
3960 The data item is a bytes object holding the non-ancillary data\n\
3961 received.  The ancdata item is a list of zero or more tuples\n\
3962 (cmsg_level, cmsg_type, cmsg_data) representing the ancillary data\n\
3963 (control messages) received: cmsg_level and cmsg_type are integers\n\
3964 specifying the protocol level and protocol-specific type respectively,\n\
3965 and cmsg_data is a bytes object holding the associated data.  The\n\
3966 msg_flags item is the bitwise OR of various flags indicating\n\
3967 conditions on the received message; see your system documentation for\n\
3968 details.  If the receiving socket is unconnected, address is the\n\
3969 address of the sending socket, if available; otherwise, its value is\n\
3970 unspecified.\n\
3971 \n\
3972 If recvmsg() raises an exception after the system call returns, it\n\
3973 will first attempt to close any file descriptors received via the\n\
3974 SCM_RIGHTS mechanism.");
3975 
3976 
3977 static PyObject *
makeval_recvmsg_into(ssize_t received,void * data)3978 makeval_recvmsg_into(ssize_t received, void *data)
3979 {
3980     return PyLong_FromSsize_t(received);
3981 }
3982 
3983 /* s.recvmsg_into(buffers[, ancbufsize[, flags]]) method */
3984 
3985 static PyObject *
sock_recvmsg_into(PySocketSockObject * s,PyObject * args)3986 sock_recvmsg_into(PySocketSockObject *s, PyObject *args)
3987 {
3988     Py_ssize_t ancbufsize = 0;
3989     int flags = 0;
3990     struct iovec *iovs = NULL;
3991     Py_ssize_t i, nitems, nbufs = 0;
3992     Py_buffer *bufs = NULL;
3993     PyObject *buffers_arg, *fast, *retval = NULL;
3994 
3995     if (!PyArg_ParseTuple(args, "O|ni:recvmsg_into",
3996                           &buffers_arg, &ancbufsize, &flags))
3997         return NULL;
3998 
3999     if ((fast = PySequence_Fast(buffers_arg,
4000                                 "recvmsg_into() argument 1 must be an "
4001                                 "iterable")) == NULL)
4002         return NULL;
4003     nitems = PySequence_Fast_GET_SIZE(fast);
4004     if (nitems > INT_MAX) {
4005         PyErr_SetString(PyExc_OSError, "recvmsg_into() argument 1 is too long");
4006         goto finally;
4007     }
4008 
4009     /* Fill in an iovec for each item, and save the Py_buffer
4010        structs to release afterwards. */
4011     if (nitems > 0 && ((iovs = PyMem_New(struct iovec, nitems)) == NULL ||
4012                        (bufs = PyMem_New(Py_buffer, nitems)) == NULL)) {
4013         PyErr_NoMemory();
4014         goto finally;
4015     }
4016     for (; nbufs < nitems; nbufs++) {
4017         if (!PyArg_Parse(PySequence_Fast_GET_ITEM(fast, nbufs),
4018                          "w*;recvmsg_into() argument 1 must be an iterable "
4019                          "of single-segment read-write buffers",
4020                          &bufs[nbufs]))
4021             goto finally;
4022         iovs[nbufs].iov_base = bufs[nbufs].buf;
4023         iovs[nbufs].iov_len = bufs[nbufs].len;
4024     }
4025 
4026     retval = sock_recvmsg_guts(s, iovs, nitems, flags, ancbufsize,
4027                                &makeval_recvmsg_into, NULL);
4028 finally:
4029     for (i = 0; i < nbufs; i++)
4030         PyBuffer_Release(&bufs[i]);
4031     PyMem_Free(bufs);
4032     PyMem_Free(iovs);
4033     Py_DECREF(fast);
4034     return retval;
4035 }
4036 
4037 PyDoc_STRVAR(recvmsg_into_doc,
4038 "recvmsg_into(buffers[, ancbufsize[, flags]]) -> (nbytes, ancdata, msg_flags, address)\n\
4039 \n\
4040 Receive normal data and ancillary data from the socket, scattering the\n\
4041 non-ancillary data into a series of buffers.  The buffers argument\n\
4042 must be an iterable of objects that export writable buffers\n\
4043 (e.g. bytearray objects); these will be filled with successive chunks\n\
4044 of the non-ancillary data until it has all been written or there are\n\
4045 no more buffers.  The ancbufsize argument sets the size in bytes of\n\
4046 the internal buffer used to receive the ancillary data; it defaults to\n\
4047 0, meaning that no ancillary data will be received.  Appropriate\n\
4048 buffer sizes for ancillary data can be calculated using CMSG_SPACE()\n\
4049 or CMSG_LEN(), and items which do not fit into the buffer might be\n\
4050 truncated or discarded.  The flags argument defaults to 0 and has the\n\
4051 same meaning as for recv().\n\
4052 \n\
4053 The return value is a 4-tuple: (nbytes, ancdata, msg_flags, address).\n\
4054 The nbytes item is the total number of bytes of non-ancillary data\n\
4055 written into the buffers.  The ancdata item is a list of zero or more\n\
4056 tuples (cmsg_level, cmsg_type, cmsg_data) representing the ancillary\n\
4057 data (control messages) received: cmsg_level and cmsg_type are\n\
4058 integers specifying the protocol level and protocol-specific type\n\
4059 respectively, and cmsg_data is a bytes object holding the associated\n\
4060 data.  The msg_flags item is the bitwise OR of various flags\n\
4061 indicating conditions on the received message; see your system\n\
4062 documentation for details.  If the receiving socket is unconnected,\n\
4063 address is the address of the sending socket, if available; otherwise,\n\
4064 its value is unspecified.\n\
4065 \n\
4066 If recvmsg_into() raises an exception after the system call returns,\n\
4067 it will first attempt to close any file descriptors received via the\n\
4068 SCM_RIGHTS mechanism.");
4069 #endif    /* CMSG_LEN */
4070 
4071 
4072 struct sock_send {
4073     char *buf;
4074     Py_ssize_t len;
4075     int flags;
4076     Py_ssize_t result;
4077 };
4078 
4079 static int
sock_send_impl(PySocketSockObject * s,void * data)4080 sock_send_impl(PySocketSockObject *s, void *data)
4081 {
4082     struct sock_send *ctx = data;
4083 
4084 #ifdef MS_WINDOWS
4085     if (ctx->len > INT_MAX)
4086         ctx->len = INT_MAX;
4087     ctx->result = send(s->sock_fd, ctx->buf, (int)ctx->len, ctx->flags);
4088 #else
4089     ctx->result = send(s->sock_fd, ctx->buf, ctx->len, ctx->flags);
4090 #endif
4091     return (ctx->result >= 0);
4092 }
4093 
4094 /* s.send(data [,flags]) method */
4095 
4096 static PyObject *
sock_send(PySocketSockObject * s,PyObject * args)4097 sock_send(PySocketSockObject *s, PyObject *args)
4098 {
4099     int flags = 0;
4100     Py_buffer pbuf;
4101     struct sock_send ctx;
4102 
4103     if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags))
4104         return NULL;
4105 
4106     if (!IS_SELECTABLE(s)) {
4107         PyBuffer_Release(&pbuf);
4108         return select_error();
4109     }
4110     ctx.buf = pbuf.buf;
4111     ctx.len = pbuf.len;
4112     ctx.flags = flags;
4113     if (sock_call(s, 1, sock_send_impl, &ctx) < 0) {
4114         PyBuffer_Release(&pbuf);
4115         return NULL;
4116     }
4117     PyBuffer_Release(&pbuf);
4118 
4119     return PyLong_FromSsize_t(ctx.result);
4120 }
4121 
4122 PyDoc_STRVAR(send_doc,
4123 "send(data[, flags]) -> count\n\
4124 \n\
4125 Send a data string to the socket.  For the optional flags\n\
4126 argument, see the Unix manual.  Return the number of bytes\n\
4127 sent; this may be less than len(data) if the network is busy.");
4128 
4129 
4130 /* s.sendall(data [,flags]) method */
4131 
4132 static PyObject *
sock_sendall(PySocketSockObject * s,PyObject * args)4133 sock_sendall(PySocketSockObject *s, PyObject *args)
4134 {
4135     char *buf;
4136     Py_ssize_t len, n;
4137     int flags = 0;
4138     Py_buffer pbuf;
4139     struct sock_send ctx;
4140     int has_timeout = (s->sock_timeout > 0);
4141     _PyTime_t interval = s->sock_timeout;
4142     _PyTime_t deadline = 0;
4143     int deadline_initialized = 0;
4144     PyObject *res = NULL;
4145 
4146     if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags))
4147         return NULL;
4148     buf = pbuf.buf;
4149     len = pbuf.len;
4150 
4151     if (!IS_SELECTABLE(s)) {
4152         PyBuffer_Release(&pbuf);
4153         return select_error();
4154     }
4155 
4156     do {
4157         if (has_timeout) {
4158             if (deadline_initialized) {
4159                 /* recompute the timeout */
4160                 interval = deadline - _PyTime_GetMonotonicClock();
4161             }
4162             else {
4163                 deadline_initialized = 1;
4164                 deadline = _PyTime_GetMonotonicClock() + s->sock_timeout;
4165             }
4166 
4167             if (interval <= 0) {
4168                 PyErr_SetString(socket_timeout, "timed out");
4169                 goto done;
4170             }
4171         }
4172 
4173         ctx.buf = buf;
4174         ctx.len = len;
4175         ctx.flags = flags;
4176         if (sock_call_ex(s, 1, sock_send_impl, &ctx, 0, NULL, interval) < 0)
4177             goto done;
4178         n = ctx.result;
4179         assert(n >= 0);
4180 
4181         buf += n;
4182         len -= n;
4183 
4184         /* We must run our signal handlers before looping again.
4185            send() can return a successful partial write when it is
4186            interrupted, so we can't restrict ourselves to EINTR. */
4187         if (PyErr_CheckSignals())
4188             goto done;
4189     } while (len > 0);
4190     PyBuffer_Release(&pbuf);
4191 
4192     Py_INCREF(Py_None);
4193     res = Py_None;
4194 
4195 done:
4196     PyBuffer_Release(&pbuf);
4197     return res;
4198 }
4199 
4200 PyDoc_STRVAR(sendall_doc,
4201 "sendall(data[, flags])\n\
4202 \n\
4203 Send a data string to the socket.  For the optional flags\n\
4204 argument, see the Unix manual.  This calls send() repeatedly\n\
4205 until all data is sent.  If an error occurs, it's impossible\n\
4206 to tell how much data has been sent.");
4207 
4208 
4209 struct sock_sendto {
4210     char *buf;
4211     Py_ssize_t len;
4212     int flags;
4213     int addrlen;
4214     sock_addr_t *addrbuf;
4215     Py_ssize_t result;
4216 };
4217 
4218 static int
sock_sendto_impl(PySocketSockObject * s,void * data)4219 sock_sendto_impl(PySocketSockObject *s, void *data)
4220 {
4221     struct sock_sendto *ctx = data;
4222 
4223 #ifdef MS_WINDOWS
4224     if (ctx->len > INT_MAX)
4225         ctx->len = INT_MAX;
4226     ctx->result = sendto(s->sock_fd, ctx->buf, (int)ctx->len, ctx->flags,
4227                          SAS2SA(ctx->addrbuf), ctx->addrlen);
4228 #else
4229     ctx->result = sendto(s->sock_fd, ctx->buf, ctx->len, ctx->flags,
4230                          SAS2SA(ctx->addrbuf), ctx->addrlen);
4231 #endif
4232     return (ctx->result >= 0);
4233 }
4234 
4235 /* s.sendto(data, [flags,] sockaddr) method */
4236 
4237 static PyObject *
sock_sendto(PySocketSockObject * s,PyObject * args)4238 sock_sendto(PySocketSockObject *s, PyObject *args)
4239 {
4240     Py_buffer pbuf;
4241     PyObject *addro;
4242     Py_ssize_t arglen;
4243     sock_addr_t addrbuf;
4244     int addrlen, flags;
4245     struct sock_sendto ctx;
4246 
4247     flags = 0;
4248     arglen = PyTuple_Size(args);
4249     switch (arglen) {
4250         case 2:
4251             if (!PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro)) {
4252                 return NULL;
4253             }
4254             break;
4255         case 3:
4256             if (!PyArg_ParseTuple(args, "y*iO:sendto",
4257                                   &pbuf, &flags, &addro)) {
4258                 return NULL;
4259             }
4260             break;
4261         default:
4262             PyErr_Format(PyExc_TypeError,
4263                          "sendto() takes 2 or 3 arguments (%zd given)",
4264                          arglen);
4265             return NULL;
4266     }
4267 
4268     if (!IS_SELECTABLE(s)) {
4269         PyBuffer_Release(&pbuf);
4270         return select_error();
4271     }
4272 
4273     if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen, "sendto")) {
4274         PyBuffer_Release(&pbuf);
4275         return NULL;
4276     }
4277 
4278     if (PySys_Audit("socket.sendto", "OO", s, addro) < 0) {
4279         return NULL;
4280     }
4281 
4282     ctx.buf = pbuf.buf;
4283     ctx.len = pbuf.len;
4284     ctx.flags = flags;
4285     ctx.addrlen = addrlen;
4286     ctx.addrbuf = &addrbuf;
4287     if (sock_call(s, 1, sock_sendto_impl, &ctx) < 0) {
4288         PyBuffer_Release(&pbuf);
4289         return NULL;
4290     }
4291     PyBuffer_Release(&pbuf);
4292 
4293     return PyLong_FromSsize_t(ctx.result);
4294 }
4295 
4296 PyDoc_STRVAR(sendto_doc,
4297 "sendto(data[, flags], address) -> count\n\
4298 \n\
4299 Like send(data, flags) but allows specifying the destination address.\n\
4300 For IP sockets, the address is a pair (hostaddr, port).");
4301 
4302 
4303 /* The sendmsg() and recvmsg[_into]() methods require a working
4304    CMSG_LEN().  See the comment near get_CMSG_LEN(). */
4305 #ifdef CMSG_LEN
4306 struct sock_sendmsg {
4307     struct msghdr *msg;
4308     int flags;
4309     ssize_t result;
4310 };
4311 
4312 static int
sock_sendmsg_iovec(PySocketSockObject * s,PyObject * data_arg,struct msghdr * msg,Py_buffer ** databufsout,Py_ssize_t * ndatabufsout)4313 sock_sendmsg_iovec(PySocketSockObject *s, PyObject *data_arg,
4314                    struct msghdr *msg,
4315                    Py_buffer **databufsout, Py_ssize_t *ndatabufsout) {
4316     Py_ssize_t ndataparts, ndatabufs = 0;
4317     int result = -1;
4318     struct iovec *iovs = NULL;
4319     PyObject *data_fast = NULL;
4320     Py_buffer *databufs = NULL;
4321 
4322     /* Fill in an iovec for each message part, and save the Py_buffer
4323        structs to release afterwards. */
4324     data_fast = PySequence_Fast(data_arg,
4325                                 "sendmsg() argument 1 must be an "
4326                                 "iterable");
4327     if (data_fast == NULL) {
4328         goto finally;
4329     }
4330 
4331     ndataparts = PySequence_Fast_GET_SIZE(data_fast);
4332     if (ndataparts > INT_MAX) {
4333         PyErr_SetString(PyExc_OSError, "sendmsg() argument 1 is too long");
4334         goto finally;
4335     }
4336 
4337     msg->msg_iovlen = ndataparts;
4338     if (ndataparts > 0) {
4339         iovs = PyMem_New(struct iovec, ndataparts);
4340         if (iovs == NULL) {
4341             PyErr_NoMemory();
4342             goto finally;
4343         }
4344         msg->msg_iov = iovs;
4345 
4346         databufs = PyMem_New(Py_buffer, ndataparts);
4347         if (databufs == NULL) {
4348             PyErr_NoMemory();
4349             goto finally;
4350         }
4351     }
4352     for (; ndatabufs < ndataparts; ndatabufs++) {
4353         if (!PyArg_Parse(PySequence_Fast_GET_ITEM(data_fast, ndatabufs),
4354                          "y*;sendmsg() argument 1 must be an iterable of "
4355                          "bytes-like objects",
4356                          &databufs[ndatabufs]))
4357             goto finally;
4358         iovs[ndatabufs].iov_base = databufs[ndatabufs].buf;
4359         iovs[ndatabufs].iov_len = databufs[ndatabufs].len;
4360     }
4361     result = 0;
4362   finally:
4363     *databufsout = databufs;
4364     *ndatabufsout = ndatabufs;
4365     Py_XDECREF(data_fast);
4366     return result;
4367 }
4368 
4369 static int
sock_sendmsg_impl(PySocketSockObject * s,void * data)4370 sock_sendmsg_impl(PySocketSockObject *s, void *data)
4371 {
4372     struct sock_sendmsg *ctx = data;
4373 
4374     ctx->result = sendmsg(s->sock_fd, ctx->msg, ctx->flags);
4375     return (ctx->result >= 0);
4376 }
4377 
4378 /* s.sendmsg(buffers[, ancdata[, flags[, address]]]) method */
4379 
4380 static PyObject *
sock_sendmsg(PySocketSockObject * s,PyObject * args)4381 sock_sendmsg(PySocketSockObject *s, PyObject *args)
4382 {
4383     Py_ssize_t i, ndatabufs = 0, ncmsgs, ncmsgbufs = 0;
4384     Py_buffer *databufs = NULL;
4385     sock_addr_t addrbuf;
4386     struct msghdr msg;
4387     struct cmsginfo {
4388         int level;
4389         int type;
4390         Py_buffer data;
4391     } *cmsgs = NULL;
4392     void *controlbuf = NULL;
4393     size_t controllen, controllen_last;
4394     int addrlen, flags = 0;
4395     PyObject *data_arg, *cmsg_arg = NULL, *addr_arg = NULL,
4396         *cmsg_fast = NULL, *retval = NULL;
4397     struct sock_sendmsg ctx;
4398 
4399     if (!PyArg_ParseTuple(args, "O|OiO:sendmsg",
4400                           &data_arg, &cmsg_arg, &flags, &addr_arg)) {
4401         return NULL;
4402     }
4403 
4404     memset(&msg, 0, sizeof(msg));
4405 
4406     /* Parse destination address. */
4407     if (addr_arg != NULL && addr_arg != Py_None) {
4408         if (!getsockaddrarg(s, addr_arg, SAS2SA(&addrbuf), &addrlen,
4409                             "sendmsg"))
4410         {
4411             goto finally;
4412         }
4413         if (PySys_Audit("socket.sendmsg", "OO", s, addr_arg) < 0) {
4414             return NULL;
4415         }
4416         msg.msg_name = &addrbuf;
4417         msg.msg_namelen = addrlen;
4418     } else {
4419         if (PySys_Audit("socket.sendmsg", "OO", s, Py_None) < 0) {
4420             return NULL;
4421         }
4422     }
4423 
4424     /* Fill in an iovec for each message part, and save the Py_buffer
4425        structs to release afterwards. */
4426     if (sock_sendmsg_iovec(s, data_arg, &msg, &databufs, &ndatabufs) == -1) {
4427         goto finally;
4428     }
4429 
4430     if (cmsg_arg == NULL)
4431         ncmsgs = 0;
4432     else {
4433         if ((cmsg_fast = PySequence_Fast(cmsg_arg,
4434                                          "sendmsg() argument 2 must be an "
4435                                          "iterable")) == NULL)
4436             goto finally;
4437         ncmsgs = PySequence_Fast_GET_SIZE(cmsg_fast);
4438     }
4439 
4440 #ifndef CMSG_SPACE
4441     if (ncmsgs > 1) {
4442         PyErr_SetString(PyExc_OSError,
4443                         "sending multiple control messages is not supported "
4444                         "on this system");
4445         goto finally;
4446     }
4447 #endif
4448     /* Save level, type and Py_buffer for each control message,
4449        and calculate total size. */
4450     if (ncmsgs > 0 && (cmsgs = PyMem_New(struct cmsginfo, ncmsgs)) == NULL) {
4451         PyErr_NoMemory();
4452         goto finally;
4453     }
4454     controllen = controllen_last = 0;
4455     while (ncmsgbufs < ncmsgs) {
4456         size_t bufsize, space;
4457 
4458         if (!PyArg_Parse(PySequence_Fast_GET_ITEM(cmsg_fast, ncmsgbufs),
4459                          "(iiy*):[sendmsg() ancillary data items]",
4460                          &cmsgs[ncmsgbufs].level,
4461                          &cmsgs[ncmsgbufs].type,
4462                          &cmsgs[ncmsgbufs].data))
4463             goto finally;
4464         bufsize = cmsgs[ncmsgbufs++].data.len;
4465 
4466 #ifdef CMSG_SPACE
4467         if (!get_CMSG_SPACE(bufsize, &space)) {
4468 #else
4469         if (!get_CMSG_LEN(bufsize, &space)) {
4470 #endif
4471             PyErr_SetString(PyExc_OSError, "ancillary data item too large");
4472             goto finally;
4473         }
4474         controllen += space;
4475         if (controllen > SOCKLEN_T_LIMIT || controllen < controllen_last) {
4476             PyErr_SetString(PyExc_OSError, "too much ancillary data");
4477             goto finally;
4478         }
4479         controllen_last = controllen;
4480     }
4481 
4482     /* Construct ancillary data block from control message info. */
4483     if (ncmsgbufs > 0) {
4484         struct cmsghdr *cmsgh = NULL;
4485 
4486         controlbuf = PyMem_Malloc(controllen);
4487         if (controlbuf == NULL) {
4488             PyErr_NoMemory();
4489             goto finally;
4490         }
4491         msg.msg_control = controlbuf;
4492 
4493         msg.msg_controllen = controllen;
4494 
4495         /* Need to zero out the buffer as a workaround for glibc's
4496            CMSG_NXTHDR() implementation.  After getting the pointer to
4497            the next header, it checks its (uninitialized) cmsg_len
4498            member to see if the "message" fits in the buffer, and
4499            returns NULL if it doesn't.  Zero-filling the buffer
4500            ensures that this doesn't happen. */
4501         memset(controlbuf, 0, controllen);
4502 
4503         for (i = 0; i < ncmsgbufs; i++) {
4504             size_t msg_len, data_len = cmsgs[i].data.len;
4505             int enough_space = 0;
4506 
4507             cmsgh = (i == 0) ? CMSG_FIRSTHDR(&msg) : CMSG_NXTHDR(&msg, cmsgh);
4508             if (cmsgh == NULL) {
4509                 PyErr_Format(PyExc_RuntimeError,
4510                              "unexpected NULL result from %s()",
4511                              (i == 0) ? "CMSG_FIRSTHDR" : "CMSG_NXTHDR");
4512                 goto finally;
4513             }
4514             if (!get_CMSG_LEN(data_len, &msg_len)) {
4515                 PyErr_SetString(PyExc_RuntimeError,
4516                                 "item size out of range for CMSG_LEN()");
4517                 goto finally;
4518             }
4519             if (cmsg_min_space(&msg, cmsgh, msg_len)) {
4520                 size_t space;
4521 
4522                 cmsgh->cmsg_len = msg_len;
4523                 if (get_cmsg_data_space(&msg, cmsgh, &space))
4524                     enough_space = (space >= data_len);
4525             }
4526             if (!enough_space) {
4527                 PyErr_SetString(PyExc_RuntimeError,
4528                                 "ancillary data does not fit in calculated "
4529                                 "space");
4530                 goto finally;
4531             }
4532             cmsgh->cmsg_level = cmsgs[i].level;
4533             cmsgh->cmsg_type = cmsgs[i].type;
4534             memcpy(CMSG_DATA(cmsgh), cmsgs[i].data.buf, data_len);
4535         }
4536     }
4537 
4538     /* Make the system call. */
4539     if (!IS_SELECTABLE(s)) {
4540         select_error();
4541         goto finally;
4542     }
4543 
4544     ctx.msg = &msg;
4545     ctx.flags = flags;
4546     if (sock_call(s, 1, sock_sendmsg_impl, &ctx) < 0)
4547         goto finally;
4548 
4549     retval = PyLong_FromSsize_t(ctx.result);
4550 
4551 finally:
4552     PyMem_Free(controlbuf);
4553     for (i = 0; i < ncmsgbufs; i++)
4554         PyBuffer_Release(&cmsgs[i].data);
4555     PyMem_Free(cmsgs);
4556     Py_XDECREF(cmsg_fast);
4557     PyMem_Free(msg.msg_iov);
4558     for (i = 0; i < ndatabufs; i++) {
4559         PyBuffer_Release(&databufs[i]);
4560     }
4561     PyMem_Free(databufs);
4562     return retval;
4563 }
4564 
4565 PyDoc_STRVAR(sendmsg_doc,
4566 "sendmsg(buffers[, ancdata[, flags[, address]]]) -> count\n\
4567 \n\
4568 Send normal and ancillary data to the socket, gathering the\n\
4569 non-ancillary data from a series of buffers and concatenating it into\n\
4570 a single message.  The buffers argument specifies the non-ancillary\n\
4571 data as an iterable of bytes-like objects (e.g. bytes objects).\n\
4572 The ancdata argument specifies the ancillary data (control messages)\n\
4573 as an iterable of zero or more tuples (cmsg_level, cmsg_type,\n\
4574 cmsg_data), where cmsg_level and cmsg_type are integers specifying the\n\
4575 protocol level and protocol-specific type respectively, and cmsg_data\n\
4576 is a bytes-like object holding the associated data.  The flags\n\
4577 argument defaults to 0 and has the same meaning as for send().  If\n\
4578 address is supplied and not None, it sets a destination address for\n\
4579 the message.  The return value is the number of bytes of non-ancillary\n\
4580 data sent.");
4581 #endif    /* CMSG_LEN */
4582 
4583 #ifdef HAVE_SOCKADDR_ALG
4584 static PyObject*
4585 sock_sendmsg_afalg(PySocketSockObject *self, PyObject *args, PyObject *kwds)
4586 {
4587     PyObject *retval = NULL;
4588 
4589     Py_ssize_t i, ndatabufs = 0;
4590     Py_buffer *databufs = NULL;
4591     PyObject *data_arg = NULL;
4592 
4593     Py_buffer iv = {NULL, NULL};
4594 
4595     PyObject *opobj = NULL;
4596     int op = -1;
4597 
4598     PyObject *assoclenobj = NULL;
4599     int assoclen = -1;
4600 
4601     unsigned int *uiptr;
4602     int flags = 0;
4603 
4604     struct msghdr msg;
4605     struct cmsghdr *header = NULL;
4606     struct af_alg_iv *alg_iv = NULL;
4607     struct sock_sendmsg ctx;
4608     Py_ssize_t controllen;
4609     void *controlbuf = NULL;
4610     static char *keywords[] = {"msg", "op", "iv", "assoclen", "flags", 0};
4611 
4612     if (self->sock_family != AF_ALG) {
4613         PyErr_SetString(PyExc_OSError,
4614                         "algset is only supported for AF_ALG");
4615         return NULL;
4616     }
4617 
4618     if (!PyArg_ParseTupleAndKeywords(args, kwds,
4619                                      "|O$O!y*O!i:sendmsg_afalg", keywords,
4620                                      &data_arg,
4621                                      &PyLong_Type, &opobj, &iv,
4622                                      &PyLong_Type, &assoclenobj, &flags)) {
4623         return NULL;
4624     }
4625 
4626     memset(&msg, 0, sizeof(msg));
4627 
4628     /* op is a required, keyword-only argument >= 0 */
4629     if (opobj != NULL) {
4630         op = _PyLong_AsInt(opobj);
4631     }
4632     if (op < 0) {
4633         /* override exception from _PyLong_AsInt() */
4634         PyErr_SetString(PyExc_TypeError,
4635                         "Invalid or missing argument 'op'");
4636         goto finally;
4637     }
4638     /* assoclen is optional but must be >= 0 */
4639     if (assoclenobj != NULL) {
4640         assoclen = _PyLong_AsInt(assoclenobj);
4641         if (assoclen == -1 && PyErr_Occurred()) {
4642             goto finally;
4643         }
4644         if (assoclen < 0) {
4645             PyErr_SetString(PyExc_TypeError,
4646                             "assoclen must be positive");
4647             goto finally;
4648         }
4649     }
4650 
4651     controllen = CMSG_SPACE(4);
4652     if (iv.buf != NULL) {
4653         controllen += CMSG_SPACE(sizeof(*alg_iv) + iv.len);
4654     }
4655     if (assoclen >= 0) {
4656         controllen += CMSG_SPACE(4);
4657     }
4658 
4659     controlbuf = PyMem_Malloc(controllen);
4660     if (controlbuf == NULL) {
4661         PyErr_NoMemory();
4662         goto finally;
4663     }
4664     memset(controlbuf, 0, controllen);
4665 
4666     msg.msg_controllen = controllen;
4667     msg.msg_control = controlbuf;
4668 
4669     /* Fill in an iovec for each message part, and save the Py_buffer
4670        structs to release afterwards. */
4671     if (data_arg != NULL) {
4672         if (sock_sendmsg_iovec(self, data_arg, &msg, &databufs, &ndatabufs) == -1) {
4673             goto finally;
4674         }
4675     }
4676 
4677     /* set operation to encrypt or decrypt */
4678     header = CMSG_FIRSTHDR(&msg);
4679     if (header == NULL) {
4680         PyErr_SetString(PyExc_RuntimeError,
4681                         "unexpected NULL result from CMSG_FIRSTHDR");
4682         goto finally;
4683     }
4684     header->cmsg_level = SOL_ALG;
4685     header->cmsg_type = ALG_SET_OP;
4686     header->cmsg_len = CMSG_LEN(4);
4687     uiptr = (void*)CMSG_DATA(header);
4688     *uiptr = (unsigned int)op;
4689 
4690     /* set initialization vector */
4691     if (iv.buf != NULL) {
4692         header = CMSG_NXTHDR(&msg, header);
4693         if (header == NULL) {
4694             PyErr_SetString(PyExc_RuntimeError,
4695                             "unexpected NULL result from CMSG_NXTHDR(iv)");
4696             goto finally;
4697         }
4698         header->cmsg_level = SOL_ALG;
4699         header->cmsg_type = ALG_SET_IV;
4700         header->cmsg_len = CMSG_SPACE(sizeof(*alg_iv) + iv.len);
4701         alg_iv = (void*)CMSG_DATA(header);
4702         alg_iv->ivlen = iv.len;
4703         memcpy(alg_iv->iv, iv.buf, iv.len);
4704     }
4705 
4706     /* set length of associated data for AEAD */
4707     if (assoclen >= 0) {
4708         header = CMSG_NXTHDR(&msg, header);
4709         if (header == NULL) {
4710             PyErr_SetString(PyExc_RuntimeError,
4711                             "unexpected NULL result from CMSG_NXTHDR(assoc)");
4712             goto finally;
4713         }
4714         header->cmsg_level = SOL_ALG;
4715         header->cmsg_type = ALG_SET_AEAD_ASSOCLEN;
4716         header->cmsg_len = CMSG_LEN(4);
4717         uiptr = (void*)CMSG_DATA(header);
4718         *uiptr = (unsigned int)assoclen;
4719     }
4720 
4721     ctx.msg = &msg;
4722     ctx.flags = flags;
4723     if (sock_call(self, 1, sock_sendmsg_impl, &ctx) < 0) {
4724         goto finally;
4725     }
4726 
4727     retval = PyLong_FromSsize_t(ctx.result);
4728 
4729   finally:
4730     PyMem_Free(controlbuf);
4731     if (iv.buf != NULL) {
4732         PyBuffer_Release(&iv);
4733     }
4734     PyMem_Free(msg.msg_iov);
4735     for (i = 0; i < ndatabufs; i++) {
4736         PyBuffer_Release(&databufs[i]);
4737     }
4738     PyMem_Free(databufs);
4739     return retval;
4740 }
4741 
4742 PyDoc_STRVAR(sendmsg_afalg_doc,
4743 "sendmsg_afalg([msg], *, op[, iv[, assoclen[, flags=MSG_MORE]]])\n\
4744 \n\
4745 Set operation mode, IV and length of associated data for an AF_ALG\n\
4746 operation socket.");
4747 #endif
4748 
4749 /* s.shutdown(how) method */
4750 
4751 static PyObject *
4752 sock_shutdown(PySocketSockObject *s, PyObject *arg)
4753 {
4754     int how;
4755     int res;
4756 
4757     how = _PyLong_AsInt(arg);
4758     if (how == -1 && PyErr_Occurred())
4759         return NULL;
4760     Py_BEGIN_ALLOW_THREADS
4761     res = shutdown(s->sock_fd, how);
4762     Py_END_ALLOW_THREADS
4763     if (res < 0)
4764         return s->errorhandler();
4765     Py_RETURN_NONE;
4766 }
4767 
4768 PyDoc_STRVAR(shutdown_doc,
4769 "shutdown(flag)\n\
4770 \n\
4771 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
4772 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
4773 
4774 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
4775 static PyObject*
4776 sock_ioctl(PySocketSockObject *s, PyObject *arg)
4777 {
4778     unsigned long cmd = SIO_RCVALL;
4779     PyObject *argO;
4780     DWORD recv;
4781 
4782     if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
4783         return NULL;
4784 
4785     switch (cmd) {
4786     case SIO_RCVALL: {
4787         unsigned int option = RCVALL_ON;
4788         if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
4789             return NULL;
4790         if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
4791                          NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
4792             return set_error();
4793         }
4794         return PyLong_FromUnsignedLong(recv); }
4795     case SIO_KEEPALIVE_VALS: {
4796         struct tcp_keepalive ka;
4797         if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
4798                         &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
4799             return NULL;
4800         if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
4801                          NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
4802             return set_error();
4803         }
4804         return PyLong_FromUnsignedLong(recv); }
4805 #if defined(SIO_LOOPBACK_FAST_PATH)
4806     case SIO_LOOPBACK_FAST_PATH: {
4807         unsigned int option;
4808         if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
4809             return NULL;
4810         if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
4811                          NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
4812             return set_error();
4813         }
4814         return PyLong_FromUnsignedLong(recv); }
4815 #endif
4816     default:
4817         PyErr_Format(PyExc_ValueError, "invalid ioctl command %lu", cmd);
4818         return NULL;
4819     }
4820 }
4821 PyDoc_STRVAR(sock_ioctl_doc,
4822 "ioctl(cmd, option) -> long\n\
4823 \n\
4824 Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
4825 SIO_RCVALL:  'option' must be one of the socket.RCVALL_* constants.\n\
4826 SIO_KEEPALIVE_VALS:  'option' is a tuple of (onoff, timeout, interval).\n\
4827 SIO_LOOPBACK_FAST_PATH: 'option' is a boolean value, and is disabled by default");
4828 #endif
4829 
4830 #if defined(MS_WINDOWS)
4831 static PyObject*
4832 sock_share(PySocketSockObject *s, PyObject *arg)
4833 {
4834     WSAPROTOCOL_INFOW info;
4835     DWORD processId;
4836     int result;
4837 
4838     if (!PyArg_ParseTuple(arg, "I", &processId))
4839         return NULL;
4840 
4841     Py_BEGIN_ALLOW_THREADS
4842     result = WSADuplicateSocketW(s->sock_fd, processId, &info);
4843     Py_END_ALLOW_THREADS
4844     if (result == SOCKET_ERROR)
4845         return set_error();
4846     return PyBytes_FromStringAndSize((const char*)&info, sizeof(info));
4847 }
4848 PyDoc_STRVAR(sock_share_doc,
4849 "share(process_id) -> bytes\n\
4850 \n\
4851 Share the socket with another process.  The target process id\n\
4852 must be provided and the resulting bytes object passed to the target\n\
4853 process.  There the shared socket can be instantiated by calling\n\
4854 socket.fromshare().");
4855 
4856 
4857 #endif
4858 
4859 /* List of methods for socket objects */
4860 
4861 static PyMethodDef sock_methods[] = {
4862     {"_accept",           (PyCFunction)sock_accept, METH_NOARGS,
4863                       accept_doc},
4864     {"bind",              (PyCFunction)sock_bind, METH_O,
4865                       bind_doc},
4866     {"close",             (PyCFunction)sock_close, METH_NOARGS,
4867                       sock_close_doc},
4868     {"connect",           (PyCFunction)sock_connect, METH_O,
4869                       connect_doc},
4870     {"connect_ex",        (PyCFunction)sock_connect_ex, METH_O,
4871                       connect_ex_doc},
4872     {"detach",            (PyCFunction)sock_detach, METH_NOARGS,
4873                       detach_doc},
4874     {"fileno",            (PyCFunction)sock_fileno, METH_NOARGS,
4875                       fileno_doc},
4876 #ifdef HAVE_GETPEERNAME
4877     {"getpeername",       (PyCFunction)sock_getpeername,
4878                       METH_NOARGS, getpeername_doc},
4879 #endif
4880     {"getsockname",       (PyCFunction)sock_getsockname,
4881                       METH_NOARGS, getsockname_doc},
4882     {"getsockopt",        (PyCFunction)sock_getsockopt, METH_VARARGS,
4883                       getsockopt_doc},
4884 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
4885     {"ioctl",             (PyCFunction)sock_ioctl, METH_VARARGS,
4886                       sock_ioctl_doc},
4887 #endif
4888 #if defined(MS_WINDOWS)
4889     {"share",         (PyCFunction)sock_share, METH_VARARGS,
4890                       sock_share_doc},
4891 #endif
4892     {"listen",            (PyCFunction)sock_listen, METH_VARARGS,
4893                       listen_doc},
4894     {"recv",              (PyCFunction)sock_recv, METH_VARARGS,
4895                       recv_doc},
4896     {"recv_into",         (PyCFunction)(void(*)(void))sock_recv_into, METH_VARARGS | METH_KEYWORDS,
4897                       recv_into_doc},
4898     {"recvfrom",          (PyCFunction)sock_recvfrom, METH_VARARGS,
4899                       recvfrom_doc},
4900     {"recvfrom_into",  (PyCFunction)(void(*)(void))sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
4901                       recvfrom_into_doc},
4902     {"send",              (PyCFunction)sock_send, METH_VARARGS,
4903                       send_doc},
4904     {"sendall",           (PyCFunction)sock_sendall, METH_VARARGS,
4905                       sendall_doc},
4906     {"sendto",            (PyCFunction)sock_sendto, METH_VARARGS,
4907                       sendto_doc},
4908     {"setblocking",       (PyCFunction)sock_setblocking, METH_O,
4909                       setblocking_doc},
4910     {"getblocking",   (PyCFunction)sock_getblocking, METH_NOARGS,
4911                       getblocking_doc},
4912     {"settimeout",    (PyCFunction)sock_settimeout, METH_O,
4913                       settimeout_doc},
4914     {"gettimeout",    (PyCFunction)sock_gettimeout, METH_NOARGS,
4915                       gettimeout_doc},
4916     {"setsockopt",        (PyCFunction)sock_setsockopt, METH_VARARGS,
4917                       setsockopt_doc},
4918     {"shutdown",          (PyCFunction)sock_shutdown, METH_O,
4919                       shutdown_doc},
4920 #ifdef CMSG_LEN
4921     {"recvmsg",           (PyCFunction)sock_recvmsg, METH_VARARGS,
4922                       recvmsg_doc},
4923     {"recvmsg_into",      (PyCFunction)sock_recvmsg_into, METH_VARARGS,
4924                       recvmsg_into_doc,},
4925     {"sendmsg",           (PyCFunction)sock_sendmsg, METH_VARARGS,
4926                       sendmsg_doc},
4927 #endif
4928 #ifdef HAVE_SOCKADDR_ALG
4929     {"sendmsg_afalg",     (PyCFunction)(void(*)(void))sock_sendmsg_afalg, METH_VARARGS | METH_KEYWORDS,
4930                       sendmsg_afalg_doc},
4931 #endif
4932     {NULL,                      NULL}           /* sentinel */
4933 };
4934 
4935 /* SockObject members */
4936 static PyMemberDef sock_memberlist[] = {
4937        {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
4938        {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
4939        {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
4940        {0},
4941 };
4942 
4943 static PyGetSetDef sock_getsetlist[] = {
4944     {"timeout", (getter)sock_gettimeout, NULL, PyDoc_STR("the socket timeout")},
4945     {NULL} /* sentinel */
4946 };
4947 
4948 /* Deallocate a socket object in response to the last Py_DECREF().
4949    First close the file description. */
4950 
4951 static void
4952 sock_finalize(PySocketSockObject *s)
4953 {
4954     SOCKET_T fd;
4955     PyObject *error_type, *error_value, *error_traceback;
4956 
4957     /* Save the current exception, if any. */
4958     PyErr_Fetch(&error_type, &error_value, &error_traceback);
4959 
4960     if (s->sock_fd != INVALID_SOCKET) {
4961         if (PyErr_ResourceWarning((PyObject *)s, 1, "unclosed %R", s)) {
4962             /* Spurious errors can appear at shutdown */
4963             if (PyErr_ExceptionMatches(PyExc_Warning)) {
4964                 PyErr_WriteUnraisable((PyObject *)s);
4965             }
4966         }
4967 
4968         /* Only close the socket *after* logging the ResourceWarning warning
4969            to allow the logger to call socket methods like
4970            socket.getsockname(). If the socket is closed before, socket
4971            methods fails with the EBADF error. */
4972         fd = s->sock_fd;
4973         s->sock_fd = INVALID_SOCKET;
4974 
4975         /* We do not want to retry upon EINTR: see sock_close() */
4976         Py_BEGIN_ALLOW_THREADS
4977         (void) SOCKETCLOSE(fd);
4978         Py_END_ALLOW_THREADS
4979     }
4980 
4981     /* Restore the saved exception. */
4982     PyErr_Restore(error_type, error_value, error_traceback);
4983 }
4984 
4985 static void
4986 sock_dealloc(PySocketSockObject *s)
4987 {
4988     if (PyObject_CallFinalizerFromDealloc((PyObject *)s) < 0)
4989         return;
4990 
4991     Py_TYPE(s)->tp_free((PyObject *)s);
4992 }
4993 
4994 
4995 static PyObject *
4996 sock_repr(PySocketSockObject *s)
4997 {
4998     long sock_fd;
4999     /* On Windows, this test is needed because SOCKET_T is unsigned */
5000     if (s->sock_fd == INVALID_SOCKET) {
5001         sock_fd = -1;
5002     }
5003 #if SIZEOF_SOCKET_T > SIZEOF_LONG
5004     else if (s->sock_fd > LONG_MAX) {
5005         /* this can occur on Win64, and actually there is a special
5006            ugly printf formatter for decimal pointer length integer
5007            printing, only bother if necessary*/
5008         PyErr_SetString(PyExc_OverflowError,
5009                         "no printf formatter to display "
5010                         "the socket descriptor in decimal");
5011         return NULL;
5012     }
5013 #endif
5014     else
5015         sock_fd = (long)s->sock_fd;
5016     return PyUnicode_FromFormat(
5017         "<socket object, fd=%ld, family=%d, type=%d, proto=%d>",
5018         sock_fd, s->sock_family,
5019         s->sock_type,
5020         s->sock_proto);
5021 }
5022 
5023 
5024 /* Create a new, uninitialized socket object. */
5025 
5026 static PyObject *
5027 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5028 {
5029     PyObject *new;
5030 
5031     new = type->tp_alloc(type, 0);
5032     if (new != NULL) {
5033         ((PySocketSockObject *)new)->sock_fd = INVALID_SOCKET;
5034         ((PySocketSockObject *)new)->sock_timeout = _PyTime_FromSeconds(-1);
5035         ((PySocketSockObject *)new)->errorhandler = &set_error;
5036     }
5037     return new;
5038 }
5039 
5040 
5041 /* Initialize a new socket object. */
5042 
5043 #ifdef SOCK_CLOEXEC
5044 /* socket() and socketpair() fail with EINVAL on Linux kernel older
5045  * than 2.6.27 if SOCK_CLOEXEC flag is set in the socket type. */
5046 static int sock_cloexec_works = -1;
5047 #endif
5048 
5049 /*ARGSUSED*/
5050 static int
5051 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
5052 {
5053     PySocketSockObject *s = (PySocketSockObject *)self;
5054     PyObject *fdobj = NULL;
5055     SOCKET_T fd = INVALID_SOCKET;
5056     int family = -1, type = -1, proto = -1;
5057     static char *keywords[] = {"family", "type", "proto", "fileno", 0};
5058 #ifndef MS_WINDOWS
5059 #ifdef SOCK_CLOEXEC
5060     int *atomic_flag_works = &sock_cloexec_works;
5061 #else
5062     int *atomic_flag_works = NULL;
5063 #endif
5064 #endif
5065 
5066     if (!PyArg_ParseTupleAndKeywords(args, kwds,
5067                                      "|iiiO:socket", keywords,
5068                                      &family, &type, &proto, &fdobj))
5069         return -1;
5070 
5071 #ifdef MS_WINDOWS
5072     /* In this case, we don't use the family, type and proto args */
5073     if (fdobj == NULL || fdobj == Py_None)
5074 #endif
5075     {
5076         if (PySys_Audit("socket.__new__", "Oiii",
5077                         s, family, type, proto) < 0) {
5078             return -1;
5079         }
5080     }
5081 
5082     if (fdobj != NULL && fdobj != Py_None) {
5083 #ifdef MS_WINDOWS
5084         /* recreate a socket that was duplicated */
5085         if (PyBytes_Check(fdobj)) {
5086             WSAPROTOCOL_INFOW info;
5087             if (PyBytes_GET_SIZE(fdobj) != sizeof(info)) {
5088                 PyErr_Format(PyExc_ValueError,
5089                     "socket descriptor string has wrong size, "
5090                     "should be %zu bytes.", sizeof(info));
5091                 return -1;
5092             }
5093             memcpy(&info, PyBytes_AS_STRING(fdobj), sizeof(info));
5094 
5095             if (PySys_Audit("socket.__new__", "Oiii", s,
5096                             info.iAddressFamily, info.iSocketType,
5097                             info.iProtocol) < 0) {
5098                 return -1;
5099             }
5100 
5101             Py_BEGIN_ALLOW_THREADS
5102             fd = WSASocketW(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
5103                      FROM_PROTOCOL_INFO, &info, 0, WSA_FLAG_OVERLAPPED);
5104             Py_END_ALLOW_THREADS
5105             if (fd == INVALID_SOCKET) {
5106                 set_error();
5107                 return -1;
5108             }
5109             family = info.iAddressFamily;
5110             type = info.iSocketType;
5111             proto = info.iProtocol;
5112         }
5113         else
5114 #endif
5115         {
5116 
5117             if (PyFloat_Check(fdobj)) {
5118                 PyErr_SetString(PyExc_TypeError,
5119                                 "integer argument expected, got float");
5120                 return -1;
5121             }
5122 
5123             fd = PyLong_AsSocket_t(fdobj);
5124             if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
5125                 return -1;
5126 #ifdef MS_WINDOWS
5127             if (fd == INVALID_SOCKET) {
5128 #else
5129             if (fd < 0) {
5130 #endif
5131                 PyErr_SetString(PyExc_ValueError, "negative file descriptor");
5132                 return -1;
5133             }
5134 
5135             /* validate that passed file descriptor is valid and a socket. */
5136             sock_addr_t addrbuf;
5137             socklen_t addrlen = sizeof(sock_addr_t);
5138 
5139             memset(&addrbuf, 0, addrlen);
5140             if (getsockname(fd, SAS2SA(&addrbuf), &addrlen) == 0) {
5141                 if (family == -1) {
5142                     family = SAS2SA(&addrbuf)->sa_family;
5143                 }
5144             } else {
5145 #ifdef MS_WINDOWS
5146                 /* getsockname() on an unbound socket is an error on Windows.
5147                    Invalid descriptor and not a socket is same error code.
5148                    Error out if family must be resolved, or bad descriptor. */
5149                 if (family == -1 || CHECK_ERRNO(ENOTSOCK)) {
5150 #else
5151                 /* getsockname() is not supported for SOL_ALG on Linux. */
5152                 if (family == -1 || CHECK_ERRNO(EBADF) || CHECK_ERRNO(ENOTSOCK)) {
5153 #endif
5154                     set_error();
5155                     return -1;
5156                 }
5157             }
5158 #ifdef SO_TYPE
5159             if (type == -1) {
5160                 int tmp;
5161                 socklen_t slen = sizeof(tmp);
5162                 if (getsockopt(fd, SOL_SOCKET, SO_TYPE,
5163                                (void *)&tmp, &slen) == 0)
5164                 {
5165                     type = tmp;
5166                 } else {
5167                     set_error();
5168                     return -1;
5169                 }
5170             }
5171 #else
5172             type = SOCK_STREAM;
5173 #endif
5174 #ifdef SO_PROTOCOL
5175             if (proto == -1) {
5176                 int tmp;
5177                 socklen_t slen = sizeof(tmp);
5178                 if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL,
5179                                (void *)&tmp, &slen) == 0)
5180                 {
5181                     proto = tmp;
5182                 } else {
5183                     set_error();
5184                     return -1;
5185                 }
5186             }
5187 #else
5188             proto = 0;
5189 #endif
5190         }
5191     }
5192     else {
5193         /* No fd, default to AF_INET and SOCK_STREAM */
5194         if (family == -1) {
5195             family = AF_INET;
5196         }
5197         if (type == -1) {
5198             type = SOCK_STREAM;
5199         }
5200         if (proto == -1) {
5201             proto = 0;
5202         }
5203 #ifdef MS_WINDOWS
5204         /* Windows implementation */
5205 #ifndef WSA_FLAG_NO_HANDLE_INHERIT
5206 #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
5207 #endif
5208 
5209         Py_BEGIN_ALLOW_THREADS
5210         if (support_wsa_no_inherit) {
5211             fd = WSASocketW(family, type, proto,
5212                            NULL, 0,
5213                            WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT);
5214             if (fd == INVALID_SOCKET) {
5215                 /* Windows 7 or Windows 2008 R2 without SP1 or the hotfix */
5216                 support_wsa_no_inherit = 0;
5217                 fd = socket(family, type, proto);
5218             }
5219         }
5220         else {
5221             fd = socket(family, type, proto);
5222         }
5223         Py_END_ALLOW_THREADS
5224 
5225         if (fd == INVALID_SOCKET) {
5226             set_error();
5227             return -1;
5228         }
5229 
5230         if (!support_wsa_no_inherit) {
5231             if (!SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0)) {
5232                 closesocket(fd);
5233                 PyErr_SetFromWindowsErr(0);
5234                 return -1;
5235             }
5236         }
5237 #else
5238         /* UNIX */
5239         Py_BEGIN_ALLOW_THREADS
5240 #ifdef SOCK_CLOEXEC
5241         if (sock_cloexec_works != 0) {
5242             fd = socket(family, type | SOCK_CLOEXEC, proto);
5243             if (sock_cloexec_works == -1) {
5244                 if (fd >= 0) {
5245                     sock_cloexec_works = 1;
5246                 }
5247                 else if (errno == EINVAL) {
5248                     /* Linux older than 2.6.27 does not support SOCK_CLOEXEC */
5249                     sock_cloexec_works = 0;
5250                     fd = socket(family, type, proto);
5251                 }
5252             }
5253         }
5254         else
5255 #endif
5256         {
5257             fd = socket(family, type, proto);
5258         }
5259         Py_END_ALLOW_THREADS
5260 
5261         if (fd == INVALID_SOCKET) {
5262             set_error();
5263             return -1;
5264         }
5265 
5266         if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
5267             SOCKETCLOSE(fd);
5268             return -1;
5269         }
5270 #endif
5271     }
5272     if (init_sockobject(s, fd, family, type, proto) == -1) {
5273         SOCKETCLOSE(fd);
5274         return -1;
5275     }
5276 
5277     return 0;
5278 
5279 }
5280 
5281 
5282 /* Type object for socket objects. */
5283 
5284 static PyTypeObject sock_type = {
5285     PyVarObject_HEAD_INIT(0, 0)         /* Must fill in type value later */
5286     "_socket.socket",                           /* tp_name */
5287     sizeof(PySocketSockObject),                 /* tp_basicsize */
5288     0,                                          /* tp_itemsize */
5289     (destructor)sock_dealloc,                   /* tp_dealloc */
5290     0,                                          /* tp_vectorcall_offset */
5291     0,                                          /* tp_getattr */
5292     0,                                          /* tp_setattr */
5293     0,                                          /* tp_as_async */
5294     (reprfunc)sock_repr,                        /* tp_repr */
5295     0,                                          /* tp_as_number */
5296     0,                                          /* tp_as_sequence */
5297     0,                                          /* tp_as_mapping */
5298     0,                                          /* tp_hash */
5299     0,                                          /* tp_call */
5300     0,                                          /* tp_str */
5301     PyObject_GenericGetAttr,                    /* tp_getattro */
5302     0,                                          /* tp_setattro */
5303     0,                                          /* tp_as_buffer */
5304     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
5305     sock_doc,                                   /* tp_doc */
5306     0,                                          /* tp_traverse */
5307     0,                                          /* tp_clear */
5308     0,                                          /* tp_richcompare */
5309     0,                                          /* tp_weaklistoffset */
5310     0,                                          /* tp_iter */
5311     0,                                          /* tp_iternext */
5312     sock_methods,                               /* tp_methods */
5313     sock_memberlist,                            /* tp_members */
5314     sock_getsetlist,                            /* tp_getset */
5315     0,                                          /* tp_base */
5316     0,                                          /* tp_dict */
5317     0,                                          /* tp_descr_get */
5318     0,                                          /* tp_descr_set */
5319     0,                                          /* tp_dictoffset */
5320     sock_initobj,                               /* tp_init */
5321     PyType_GenericAlloc,                        /* tp_alloc */
5322     sock_new,                                   /* tp_new */
5323     PyObject_Del,                               /* tp_free */
5324     0,                                          /* tp_is_gc */
5325     0,                                          /* tp_bases */
5326     0,                                          /* tp_mro */
5327     0,                                          /* tp_cache */
5328     0,                                          /* tp_subclasses */
5329     0,                                          /* tp_weaklist */
5330     0,                                          /* tp_del */
5331     0,                                          /* tp_version_tag */
5332     (destructor)sock_finalize,                  /* tp_finalize */
5333 };
5334 
5335 
5336 /* Python interface to gethostname(). */
5337 
5338 /*ARGSUSED*/
5339 static PyObject *
5340 socket_gethostname(PyObject *self, PyObject *unused)
5341 {
5342     if (PySys_Audit("socket.gethostname", NULL) < 0) {
5343         return NULL;
5344     }
5345 
5346 #ifdef MS_WINDOWS
5347     /* Don't use winsock's gethostname, as this returns the ANSI
5348        version of the hostname, whereas we need a Unicode string.
5349        Otherwise, gethostname apparently also returns the DNS name. */
5350     wchar_t buf[MAX_COMPUTERNAME_LENGTH + 1];
5351     DWORD size = Py_ARRAY_LENGTH(buf);
5352     wchar_t *name;
5353     PyObject *result;
5354 
5355     if (GetComputerNameExW(ComputerNamePhysicalDnsHostname, buf, &size))
5356         return PyUnicode_FromWideChar(buf, size);
5357 
5358     if (GetLastError() != ERROR_MORE_DATA)
5359         return PyErr_SetFromWindowsErr(0);
5360 
5361     if (size == 0)
5362         return PyUnicode_New(0, 0);
5363 
5364     /* MSDN says ERROR_MORE_DATA may occur because DNS allows longer
5365        names */
5366     name = PyMem_New(wchar_t, size);
5367     if (!name) {
5368         PyErr_NoMemory();
5369         return NULL;
5370     }
5371     if (!GetComputerNameExW(ComputerNamePhysicalDnsHostname,
5372                            name,
5373                            &size))
5374     {
5375         PyMem_Free(name);
5376         return PyErr_SetFromWindowsErr(0);
5377     }
5378 
5379     result = PyUnicode_FromWideChar(name, size);
5380     PyMem_Free(name);
5381     return result;
5382 #else
5383     char buf[1024];
5384     int res;
5385     Py_BEGIN_ALLOW_THREADS
5386     res = gethostname(buf, (int) sizeof buf - 1);
5387     Py_END_ALLOW_THREADS
5388     if (res < 0)
5389         return set_error();
5390     buf[sizeof buf - 1] = '\0';
5391     return PyUnicode_DecodeFSDefault(buf);
5392 #endif
5393 }
5394 
5395 PyDoc_STRVAR(gethostname_doc,
5396 "gethostname() -> string\n\
5397 \n\
5398 Return the current host name.");
5399 
5400 #ifdef HAVE_SETHOSTNAME
5401 PyDoc_STRVAR(sethostname_doc,
5402 "sethostname(name)\n\n\
5403 Sets the hostname to name.");
5404 
5405 static PyObject *
5406 socket_sethostname(PyObject *self, PyObject *args)
5407 {
5408     PyObject *hnobj;
5409     Py_buffer buf;
5410     int res, flag = 0;
5411 
5412 #ifdef _AIX
5413 /* issue #18259, not declared in any useful header file */
5414 extern int sethostname(const char *, size_t);
5415 #endif
5416 
5417     if (!PyArg_ParseTuple(args, "S:sethostname", &hnobj)) {
5418         PyErr_Clear();
5419         if (!PyArg_ParseTuple(args, "O&:sethostname",
5420                 PyUnicode_FSConverter, &hnobj))
5421             return NULL;
5422         flag = 1;
5423     }
5424 
5425     if (PySys_Audit("socket.sethostname", "(O)", hnobj) < 0) {
5426         return NULL;
5427     }
5428 
5429     res = PyObject_GetBuffer(hnobj, &buf, PyBUF_SIMPLE);
5430     if (!res) {
5431         res = sethostname(buf.buf, buf.len);
5432         PyBuffer_Release(&buf);
5433     }
5434     if (flag)
5435         Py_DECREF(hnobj);
5436     if (res)
5437         return set_error();
5438     Py_RETURN_NONE;
5439 }
5440 #endif
5441 
5442 /* Python interface to gethostbyname(name). */
5443 
5444 /*ARGSUSED*/
5445 static PyObject *
5446 socket_gethostbyname(PyObject *self, PyObject *args)
5447 {
5448     char *name;
5449     struct sockaddr_in addrbuf;
5450     PyObject *ret = NULL;
5451 
5452     if (!PyArg_ParseTuple(args, "et:gethostbyname", "idna", &name))
5453         return NULL;
5454     if (PySys_Audit("socket.gethostbyname", "O", args) < 0) {
5455         goto finally;
5456     }
5457     if (setipaddr(name, (struct sockaddr *)&addrbuf,  sizeof(addrbuf), AF_INET) < 0)
5458         goto finally;
5459     ret = make_ipv4_addr(&addrbuf);
5460 finally:
5461     PyMem_Free(name);
5462     return ret;
5463 }
5464 
5465 PyDoc_STRVAR(gethostbyname_doc,
5466 "gethostbyname(host) -> address\n\
5467 \n\
5468 Return the IP address (a string of the form '255.255.255.255') for a host.");
5469 
5470 
5471 static PyObject*
5472 sock_decode_hostname(const char *name)
5473 {
5474 #ifdef MS_WINDOWS
5475     /* Issue #26227: gethostbyaddr() returns a string encoded
5476      * to the ANSI code page */
5477     return PyUnicode_DecodeMBCS(name, strlen(name), "surrogatepass");
5478 #else
5479     /* Decode from UTF-8 */
5480     return PyUnicode_FromString(name);
5481 #endif
5482 }
5483 
5484 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
5485 
5486 static PyObject *
5487 gethost_common(struct hostent *h, struct sockaddr *addr, size_t alen, int af)
5488 {
5489     char **pch;
5490     PyObject *rtn_tuple = (PyObject *)NULL;
5491     PyObject *name_list = (PyObject *)NULL;
5492     PyObject *addr_list = (PyObject *)NULL;
5493     PyObject *tmp;
5494     PyObject *name;
5495 
5496     if (h == NULL) {
5497         /* Let's get real error message to return */
5498         set_herror(h_errno);
5499         return NULL;
5500     }
5501 
5502     if (h->h_addrtype != af) {
5503         /* Let's get real error message to return */
5504         errno = EAFNOSUPPORT;
5505         PyErr_SetFromErrno(PyExc_OSError);
5506         return NULL;
5507     }
5508 
5509     switch (af) {
5510 
5511     case AF_INET:
5512         if (alen < sizeof(struct sockaddr_in))
5513             return NULL;
5514         break;
5515 
5516 #ifdef ENABLE_IPV6
5517     case AF_INET6:
5518         if (alen < sizeof(struct sockaddr_in6))
5519             return NULL;
5520         break;
5521 #endif
5522 
5523     }
5524 
5525     if ((name_list = PyList_New(0)) == NULL)
5526         goto err;
5527 
5528     if ((addr_list = PyList_New(0)) == NULL)
5529         goto err;
5530 
5531     /* SF #1511317: h_aliases can be NULL */
5532     if (h->h_aliases) {
5533         for (pch = h->h_aliases; *pch != NULL; pch++) {
5534             int status;
5535             tmp = PyUnicode_FromString(*pch);
5536             if (tmp == NULL)
5537                 goto err;
5538 
5539             status = PyList_Append(name_list, tmp);
5540             Py_DECREF(tmp);
5541 
5542             if (status)
5543                 goto err;
5544         }
5545     }
5546 
5547     for (pch = h->h_addr_list; *pch != NULL; pch++) {
5548         int status;
5549 
5550         switch (af) {
5551 
5552         case AF_INET:
5553             {
5554             struct sockaddr_in sin;
5555             memset(&sin, 0, sizeof(sin));
5556             sin.sin_family = af;
5557 #ifdef HAVE_SOCKADDR_SA_LEN
5558             sin.sin_len = sizeof(sin);
5559 #endif
5560             memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
5561             tmp = make_ipv4_addr(&sin);
5562 
5563             if (pch == h->h_addr_list && alen >= sizeof(sin))
5564                 memcpy((char *) addr, &sin, sizeof(sin));
5565             break;
5566             }
5567 
5568 #ifdef ENABLE_IPV6
5569         case AF_INET6:
5570             {
5571             struct sockaddr_in6 sin6;
5572             memset(&sin6, 0, sizeof(sin6));
5573             sin6.sin6_family = af;
5574 #ifdef HAVE_SOCKADDR_SA_LEN
5575             sin6.sin6_len = sizeof(sin6);
5576 #endif
5577             memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
5578             tmp = make_ipv6_addr(&sin6);
5579 
5580             if (pch == h->h_addr_list && alen >= sizeof(sin6))
5581                 memcpy((char *) addr, &sin6, sizeof(sin6));
5582             break;
5583             }
5584 #endif
5585 
5586         default:                /* can't happen */
5587             PyErr_SetString(PyExc_OSError,
5588                             "unsupported address family");
5589             return NULL;
5590         }
5591 
5592         if (tmp == NULL)
5593             goto err;
5594 
5595         status = PyList_Append(addr_list, tmp);
5596         Py_DECREF(tmp);
5597 
5598         if (status)
5599             goto err;
5600     }
5601 
5602     name = sock_decode_hostname(h->h_name);
5603     if (name == NULL)
5604         goto err;
5605     rtn_tuple = Py_BuildValue("NOO", name, name_list, addr_list);
5606 
5607  err:
5608     Py_XDECREF(name_list);
5609     Py_XDECREF(addr_list);
5610     return rtn_tuple;
5611 }
5612 
5613 
5614 /* Python interface to gethostbyname_ex(name). */
5615 
5616 /*ARGSUSED*/
5617 static PyObject *
5618 socket_gethostbyname_ex(PyObject *self, PyObject *args)
5619 {
5620     char *name;
5621     struct hostent *h;
5622     sock_addr_t addr;
5623     struct sockaddr *sa;
5624     PyObject *ret = NULL;
5625 #ifdef HAVE_GETHOSTBYNAME_R
5626     struct hostent hp_allocated;
5627 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
5628     struct hostent_data data;
5629 #else
5630     char buf[16384];
5631     int buf_len = (sizeof buf) - 1;
5632     int errnop;
5633 #endif
5634 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
5635     int result;
5636 #endif
5637 #endif /* HAVE_GETHOSTBYNAME_R */
5638 
5639     if (!PyArg_ParseTuple(args, "et:gethostbyname_ex", "idna", &name))
5640         return NULL;
5641     if (PySys_Audit("socket.gethostbyname", "O", args) < 0) {
5642         goto finally;
5643     }
5644     if (setipaddr(name, SAS2SA(&addr), sizeof(addr), AF_INET) < 0)
5645         goto finally;
5646     Py_BEGIN_ALLOW_THREADS
5647 #ifdef HAVE_GETHOSTBYNAME_R
5648 #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
5649     gethostbyname_r(name, &hp_allocated, buf, buf_len,
5650                              &h, &errnop);
5651 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
5652     h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
5653 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
5654     memset((void *) &data, '\0', sizeof(data));
5655     result = gethostbyname_r(name, &hp_allocated, &data);
5656     h = (result != 0) ? NULL : &hp_allocated;
5657 #endif
5658 #else /* not HAVE_GETHOSTBYNAME_R */
5659 #ifdef USE_GETHOSTBYNAME_LOCK
5660     PyThread_acquire_lock(netdb_lock, 1);
5661 #endif
5662     SUPPRESS_DEPRECATED_CALL
5663     h = gethostbyname(name);
5664 #endif /* HAVE_GETHOSTBYNAME_R */
5665     Py_END_ALLOW_THREADS
5666     /* Some C libraries would require addr.__ss_family instead of
5667        addr.ss_family.
5668        Therefore, we cast the sockaddr_storage into sockaddr to
5669        access sa_family. */
5670     sa = SAS2SA(&addr);
5671     ret = gethost_common(h, SAS2SA(&addr), sizeof(addr),
5672                          sa->sa_family);
5673 #ifdef USE_GETHOSTBYNAME_LOCK
5674     PyThread_release_lock(netdb_lock);
5675 #endif
5676 finally:
5677     PyMem_Free(name);
5678     return ret;
5679 }
5680 
5681 PyDoc_STRVAR(ghbn_ex_doc,
5682 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
5683 \n\
5684 Return the true host name, a list of aliases, and a list of IP addresses,\n\
5685 for a host.  The host argument is a string giving a host name or IP number.");
5686 
5687 
5688 /* Python interface to gethostbyaddr(IP). */
5689 
5690 /*ARGSUSED*/
5691 static PyObject *
5692 socket_gethostbyaddr(PyObject *self, PyObject *args)
5693 {
5694     sock_addr_t addr;
5695     struct sockaddr *sa = SAS2SA(&addr);
5696     char *ip_num;
5697     struct hostent *h;
5698     PyObject *ret = NULL;
5699 #ifdef HAVE_GETHOSTBYNAME_R
5700     struct hostent hp_allocated;
5701 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
5702     struct hostent_data data;
5703 #else
5704     /* glibcs up to 2.10 assume that the buf argument to
5705        gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
5706        does not ensure. The attribute below instructs the compiler
5707        to maintain this alignment. */
5708     char buf[16384] Py_ALIGNED(8);
5709     int buf_len = (sizeof buf) - 1;
5710     int errnop;
5711 #endif
5712 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
5713     int result;
5714 #endif
5715 #endif /* HAVE_GETHOSTBYNAME_R */
5716     const char *ap;
5717     int al;
5718     int af;
5719 
5720     if (!PyArg_ParseTuple(args, "et:gethostbyaddr", "idna", &ip_num))
5721         return NULL;
5722     if (PySys_Audit("socket.gethostbyaddr", "O", args) < 0) {
5723         goto finally;
5724     }
5725     af = AF_UNSPEC;
5726     if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
5727         goto finally;
5728     af = sa->sa_family;
5729     ap = NULL;
5730     /* al = 0; */
5731     switch (af) {
5732     case AF_INET:
5733         ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
5734         al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
5735         break;
5736 #ifdef ENABLE_IPV6
5737     case AF_INET6:
5738         ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
5739         al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
5740         break;
5741 #endif
5742     default:
5743         PyErr_SetString(PyExc_OSError, "unsupported address family");
5744         goto finally;
5745     }
5746     Py_BEGIN_ALLOW_THREADS
5747 #ifdef HAVE_GETHOSTBYNAME_R
5748 #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
5749     gethostbyaddr_r(ap, al, af,
5750         &hp_allocated, buf, buf_len,
5751         &h, &errnop);
5752 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
5753     h = gethostbyaddr_r(ap, al, af,
5754                         &hp_allocated, buf, buf_len, &errnop);
5755 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
5756     memset((void *) &data, '\0', sizeof(data));
5757     result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
5758     h = (result != 0) ? NULL : &hp_allocated;
5759 #endif
5760 #else /* not HAVE_GETHOSTBYNAME_R */
5761 #ifdef USE_GETHOSTBYNAME_LOCK
5762     PyThread_acquire_lock(netdb_lock, 1);
5763 #endif
5764     SUPPRESS_DEPRECATED_CALL
5765     h = gethostbyaddr(ap, al, af);
5766 #endif /* HAVE_GETHOSTBYNAME_R */
5767     Py_END_ALLOW_THREADS
5768     ret = gethost_common(h, SAS2SA(&addr), sizeof(addr), af);
5769 #ifdef USE_GETHOSTBYNAME_LOCK
5770     PyThread_release_lock(netdb_lock);
5771 #endif
5772 finally:
5773     PyMem_Free(ip_num);
5774     return ret;
5775 }
5776 
5777 PyDoc_STRVAR(gethostbyaddr_doc,
5778 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
5779 \n\
5780 Return the true host name, a list of aliases, and a list of IP addresses,\n\
5781 for a host.  The host argument is a string giving a host name or IP number.");
5782 
5783 
5784 /* Python interface to getservbyname(name).
5785    This only returns the port number, since the other info is already
5786    known or not useful (like the list of aliases). */
5787 
5788 /*ARGSUSED*/
5789 static PyObject *
5790 socket_getservbyname(PyObject *self, PyObject *args)
5791 {
5792     const char *name, *proto=NULL;
5793     struct servent *sp;
5794     if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
5795         return NULL;
5796 
5797     if (PySys_Audit("socket.getservbyname", "ss", name, proto) < 0) {
5798         return NULL;
5799     }
5800 
5801     Py_BEGIN_ALLOW_THREADS
5802     sp = getservbyname(name, proto);
5803     Py_END_ALLOW_THREADS
5804     if (sp == NULL) {
5805         PyErr_SetString(PyExc_OSError, "service/proto not found");
5806         return NULL;
5807     }
5808     return PyLong_FromLong((long) ntohs(sp->s_port));
5809 }
5810 
5811 PyDoc_STRVAR(getservbyname_doc,
5812 "getservbyname(servicename[, protocolname]) -> integer\n\
5813 \n\
5814 Return a port number from a service name and protocol name.\n\
5815 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
5816 otherwise any protocol will match.");
5817 
5818 
5819 /* Python interface to getservbyport(port).
5820    This only returns the service name, since the other info is already
5821    known or not useful (like the list of aliases). */
5822 
5823 /*ARGSUSED*/
5824 static PyObject *
5825 socket_getservbyport(PyObject *self, PyObject *args)
5826 {
5827     int port;
5828     const char *proto=NULL;
5829     struct servent *sp;
5830     if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
5831         return NULL;
5832     if (port < 0 || port > 0xffff) {
5833         PyErr_SetString(
5834             PyExc_OverflowError,
5835             "getservbyport: port must be 0-65535.");
5836         return NULL;
5837     }
5838 
5839     if (PySys_Audit("socket.getservbyport", "is", port, proto) < 0) {
5840         return NULL;
5841     }
5842 
5843     Py_BEGIN_ALLOW_THREADS
5844     sp = getservbyport(htons((short)port), proto);
5845     Py_END_ALLOW_THREADS
5846     if (sp == NULL) {
5847         PyErr_SetString(PyExc_OSError, "port/proto not found");
5848         return NULL;
5849     }
5850     return PyUnicode_FromString(sp->s_name);
5851 }
5852 
5853 PyDoc_STRVAR(getservbyport_doc,
5854 "getservbyport(port[, protocolname]) -> string\n\
5855 \n\
5856 Return the service name from a port number and protocol name.\n\
5857 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
5858 otherwise any protocol will match.");
5859 
5860 /* Python interface to getprotobyname(name).
5861    This only returns the protocol number, since the other info is
5862    already known or not useful (like the list of aliases). */
5863 
5864 /*ARGSUSED*/
5865 static PyObject *
5866 socket_getprotobyname(PyObject *self, PyObject *args)
5867 {
5868     const char *name;
5869     struct protoent *sp;
5870     if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
5871         return NULL;
5872     Py_BEGIN_ALLOW_THREADS
5873     sp = getprotobyname(name);
5874     Py_END_ALLOW_THREADS
5875     if (sp == NULL) {
5876         PyErr_SetString(PyExc_OSError, "protocol not found");
5877         return NULL;
5878     }
5879     return PyLong_FromLong((long) sp->p_proto);
5880 }
5881 
5882 PyDoc_STRVAR(getprotobyname_doc,
5883 "getprotobyname(name) -> integer\n\
5884 \n\
5885 Return the protocol number for the named protocol.  (Rarely used.)");
5886 
5887 static PyObject *
5888 socket_close(PyObject *self, PyObject *fdobj)
5889 {
5890     SOCKET_T fd;
5891     int res;
5892 
5893     fd = PyLong_AsSocket_t(fdobj);
5894     if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
5895         return NULL;
5896     Py_BEGIN_ALLOW_THREADS
5897     res = SOCKETCLOSE(fd);
5898     Py_END_ALLOW_THREADS
5899     /* bpo-30319: The peer can already have closed the connection.
5900        Python ignores ECONNRESET on close(). */
5901     if (res < 0 && !CHECK_ERRNO(ECONNRESET)) {
5902         return set_error();
5903     }
5904     Py_RETURN_NONE;
5905 }
5906 
5907 PyDoc_STRVAR(close_doc,
5908 "close(integer) -> None\n\
5909 \n\
5910 Close an integer socket file descriptor.  This is like os.close(), but for\n\
5911 sockets; on some platforms os.close() won't work for socket file descriptors.");
5912 
5913 #ifndef NO_DUP
5914 /* dup() function for socket fds */
5915 
5916 static PyObject *
5917 socket_dup(PyObject *self, PyObject *fdobj)
5918 {
5919     SOCKET_T fd, newfd;
5920     PyObject *newfdobj;
5921 #ifdef MS_WINDOWS
5922     WSAPROTOCOL_INFOW info;
5923 #endif
5924 
5925     fd = PyLong_AsSocket_t(fdobj);
5926     if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
5927         return NULL;
5928 
5929 #ifdef MS_WINDOWS
5930     if (WSADuplicateSocketW(fd, GetCurrentProcessId(), &info))
5931         return set_error();
5932 
5933     newfd = WSASocketW(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
5934                       FROM_PROTOCOL_INFO,
5935                       &info, 0, WSA_FLAG_OVERLAPPED);
5936     if (newfd == INVALID_SOCKET)
5937         return set_error();
5938 
5939     if (!SetHandleInformation((HANDLE)newfd, HANDLE_FLAG_INHERIT, 0)) {
5940         closesocket(newfd);
5941         PyErr_SetFromWindowsErr(0);
5942         return NULL;
5943     }
5944 #else
5945     /* On UNIX, dup can be used to duplicate the file descriptor of a socket */
5946     newfd = _Py_dup(fd);
5947     if (newfd == INVALID_SOCKET)
5948         return NULL;
5949 #endif
5950 
5951     newfdobj = PyLong_FromSocket_t(newfd);
5952     if (newfdobj == NULL)
5953         SOCKETCLOSE(newfd);
5954     return newfdobj;
5955 }
5956 
5957 PyDoc_STRVAR(dup_doc,
5958 "dup(integer) -> integer\n\
5959 \n\
5960 Duplicate an integer socket file descriptor.  This is like os.dup(), but for\n\
5961 sockets; on some platforms os.dup() won't work for socket file descriptors.");
5962 #endif
5963 
5964 
5965 #ifdef HAVE_SOCKETPAIR
5966 /* Create a pair of sockets using the socketpair() function.
5967    Arguments as for socket() except the default family is AF_UNIX if
5968    defined on the platform; otherwise, the default is AF_INET. */
5969 
5970 /*ARGSUSED*/
5971 static PyObject *
5972 socket_socketpair(PyObject *self, PyObject *args)
5973 {
5974     PySocketSockObject *s0 = NULL, *s1 = NULL;
5975     SOCKET_T sv[2];
5976     int family, type = SOCK_STREAM, proto = 0;
5977     PyObject *res = NULL;
5978 #ifdef SOCK_CLOEXEC
5979     int *atomic_flag_works = &sock_cloexec_works;
5980 #else
5981     int *atomic_flag_works = NULL;
5982 #endif
5983     int ret;
5984 
5985 #if defined(AF_UNIX)
5986     family = AF_UNIX;
5987 #else
5988     family = AF_INET;
5989 #endif
5990     if (!PyArg_ParseTuple(args, "|iii:socketpair",
5991                           &family, &type, &proto))
5992         return NULL;
5993 
5994     /* Create a pair of socket fds */
5995     Py_BEGIN_ALLOW_THREADS
5996 #ifdef SOCK_CLOEXEC
5997     if (sock_cloexec_works != 0) {
5998         ret = socketpair(family, type | SOCK_CLOEXEC, proto, sv);
5999         if (sock_cloexec_works == -1) {
6000             if (ret >= 0) {
6001                 sock_cloexec_works = 1;
6002             }
6003             else if (errno == EINVAL) {
6004                 /* Linux older than 2.6.27 does not support SOCK_CLOEXEC */
6005                 sock_cloexec_works = 0;
6006                 ret = socketpair(family, type, proto, sv);
6007             }
6008         }
6009     }
6010     else
6011 #endif
6012     {
6013         ret = socketpair(family, type, proto, sv);
6014     }
6015     Py_END_ALLOW_THREADS
6016 
6017     if (ret < 0)
6018         return set_error();
6019 
6020     if (_Py_set_inheritable(sv[0], 0, atomic_flag_works) < 0)
6021         goto finally;
6022     if (_Py_set_inheritable(sv[1], 0, atomic_flag_works) < 0)
6023         goto finally;
6024 
6025     s0 = new_sockobject(sv[0], family, type, proto);
6026     if (s0 == NULL)
6027         goto finally;
6028     s1 = new_sockobject(sv[1], family, type, proto);
6029     if (s1 == NULL)
6030         goto finally;
6031     res = PyTuple_Pack(2, s0, s1);
6032 
6033 finally:
6034     if (res == NULL) {
6035         if (s0 == NULL)
6036             SOCKETCLOSE(sv[0]);
6037         if (s1 == NULL)
6038             SOCKETCLOSE(sv[1]);
6039     }
6040     Py_XDECREF(s0);
6041     Py_XDECREF(s1);
6042     return res;
6043 }
6044 
6045 PyDoc_STRVAR(socketpair_doc,
6046 "socketpair([family[, type [, proto]]]) -> (socket object, socket object)\n\
6047 \n\
6048 Create a pair of socket objects from the sockets returned by the platform\n\
6049 socketpair() function.\n\
6050 The arguments are the same as for socket() except the default family is\n\
6051 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
6052 
6053 #endif /* HAVE_SOCKETPAIR */
6054 
6055 
6056 static PyObject *
6057 socket_ntohs(PyObject *self, PyObject *args)
6058 {
6059     int x;
6060 
6061     if (!PyArg_ParseTuple(args, "i:ntohs", &x)) {
6062         return NULL;
6063     }
6064     if (x < 0) {
6065         PyErr_SetString(PyExc_OverflowError,
6066                         "ntohs: can't convert negative Python int to C "
6067                         "16-bit unsigned integer");
6068         return NULL;
6069     }
6070     if (x > 0xffff) {
6071         if (PyErr_WarnEx(PyExc_DeprecationWarning,
6072                          "ntohs: Python int too large to convert to C "
6073                          "16-bit unsigned integer (The silent truncation "
6074                          "is deprecated)",
6075                          1)) {
6076             return NULL;
6077         }
6078     }
6079     return PyLong_FromUnsignedLong(ntohs((unsigned short)x));
6080 }
6081 
6082 PyDoc_STRVAR(ntohs_doc,
6083 "ntohs(integer) -> integer\n\
6084 \n\
6085 Convert a 16-bit unsigned integer from network to host byte order.\n\
6086 Note that in case the received integer does not fit in 16-bit unsigned\n\
6087 integer, but does fit in a positive C int, it is silently truncated to\n\
6088 16-bit unsigned integer.\n\
6089 However, this silent truncation feature is deprecated, and will raise an\n\
6090 exception in future versions of Python.");
6091 
6092 
6093 static PyObject *
6094 socket_ntohl(PyObject *self, PyObject *arg)
6095 {
6096     unsigned long x;
6097 
6098     if (PyLong_Check(arg)) {
6099         x = PyLong_AsUnsignedLong(arg);
6100         if (x == (unsigned long) -1 && PyErr_Occurred())
6101             return NULL;
6102 #if SIZEOF_LONG > 4
6103         {
6104             unsigned long y;
6105             /* only want the trailing 32 bits */
6106             y = x & 0xFFFFFFFFUL;
6107             if (y ^ x)
6108                 return PyErr_Format(PyExc_OverflowError,
6109                             "int larger than 32 bits");
6110             x = y;
6111         }
6112 #endif
6113     }
6114     else
6115         return PyErr_Format(PyExc_TypeError,
6116                             "expected int, %s found",
6117                             Py_TYPE(arg)->tp_name);
6118     return PyLong_FromUnsignedLong(ntohl(x));
6119 }
6120 
6121 PyDoc_STRVAR(ntohl_doc,
6122 "ntohl(integer) -> integer\n\
6123 \n\
6124 Convert a 32-bit integer from network to host byte order.");
6125 
6126 
6127 static PyObject *
6128 socket_htons(PyObject *self, PyObject *args)
6129 {
6130     int x;
6131 
6132     if (!PyArg_ParseTuple(args, "i:htons", &x)) {
6133         return NULL;
6134     }
6135     if (x < 0) {
6136         PyErr_SetString(PyExc_OverflowError,
6137                         "htons: can't convert negative Python int to C "
6138                         "16-bit unsigned integer");
6139         return NULL;
6140     }
6141     if (x > 0xffff) {
6142         if (PyErr_WarnEx(PyExc_DeprecationWarning,
6143                          "htons: Python int too large to convert to C "
6144                          "16-bit unsigned integer (The silent truncation "
6145                          "is deprecated)",
6146                          1)) {
6147             return NULL;
6148         }
6149     }
6150     return PyLong_FromUnsignedLong(htons((unsigned short)x));
6151 }
6152 
6153 PyDoc_STRVAR(htons_doc,
6154 "htons(integer) -> integer\n\
6155 \n\
6156 Convert a 16-bit unsigned integer from host to network byte order.\n\
6157 Note that in case the received integer does not fit in 16-bit unsigned\n\
6158 integer, but does fit in a positive C int, it is silently truncated to\n\
6159 16-bit unsigned integer.\n\
6160 However, this silent truncation feature is deprecated, and will raise an\n\
6161 exception in future versions of Python.");
6162 
6163 
6164 static PyObject *
6165 socket_htonl(PyObject *self, PyObject *arg)
6166 {
6167     unsigned long x;
6168 
6169     if (PyLong_Check(arg)) {
6170         x = PyLong_AsUnsignedLong(arg);
6171         if (x == (unsigned long) -1 && PyErr_Occurred())
6172             return NULL;
6173 #if SIZEOF_LONG > 4
6174         {
6175             unsigned long y;
6176             /* only want the trailing 32 bits */
6177             y = x & 0xFFFFFFFFUL;
6178             if (y ^ x)
6179                 return PyErr_Format(PyExc_OverflowError,
6180                             "int larger than 32 bits");
6181             x = y;
6182         }
6183 #endif
6184     }
6185     else
6186         return PyErr_Format(PyExc_TypeError,
6187                             "expected int, %s found",
6188                             Py_TYPE(arg)->tp_name);
6189     return PyLong_FromUnsignedLong(htonl((unsigned long)x));
6190 }
6191 
6192 PyDoc_STRVAR(htonl_doc,
6193 "htonl(integer) -> integer\n\
6194 \n\
6195 Convert a 32-bit integer from host to network byte order.");
6196 
6197 /* socket.inet_aton() and socket.inet_ntoa() functions. */
6198 
6199 PyDoc_STRVAR(inet_aton_doc,
6200 "inet_aton(string) -> bytes giving packed 32-bit IP representation\n\
6201 \n\
6202 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
6203 binary format used in low-level network functions.");
6204 
6205 static PyObject*
6206 socket_inet_aton(PyObject *self, PyObject *args)
6207 {
6208 #ifdef HAVE_INET_ATON
6209     struct in_addr buf;
6210 #endif
6211 
6212 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
6213 #if (SIZEOF_INT != 4)
6214 #error "Not sure if in_addr_t exists and int is not 32-bits."
6215 #endif
6216     /* Have to use inet_addr() instead */
6217     unsigned int packed_addr;
6218 #endif
6219     const char *ip_addr;
6220 
6221     if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
6222         return NULL;
6223 
6224 
6225 #ifdef HAVE_INET_ATON
6226 
6227 #ifdef USE_INET_ATON_WEAKLINK
6228     if (inet_aton != NULL) {
6229 #endif
6230     if (inet_aton(ip_addr, &buf))
6231         return PyBytes_FromStringAndSize((char *)(&buf),
6232                                           sizeof(buf));
6233 
6234     PyErr_SetString(PyExc_OSError,
6235                     "illegal IP address string passed to inet_aton");
6236     return NULL;
6237 
6238 #ifdef USE_INET_ATON_WEAKLINK
6239    } else {
6240 #endif
6241 
6242 #endif
6243 
6244 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
6245 
6246     /* special-case this address as inet_addr might return INADDR_NONE
6247      * for this */
6248     if (strcmp(ip_addr, "255.255.255.255") == 0) {
6249         packed_addr = INADDR_BROADCAST;
6250     } else {
6251 
6252         SUPPRESS_DEPRECATED_CALL
6253         packed_addr = inet_addr(ip_addr);
6254 
6255         if (packed_addr == INADDR_NONE) {               /* invalid address */
6256             PyErr_SetString(PyExc_OSError,
6257                 "illegal IP address string passed to inet_aton");
6258             return NULL;
6259         }
6260     }
6261     return PyBytes_FromStringAndSize((char *) &packed_addr,
6262                                       sizeof(packed_addr));
6263 
6264 #ifdef USE_INET_ATON_WEAKLINK
6265    }
6266 #endif
6267 
6268 #endif
6269 }
6270 
6271 PyDoc_STRVAR(inet_ntoa_doc,
6272 "inet_ntoa(packed_ip) -> ip_address_string\n\
6273 \n\
6274 Convert an IP address from 32-bit packed binary format to string format");
6275 
6276 static PyObject*
6277 socket_inet_ntoa(PyObject *self, PyObject *args)
6278 {
6279     Py_buffer packed_ip;
6280     struct in_addr packed_addr;
6281 
6282     if (!PyArg_ParseTuple(args, "y*:inet_ntoa", &packed_ip)) {
6283         return NULL;
6284     }
6285 
6286     if (packed_ip.len != sizeof(packed_addr)) {
6287         PyErr_SetString(PyExc_OSError,
6288             "packed IP wrong length for inet_ntoa");
6289         PyBuffer_Release(&packed_ip);
6290         return NULL;
6291     }
6292 
6293     memcpy(&packed_addr, packed_ip.buf, packed_ip.len);
6294     PyBuffer_Release(&packed_ip);
6295 
6296     SUPPRESS_DEPRECATED_CALL
6297     return PyUnicode_FromString(inet_ntoa(packed_addr));
6298 }
6299 
6300 #ifdef HAVE_INET_PTON
6301 
6302 PyDoc_STRVAR(inet_pton_doc,
6303 "inet_pton(af, ip) -> packed IP address string\n\
6304 \n\
6305 Convert an IP address from string format to a packed string suitable\n\
6306 for use with low-level network functions.");
6307 
6308 static PyObject *
6309 socket_inet_pton(PyObject *self, PyObject *args)
6310 {
6311     int af;
6312     const char* ip;
6313     int retval;
6314 #ifdef ENABLE_IPV6
6315     char packed[Py_MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
6316 #else
6317     char packed[sizeof(struct in_addr)];
6318 #endif
6319     if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
6320         return NULL;
6321     }
6322 
6323 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
6324     if(af == AF_INET6) {
6325         PyErr_SetString(PyExc_OSError,
6326                         "can't use AF_INET6, IPv6 is disabled");
6327         return NULL;
6328     }
6329 #endif
6330 
6331     retval = inet_pton(af, ip, packed);
6332     if (retval < 0) {
6333         PyErr_SetFromErrno(PyExc_OSError);
6334         return NULL;
6335     } else if (retval == 0) {
6336         PyErr_SetString(PyExc_OSError,
6337             "illegal IP address string passed to inet_pton");
6338         return NULL;
6339     } else if (af == AF_INET) {
6340         return PyBytes_FromStringAndSize(packed,
6341                                           sizeof(struct in_addr));
6342 #ifdef ENABLE_IPV6
6343     } else if (af == AF_INET6) {
6344         return PyBytes_FromStringAndSize(packed,
6345                                           sizeof(struct in6_addr));
6346 #endif
6347     } else {
6348         PyErr_SetString(PyExc_OSError, "unknown address family");
6349         return NULL;
6350     }
6351 }
6352 
6353 PyDoc_STRVAR(inet_ntop_doc,
6354 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
6355 \n\
6356 Convert a packed IP address of the given family to string format.");
6357 
6358 static PyObject *
6359 socket_inet_ntop(PyObject *self, PyObject *args)
6360 {
6361     int af;
6362     Py_buffer packed_ip;
6363     const char* retval;
6364 #ifdef ENABLE_IPV6
6365     char ip[Py_MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN)];
6366 #else
6367     char ip[INET_ADDRSTRLEN];
6368 #endif
6369 
6370     if (!PyArg_ParseTuple(args, "iy*:inet_ntop", &af, &packed_ip)) {
6371         return NULL;
6372     }
6373 
6374     if (af == AF_INET) {
6375         if (packed_ip.len != sizeof(struct in_addr)) {
6376             PyErr_SetString(PyExc_ValueError,
6377                 "invalid length of packed IP address string");
6378             PyBuffer_Release(&packed_ip);
6379             return NULL;
6380         }
6381 #ifdef ENABLE_IPV6
6382     } else if (af == AF_INET6) {
6383         if (packed_ip.len != sizeof(struct in6_addr)) {
6384             PyErr_SetString(PyExc_ValueError,
6385                 "invalid length of packed IP address string");
6386             PyBuffer_Release(&packed_ip);
6387             return NULL;
6388         }
6389 #endif
6390     } else {
6391         PyErr_Format(PyExc_ValueError,
6392             "unknown address family %d", af);
6393         PyBuffer_Release(&packed_ip);
6394         return NULL;
6395     }
6396 
6397     /* inet_ntop guarantee NUL-termination of resulting string. */
6398     retval = inet_ntop(af, packed_ip.buf, ip, sizeof(ip));
6399     PyBuffer_Release(&packed_ip);
6400     if (!retval) {
6401         PyErr_SetFromErrno(PyExc_OSError);
6402         return NULL;
6403     } else {
6404         return PyUnicode_FromString(retval);
6405     }
6406 }
6407 
6408 #endif /* HAVE_INET_PTON */
6409 
6410 /* Python interface to getaddrinfo(host, port). */
6411 
6412 /*ARGSUSED*/
6413 static PyObject *
6414 socket_getaddrinfo(PyObject *self, PyObject *args, PyObject* kwargs)
6415 {
6416     static char* kwnames[] = {"host", "port", "family", "type", "proto",
6417                               "flags", 0};
6418     struct addrinfo hints, *res;
6419     struct addrinfo *res0 = NULL;
6420     PyObject *hobj = NULL;
6421     PyObject *pobj = (PyObject *)NULL;
6422     char pbuf[30];
6423     const char *hptr, *pptr;
6424     int family, socktype, protocol, flags;
6425     int error;
6426     PyObject *all = (PyObject *)NULL;
6427     PyObject *idna = NULL;
6428 
6429     socktype = protocol = flags = 0;
6430     family = AF_UNSPEC;
6431     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|iiii:getaddrinfo",
6432                           kwnames, &hobj, &pobj, &family, &socktype,
6433                           &protocol, &flags)) {
6434         return NULL;
6435     }
6436     if (hobj == Py_None) {
6437         hptr = NULL;
6438     } else if (PyUnicode_Check(hobj)) {
6439         idna = PyUnicode_AsEncodedString(hobj, "idna", NULL);
6440         if (!idna)
6441             return NULL;
6442         assert(PyBytes_Check(idna));
6443         hptr = PyBytes_AS_STRING(idna);
6444     } else if (PyBytes_Check(hobj)) {
6445         hptr = PyBytes_AsString(hobj);
6446     } else {
6447         PyErr_SetString(PyExc_TypeError,
6448                         "getaddrinfo() argument 1 must be string or None");
6449         return NULL;
6450     }
6451     if (PyLong_CheckExact(pobj)) {
6452         long value = PyLong_AsLong(pobj);
6453         if (value == -1 && PyErr_Occurred())
6454             goto err;
6455         PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", value);
6456         pptr = pbuf;
6457     } else if (PyUnicode_Check(pobj)) {
6458         pptr = PyUnicode_AsUTF8(pobj);
6459         if (pptr == NULL)
6460             goto err;
6461     } else if (PyBytes_Check(pobj)) {
6462         pptr = PyBytes_AS_STRING(pobj);
6463     } else if (pobj == Py_None) {
6464         pptr = (char *)NULL;
6465     } else {
6466         PyErr_SetString(PyExc_OSError, "Int or String expected");
6467         goto err;
6468     }
6469 #if defined(__APPLE__) && defined(AI_NUMERICSERV)
6470     if ((flags & AI_NUMERICSERV) && (pptr == NULL || (pptr[0] == '0' && pptr[1] == 0))) {
6471         /* On OSX up to at least OSX 10.8 getaddrinfo crashes
6472          * if AI_NUMERICSERV is set and the servname is NULL or "0".
6473          * This workaround avoids a segfault in libsystem.
6474          */
6475         pptr = "00";
6476     }
6477 #endif
6478 
6479     if (PySys_Audit("socket.getaddrinfo", "OOiii",
6480                     hobj, pobj, family, socktype, protocol) < 0) {
6481         return NULL;
6482     }
6483 
6484     memset(&hints, 0, sizeof(hints));
6485     hints.ai_family = family;
6486     hints.ai_socktype = socktype;
6487     hints.ai_protocol = protocol;
6488     hints.ai_flags = flags;
6489     Py_BEGIN_ALLOW_THREADS
6490     ACQUIRE_GETADDRINFO_LOCK
6491     error = getaddrinfo(hptr, pptr, &hints, &res0);
6492     Py_END_ALLOW_THREADS
6493     RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
6494     if (error) {
6495         set_gaierror(error);
6496         goto err;
6497     }
6498 
6499     all = PyList_New(0);
6500     if (all == NULL)
6501         goto err;
6502     for (res = res0; res; res = res->ai_next) {
6503         PyObject *single;
6504         PyObject *addr =
6505             makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
6506         if (addr == NULL)
6507             goto err;
6508         single = Py_BuildValue("iiisO", res->ai_family,
6509             res->ai_socktype, res->ai_protocol,
6510             res->ai_canonname ? res->ai_canonname : "",
6511             addr);
6512         Py_DECREF(addr);
6513         if (single == NULL)
6514             goto err;
6515 
6516         if (PyList_Append(all, single)) {
6517             Py_DECREF(single);
6518             goto err;
6519         }
6520         Py_DECREF(single);
6521     }
6522     Py_XDECREF(idna);
6523     if (res0)
6524         freeaddrinfo(res0);
6525     return all;
6526  err:
6527     Py_XDECREF(all);
6528     Py_XDECREF(idna);
6529     if (res0)
6530         freeaddrinfo(res0);
6531     return (PyObject *)NULL;
6532 }
6533 
6534 PyDoc_STRVAR(getaddrinfo_doc,
6535 "getaddrinfo(host, port [, family, type, proto, flags])\n\
6536     -> list of (family, type, proto, canonname, sockaddr)\n\
6537 \n\
6538 Resolve host and port into addrinfo struct.");
6539 
6540 /* Python interface to getnameinfo(sa, flags). */
6541 
6542 /*ARGSUSED*/
6543 static PyObject *
6544 socket_getnameinfo(PyObject *self, PyObject *args)
6545 {
6546     PyObject *sa = (PyObject *)NULL;
6547     int flags;
6548     const char *hostp;
6549     int port;
6550     unsigned int flowinfo, scope_id;
6551     char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
6552     struct addrinfo hints, *res = NULL;
6553     int error;
6554     PyObject *ret = (PyObject *)NULL;
6555     PyObject *name;
6556 
6557     flags = flowinfo = scope_id = 0;
6558     if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
6559         return NULL;
6560     if (!PyTuple_Check(sa)) {
6561         PyErr_SetString(PyExc_TypeError,
6562                         "getnameinfo() argument 1 must be a tuple");
6563         return NULL;
6564     }
6565     if (!PyArg_ParseTuple(sa, "si|II;getnameinfo(): illegal sockaddr argument",
6566                           &hostp, &port, &flowinfo, &scope_id))
6567     {
6568         return NULL;
6569     }
6570     if (flowinfo > 0xfffff) {
6571         PyErr_SetString(PyExc_OverflowError,
6572                         "getnameinfo(): flowinfo must be 0-1048575.");
6573         return NULL;
6574     }
6575 
6576     if (PySys_Audit("socket.getnameinfo", "(O)", sa) < 0) {
6577         return NULL;
6578     }
6579 
6580     PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
6581     memset(&hints, 0, sizeof(hints));
6582     hints.ai_family = AF_UNSPEC;
6583     hints.ai_socktype = SOCK_DGRAM;     /* make numeric port happy */
6584     hints.ai_flags = AI_NUMERICHOST;    /* don't do any name resolution */
6585     Py_BEGIN_ALLOW_THREADS
6586     ACQUIRE_GETADDRINFO_LOCK
6587     error = getaddrinfo(hostp, pbuf, &hints, &res);
6588     Py_END_ALLOW_THREADS
6589     RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
6590     if (error) {
6591         set_gaierror(error);
6592         goto fail;
6593     }
6594     if (res->ai_next) {
6595         PyErr_SetString(PyExc_OSError,
6596             "sockaddr resolved to multiple addresses");
6597         goto fail;
6598     }
6599     switch (res->ai_family) {
6600     case AF_INET:
6601         {
6602         if (PyTuple_GET_SIZE(sa) != 2) {
6603             PyErr_SetString(PyExc_OSError,
6604                 "IPv4 sockaddr must be 2 tuple");
6605             goto fail;
6606         }
6607         break;
6608         }
6609 #ifdef ENABLE_IPV6
6610     case AF_INET6:
6611         {
6612         struct sockaddr_in6 *sin6;
6613         sin6 = (struct sockaddr_in6 *)res->ai_addr;
6614         sin6->sin6_flowinfo = htonl(flowinfo);
6615         sin6->sin6_scope_id = scope_id;
6616         break;
6617         }
6618 #endif
6619     }
6620     error = getnameinfo(res->ai_addr, (socklen_t) res->ai_addrlen,
6621                     hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
6622     if (error) {
6623         set_gaierror(error);
6624         goto fail;
6625     }
6626 
6627     name = sock_decode_hostname(hbuf);
6628     if (name == NULL)
6629         goto fail;
6630     ret = Py_BuildValue("Ns", name, pbuf);
6631 
6632 fail:
6633     if (res)
6634         freeaddrinfo(res);
6635     return ret;
6636 }
6637 
6638 PyDoc_STRVAR(getnameinfo_doc,
6639 "getnameinfo(sockaddr, flags) --> (host, port)\n\
6640 \n\
6641 Get host and port for a sockaddr.");
6642 
6643 
6644 /* Python API to getting and setting the default timeout value. */
6645 
6646 static PyObject *
6647 socket_getdefaulttimeout(PyObject *self, PyObject *Py_UNUSED(ignored))
6648 {
6649     if (defaulttimeout < 0) {
6650         Py_RETURN_NONE;
6651     }
6652     else {
6653         double seconds = _PyTime_AsSecondsDouble(defaulttimeout);
6654         return PyFloat_FromDouble(seconds);
6655     }
6656 }
6657 
6658 PyDoc_STRVAR(getdefaulttimeout_doc,
6659 "getdefaulttimeout() -> timeout\n\
6660 \n\
6661 Returns the default timeout in seconds (float) for new socket objects.\n\
6662 A value of None indicates that new socket objects have no timeout.\n\
6663 When the socket module is first imported, the default is None.");
6664 
6665 static PyObject *
6666 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
6667 {
6668     _PyTime_t timeout;
6669 
6670     if (socket_parse_timeout(&timeout, arg) < 0)
6671         return NULL;
6672 
6673     defaulttimeout = timeout;
6674 
6675     Py_RETURN_NONE;
6676 }
6677 
6678 PyDoc_STRVAR(setdefaulttimeout_doc,
6679 "setdefaulttimeout(timeout)\n\
6680 \n\
6681 Set the default timeout in seconds (float) for new socket objects.\n\
6682 A value of None indicates that new socket objects have no timeout.\n\
6683 When the socket module is first imported, the default is None.");
6684 
6685 #if defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
6686 /* Python API for getting interface indices and names */
6687 
6688 static PyObject *
6689 socket_if_nameindex(PyObject *self, PyObject *arg)
6690 {
6691     PyObject *list = PyList_New(0);
6692     if (list == NULL) {
6693         return NULL;
6694     }
6695 #ifdef MS_WINDOWS
6696     PMIB_IF_TABLE2 tbl;
6697     int ret;
6698     if ((ret = GetIfTable2Ex(MibIfTableRaw, &tbl)) != NO_ERROR) {
6699         Py_DECREF(list);
6700         // ret is used instead of GetLastError()
6701         return PyErr_SetFromWindowsErr(ret);
6702     }
6703     for (ULONG i = 0; i < tbl->NumEntries; ++i) {
6704         MIB_IF_ROW2 r = tbl->Table[i];
6705         WCHAR buf[NDIS_IF_MAX_STRING_SIZE + 1];
6706         if ((ret = ConvertInterfaceLuidToNameW(&r.InterfaceLuid, buf,
6707                                                Py_ARRAY_LENGTH(buf)))) {
6708             Py_DECREF(list);
6709             FreeMibTable(tbl);
6710             // ret is used instead of GetLastError()
6711             return PyErr_SetFromWindowsErr(ret);
6712         }
6713         PyObject *tuple = Py_BuildValue("Iu", r.InterfaceIndex, buf);
6714         if (tuple == NULL || PyList_Append(list, tuple) == -1) {
6715             Py_XDECREF(tuple);
6716             Py_DECREF(list);
6717             FreeMibTable(tbl);
6718             return NULL;
6719         }
6720         Py_DECREF(tuple);
6721     }
6722     FreeMibTable(tbl);
6723     return list;
6724 #else
6725     int i;
6726     struct if_nameindex *ni;
6727 
6728     ni = if_nameindex();
6729     if (ni == NULL) {
6730         Py_DECREF(list);
6731         PyErr_SetFromErrno(PyExc_OSError);
6732         return NULL;
6733     }
6734 
6735 #ifdef _Py_MEMORY_SANITIZER
6736     __msan_unpoison(ni, sizeof(ni));
6737     __msan_unpoison(&ni[0], sizeof(ni[0]));
6738 #endif
6739     for (i = 0; ni[i].if_index != 0 && i < INT_MAX; i++) {
6740 #ifdef _Py_MEMORY_SANITIZER
6741         /* This one isn't the end sentinel, the next one must exist. */
6742         __msan_unpoison(&ni[i+1], sizeof(ni[0]));
6743         /* Otherwise Py_BuildValue internals are flagged by MSan when
6744            they access the not-msan-tracked if_name string data. */
6745         {
6746             char *to_sanitize = ni[i].if_name;
6747             do {
6748                 __msan_unpoison(to_sanitize, 1);
6749             } while (*to_sanitize++ != '\0');
6750         }
6751 #endif
6752         PyObject *ni_tuple = Py_BuildValue("IO&",
6753                 ni[i].if_index, PyUnicode_DecodeFSDefault, ni[i].if_name);
6754 
6755         if (ni_tuple == NULL || PyList_Append(list, ni_tuple) == -1) {
6756             Py_XDECREF(ni_tuple);
6757             Py_DECREF(list);
6758             if_freenameindex(ni);
6759             return NULL;
6760         }
6761         Py_DECREF(ni_tuple);
6762     }
6763 
6764     if_freenameindex(ni);
6765     return list;
6766 #endif
6767 }
6768 
6769 PyDoc_STRVAR(if_nameindex_doc,
6770 "if_nameindex()\n\
6771 \n\
6772 Returns a list of network interface information (index, name) tuples.");
6773 
6774 static PyObject *
6775 socket_if_nametoindex(PyObject *self, PyObject *args)
6776 {
6777     PyObject *oname;
6778 #ifdef MS_WINDOWS
6779     NET_IFINDEX index;
6780 #else
6781     unsigned long index;
6782 #endif
6783     if (!PyArg_ParseTuple(args, "O&:if_nametoindex",
6784                           PyUnicode_FSConverter, &oname))
6785         return NULL;
6786 
6787     index = if_nametoindex(PyBytes_AS_STRING(oname));
6788     Py_DECREF(oname);
6789     if (index == 0) {
6790         /* if_nametoindex() doesn't set errno */
6791         PyErr_SetString(PyExc_OSError, "no interface with this name");
6792         return NULL;
6793     }
6794 
6795     return PyLong_FromUnsignedLong(index);
6796 }
6797 
6798 PyDoc_STRVAR(if_nametoindex_doc,
6799 "if_nametoindex(if_name)\n\
6800 \n\
6801 Returns the interface index corresponding to the interface name if_name.");
6802 
6803 static PyObject *
6804 socket_if_indextoname(PyObject *self, PyObject *arg)
6805 {
6806 #ifdef MS_WINDOWS
6807     NET_IFINDEX index;
6808 #else
6809     unsigned long index;
6810 #endif
6811     char name[IF_NAMESIZE + 1];
6812 
6813     index = PyLong_AsUnsignedLong(arg);
6814     if (index == (unsigned long) -1)
6815         return NULL;
6816 
6817     if (if_indextoname(index, name) == NULL) {
6818         PyErr_SetFromErrno(PyExc_OSError);
6819         return NULL;
6820     }
6821 
6822     return PyUnicode_DecodeFSDefault(name);
6823 }
6824 
6825 PyDoc_STRVAR(if_indextoname_doc,
6826 "if_indextoname(if_index)\n\
6827 \n\
6828 Returns the interface name corresponding to the interface index if_index.");
6829 
6830 #endif // defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
6831 
6832 
6833 #ifdef CMSG_LEN
6834 /* Python interface to CMSG_LEN(length). */
6835 
6836 static PyObject *
6837 socket_CMSG_LEN(PyObject *self, PyObject *args)
6838 {
6839     Py_ssize_t length;
6840     size_t result;
6841 
6842     if (!PyArg_ParseTuple(args, "n:CMSG_LEN", &length))
6843         return NULL;
6844     if (length < 0 || !get_CMSG_LEN(length, &result)) {
6845         PyErr_Format(PyExc_OverflowError, "CMSG_LEN() argument out of range");
6846         return NULL;
6847     }
6848     return PyLong_FromSize_t(result);
6849 }
6850 
6851 PyDoc_STRVAR(CMSG_LEN_doc,
6852 "CMSG_LEN(length) -> control message length\n\
6853 \n\
6854 Return the total length, without trailing padding, of an ancillary\n\
6855 data item with associated data of the given length.  This value can\n\
6856 often be used as the buffer size for recvmsg() to receive a single\n\
6857 item of ancillary data, but RFC 3542 requires portable applications to\n\
6858 use CMSG_SPACE() and thus include space for padding, even when the\n\
6859 item will be the last in the buffer.  Raises OverflowError if length\n\
6860 is outside the permissible range of values.");
6861 
6862 
6863 #ifdef CMSG_SPACE
6864 /* Python interface to CMSG_SPACE(length). */
6865 
6866 static PyObject *
6867 socket_CMSG_SPACE(PyObject *self, PyObject *args)
6868 {
6869     Py_ssize_t length;
6870     size_t result;
6871 
6872     if (!PyArg_ParseTuple(args, "n:CMSG_SPACE", &length))
6873         return NULL;
6874     if (length < 0 || !get_CMSG_SPACE(length, &result)) {
6875         PyErr_SetString(PyExc_OverflowError,
6876                         "CMSG_SPACE() argument out of range");
6877         return NULL;
6878     }
6879     return PyLong_FromSize_t(result);
6880 }
6881 
6882 PyDoc_STRVAR(CMSG_SPACE_doc,
6883 "CMSG_SPACE(length) -> buffer size\n\
6884 \n\
6885 Return the buffer size needed for recvmsg() to receive an ancillary\n\
6886 data item with associated data of the given length, along with any\n\
6887 trailing padding.  The buffer space needed to receive multiple items\n\
6888 is the sum of the CMSG_SPACE() values for their associated data\n\
6889 lengths.  Raises OverflowError if length is outside the permissible\n\
6890 range of values.");
6891 #endif    /* CMSG_SPACE */
6892 #endif    /* CMSG_LEN */
6893 
6894 
6895 /* List of functions exported by this module. */
6896 
6897 static PyMethodDef socket_methods[] = {
6898     {"gethostbyname",           socket_gethostbyname,
6899      METH_VARARGS, gethostbyname_doc},
6900     {"gethostbyname_ex",        socket_gethostbyname_ex,
6901      METH_VARARGS, ghbn_ex_doc},
6902     {"gethostbyaddr",           socket_gethostbyaddr,
6903      METH_VARARGS, gethostbyaddr_doc},
6904     {"gethostname",             socket_gethostname,
6905      METH_NOARGS,  gethostname_doc},
6906 #ifdef HAVE_SETHOSTNAME
6907     {"sethostname",             socket_sethostname,
6908      METH_VARARGS,  sethostname_doc},
6909 #endif
6910     {"getservbyname",           socket_getservbyname,
6911      METH_VARARGS, getservbyname_doc},
6912     {"getservbyport",           socket_getservbyport,
6913      METH_VARARGS, getservbyport_doc},
6914     {"getprotobyname",          socket_getprotobyname,
6915      METH_VARARGS, getprotobyname_doc},
6916     {"close",                   socket_close,
6917      METH_O, close_doc},
6918 #ifndef NO_DUP
6919     {"dup",                     socket_dup,
6920      METH_O, dup_doc},
6921 #endif
6922 #ifdef HAVE_SOCKETPAIR
6923     {"socketpair",              socket_socketpair,
6924      METH_VARARGS, socketpair_doc},
6925 #endif
6926     {"ntohs",                   socket_ntohs,
6927      METH_VARARGS, ntohs_doc},
6928     {"ntohl",                   socket_ntohl,
6929      METH_O, ntohl_doc},
6930     {"htons",                   socket_htons,
6931      METH_VARARGS, htons_doc},
6932     {"htonl",                   socket_htonl,
6933      METH_O, htonl_doc},
6934     {"inet_aton",               socket_inet_aton,
6935      METH_VARARGS, inet_aton_doc},
6936     {"inet_ntoa",               socket_inet_ntoa,
6937      METH_VARARGS, inet_ntoa_doc},
6938 #ifdef HAVE_INET_PTON
6939     {"inet_pton",               socket_inet_pton,
6940      METH_VARARGS, inet_pton_doc},
6941     {"inet_ntop",               socket_inet_ntop,
6942      METH_VARARGS, inet_ntop_doc},
6943 #endif
6944     {"getaddrinfo",             (PyCFunction)(void(*)(void))socket_getaddrinfo,
6945      METH_VARARGS | METH_KEYWORDS, getaddrinfo_doc},
6946     {"getnameinfo",             socket_getnameinfo,
6947      METH_VARARGS, getnameinfo_doc},
6948     {"getdefaulttimeout",       socket_getdefaulttimeout,
6949      METH_NOARGS, getdefaulttimeout_doc},
6950     {"setdefaulttimeout",       socket_setdefaulttimeout,
6951      METH_O, setdefaulttimeout_doc},
6952 #if defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
6953     {"if_nameindex", socket_if_nameindex,
6954      METH_NOARGS, if_nameindex_doc},
6955     {"if_nametoindex", socket_if_nametoindex,
6956      METH_VARARGS, if_nametoindex_doc},
6957     {"if_indextoname", socket_if_indextoname,
6958      METH_O, if_indextoname_doc},
6959 #endif
6960 #ifdef CMSG_LEN
6961     {"CMSG_LEN",                socket_CMSG_LEN,
6962      METH_VARARGS, CMSG_LEN_doc},
6963 #ifdef CMSG_SPACE
6964     {"CMSG_SPACE",              socket_CMSG_SPACE,
6965      METH_VARARGS, CMSG_SPACE_doc},
6966 #endif
6967 #endif
6968     {NULL,                      NULL}            /* Sentinel */
6969 };
6970 
6971 
6972 #ifdef MS_WINDOWS
6973 #define OS_INIT_DEFINED
6974 
6975 /* Additional initialization and cleanup for Windows */
6976 
6977 static void
6978 os_cleanup(void)
6979 {
6980     WSACleanup();
6981 }
6982 
6983 static int
6984 os_init(void)
6985 {
6986     WSADATA WSAData;
6987     int ret;
6988     ret = WSAStartup(0x0101, &WSAData);
6989     switch (ret) {
6990     case 0:     /* No error */
6991         Py_AtExit(os_cleanup);
6992         return 1; /* Success */
6993     case WSASYSNOTREADY:
6994         PyErr_SetString(PyExc_ImportError,
6995                         "WSAStartup failed: network not ready");
6996         break;
6997     case WSAVERNOTSUPPORTED:
6998     case WSAEINVAL:
6999         PyErr_SetString(
7000             PyExc_ImportError,
7001             "WSAStartup failed: requested version not supported");
7002         break;
7003     default:
7004         PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret);
7005         break;
7006     }
7007     return 0; /* Failure */
7008 }
7009 
7010 #endif /* MS_WINDOWS */
7011 
7012 
7013 
7014 #ifndef OS_INIT_DEFINED
7015 static int
7016 os_init(void)
7017 {
7018     return 1; /* Success */
7019 }
7020 #endif
7021 
7022 
7023 /* C API table - always add new things to the end for binary
7024    compatibility. */
7025 static
7026 PySocketModule_APIObject PySocketModuleAPI =
7027 {
7028     &sock_type,
7029     NULL,
7030     NULL
7031 };
7032 
7033 
7034 /* Initialize the _socket module.
7035 
7036    This module is actually called "_socket", and there's a wrapper
7037    "socket.py" which implements some additional functionality.
7038    The import of "_socket" may fail with an ImportError exception if
7039    os-specific initialization fails.  On Windows, this does WINSOCK
7040    initialization.  When WINSOCK is initialized successfully, a call to
7041    WSACleanup() is scheduled to be made at exit time.
7042 */
7043 
7044 PyDoc_STRVAR(socket_doc,
7045 "Implementation module for socket operations.\n\
7046 \n\
7047 See the socket module for documentation.");
7048 
7049 static struct PyModuleDef socketmodule = {
7050     PyModuleDef_HEAD_INIT,
7051     PySocket_MODULE_NAME,
7052     socket_doc,
7053     -1,
7054     socket_methods,
7055     NULL,
7056     NULL,
7057     NULL,
7058     NULL
7059 };
7060 
7061 PyMODINIT_FUNC
7062 PyInit__socket(void)
7063 {
7064     PyObject *m, *has_ipv6;
7065 
7066     if (!os_init())
7067         return NULL;
7068 
7069 #ifdef MS_WINDOWS
7070     if (support_wsa_no_inherit == -1) {
7071         support_wsa_no_inherit = IsWindows7SP1OrGreater();
7072     }
7073 #endif
7074 
7075     Py_TYPE(&sock_type) = &PyType_Type;
7076     m = PyModule_Create(&socketmodule);
7077     if (m == NULL)
7078         return NULL;
7079 
7080     Py_INCREF(PyExc_OSError);
7081     PySocketModuleAPI.error = PyExc_OSError;
7082     Py_INCREF(PyExc_OSError);
7083     PyModule_AddObject(m, "error", PyExc_OSError);
7084     socket_herror = PyErr_NewException("socket.herror",
7085                                        PyExc_OSError, NULL);
7086     if (socket_herror == NULL)
7087         return NULL;
7088     Py_INCREF(socket_herror);
7089     PyModule_AddObject(m, "herror", socket_herror);
7090     socket_gaierror = PyErr_NewException("socket.gaierror", PyExc_OSError,
7091         NULL);
7092     if (socket_gaierror == NULL)
7093         return NULL;
7094     Py_INCREF(socket_gaierror);
7095     PyModule_AddObject(m, "gaierror", socket_gaierror);
7096     socket_timeout = PyErr_NewException("socket.timeout",
7097                                         PyExc_OSError, NULL);
7098     if (socket_timeout == NULL)
7099         return NULL;
7100     PySocketModuleAPI.timeout_error = socket_timeout;
7101     Py_INCREF(socket_timeout);
7102     PyModule_AddObject(m, "timeout", socket_timeout);
7103     Py_INCREF((PyObject *)&sock_type);
7104     if (PyModule_AddObject(m, "SocketType",
7105                            (PyObject *)&sock_type) != 0)
7106         return NULL;
7107     Py_INCREF((PyObject *)&sock_type);
7108     if (PyModule_AddObject(m, "socket",
7109                            (PyObject *)&sock_type) != 0)
7110         return NULL;
7111 
7112 #ifdef ENABLE_IPV6
7113     has_ipv6 = Py_True;
7114 #else
7115     has_ipv6 = Py_False;
7116 #endif
7117     Py_INCREF(has_ipv6);
7118     PyModule_AddObject(m, "has_ipv6", has_ipv6);
7119 
7120     /* Export C API */
7121     if (PyModule_AddObject(m, PySocket_CAPI_NAME,
7122            PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL)
7123                              ) != 0)
7124         return NULL;
7125 
7126     /* Address families (we only support AF_INET and AF_UNIX) */
7127 #ifdef AF_UNSPEC
7128     PyModule_AddIntMacro(m, AF_UNSPEC);
7129 #endif
7130     PyModule_AddIntMacro(m, AF_INET);
7131 #if defined(AF_UNIX)
7132     PyModule_AddIntMacro(m, AF_UNIX);
7133 #endif /* AF_UNIX */
7134 #ifdef AF_AX25
7135     /* Amateur Radio AX.25 */
7136     PyModule_AddIntMacro(m, AF_AX25);
7137 #endif
7138 #ifdef AF_IPX
7139     PyModule_AddIntMacro(m, AF_IPX); /* Novell IPX */
7140 #endif
7141 #ifdef AF_APPLETALK
7142     /* Appletalk DDP */
7143     PyModule_AddIntMacro(m, AF_APPLETALK);
7144 #endif
7145 #ifdef AF_NETROM
7146     /* Amateur radio NetROM */
7147     PyModule_AddIntMacro(m, AF_NETROM);
7148 #endif
7149 #ifdef AF_BRIDGE
7150     /* Multiprotocol bridge */
7151     PyModule_AddIntMacro(m, AF_BRIDGE);
7152 #endif
7153 #ifdef AF_ATMPVC
7154     /* ATM PVCs */
7155     PyModule_AddIntMacro(m, AF_ATMPVC);
7156 #endif
7157 #ifdef AF_AAL5
7158     /* Reserved for Werner's ATM */
7159     PyModule_AddIntMacro(m, AF_AAL5);
7160 #endif
7161 #ifdef HAVE_SOCKADDR_ALG
7162     PyModule_AddIntMacro(m, AF_ALG); /* Linux crypto */
7163 #endif
7164 #ifdef AF_X25
7165     /* Reserved for X.25 project */
7166     PyModule_AddIntMacro(m, AF_X25);
7167 #endif
7168 #ifdef AF_INET6
7169     PyModule_AddIntMacro(m, AF_INET6); /* IP version 6 */
7170 #endif
7171 #ifdef AF_ROSE
7172     /* Amateur Radio X.25 PLP */
7173     PyModule_AddIntMacro(m, AF_ROSE);
7174 #endif
7175 #ifdef AF_DECnet
7176     /* Reserved for DECnet project */
7177     PyModule_AddIntMacro(m, AF_DECnet);
7178 #endif
7179 #ifdef AF_NETBEUI
7180     /* Reserved for 802.2LLC project */
7181     PyModule_AddIntMacro(m, AF_NETBEUI);
7182 #endif
7183 #ifdef AF_SECURITY
7184     /* Security callback pseudo AF */
7185     PyModule_AddIntMacro(m, AF_SECURITY);
7186 #endif
7187 #ifdef AF_KEY
7188     /* PF_KEY key management API */
7189     PyModule_AddIntMacro(m, AF_KEY);
7190 #endif
7191 #ifdef AF_NETLINK
7192     /*  */
7193     PyModule_AddIntMacro(m, AF_NETLINK);
7194     PyModule_AddIntMacro(m, NETLINK_ROUTE);
7195 #ifdef NETLINK_SKIP
7196     PyModule_AddIntMacro(m, NETLINK_SKIP);
7197 #endif
7198 #ifdef NETLINK_W1
7199     PyModule_AddIntMacro(m, NETLINK_W1);
7200 #endif
7201     PyModule_AddIntMacro(m, NETLINK_USERSOCK);
7202     PyModule_AddIntMacro(m, NETLINK_FIREWALL);
7203 #ifdef NETLINK_TCPDIAG
7204     PyModule_AddIntMacro(m, NETLINK_TCPDIAG);
7205 #endif
7206 #ifdef NETLINK_NFLOG
7207     PyModule_AddIntMacro(m, NETLINK_NFLOG);
7208 #endif
7209 #ifdef NETLINK_XFRM
7210     PyModule_AddIntMacro(m, NETLINK_XFRM);
7211 #endif
7212 #ifdef NETLINK_ARPD
7213     PyModule_AddIntMacro(m, NETLINK_ARPD);
7214 #endif
7215 #ifdef NETLINK_ROUTE6
7216     PyModule_AddIntMacro(m, NETLINK_ROUTE6);
7217 #endif
7218     PyModule_AddIntMacro(m, NETLINK_IP6_FW);
7219 #ifdef NETLINK_DNRTMSG
7220     PyModule_AddIntMacro(m, NETLINK_DNRTMSG);
7221 #endif
7222 #ifdef NETLINK_TAPBASE
7223     PyModule_AddIntMacro(m, NETLINK_TAPBASE);
7224 #endif
7225 #ifdef NETLINK_CRYPTO
7226     PyModule_AddIntMacro(m, NETLINK_CRYPTO);
7227 #endif
7228 #endif /* AF_NETLINK */
7229 
7230 #ifdef AF_QIPCRTR
7231     /* Qualcomm IPCROUTER */
7232     PyModule_AddIntMacro(m, AF_QIPCRTR);
7233 #endif
7234 
7235 #ifdef AF_VSOCK
7236     PyModule_AddIntConstant(m, "AF_VSOCK", AF_VSOCK);
7237     PyModule_AddIntConstant(m, "SO_VM_SOCKETS_BUFFER_SIZE", 0);
7238     PyModule_AddIntConstant(m, "SO_VM_SOCKETS_BUFFER_MIN_SIZE", 1);
7239     PyModule_AddIntConstant(m, "SO_VM_SOCKETS_BUFFER_MAX_SIZE", 2);
7240     PyModule_AddIntConstant(m, "VMADDR_CID_ANY", 0xffffffff);
7241     PyModule_AddIntConstant(m, "VMADDR_PORT_ANY", 0xffffffff);
7242     PyModule_AddIntConstant(m, "VMADDR_CID_HOST", 2);
7243     PyModule_AddIntConstant(m, "VM_SOCKETS_INVALID_VERSION", 0xffffffff);
7244     PyModule_AddIntConstant(m, "IOCTL_VM_SOCKETS_GET_LOCAL_CID",  _IO(7, 0xb9));
7245 #endif
7246 
7247 #ifdef AF_ROUTE
7248     /* Alias to emulate 4.4BSD */
7249     PyModule_AddIntMacro(m, AF_ROUTE);
7250 #endif
7251 #ifdef AF_LINK
7252     PyModule_AddIntMacro(m, AF_LINK);
7253 #endif
7254 #ifdef AF_ASH
7255     /* Ash */
7256     PyModule_AddIntMacro(m, AF_ASH);
7257 #endif
7258 #ifdef AF_ECONET
7259     /* Acorn Econet */
7260     PyModule_AddIntMacro(m, AF_ECONET);
7261 #endif
7262 #ifdef AF_ATMSVC
7263     /* ATM SVCs */
7264     PyModule_AddIntMacro(m, AF_ATMSVC);
7265 #endif
7266 #ifdef AF_SNA
7267     /* Linux SNA Project (nutters!) */
7268     PyModule_AddIntMacro(m, AF_SNA);
7269 #endif
7270 #ifdef AF_IRDA
7271     /* IRDA sockets */
7272     PyModule_AddIntMacro(m, AF_IRDA);
7273 #endif
7274 #ifdef AF_PPPOX
7275     /* PPPoX sockets */
7276     PyModule_AddIntMacro(m, AF_PPPOX);
7277 #endif
7278 #ifdef AF_WANPIPE
7279     /* Wanpipe API Sockets */
7280     PyModule_AddIntMacro(m, AF_WANPIPE);
7281 #endif
7282 #ifdef AF_LLC
7283     /* Linux LLC */
7284     PyModule_AddIntMacro(m, AF_LLC);
7285 #endif
7286 
7287 #ifdef USE_BLUETOOTH
7288     PyModule_AddIntMacro(m, AF_BLUETOOTH);
7289     PyModule_AddIntMacro(m, BTPROTO_L2CAP);
7290     PyModule_AddIntMacro(m, BTPROTO_HCI);
7291     PyModule_AddIntMacro(m, SOL_HCI);
7292 #if !defined(__NetBSD__) && !defined(__DragonFly__)
7293     PyModule_AddIntMacro(m, HCI_FILTER);
7294 #endif
7295 #if !defined(__FreeBSD__)
7296 #if !defined(__NetBSD__) && !defined(__DragonFly__)
7297     PyModule_AddIntMacro(m, HCI_TIME_STAMP);
7298 #endif
7299     PyModule_AddIntMacro(m, HCI_DATA_DIR);
7300     PyModule_AddIntMacro(m, BTPROTO_SCO);
7301 #endif
7302     PyModule_AddIntMacro(m, BTPROTO_RFCOMM);
7303     PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
7304     PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
7305 #endif
7306 
7307 #ifdef AF_CAN
7308     /* Controller Area Network */
7309     PyModule_AddIntMacro(m, AF_CAN);
7310 #endif
7311 #ifdef PF_CAN
7312     /* Controller Area Network */
7313     PyModule_AddIntMacro(m, PF_CAN);
7314 #endif
7315 
7316 /* Reliable Datagram Sockets */
7317 #ifdef AF_RDS
7318     PyModule_AddIntMacro(m, AF_RDS);
7319 #endif
7320 #ifdef PF_RDS
7321     PyModule_AddIntMacro(m, PF_RDS);
7322 #endif
7323 
7324 /* Kernel event messages */
7325 #ifdef PF_SYSTEM
7326     PyModule_AddIntMacro(m, PF_SYSTEM);
7327 #endif
7328 #ifdef AF_SYSTEM
7329     PyModule_AddIntMacro(m, AF_SYSTEM);
7330 #endif
7331 
7332 #ifdef AF_PACKET
7333     PyModule_AddIntMacro(m, AF_PACKET);
7334 #endif
7335 #ifdef PF_PACKET
7336     PyModule_AddIntMacro(m, PF_PACKET);
7337 #endif
7338 #ifdef PACKET_HOST
7339     PyModule_AddIntMacro(m, PACKET_HOST);
7340 #endif
7341 #ifdef PACKET_BROADCAST
7342     PyModule_AddIntMacro(m, PACKET_BROADCAST);
7343 #endif
7344 #ifdef PACKET_MULTICAST
7345     PyModule_AddIntMacro(m, PACKET_MULTICAST);
7346 #endif
7347 #ifdef PACKET_OTHERHOST
7348     PyModule_AddIntMacro(m, PACKET_OTHERHOST);
7349 #endif
7350 #ifdef PACKET_OUTGOING
7351     PyModule_AddIntMacro(m, PACKET_OUTGOING);
7352 #endif
7353 #ifdef PACKET_LOOPBACK
7354     PyModule_AddIntMacro(m, PACKET_LOOPBACK);
7355 #endif
7356 #ifdef PACKET_FASTROUTE
7357     PyModule_AddIntMacro(m, PACKET_FASTROUTE);
7358 #endif
7359 
7360 #ifdef HAVE_LINUX_TIPC_H
7361     PyModule_AddIntMacro(m, AF_TIPC);
7362 
7363     /* for addresses */
7364     PyModule_AddIntMacro(m, TIPC_ADDR_NAMESEQ);
7365     PyModule_AddIntMacro(m, TIPC_ADDR_NAME);
7366     PyModule_AddIntMacro(m, TIPC_ADDR_ID);
7367 
7368     PyModule_AddIntMacro(m, TIPC_ZONE_SCOPE);
7369     PyModule_AddIntMacro(m, TIPC_CLUSTER_SCOPE);
7370     PyModule_AddIntMacro(m, TIPC_NODE_SCOPE);
7371 
7372     /* for setsockopt() */
7373     PyModule_AddIntMacro(m, SOL_TIPC);
7374     PyModule_AddIntMacro(m, TIPC_IMPORTANCE);
7375     PyModule_AddIntMacro(m, TIPC_SRC_DROPPABLE);
7376     PyModule_AddIntMacro(m, TIPC_DEST_DROPPABLE);
7377     PyModule_AddIntMacro(m, TIPC_CONN_TIMEOUT);
7378 
7379     PyModule_AddIntMacro(m, TIPC_LOW_IMPORTANCE);
7380     PyModule_AddIntMacro(m, TIPC_MEDIUM_IMPORTANCE);
7381     PyModule_AddIntMacro(m, TIPC_HIGH_IMPORTANCE);
7382     PyModule_AddIntMacro(m, TIPC_CRITICAL_IMPORTANCE);
7383 
7384     /* for subscriptions */
7385     PyModule_AddIntMacro(m, TIPC_SUB_PORTS);
7386     PyModule_AddIntMacro(m, TIPC_SUB_SERVICE);
7387 #ifdef TIPC_SUB_CANCEL
7388     /* doesn't seem to be available everywhere */
7389     PyModule_AddIntMacro(m, TIPC_SUB_CANCEL);
7390 #endif
7391     PyModule_AddIntMacro(m, TIPC_WAIT_FOREVER);
7392     PyModule_AddIntMacro(m, TIPC_PUBLISHED);
7393     PyModule_AddIntMacro(m, TIPC_WITHDRAWN);
7394     PyModule_AddIntMacro(m, TIPC_SUBSCR_TIMEOUT);
7395     PyModule_AddIntMacro(m, TIPC_CFG_SRV);
7396     PyModule_AddIntMacro(m, TIPC_TOP_SRV);
7397 #endif
7398 
7399 #ifdef HAVE_SOCKADDR_ALG
7400     /* Socket options */
7401     PyModule_AddIntMacro(m, ALG_SET_KEY);
7402     PyModule_AddIntMacro(m, ALG_SET_IV);
7403     PyModule_AddIntMacro(m, ALG_SET_OP);
7404     PyModule_AddIntMacro(m, ALG_SET_AEAD_ASSOCLEN);
7405     PyModule_AddIntMacro(m, ALG_SET_AEAD_AUTHSIZE);
7406     PyModule_AddIntMacro(m, ALG_SET_PUBKEY);
7407 
7408     /* Operations */
7409     PyModule_AddIntMacro(m, ALG_OP_DECRYPT);
7410     PyModule_AddIntMacro(m, ALG_OP_ENCRYPT);
7411     PyModule_AddIntMacro(m, ALG_OP_SIGN);
7412     PyModule_AddIntMacro(m, ALG_OP_VERIFY);
7413 #endif
7414 
7415     /* Socket types */
7416     PyModule_AddIntMacro(m, SOCK_STREAM);
7417     PyModule_AddIntMacro(m, SOCK_DGRAM);
7418 /* We have incomplete socket support. */
7419 #ifdef SOCK_RAW
7420     /* SOCK_RAW is marked as optional in the POSIX specification */
7421     PyModule_AddIntMacro(m, SOCK_RAW);
7422 #endif
7423     PyModule_AddIntMacro(m, SOCK_SEQPACKET);
7424 #if defined(SOCK_RDM)
7425     PyModule_AddIntMacro(m, SOCK_RDM);
7426 #endif
7427 #ifdef SOCK_CLOEXEC
7428     PyModule_AddIntMacro(m, SOCK_CLOEXEC);
7429 #endif
7430 #ifdef SOCK_NONBLOCK
7431     PyModule_AddIntMacro(m, SOCK_NONBLOCK);
7432 #endif
7433 
7434 #ifdef  SO_DEBUG
7435     PyModule_AddIntMacro(m, SO_DEBUG);
7436 #endif
7437 #ifdef  SO_ACCEPTCONN
7438     PyModule_AddIntMacro(m, SO_ACCEPTCONN);
7439 #endif
7440 #ifdef  SO_REUSEADDR
7441     PyModule_AddIntMacro(m, SO_REUSEADDR);
7442 #endif
7443 #ifdef SO_EXCLUSIVEADDRUSE
7444     PyModule_AddIntMacro(m, SO_EXCLUSIVEADDRUSE);
7445 #endif
7446 
7447 #ifdef  SO_KEEPALIVE
7448     PyModule_AddIntMacro(m, SO_KEEPALIVE);
7449 #endif
7450 #ifdef  SO_DONTROUTE
7451     PyModule_AddIntMacro(m, SO_DONTROUTE);
7452 #endif
7453 #ifdef  SO_BROADCAST
7454     PyModule_AddIntMacro(m, SO_BROADCAST);
7455 #endif
7456 #ifdef  SO_USELOOPBACK
7457     PyModule_AddIntMacro(m, SO_USELOOPBACK);
7458 #endif
7459 #ifdef  SO_LINGER
7460     PyModule_AddIntMacro(m, SO_LINGER);
7461 #endif
7462 #ifdef  SO_OOBINLINE
7463     PyModule_AddIntMacro(m, SO_OOBINLINE);
7464 #endif
7465 #ifndef __GNU__
7466 #ifdef  SO_REUSEPORT
7467     PyModule_AddIntMacro(m, SO_REUSEPORT);
7468 #endif
7469 #endif
7470 #ifdef  SO_SNDBUF
7471     PyModule_AddIntMacro(m, SO_SNDBUF);
7472 #endif
7473 #ifdef  SO_RCVBUF
7474     PyModule_AddIntMacro(m, SO_RCVBUF);
7475 #endif
7476 #ifdef  SO_SNDLOWAT
7477     PyModule_AddIntMacro(m, SO_SNDLOWAT);
7478 #endif
7479 #ifdef  SO_RCVLOWAT
7480     PyModule_AddIntMacro(m, SO_RCVLOWAT);
7481 #endif
7482 #ifdef  SO_SNDTIMEO
7483     PyModule_AddIntMacro(m, SO_SNDTIMEO);
7484 #endif
7485 #ifdef  SO_RCVTIMEO
7486     PyModule_AddIntMacro(m, SO_RCVTIMEO);
7487 #endif
7488 #ifdef  SO_ERROR
7489     PyModule_AddIntMacro(m, SO_ERROR);
7490 #endif
7491 #ifdef  SO_TYPE
7492     PyModule_AddIntMacro(m, SO_TYPE);
7493 #endif
7494 #ifdef  SO_SETFIB
7495     PyModule_AddIntMacro(m, SO_SETFIB);
7496 #endif
7497 #ifdef  SO_PASSCRED
7498     PyModule_AddIntMacro(m, SO_PASSCRED);
7499 #endif
7500 #ifdef  SO_PEERCRED
7501     PyModule_AddIntMacro(m, SO_PEERCRED);
7502 #endif
7503 #ifdef  LOCAL_PEERCRED
7504     PyModule_AddIntMacro(m, LOCAL_PEERCRED);
7505 #endif
7506 #ifdef  SO_PASSSEC
7507     PyModule_AddIntMacro(m, SO_PASSSEC);
7508 #endif
7509 #ifdef  SO_PEERSEC
7510     PyModule_AddIntMacro(m, SO_PEERSEC);
7511 #endif
7512 #ifdef  SO_BINDTODEVICE
7513     PyModule_AddIntMacro(m, SO_BINDTODEVICE);
7514 #endif
7515 #ifdef  SO_PRIORITY
7516     PyModule_AddIntMacro(m, SO_PRIORITY);
7517 #endif
7518 #ifdef  SO_MARK
7519     PyModule_AddIntMacro(m, SO_MARK);
7520 #endif
7521 #ifdef SO_DOMAIN
7522     PyModule_AddIntMacro(m, SO_DOMAIN);
7523 #endif
7524 #ifdef SO_PROTOCOL
7525     PyModule_AddIntMacro(m, SO_PROTOCOL);
7526 #endif
7527 
7528     /* Maximum number of connections for "listen" */
7529 #ifdef  SOMAXCONN
7530     PyModule_AddIntMacro(m, SOMAXCONN);
7531 #else
7532     PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
7533 #endif
7534 
7535     /* Ancillary message types */
7536 #ifdef  SCM_RIGHTS
7537     PyModule_AddIntMacro(m, SCM_RIGHTS);
7538 #endif
7539 #ifdef  SCM_CREDENTIALS
7540     PyModule_AddIntMacro(m, SCM_CREDENTIALS);
7541 #endif
7542 #ifdef  SCM_CREDS
7543     PyModule_AddIntMacro(m, SCM_CREDS);
7544 #endif
7545 
7546     /* Flags for send, recv */
7547 #ifdef  MSG_OOB
7548     PyModule_AddIntMacro(m, MSG_OOB);
7549 #endif
7550 #ifdef  MSG_PEEK
7551     PyModule_AddIntMacro(m, MSG_PEEK);
7552 #endif
7553 #ifdef  MSG_DONTROUTE
7554     PyModule_AddIntMacro(m, MSG_DONTROUTE);
7555 #endif
7556 #ifdef  MSG_DONTWAIT
7557     PyModule_AddIntMacro(m, MSG_DONTWAIT);
7558 #endif
7559 #ifdef  MSG_EOR
7560     PyModule_AddIntMacro(m, MSG_EOR);
7561 #endif
7562 #ifdef  MSG_TRUNC
7563     PyModule_AddIntMacro(m, MSG_TRUNC);
7564 #endif
7565 #ifdef  MSG_CTRUNC
7566     PyModule_AddIntMacro(m, MSG_CTRUNC);
7567 #endif
7568 #ifdef  MSG_WAITALL
7569     PyModule_AddIntMacro(m, MSG_WAITALL);
7570 #endif
7571 #ifdef  MSG_BTAG
7572     PyModule_AddIntMacro(m, MSG_BTAG);
7573 #endif
7574 #ifdef  MSG_ETAG
7575     PyModule_AddIntMacro(m, MSG_ETAG);
7576 #endif
7577 #ifdef  MSG_NOSIGNAL
7578     PyModule_AddIntMacro(m, MSG_NOSIGNAL);
7579 #endif
7580 #ifdef  MSG_NOTIFICATION
7581     PyModule_AddIntMacro(m, MSG_NOTIFICATION);
7582 #endif
7583 #ifdef  MSG_CMSG_CLOEXEC
7584     PyModule_AddIntMacro(m, MSG_CMSG_CLOEXEC);
7585 #endif
7586 #ifdef  MSG_ERRQUEUE
7587     PyModule_AddIntMacro(m, MSG_ERRQUEUE);
7588 #endif
7589 #ifdef  MSG_CONFIRM
7590     PyModule_AddIntMacro(m, MSG_CONFIRM);
7591 #endif
7592 #ifdef  MSG_MORE
7593     PyModule_AddIntMacro(m, MSG_MORE);
7594 #endif
7595 #ifdef  MSG_EOF
7596     PyModule_AddIntMacro(m, MSG_EOF);
7597 #endif
7598 #ifdef  MSG_BCAST
7599     PyModule_AddIntMacro(m, MSG_BCAST);
7600 #endif
7601 #ifdef  MSG_MCAST
7602     PyModule_AddIntMacro(m, MSG_MCAST);
7603 #endif
7604 #ifdef MSG_FASTOPEN
7605     PyModule_AddIntMacro(m, MSG_FASTOPEN);
7606 #endif
7607 
7608     /* Protocol level and numbers, usable for [gs]etsockopt */
7609 #ifdef  SOL_SOCKET
7610     PyModule_AddIntMacro(m, SOL_SOCKET);
7611 #endif
7612 #ifdef  SOL_IP
7613     PyModule_AddIntMacro(m, SOL_IP);
7614 #else
7615     PyModule_AddIntConstant(m, "SOL_IP", 0);
7616 #endif
7617 #ifdef  SOL_IPX
7618     PyModule_AddIntMacro(m, SOL_IPX);
7619 #endif
7620 #ifdef  SOL_AX25
7621     PyModule_AddIntMacro(m, SOL_AX25);
7622 #endif
7623 #ifdef  SOL_ATALK
7624     PyModule_AddIntMacro(m, SOL_ATALK);
7625 #endif
7626 #ifdef  SOL_NETROM
7627     PyModule_AddIntMacro(m, SOL_NETROM);
7628 #endif
7629 #ifdef  SOL_ROSE
7630     PyModule_AddIntMacro(m, SOL_ROSE);
7631 #endif
7632 #ifdef  SOL_TCP
7633     PyModule_AddIntMacro(m, SOL_TCP);
7634 #else
7635     PyModule_AddIntConstant(m, "SOL_TCP", 6);
7636 #endif
7637 #ifdef  SOL_UDP
7638     PyModule_AddIntMacro(m, SOL_UDP);
7639 #else
7640     PyModule_AddIntConstant(m, "SOL_UDP", 17);
7641 #endif
7642 #ifdef SOL_CAN_BASE
7643     PyModule_AddIntMacro(m, SOL_CAN_BASE);
7644 #endif
7645 #ifdef SOL_CAN_RAW
7646     PyModule_AddIntMacro(m, SOL_CAN_RAW);
7647     PyModule_AddIntMacro(m, CAN_RAW);
7648 #endif
7649 #ifdef HAVE_LINUX_CAN_H
7650     PyModule_AddIntMacro(m, CAN_EFF_FLAG);
7651     PyModule_AddIntMacro(m, CAN_RTR_FLAG);
7652     PyModule_AddIntMacro(m, CAN_ERR_FLAG);
7653 
7654     PyModule_AddIntMacro(m, CAN_SFF_MASK);
7655     PyModule_AddIntMacro(m, CAN_EFF_MASK);
7656     PyModule_AddIntMacro(m, CAN_ERR_MASK);
7657 #ifdef CAN_ISOTP
7658     PyModule_AddIntMacro(m, CAN_ISOTP);
7659 #endif
7660 #endif
7661 #ifdef HAVE_LINUX_CAN_RAW_H
7662     PyModule_AddIntMacro(m, CAN_RAW_FILTER);
7663     PyModule_AddIntMacro(m, CAN_RAW_ERR_FILTER);
7664     PyModule_AddIntMacro(m, CAN_RAW_LOOPBACK);
7665     PyModule_AddIntMacro(m, CAN_RAW_RECV_OWN_MSGS);
7666 #endif
7667 #ifdef HAVE_LINUX_CAN_RAW_FD_FRAMES
7668     PyModule_AddIntMacro(m, CAN_RAW_FD_FRAMES);
7669 #endif
7670 #ifdef HAVE_LINUX_CAN_BCM_H
7671     PyModule_AddIntMacro(m, CAN_BCM);
7672 
7673     /* BCM opcodes */
7674     PyModule_AddIntConstant(m, "CAN_BCM_TX_SETUP", TX_SETUP);
7675     PyModule_AddIntConstant(m, "CAN_BCM_TX_DELETE", TX_DELETE);
7676     PyModule_AddIntConstant(m, "CAN_BCM_TX_READ", TX_READ);
7677     PyModule_AddIntConstant(m, "CAN_BCM_TX_SEND", TX_SEND);
7678     PyModule_AddIntConstant(m, "CAN_BCM_RX_SETUP", RX_SETUP);
7679     PyModule_AddIntConstant(m, "CAN_BCM_RX_DELETE", RX_DELETE);
7680     PyModule_AddIntConstant(m, "CAN_BCM_RX_READ", RX_READ);
7681     PyModule_AddIntConstant(m, "CAN_BCM_TX_STATUS", TX_STATUS);
7682     PyModule_AddIntConstant(m, "CAN_BCM_TX_EXPIRED", TX_EXPIRED);
7683     PyModule_AddIntConstant(m, "CAN_BCM_RX_STATUS", RX_STATUS);
7684     PyModule_AddIntConstant(m, "CAN_BCM_RX_TIMEOUT", RX_TIMEOUT);
7685     PyModule_AddIntConstant(m, "CAN_BCM_RX_CHANGED", RX_CHANGED);
7686 
7687     /* BCM flags */
7688     PyModule_AddIntConstant(m, "CAN_BCM_SETTIMER", SETTIMER);
7689     PyModule_AddIntConstant(m, "CAN_BCM_STARTTIMER", STARTTIMER);
7690     PyModule_AddIntConstant(m, "CAN_BCM_TX_COUNTEVT", TX_COUNTEVT);
7691     PyModule_AddIntConstant(m, "CAN_BCM_TX_ANNOUNCE", TX_ANNOUNCE);
7692     PyModule_AddIntConstant(m, "CAN_BCM_TX_CP_CAN_ID", TX_CP_CAN_ID);
7693     PyModule_AddIntConstant(m, "CAN_BCM_RX_FILTER_ID", RX_FILTER_ID);
7694     PyModule_AddIntConstant(m, "CAN_BCM_RX_CHECK_DLC", RX_CHECK_DLC);
7695     PyModule_AddIntConstant(m, "CAN_BCM_RX_NO_AUTOTIMER", RX_NO_AUTOTIMER);
7696     PyModule_AddIntConstant(m, "CAN_BCM_RX_ANNOUNCE_RESUME", RX_ANNOUNCE_RESUME);
7697     PyModule_AddIntConstant(m, "CAN_BCM_TX_RESET_MULTI_IDX", TX_RESET_MULTI_IDX);
7698     PyModule_AddIntConstant(m, "CAN_BCM_RX_RTR_FRAME", RX_RTR_FRAME);
7699 #ifdef CAN_FD_FRAME
7700     /* CAN_FD_FRAME was only introduced in the 4.8.x kernel series */
7701     PyModule_AddIntConstant(m, "CAN_BCM_CAN_FD_FRAME", CAN_FD_FRAME);
7702 #endif
7703 #endif
7704 #ifdef SOL_RDS
7705     PyModule_AddIntMacro(m, SOL_RDS);
7706 #endif
7707 #ifdef HAVE_SOCKADDR_ALG
7708     PyModule_AddIntMacro(m, SOL_ALG);
7709 #endif
7710 #ifdef RDS_CANCEL_SENT_TO
7711     PyModule_AddIntMacro(m, RDS_CANCEL_SENT_TO);
7712 #endif
7713 #ifdef RDS_GET_MR
7714     PyModule_AddIntMacro(m, RDS_GET_MR);
7715 #endif
7716 #ifdef RDS_FREE_MR
7717     PyModule_AddIntMacro(m, RDS_FREE_MR);
7718 #endif
7719 #ifdef RDS_RECVERR
7720     PyModule_AddIntMacro(m, RDS_RECVERR);
7721 #endif
7722 #ifdef RDS_CONG_MONITOR
7723     PyModule_AddIntMacro(m, RDS_CONG_MONITOR);
7724 #endif
7725 #ifdef RDS_GET_MR_FOR_DEST
7726     PyModule_AddIntMacro(m, RDS_GET_MR_FOR_DEST);
7727 #endif
7728 #ifdef  IPPROTO_IP
7729     PyModule_AddIntMacro(m, IPPROTO_IP);
7730 #else
7731     PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
7732 #endif
7733 #ifdef  IPPROTO_HOPOPTS
7734     PyModule_AddIntMacro(m, IPPROTO_HOPOPTS);
7735 #endif
7736 #ifdef  IPPROTO_ICMP
7737     PyModule_AddIntMacro(m, IPPROTO_ICMP);
7738 #else
7739     PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
7740 #endif
7741 #ifdef  IPPROTO_IGMP
7742     PyModule_AddIntMacro(m, IPPROTO_IGMP);
7743 #endif
7744 #ifdef  IPPROTO_GGP
7745     PyModule_AddIntMacro(m, IPPROTO_GGP);
7746 #endif
7747 #ifdef  IPPROTO_IPV4
7748     PyModule_AddIntMacro(m, IPPROTO_IPV4);
7749 #endif
7750 #ifdef  IPPROTO_IPV6
7751     PyModule_AddIntMacro(m, IPPROTO_IPV6);
7752 #endif
7753 #ifdef  IPPROTO_IPIP
7754     PyModule_AddIntMacro(m, IPPROTO_IPIP);
7755 #endif
7756 #ifdef  IPPROTO_TCP
7757     PyModule_AddIntMacro(m, IPPROTO_TCP);
7758 #else
7759     PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
7760 #endif
7761 #ifdef  IPPROTO_EGP
7762     PyModule_AddIntMacro(m, IPPROTO_EGP);
7763 #endif
7764 #ifdef  IPPROTO_PUP
7765     PyModule_AddIntMacro(m, IPPROTO_PUP);
7766 #endif
7767 #ifdef  IPPROTO_UDP
7768     PyModule_AddIntMacro(m, IPPROTO_UDP);
7769 #else
7770     PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
7771 #endif
7772 #ifdef  IPPROTO_IDP
7773     PyModule_AddIntMacro(m, IPPROTO_IDP);
7774 #endif
7775 #ifdef  IPPROTO_HELLO
7776     PyModule_AddIntMacro(m, IPPROTO_HELLO);
7777 #endif
7778 #ifdef  IPPROTO_ND
7779     PyModule_AddIntMacro(m, IPPROTO_ND);
7780 #endif
7781 #ifdef  IPPROTO_TP
7782     PyModule_AddIntMacro(m, IPPROTO_TP);
7783 #endif
7784 #ifdef  IPPROTO_ROUTING
7785     PyModule_AddIntMacro(m, IPPROTO_ROUTING);
7786 #endif
7787 #ifdef  IPPROTO_FRAGMENT
7788     PyModule_AddIntMacro(m, IPPROTO_FRAGMENT);
7789 #endif
7790 #ifdef  IPPROTO_RSVP
7791     PyModule_AddIntMacro(m, IPPROTO_RSVP);
7792 #endif
7793 #ifdef  IPPROTO_GRE
7794     PyModule_AddIntMacro(m, IPPROTO_GRE);
7795 #endif
7796 #ifdef  IPPROTO_ESP
7797     PyModule_AddIntMacro(m, IPPROTO_ESP);
7798 #endif
7799 #ifdef  IPPROTO_AH
7800     PyModule_AddIntMacro(m, IPPROTO_AH);
7801 #endif
7802 #ifdef  IPPROTO_MOBILE
7803     PyModule_AddIntMacro(m, IPPROTO_MOBILE);
7804 #endif
7805 #ifdef  IPPROTO_ICMPV6
7806     PyModule_AddIntMacro(m, IPPROTO_ICMPV6);
7807 #endif
7808 #ifdef  IPPROTO_NONE
7809     PyModule_AddIntMacro(m, IPPROTO_NONE);
7810 #endif
7811 #ifdef  IPPROTO_DSTOPTS
7812     PyModule_AddIntMacro(m, IPPROTO_DSTOPTS);
7813 #endif
7814 #ifdef  IPPROTO_XTP
7815     PyModule_AddIntMacro(m, IPPROTO_XTP);
7816 #endif
7817 #ifdef  IPPROTO_EON
7818     PyModule_AddIntMacro(m, IPPROTO_EON);
7819 #endif
7820 #ifdef  IPPROTO_PIM
7821     PyModule_AddIntMacro(m, IPPROTO_PIM);
7822 #endif
7823 #ifdef  IPPROTO_IPCOMP
7824     PyModule_AddIntMacro(m, IPPROTO_IPCOMP);
7825 #endif
7826 #ifdef  IPPROTO_VRRP
7827     PyModule_AddIntMacro(m, IPPROTO_VRRP);
7828 #endif
7829 #ifdef  IPPROTO_SCTP
7830     PyModule_AddIntMacro(m, IPPROTO_SCTP);
7831 #endif
7832 #ifdef  IPPROTO_BIP
7833     PyModule_AddIntMacro(m, IPPROTO_BIP);
7834 #endif
7835 /**/
7836 #ifdef  IPPROTO_RAW
7837     PyModule_AddIntMacro(m, IPPROTO_RAW);
7838 #else
7839     PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
7840 #endif
7841 #ifdef  IPPROTO_MAX
7842     PyModule_AddIntMacro(m, IPPROTO_MAX);
7843 #endif
7844 
7845 #ifdef  MS_WINDOWS
7846     PyModule_AddIntMacro(m, IPPROTO_ICLFXBM);
7847     PyModule_AddIntMacro(m, IPPROTO_ST);
7848     PyModule_AddIntMacro(m, IPPROTO_CBT);
7849     PyModule_AddIntMacro(m, IPPROTO_IGP);
7850     PyModule_AddIntMacro(m, IPPROTO_RDP);
7851     PyModule_AddIntMacro(m, IPPROTO_PGM);
7852     PyModule_AddIntMacro(m, IPPROTO_L2TP);
7853     PyModule_AddIntMacro(m, IPPROTO_SCTP);
7854 #endif
7855 
7856 #ifdef  SYSPROTO_CONTROL
7857     PyModule_AddIntMacro(m, SYSPROTO_CONTROL);
7858 #endif
7859 
7860     /* Some port configuration */
7861 #ifdef  IPPORT_RESERVED
7862     PyModule_AddIntMacro(m, IPPORT_RESERVED);
7863 #else
7864     PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
7865 #endif
7866 #ifdef  IPPORT_USERRESERVED
7867     PyModule_AddIntMacro(m, IPPORT_USERRESERVED);
7868 #else
7869     PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
7870 #endif
7871 
7872     /* Some reserved IP v.4 addresses */
7873 #ifdef  INADDR_ANY
7874     PyModule_AddIntMacro(m, INADDR_ANY);
7875 #else
7876     PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
7877 #endif
7878 #ifdef  INADDR_BROADCAST
7879     PyModule_AddIntMacro(m, INADDR_BROADCAST);
7880 #else
7881     PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
7882 #endif
7883 #ifdef  INADDR_LOOPBACK
7884     PyModule_AddIntMacro(m, INADDR_LOOPBACK);
7885 #else
7886     PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
7887 #endif
7888 #ifdef  INADDR_UNSPEC_GROUP
7889     PyModule_AddIntMacro(m, INADDR_UNSPEC_GROUP);
7890 #else
7891     PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
7892 #endif
7893 #ifdef  INADDR_ALLHOSTS_GROUP
7894     PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
7895                             INADDR_ALLHOSTS_GROUP);
7896 #else
7897     PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
7898 #endif
7899 #ifdef  INADDR_MAX_LOCAL_GROUP
7900     PyModule_AddIntMacro(m, INADDR_MAX_LOCAL_GROUP);
7901 #else
7902     PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
7903 #endif
7904 #ifdef  INADDR_NONE
7905     PyModule_AddIntMacro(m, INADDR_NONE);
7906 #else
7907     PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
7908 #endif
7909 
7910     /* IPv4 [gs]etsockopt options */
7911 #ifdef  IP_OPTIONS
7912     PyModule_AddIntMacro(m, IP_OPTIONS);
7913 #endif
7914 #ifdef  IP_HDRINCL
7915     PyModule_AddIntMacro(m, IP_HDRINCL);
7916 #endif
7917 #ifdef  IP_TOS
7918     PyModule_AddIntMacro(m, IP_TOS);
7919 #endif
7920 #ifdef  IP_TTL
7921     PyModule_AddIntMacro(m, IP_TTL);
7922 #endif
7923 #ifdef  IP_RECVOPTS
7924     PyModule_AddIntMacro(m, IP_RECVOPTS);
7925 #endif
7926 #ifdef  IP_RECVRETOPTS
7927     PyModule_AddIntMacro(m, IP_RECVRETOPTS);
7928 #endif
7929 #ifdef  IP_RECVDSTADDR
7930     PyModule_AddIntMacro(m, IP_RECVDSTADDR);
7931 #endif
7932 #ifdef  IP_RETOPTS
7933     PyModule_AddIntMacro(m, IP_RETOPTS);
7934 #endif
7935 #ifdef  IP_MULTICAST_IF
7936     PyModule_AddIntMacro(m, IP_MULTICAST_IF);
7937 #endif
7938 #ifdef  IP_MULTICAST_TTL
7939     PyModule_AddIntMacro(m, IP_MULTICAST_TTL);
7940 #endif
7941 #ifdef  IP_MULTICAST_LOOP
7942     PyModule_AddIntMacro(m, IP_MULTICAST_LOOP);
7943 #endif
7944 #ifdef  IP_ADD_MEMBERSHIP
7945     PyModule_AddIntMacro(m, IP_ADD_MEMBERSHIP);
7946 #endif
7947 #ifdef  IP_DROP_MEMBERSHIP
7948     PyModule_AddIntMacro(m, IP_DROP_MEMBERSHIP);
7949 #endif
7950 #ifdef  IP_DEFAULT_MULTICAST_TTL
7951     PyModule_AddIntMacro(m, IP_DEFAULT_MULTICAST_TTL);
7952 #endif
7953 #ifdef  IP_DEFAULT_MULTICAST_LOOP
7954     PyModule_AddIntMacro(m, IP_DEFAULT_MULTICAST_LOOP);
7955 #endif
7956 #ifdef  IP_MAX_MEMBERSHIPS
7957     PyModule_AddIntMacro(m, IP_MAX_MEMBERSHIPS);
7958 #endif
7959 #ifdef  IP_TRANSPARENT
7960     PyModule_AddIntMacro(m, IP_TRANSPARENT);
7961 #endif
7962 
7963     /* IPv6 [gs]etsockopt options, defined in RFC2553 */
7964 #ifdef  IPV6_JOIN_GROUP
7965     PyModule_AddIntMacro(m, IPV6_JOIN_GROUP);
7966 #endif
7967 #ifdef  IPV6_LEAVE_GROUP
7968     PyModule_AddIntMacro(m, IPV6_LEAVE_GROUP);
7969 #endif
7970 #ifdef  IPV6_MULTICAST_HOPS
7971     PyModule_AddIntMacro(m, IPV6_MULTICAST_HOPS);
7972 #endif
7973 #ifdef  IPV6_MULTICAST_IF
7974     PyModule_AddIntMacro(m, IPV6_MULTICAST_IF);
7975 #endif
7976 #ifdef  IPV6_MULTICAST_LOOP
7977     PyModule_AddIntMacro(m, IPV6_MULTICAST_LOOP);
7978 #endif
7979 #ifdef  IPV6_UNICAST_HOPS
7980     PyModule_AddIntMacro(m, IPV6_UNICAST_HOPS);
7981 #endif
7982     /* Additional IPV6 socket options, defined in RFC 3493 */
7983 #ifdef IPV6_V6ONLY
7984     PyModule_AddIntMacro(m, IPV6_V6ONLY);
7985 #endif
7986     /* Advanced IPV6 socket options, from RFC 3542 */
7987 #ifdef IPV6_CHECKSUM
7988     PyModule_AddIntMacro(m, IPV6_CHECKSUM);
7989 #endif
7990 #ifdef IPV6_DONTFRAG
7991     PyModule_AddIntMacro(m, IPV6_DONTFRAG);
7992 #endif
7993 #ifdef IPV6_DSTOPTS
7994     PyModule_AddIntMacro(m, IPV6_DSTOPTS);
7995 #endif
7996 #ifdef IPV6_HOPLIMIT
7997     PyModule_AddIntMacro(m, IPV6_HOPLIMIT);
7998 #endif
7999 #ifdef IPV6_HOPOPTS
8000     PyModule_AddIntMacro(m, IPV6_HOPOPTS);
8001 #endif
8002 #ifdef IPV6_NEXTHOP
8003     PyModule_AddIntMacro(m, IPV6_NEXTHOP);
8004 #endif
8005 #ifdef IPV6_PATHMTU
8006     PyModule_AddIntMacro(m, IPV6_PATHMTU);
8007 #endif
8008 #ifdef IPV6_PKTINFO
8009     PyModule_AddIntMacro(m, IPV6_PKTINFO);
8010 #endif
8011 #ifdef IPV6_RECVDSTOPTS
8012     PyModule_AddIntMacro(m, IPV6_RECVDSTOPTS);
8013 #endif
8014 #ifdef IPV6_RECVHOPLIMIT
8015     PyModule_AddIntMacro(m, IPV6_RECVHOPLIMIT);
8016 #endif
8017 #ifdef IPV6_RECVHOPOPTS
8018     PyModule_AddIntMacro(m, IPV6_RECVHOPOPTS);
8019 #endif
8020 #ifdef IPV6_RECVPKTINFO
8021     PyModule_AddIntMacro(m, IPV6_RECVPKTINFO);
8022 #endif
8023 #ifdef IPV6_RECVRTHDR
8024     PyModule_AddIntMacro(m, IPV6_RECVRTHDR);
8025 #endif
8026 #ifdef IPV6_RECVTCLASS
8027     PyModule_AddIntMacro(m, IPV6_RECVTCLASS);
8028 #endif
8029 #ifdef IPV6_RTHDR
8030     PyModule_AddIntMacro(m, IPV6_RTHDR);
8031 #endif
8032 #ifdef IPV6_RTHDRDSTOPTS
8033     PyModule_AddIntMacro(m, IPV6_RTHDRDSTOPTS);
8034 #endif
8035 #ifdef IPV6_RTHDR_TYPE_0
8036     PyModule_AddIntMacro(m, IPV6_RTHDR_TYPE_0);
8037 #endif
8038 #ifdef IPV6_RECVPATHMTU
8039     PyModule_AddIntMacro(m, IPV6_RECVPATHMTU);
8040 #endif
8041 #ifdef IPV6_TCLASS
8042     PyModule_AddIntMacro(m, IPV6_TCLASS);
8043 #endif
8044 #ifdef IPV6_USE_MIN_MTU
8045     PyModule_AddIntMacro(m, IPV6_USE_MIN_MTU);
8046 #endif
8047 
8048     /* TCP options */
8049 #ifdef  TCP_NODELAY
8050     PyModule_AddIntMacro(m, TCP_NODELAY);
8051 #endif
8052 #ifdef  TCP_MAXSEG
8053     PyModule_AddIntMacro(m, TCP_MAXSEG);
8054 #endif
8055 #ifdef  TCP_CORK
8056     PyModule_AddIntMacro(m, TCP_CORK);
8057 #endif
8058 #ifdef  TCP_KEEPIDLE
8059     PyModule_AddIntMacro(m, TCP_KEEPIDLE);
8060 #endif
8061 #ifdef  TCP_KEEPINTVL
8062     PyModule_AddIntMacro(m, TCP_KEEPINTVL);
8063 #endif
8064 #ifdef  TCP_KEEPCNT
8065     PyModule_AddIntMacro(m, TCP_KEEPCNT);
8066 #endif
8067 #ifdef  TCP_SYNCNT
8068     PyModule_AddIntMacro(m, TCP_SYNCNT);
8069 #endif
8070 #ifdef  TCP_LINGER2
8071     PyModule_AddIntMacro(m, TCP_LINGER2);
8072 #endif
8073 #ifdef  TCP_DEFER_ACCEPT
8074     PyModule_AddIntMacro(m, TCP_DEFER_ACCEPT);
8075 #endif
8076 #ifdef  TCP_WINDOW_CLAMP
8077     PyModule_AddIntMacro(m, TCP_WINDOW_CLAMP);
8078 #endif
8079 #ifdef  TCP_INFO
8080     PyModule_AddIntMacro(m, TCP_INFO);
8081 #endif
8082 #ifdef  TCP_QUICKACK
8083     PyModule_AddIntMacro(m, TCP_QUICKACK);
8084 #endif
8085 #ifdef  TCP_FASTOPEN
8086     PyModule_AddIntMacro(m, TCP_FASTOPEN);
8087 #endif
8088 #ifdef  TCP_CONGESTION
8089     PyModule_AddIntMacro(m, TCP_CONGESTION);
8090 #endif
8091 #ifdef  TCP_USER_TIMEOUT
8092     PyModule_AddIntMacro(m, TCP_USER_TIMEOUT);
8093 #endif
8094 #ifdef  TCP_NOTSENT_LOWAT
8095     PyModule_AddIntMacro(m, TCP_NOTSENT_LOWAT);
8096 #endif
8097 
8098     /* IPX options */
8099 #ifdef  IPX_TYPE
8100     PyModule_AddIntMacro(m, IPX_TYPE);
8101 #endif
8102 
8103 /* Reliable Datagram Sockets */
8104 #ifdef RDS_CMSG_RDMA_ARGS
8105     PyModule_AddIntMacro(m, RDS_CMSG_RDMA_ARGS);
8106 #endif
8107 #ifdef RDS_CMSG_RDMA_DEST
8108     PyModule_AddIntMacro(m, RDS_CMSG_RDMA_DEST);
8109 #endif
8110 #ifdef RDS_CMSG_RDMA_MAP
8111     PyModule_AddIntMacro(m, RDS_CMSG_RDMA_MAP);
8112 #endif
8113 #ifdef RDS_CMSG_RDMA_STATUS
8114     PyModule_AddIntMacro(m, RDS_CMSG_RDMA_STATUS);
8115 #endif
8116 #ifdef RDS_CMSG_RDMA_UPDATE
8117     PyModule_AddIntMacro(m, RDS_CMSG_RDMA_UPDATE);
8118 #endif
8119 #ifdef RDS_RDMA_READWRITE
8120     PyModule_AddIntMacro(m, RDS_RDMA_READWRITE);
8121 #endif
8122 #ifdef RDS_RDMA_FENCE
8123     PyModule_AddIntMacro(m, RDS_RDMA_FENCE);
8124 #endif
8125 #ifdef RDS_RDMA_INVALIDATE
8126     PyModule_AddIntMacro(m, RDS_RDMA_INVALIDATE);
8127 #endif
8128 #ifdef RDS_RDMA_USE_ONCE
8129     PyModule_AddIntMacro(m, RDS_RDMA_USE_ONCE);
8130 #endif
8131 #ifdef RDS_RDMA_DONTWAIT
8132     PyModule_AddIntMacro(m, RDS_RDMA_DONTWAIT);
8133 #endif
8134 #ifdef RDS_RDMA_NOTIFY_ME
8135     PyModule_AddIntMacro(m, RDS_RDMA_NOTIFY_ME);
8136 #endif
8137 #ifdef RDS_RDMA_SILENT
8138     PyModule_AddIntMacro(m, RDS_RDMA_SILENT);
8139 #endif
8140 
8141     /* get{addr,name}info parameters */
8142 #ifdef EAI_ADDRFAMILY
8143     PyModule_AddIntMacro(m, EAI_ADDRFAMILY);
8144 #endif
8145 #ifdef EAI_AGAIN
8146     PyModule_AddIntMacro(m, EAI_AGAIN);
8147 #endif
8148 #ifdef EAI_BADFLAGS
8149     PyModule_AddIntMacro(m, EAI_BADFLAGS);
8150 #endif
8151 #ifdef EAI_FAIL
8152     PyModule_AddIntMacro(m, EAI_FAIL);
8153 #endif
8154 #ifdef EAI_FAMILY
8155     PyModule_AddIntMacro(m, EAI_FAMILY);
8156 #endif
8157 #ifdef EAI_MEMORY
8158     PyModule_AddIntMacro(m, EAI_MEMORY);
8159 #endif
8160 #ifdef EAI_NODATA
8161     PyModule_AddIntMacro(m, EAI_NODATA);
8162 #endif
8163 #ifdef EAI_NONAME
8164     PyModule_AddIntMacro(m, EAI_NONAME);
8165 #endif
8166 #ifdef EAI_OVERFLOW
8167     PyModule_AddIntMacro(m, EAI_OVERFLOW);
8168 #endif
8169 #ifdef EAI_SERVICE
8170     PyModule_AddIntMacro(m, EAI_SERVICE);
8171 #endif
8172 #ifdef EAI_SOCKTYPE
8173     PyModule_AddIntMacro(m, EAI_SOCKTYPE);
8174 #endif
8175 #ifdef EAI_SYSTEM
8176     PyModule_AddIntMacro(m, EAI_SYSTEM);
8177 #endif
8178 #ifdef EAI_BADHINTS
8179     PyModule_AddIntMacro(m, EAI_BADHINTS);
8180 #endif
8181 #ifdef EAI_PROTOCOL
8182     PyModule_AddIntMacro(m, EAI_PROTOCOL);
8183 #endif
8184 #ifdef EAI_MAX
8185     PyModule_AddIntMacro(m, EAI_MAX);
8186 #endif
8187 #ifdef AI_PASSIVE
8188     PyModule_AddIntMacro(m, AI_PASSIVE);
8189 #endif
8190 #ifdef AI_CANONNAME
8191     PyModule_AddIntMacro(m, AI_CANONNAME);
8192 #endif
8193 #ifdef AI_NUMERICHOST
8194     PyModule_AddIntMacro(m, AI_NUMERICHOST);
8195 #endif
8196 #ifdef AI_NUMERICSERV
8197     PyModule_AddIntMacro(m, AI_NUMERICSERV);
8198 #endif
8199 #ifdef AI_MASK
8200     PyModule_AddIntMacro(m, AI_MASK);
8201 #endif
8202 #ifdef AI_ALL
8203     PyModule_AddIntMacro(m, AI_ALL);
8204 #endif
8205 #ifdef AI_V4MAPPED_CFG
8206     PyModule_AddIntMacro(m, AI_V4MAPPED_CFG);
8207 #endif
8208 #ifdef AI_ADDRCONFIG
8209     PyModule_AddIntMacro(m, AI_ADDRCONFIG);
8210 #endif
8211 #ifdef AI_V4MAPPED
8212     PyModule_AddIntMacro(m, AI_V4MAPPED);
8213 #endif
8214 #ifdef AI_DEFAULT
8215     PyModule_AddIntMacro(m, AI_DEFAULT);
8216 #endif
8217 #ifdef NI_MAXHOST
8218     PyModule_AddIntMacro(m, NI_MAXHOST);
8219 #endif
8220 #ifdef NI_MAXSERV
8221     PyModule_AddIntMacro(m, NI_MAXSERV);
8222 #endif
8223 #ifdef NI_NOFQDN
8224     PyModule_AddIntMacro(m, NI_NOFQDN);
8225 #endif
8226 #ifdef NI_NUMERICHOST
8227     PyModule_AddIntMacro(m, NI_NUMERICHOST);
8228 #endif
8229 #ifdef NI_NAMEREQD
8230     PyModule_AddIntMacro(m, NI_NAMEREQD);
8231 #endif
8232 #ifdef NI_NUMERICSERV
8233     PyModule_AddIntMacro(m, NI_NUMERICSERV);
8234 #endif
8235 #ifdef NI_DGRAM
8236     PyModule_AddIntMacro(m, NI_DGRAM);
8237 #endif
8238 
8239     /* shutdown() parameters */
8240 #ifdef SHUT_RD
8241     PyModule_AddIntMacro(m, SHUT_RD);
8242 #elif defined(SD_RECEIVE)
8243     PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
8244 #else
8245     PyModule_AddIntConstant(m, "SHUT_RD", 0);
8246 #endif
8247 #ifdef SHUT_WR
8248     PyModule_AddIntMacro(m, SHUT_WR);
8249 #elif defined(SD_SEND)
8250     PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
8251 #else
8252     PyModule_AddIntConstant(m, "SHUT_WR", 1);
8253 #endif
8254 #ifdef SHUT_RDWR
8255     PyModule_AddIntMacro(m, SHUT_RDWR);
8256 #elif defined(SD_BOTH)
8257     PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
8258 #else
8259     PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
8260 #endif
8261 
8262 #ifdef SIO_RCVALL
8263     {
8264         DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS,
8265 #if defined(SIO_LOOPBACK_FAST_PATH)
8266             SIO_LOOPBACK_FAST_PATH
8267 #endif
8268         };
8269         const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS",
8270 #if defined(SIO_LOOPBACK_FAST_PATH)
8271             "SIO_LOOPBACK_FAST_PATH"
8272 #endif
8273         };
8274         int i;
8275         for(i = 0; i<Py_ARRAY_LENGTH(codes); ++i) {
8276             PyObject *tmp;
8277             tmp = PyLong_FromUnsignedLong(codes[i]);
8278             if (tmp == NULL)
8279                 return NULL;
8280             PyModule_AddObject(m, names[i], tmp);
8281         }
8282     }
8283     PyModule_AddIntMacro(m, RCVALL_OFF);
8284     PyModule_AddIntMacro(m, RCVALL_ON);
8285     PyModule_AddIntMacro(m, RCVALL_SOCKETLEVELONLY);
8286 #ifdef RCVALL_IPLEVEL
8287     PyModule_AddIntMacro(m, RCVALL_IPLEVEL);
8288 #endif
8289 #ifdef RCVALL_MAX
8290     PyModule_AddIntMacro(m, RCVALL_MAX);
8291 #endif
8292 #endif /* _MSTCPIP_ */
8293 
8294     /* Initialize gethostbyname lock */
8295 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
8296     netdb_lock = PyThread_allocate_lock();
8297 #endif
8298 
8299 #ifdef MS_WINDOWS
8300     /* remove some flags on older version Windows during run-time */
8301     remove_unusable_flags(m);
8302 #endif
8303 
8304     return m;
8305 }
8306