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