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