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