LCOV - code coverage report
Current view: top level - libreoffice/workdir/unxlngi6.pro/UnpackedTarball/python3/Modules - socketmodule.c (source / functions) Hit Total Coverage
Test: libreoffice_filtered.info Lines: 289 1974 14.6 %
Date: 2012-12-17 Functions: 2 87 2.3 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /* Socket module */
       2             : 
       3             : /*
       4             : 
       5             : This module provides an interface to Berkeley socket IPC.
       6             : 
       7             : Limitations:
       8             : 
       9             : - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
      10             :   portable manner, though AF_PACKET, AF_NETLINK and AF_TIPC are supported
      11             :   under Linux.
      12             : - No read/write operations (use sendall/recv or makefile instead).
      13             : - Additional restrictions apply on some non-Unix platforms (compensated
      14             :   for by socket.py).
      15             : 
      16             : Module interface:
      17             : 
      18             : - socket.error: exception raised for socket specific errors
      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, socktype, proto, flags])
      37             :     --> List of (family, socktype, 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_TIPC socket address is expressed as
      59             :  (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
      60             :     TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
      61             :   and scope can be one of:
      62             :     TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
      63             :   The meaning of v1, v2 and v3 depends on the value of addr_type:
      64             :     if addr_type is TIPC_ADDR_NAME:
      65             :         v1 is the server type
      66             :         v2 is the port identifier
      67             :         v3 is ignored
      68             :     if addr_type is TIPC_ADDR_NAMESEQ:
      69             :         v1 is the server type
      70             :         v2 is the lower port number
      71             :         v3 is the upper port number
      72             :     if addr_type is TIPC_ADDR_ID:
      73             :         v1 is the node
      74             :         v2 is the ref
      75             :         v3 is ignored
      76             : 
      77             : 
      78             : Local naming conventions:
      79             : 
      80             : - names starting with sock_ are socket object methods
      81             : - names starting with socket_ are module-level functions
      82             : - names starting with PySocket are exported through socketmodule.h
      83             : 
      84             : */
      85             : 
      86             : #ifdef __APPLE__
      87             :   /*
      88             :    * inet_aton is not available on OSX 10.3, yet we want to use a binary
      89             :    * that was build on 10.4 or later to work on that release, weak linking
      90             :    * comes to the rescue.
      91             :    */
      92             : # pragma weak inet_aton
      93             : #endif
      94             : 
      95             : #include "Python.h"
      96             : #include "structmember.h"
      97             : 
      98             : #undef MAX
      99             : #define MAX(x, y) ((x) < (y) ? (y) : (x))
     100             : 
     101             : /* Socket object documentation */
     102             : PyDoc_STRVAR(sock_doc,
     103             : "socket([family[, type[, proto]]]) -> socket object\n\
     104             : \n\
     105             : Open a socket of the given type.  The family argument specifies the\n\
     106             : address family; it defaults to AF_INET.  The type argument specifies\n\
     107             : whether this is a stream (SOCK_STREAM, this is the default)\n\
     108             : or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,\n\
     109             : specifying the default protocol.  Keyword arguments are accepted.\n\
     110             : \n\
     111             : A socket object represents one endpoint of a network connection.\n\
     112             : \n\
     113             : Methods of socket objects (keyword arguments not allowed):\n\
     114             : \n\
     115             : _accept() -- accept connection, returning new socket fd and client address\n\
     116             : bind(addr) -- bind the socket to a local address\n\
     117             : close() -- close the socket\n\
     118             : connect(addr) -- connect the socket to a remote address\n\
     119             : connect_ex(addr) -- connect, return an error code instead of an exception\n\
     120             : _dup() -- return a new socket fd duplicated from fileno()\n\
     121             : fileno() -- return underlying file descriptor\n\
     122             : getpeername() -- return remote address [*]\n\
     123             : getsockname() -- return local address\n\
     124             : getsockopt(level, optname[, buflen]) -- get socket options\n\
     125             : gettimeout() -- return timeout or None\n\
     126             : listen(n) -- start listening for incoming connections\n\
     127             : recv(buflen[, flags]) -- receive data\n\
     128             : recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
     129             : recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
     130             : recvfrom_into(buffer[, nbytes, [, flags])\n\
     131             :   -- receive data and sender\'s address (into a buffer)\n\
     132             : sendall(data[, flags]) -- send all data\n\
     133             : send(data[, flags]) -- send data, may not send all of it\n\
     134             : sendto(data[, flags], addr) -- send data to a given address\n\
     135             : setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
     136             : setsockopt(level, optname, value) -- set socket options\n\
     137             : settimeout(None | float) -- set or clear the timeout\n\
     138             : shutdown(how) -- shut down traffic in one or both directions\n\
     139             : if_nameindex() -- return all network interface indices and names\n\
     140             : if_nametoindex(name) -- return the corresponding interface index\n\
     141             : if_indextoname(index) -- return the corresponding interface name\n\
     142             : \n\
     143             :  [*] not available on all platforms!");
     144             : 
     145             : /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
     146             :    I hope some day someone can clean this up please... */
     147             : 
     148             : /* Hacks for gethostbyname_r().  On some non-Linux platforms, the configure
     149             :    script doesn't get this right, so we hardcode some platform checks below.
     150             :    On the other hand, not all Linux versions agree, so there the settings
     151             :    computed by the configure script are needed! */
     152             : 
     153             : #ifndef linux
     154             : # undef HAVE_GETHOSTBYNAME_R_3_ARG
     155             : # undef HAVE_GETHOSTBYNAME_R_5_ARG
     156             : # undef HAVE_GETHOSTBYNAME_R_6_ARG
     157             : #endif
     158             : 
     159             : #if defined(__OpenBSD__)
     160             : # include <sys/uio.h>
     161             : #endif
     162             : 
     163             : #ifndef WITH_THREAD
     164             : # undef HAVE_GETHOSTBYNAME_R
     165             : #endif
     166             : 
     167             : #ifdef HAVE_GETHOSTBYNAME_R
     168             : # if defined(_AIX)
     169             : #  define HAVE_GETHOSTBYNAME_R_3_ARG
     170             : # elif defined(__sun) || defined(__sgi)
     171             : #  define HAVE_GETHOSTBYNAME_R_5_ARG
     172             : # elif defined(linux)
     173             : /* Rely on the configure script */
     174             : # else
     175             : #  undef HAVE_GETHOSTBYNAME_R
     176             : # endif
     177             : #endif
     178             : 
     179             : #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
     180             :     !defined(MS_WINDOWS)
     181             : # define USE_GETHOSTBYNAME_LOCK
     182             : #endif
     183             : 
     184             : /* To use __FreeBSD_version */
     185             : #ifdef HAVE_SYS_PARAM_H
     186             : #include <sys/param.h>
     187             : #endif
     188             : /* On systems on which getaddrinfo() is believed to not be thread-safe,
     189             :    (this includes the getaddrinfo emulation) protect access with a lock. */
     190             : #if defined(WITH_THREAD) && (defined(__APPLE__) || \
     191             :     (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
     192             :     defined(__OpenBSD__) || defined(__NetBSD__) || \
     193             :     defined(__VMS) || !defined(HAVE_GETADDRINFO))
     194             : #define USE_GETADDRINFO_LOCK
     195             : #endif
     196             : 
     197             : #ifdef USE_GETADDRINFO_LOCK
     198             : #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
     199             : #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
     200             : #else
     201             : #define ACQUIRE_GETADDRINFO_LOCK
     202             : #define RELEASE_GETADDRINFO_LOCK
     203             : #endif
     204             : 
     205             : #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
     206             : # include "pythread.h"
     207             : #endif
     208             : 
     209             : #if defined(PYCC_VACPP)
     210             : # include <types.h>
     211             : # include <io.h>
     212             : # include <sys/ioctl.h>
     213             : # include <utils.h>
     214             : # include <ctype.h>
     215             : #endif
     216             : 
     217             : #if defined(__VMS)
     218             : #  include <ioctl.h>
     219             : #endif
     220             : 
     221             : #ifdef __APPLE__
     222             : # include <sys/ioctl.h>
     223             : #endif
     224             : 
     225             : 
     226             : #if defined(PYOS_OS2)
     227             : # define  INCL_DOS
     228             : # define  INCL_DOSERRORS
     229             : # define  INCL_NOPMAPI
     230             : # include <os2.h>
     231             : #endif
     232             : 
     233             : #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
     234             : /* make sure that the reentrant (gethostbyaddr_r etc)
     235             :    functions are declared correctly if compiling with
     236             :    MIPSPro 7.x in ANSI C mode (default) */
     237             : 
     238             : /* XXX Using _SGIAPI is the wrong thing,
     239             :    but I don't know what the right thing is. */
     240             : #undef _SGIAPI /* to avoid warning */
     241             : #define _SGIAPI 1
     242             : 
     243             : #undef _XOPEN_SOURCE
     244             : #include <sys/socket.h>
     245             : #include <sys/types.h>
     246             : #include <netinet/in.h>
     247             : #ifdef _SS_ALIGNSIZE
     248             : #define HAVE_GETADDRINFO 1
     249             : #define HAVE_GETNAMEINFO 1
     250             : #endif
     251             : 
     252             : #define HAVE_INET_PTON
     253             : #include <netdb.h>
     254             : #endif
     255             : 
     256             : /* Irix 6.5 fails to define this variable at all. This is needed
     257             :    for both GCC and SGI's compiler. I'd say that the SGI headers
     258             :    are just busted. Same thing for Solaris. */
     259             : #if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
     260             : #define INET_ADDRSTRLEN 16
     261             : #endif
     262             : 
     263             : /* Generic includes */
     264             : #ifdef HAVE_SYS_TYPES_H
     265             : #include <sys/types.h>
     266             : #endif
     267             : 
     268             : #ifdef HAVE_SYS_SOCKET_H
     269             : #include <sys/socket.h>
     270             : #endif
     271             : 
     272             : #ifdef HAVE_NET_IF_H
     273             : #include <net/if.h>
     274             : #endif
     275             : 
     276             : /* Generic socket object definitions and includes */
     277             : #define PySocket_BUILDING_SOCKET
     278             : #include "socketmodule.h"
     279             : 
     280             : /* Addressing includes */
     281             : 
     282             : #ifndef MS_WINDOWS
     283             : 
     284             : /* Non-MS WINDOWS includes */
     285             : # include <netdb.h>
     286             : # include <unistd.h>
     287             : 
     288             : /* Headers needed for inet_ntoa() and inet_addr() */
     289             : # if defined(PYOS_OS2) && defined(PYCC_VACPP)
     290             : #  include <netdb.h>
     291             : typedef size_t socklen_t;
     292             : # else
     293             : #   include <arpa/inet.h>
     294             : # endif
     295             : 
     296             : #  include <fcntl.h>
     297             : 
     298             : #else
     299             : 
     300             : /* MS_WINDOWS includes */
     301             : # ifdef HAVE_FCNTL_H
     302             : #  include <fcntl.h>
     303             : # endif
     304             : 
     305             : #endif
     306             : 
     307             : #include <stddef.h>
     308             : 
     309             : #ifndef offsetof
     310             : # define offsetof(type, member) ((size_t)(&((type *)0)->member))
     311             : #endif
     312             : 
     313             : #ifndef O_NONBLOCK
     314             : # define O_NONBLOCK O_NDELAY
     315             : #endif
     316             : 
     317             : /* include Python's addrinfo.h unless it causes trouble */
     318             : #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
     319             :   /* Do not include addinfo.h on some newer IRIX versions.
     320             :    * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
     321             :    * for example, but not by 6.5.10.
     322             :    */
     323             : #elif defined(_MSC_VER) && _MSC_VER>1201
     324             :   /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
     325             :    * EAI_* constants are defined in (the already included) ws2tcpip.h.
     326             :    */
     327             : #else
     328             : #  include "addrinfo.h"
     329             : #endif
     330             : 
     331             : #ifndef HAVE_INET_PTON
     332             : #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
     333             : int inet_pton(int af, const char *src, void *dst);
     334             : const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
     335             : #endif
     336             : #endif
     337             : 
     338             : #ifdef __APPLE__
     339             : /* On OS X, getaddrinfo returns no error indication of lookup
     340             :    failure, so we must use the emulation instead of the libinfo
     341             :    implementation. Unfortunately, performing an autoconf test
     342             :    for this bug would require DNS access for the machine performing
     343             :    the configuration, which is not acceptable. Therefore, we
     344             :    determine the bug just by checking for __APPLE__. If this bug
     345             :    gets ever fixed, perhaps checking for sys/version.h would be
     346             :    appropriate, which is 10/0 on the system with the bug. */
     347             : #ifndef HAVE_GETNAMEINFO
     348             : /* This bug seems to be fixed in Jaguar. Ths easiest way I could
     349             :    Find to check for Jaguar is that it has getnameinfo(), which
     350             :    older releases don't have */
     351             : #undef HAVE_GETADDRINFO
     352             : #endif
     353             : 
     354             : #ifdef HAVE_INET_ATON
     355             : #define USE_INET_ATON_WEAKLINK
     356             : #endif
     357             : 
     358             : #endif
     359             : 
     360             : /* I know this is a bad practice, but it is the easiest... */
     361             : #if !defined(HAVE_GETADDRINFO)
     362             : /* avoid clashes with the C library definition of the symbol. */
     363             : #define getaddrinfo fake_getaddrinfo
     364             : #define gai_strerror fake_gai_strerror
     365             : #define freeaddrinfo fake_freeaddrinfo
     366             : #include "getaddrinfo.c"
     367             : #endif
     368             : #if !defined(HAVE_GETNAMEINFO)
     369             : #define getnameinfo fake_getnameinfo
     370             : #include "getnameinfo.c"
     371             : #endif
     372             : 
     373             : #ifdef MS_WINDOWS
     374             : /* On Windows a socket is really a handle not an fd */
     375             : static SOCKET
     376             : dup_socket(SOCKET handle)
     377             : {
     378             :     WSAPROTOCOL_INFO info;
     379             : 
     380             :     if (WSADuplicateSocket(handle, GetCurrentProcessId(), &info))
     381             :         return INVALID_SOCKET;
     382             : 
     383             :     return WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
     384             :                      FROM_PROTOCOL_INFO, &info, 0, WSA_FLAG_OVERLAPPED);
     385             : }
     386             : #define SOCKETCLOSE closesocket
     387             : #else
     388             : /* On Unix we can use dup to duplicate the file descriptor of a socket*/
     389             : #define dup_socket(fd) dup(fd)
     390             : #endif
     391             : 
     392             : #ifdef MS_WIN32
     393             : #undef EAFNOSUPPORT
     394             : #define EAFNOSUPPORT WSAEAFNOSUPPORT
     395             : #define snprintf _snprintf
     396             : #endif
     397             : 
     398             : #if defined(PYOS_OS2) && !defined(PYCC_GCC)
     399             : #define SOCKETCLOSE soclose
     400             : #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
     401             : #endif
     402             : 
     403             : #ifndef SOCKETCLOSE
     404             : #define SOCKETCLOSE close
     405             : #endif
     406             : 
     407             : #if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
     408             : #define USE_BLUETOOTH 1
     409             : #if defined(__FreeBSD__)
     410             : #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
     411             : #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
     412             : #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
     413             : #define SOL_HCI SOL_HCI_RAW
     414             : #define HCI_FILTER SO_HCI_RAW_FILTER
     415             : #define sockaddr_l2 sockaddr_l2cap
     416             : #define sockaddr_rc sockaddr_rfcomm
     417             : #define hci_dev hci_node
     418             : #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
     419             : #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
     420             : #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
     421             : #elif defined(__NetBSD__) || defined(__DragonFly__)
     422             : #define sockaddr_l2 sockaddr_bt
     423             : #define sockaddr_rc sockaddr_bt
     424             : #define sockaddr_hci sockaddr_bt
     425             : #define sockaddr_sco sockaddr_bt
     426             : #define SOL_HCI BTPROTO_HCI
     427             : #define HCI_DATA_DIR SO_HCI_DIRECTION
     428             : #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
     429             : #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
     430             : #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
     431             : #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
     432             : #else
     433             : #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
     434             : #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
     435             : #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
     436             : #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
     437             : #endif
     438             : #endif
     439             : 
     440             : #ifdef __VMS
     441             : /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
     442             : #define SEGMENT_SIZE (32 * 1024 -1)
     443             : #endif
     444             : 
     445             : /* Convert "sock_addr_t *" to "struct sockaddr *". */
     446             : #define SAS2SA(x)       (&((x)->sa))
     447             : 
     448             : /*
     449             :  * Constants for getnameinfo()
     450             :  */
     451             : #if !defined(NI_MAXHOST)
     452             : #define NI_MAXHOST 1025
     453             : #endif
     454             : #if !defined(NI_MAXSERV)
     455             : #define NI_MAXSERV 32
     456             : #endif
     457             : 
     458             : #ifndef INVALID_SOCKET /* MS defines this */
     459             : #define INVALID_SOCKET (-1)
     460             : #endif
     461             : 
     462             : /* XXX There's a problem here: *static* functions are not supposed to have
     463             :    a Py prefix (or use CapitalizedWords).  Later... */
     464             : 
     465             : /* Global variable holding the exception type for errors detected
     466             :    by this module (but not argument type or memory errors, etc.). */
     467             : static PyObject *socket_herror;
     468             : static PyObject *socket_gaierror;
     469             : static PyObject *socket_timeout;
     470             : 
     471             : /* A forward reference to the socket type object.
     472             :    The sock_type variable contains pointers to various functions,
     473             :    some of which call new_sockobject(), which uses sock_type, so
     474             :    there has to be a circular reference. */
     475             : static PyTypeObject sock_type;
     476             : 
     477             : #if defined(HAVE_POLL_H)
     478             : #include <poll.h>
     479             : #elif defined(HAVE_SYS_POLL_H)
     480             : #include <sys/poll.h>
     481             : #endif
     482             : 
     483             : /* Largest value to try to store in a socklen_t (used when handling
     484             :    ancillary data).  POSIX requires socklen_t to hold at least
     485             :    (2**31)-1 and recommends against storing larger values, but
     486             :    socklen_t was originally int in the BSD interface, so to be on the
     487             :    safe side we use the smaller of (2**31)-1 and INT_MAX. */
     488             : #if INT_MAX > 0x7fffffff
     489             : #define SOCKLEN_T_LIMIT 0x7fffffff
     490             : #else
     491             : #define SOCKLEN_T_LIMIT INT_MAX
     492             : #endif
     493             : 
     494             : #ifdef HAVE_POLL
     495             : /* Instead of select(), we'll use poll() since poll() works on any fd. */
     496             : #define IS_SELECTABLE(s) 1
     497             : /* Can we call select() with this socket without a buffer overrun? */
     498             : #else
     499             : /* If there's no timeout left, we don't have to call select, so it's a safe,
     500             :  * little white lie. */
     501             : #define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0.0)
     502             : #endif
     503             : 
     504             : static PyObject*
     505           0 : select_error(void)
     506             : {
     507           0 :     PyErr_SetString(PyExc_OSError, "unable to select on socket");
     508           0 :     return NULL;
     509             : }
     510             : 
     511             : #ifdef MS_WINDOWS
     512             : #ifndef WSAEAGAIN
     513             : #define WSAEAGAIN WSAEWOULDBLOCK
     514             : #endif
     515             : #define CHECK_ERRNO(expected) \
     516             :     (WSAGetLastError() == WSA ## expected)
     517             : #else
     518             : #define CHECK_ERRNO(expected) \
     519             :     (errno == expected)
     520             : #endif
     521             : 
     522             : /* Convenience function to raise an error according to errno
     523             :    and return a NULL pointer from a function. */
     524             : 
     525             : static PyObject *
     526           0 : set_error(void)
     527             : {
     528             : #ifdef MS_WINDOWS
     529             :     int err_no = WSAGetLastError();
     530             :     /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
     531             :        recognizes the error codes used by both GetLastError() and
     532             :        WSAGetLastError */
     533             :     if (err_no)
     534             :         return PyErr_SetExcFromWindowsErr(PyExc_OSError, err_no);
     535             : #endif
     536             : 
     537             : #if defined(PYOS_OS2) && !defined(PYCC_GCC)
     538             :     if (sock_errno() != NO_ERROR) {
     539             :         APIRET rc;
     540             :         ULONG  msglen;
     541             :         char outbuf[100];
     542             :         int myerrorcode = sock_errno();
     543             : 
     544             :         /* Retrieve socket-related error message from MPTN.MSG file */
     545             :         rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
     546             :                            myerrorcode - SOCBASEERR + 26,
     547             :                            "mptn.msg",
     548             :                            &msglen);
     549             :         if (rc == NO_ERROR) {
     550             :             PyObject *v;
     551             : 
     552             :             /* OS/2 doesn't guarantee a terminator */
     553             :             outbuf[msglen] = '\0';
     554             :             if (strlen(outbuf) > 0) {
     555             :                 /* If non-empty msg, trim CRLF */
     556             :                 char *lastc = &outbuf[ strlen(outbuf)-1 ];
     557             :                 while (lastc > outbuf &&
     558             :                        isspace(Py_CHARMASK(*lastc))) {
     559             :                     /* Trim trailing whitespace (CRLF) */
     560             :                     *lastc-- = '\0';
     561             :                 }
     562             :             }
     563             :             v = Py_BuildValue("(is)", myerrorcode, outbuf);
     564             :             if (v != NULL) {
     565             :                 PyErr_SetObject(PyExc_OSError, v);
     566             :                 Py_DECREF(v);
     567             :             }
     568             :             return NULL;
     569             :         }
     570             :     }
     571             : #endif
     572             : 
     573           0 :     return PyErr_SetFromErrno(PyExc_OSError);
     574             : }
     575             : 
     576             : 
     577             : static PyObject *
     578           0 : set_herror(int h_error)
     579             : {
     580             :     PyObject *v;
     581             : 
     582             : #ifdef HAVE_HSTRERROR
     583           0 :     v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
     584             : #else
     585             :     v = Py_BuildValue("(is)", h_error, "host not found");
     586             : #endif
     587           0 :     if (v != NULL) {
     588           0 :         PyErr_SetObject(socket_herror, v);
     589           0 :         Py_DECREF(v);
     590             :     }
     591             : 
     592           0 :     return NULL;
     593             : }
     594             : 
     595             : 
     596             : static PyObject *
     597           0 : set_gaierror(int error)
     598             : {
     599             :     PyObject *v;
     600             : 
     601             : #ifdef EAI_SYSTEM
     602             :     /* EAI_SYSTEM is not available on Windows XP. */
     603           0 :     if (error == EAI_SYSTEM)
     604           0 :         return set_error();
     605             : #endif
     606             : 
     607             : #ifdef HAVE_GAI_STRERROR
     608           0 :     v = Py_BuildValue("(is)", error, gai_strerror(error));
     609             : #else
     610             :     v = Py_BuildValue("(is)", error, "getaddrinfo failed");
     611             : #endif
     612           0 :     if (v != NULL) {
     613           0 :         PyErr_SetObject(socket_gaierror, v);
     614           0 :         Py_DECREF(v);
     615             :     }
     616             : 
     617           0 :     return NULL;
     618             : }
     619             : 
     620             : #ifdef __VMS
     621             : /* Function to send in segments */
     622             : static int
     623             : sendsegmented(int sock_fd, char *buf, int len, int flags)
     624             : {
     625             :     int n = 0;
     626             :     int remaining = len;
     627             : 
     628             :     while (remaining > 0) {
     629             :         unsigned int segment;
     630             : 
     631             :         segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
     632             :         n = send(sock_fd, buf, segment, flags);
     633             :         if (n < 0) {
     634             :             return n;
     635             :         }
     636             :         remaining -= segment;
     637             :         buf += segment;
     638             :     } /* end while */
     639             : 
     640             :     return len;
     641             : }
     642             : #endif
     643             : 
     644             : /* Function to perform the setting of socket blocking mode
     645             :    internally. block = (1 | 0). */
     646             : static int
     647           0 : internal_setblocking(PySocketSockObject *s, int block)
     648             : {
     649             : #ifndef MS_WINDOWS
     650             :     int delay_flag;
     651             : #endif
     652             : #ifdef SOCK_NONBLOCK
     653           0 :     if (block)
     654           0 :         s->sock_type &= (~SOCK_NONBLOCK);
     655             :     else
     656           0 :         s->sock_type |= SOCK_NONBLOCK;
     657             : #endif
     658             : 
     659           0 :     Py_BEGIN_ALLOW_THREADS
     660             : #ifndef MS_WINDOWS
     661             : #if defined(PYOS_OS2) && !defined(PYCC_GCC)
     662             :     block = !block;
     663             :     ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
     664             : #elif defined(__VMS)
     665             :     block = !block;
     666             :     ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
     667             : #else  /* !PYOS_OS2 && !__VMS */
     668           0 :     delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
     669           0 :     if (block)
     670           0 :         delay_flag &= (~O_NONBLOCK);
     671             :     else
     672           0 :         delay_flag |= O_NONBLOCK;
     673           0 :     fcntl(s->sock_fd, F_SETFL, delay_flag);
     674             : #endif /* !PYOS_OS2 */
     675             : #else /* MS_WINDOWS */
     676             :     block = !block;
     677             :     ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
     678             : #endif /* MS_WINDOWS */
     679           0 :     Py_END_ALLOW_THREADS
     680             : 
     681             :     /* Since these don't return anything */
     682           0 :     return 1;
     683             : }
     684             : 
     685             : /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
     686             :    The argument writing indicates the direction.
     687             :    This does not raise an exception; we'll let our caller do that
     688             :    after they've reacquired the interpreter lock.
     689             :    Returns 1 on timeout, -1 on error, 0 otherwise. */
     690             : static int
     691           0 : internal_select_ex(PySocketSockObject *s, int writing, double interval)
     692             : {
     693             :     int n;
     694             : 
     695             :     /* Nothing to do unless we're in timeout mode (not non-blocking) */
     696           0 :     if (s->sock_timeout <= 0.0)
     697           0 :         return 0;
     698             : 
     699             :     /* Guard against closed socket */
     700           0 :     if (s->sock_fd < 0)
     701           0 :         return 0;
     702             : 
     703             :     /* Handling this condition here simplifies the select loops */
     704           0 :     if (interval < 0.0)
     705           0 :         return 1;
     706             : 
     707             :     /* Prefer poll, if available, since you can poll() any fd
     708             :      * which can't be done with select(). */
     709             : #ifdef HAVE_POLL
     710             :     {
     711             :         struct pollfd pollfd;
     712             :         int timeout;
     713             : 
     714           0 :         pollfd.fd = s->sock_fd;
     715           0 :         pollfd.events = writing ? POLLOUT : POLLIN;
     716             : 
     717             :         /* s->sock_timeout is in seconds, timeout in ms */
     718           0 :         timeout = (int)(interval * 1000 + 0.5);
     719           0 :         n = poll(&pollfd, 1, timeout);
     720             :     }
     721             : #else
     722             :     {
     723             :         /* Construct the arguments to select */
     724             :         fd_set fds;
     725             :         struct timeval tv;
     726             :         tv.tv_sec = (int)interval;
     727             :         tv.tv_usec = (int)((interval - tv.tv_sec) * 1e6);
     728             :         FD_ZERO(&fds);
     729             :         FD_SET(s->sock_fd, &fds);
     730             : 
     731             :         /* See if the socket is ready */
     732             :         if (writing)
     733             :             n = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
     734             :                        NULL, &fds, NULL, &tv);
     735             :         else
     736             :             n = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
     737             :                        &fds, NULL, NULL, &tv);
     738             :     }
     739             : #endif
     740             : 
     741           0 :     if (n < 0)
     742           0 :         return -1;
     743           0 :     if (n == 0)
     744           0 :         return 1;
     745           0 :     return 0;
     746             : }
     747             : 
     748             : static int
     749           0 : internal_select(PySocketSockObject *s, int writing)
     750             : {
     751           0 :     return internal_select_ex(s, writing, s->sock_timeout);
     752             : }
     753             : 
     754             : /*
     755             :    Two macros for automatic retry of select() in case of false positives
     756             :    (for example, select() could indicate a socket is ready for reading
     757             :     but the data then discarded by the OS because of a wrong checksum).
     758             :    Here is an example of use:
     759             : 
     760             :     BEGIN_SELECT_LOOP(s)
     761             :     Py_BEGIN_ALLOW_THREADS
     762             :     timeout = internal_select_ex(s, 0, interval);
     763             :     if (!timeout)
     764             :         outlen = recv(s->sock_fd, cbuf, len, flags);
     765             :     Py_END_ALLOW_THREADS
     766             :     if (timeout == 1) {
     767             :         PyErr_SetString(socket_timeout, "timed out");
     768             :         return -1;
     769             :     }
     770             :     END_SELECT_LOOP(s)
     771             : */
     772             : 
     773             : #define BEGIN_SELECT_LOOP(s) \
     774             :     { \
     775             :         _PyTime_timeval now, deadline = {0, 0}; \
     776             :         double interval = s->sock_timeout; \
     777             :         int has_timeout = s->sock_timeout > 0.0; \
     778             :         if (has_timeout) { \
     779             :             _PyTime_gettimeofday(&now); \
     780             :             deadline = now; \
     781             :             _PyTime_ADD_SECONDS(deadline, s->sock_timeout); \
     782             :         } \
     783             :         while (1) { \
     784             :             errno = 0; \
     785             : 
     786             : #define END_SELECT_LOOP(s) \
     787             :             if (!has_timeout || \
     788             :                 (!CHECK_ERRNO(EWOULDBLOCK) && !CHECK_ERRNO(EAGAIN))) \
     789             :                 break; \
     790             :             _PyTime_gettimeofday(&now); \
     791             :             interval = _PyTime_INTERVAL(now, deadline); \
     792             :         } \
     793             :     } \
     794             : 
     795             : /* Initialize a new socket object. */
     796             : 
     797             : static double defaulttimeout = -1.0; /* Default timeout for new sockets */
     798             : 
     799             : static void
     800           0 : init_sockobject(PySocketSockObject *s,
     801             :                 SOCKET_T fd, int family, int type, int proto)
     802             : {
     803           0 :     s->sock_fd = fd;
     804           0 :     s->sock_family = family;
     805           0 :     s->sock_type = type;
     806           0 :     s->sock_proto = proto;
     807             : 
     808           0 :     s->errorhandler = &set_error;
     809             : #ifdef SOCK_NONBLOCK
     810           0 :     if (type & SOCK_NONBLOCK)
     811           0 :         s->sock_timeout = 0.0;
     812             :     else
     813             : #endif
     814             :     {
     815           0 :         s->sock_timeout = defaulttimeout;
     816           0 :         if (defaulttimeout >= 0.0)
     817           0 :             internal_setblocking(s, 0);
     818             :     }
     819             : 
     820           0 : }
     821             : 
     822             : 
     823             : /* Create a new socket object.
     824             :    This just creates the object and initializes it.
     825             :    If the creation fails, return NULL and set an exception (implicit
     826             :    in NEWOBJ()). */
     827             : 
     828             : static PySocketSockObject *
     829           0 : new_sockobject(SOCKET_T fd, int family, int type, int proto)
     830             : {
     831             :     PySocketSockObject *s;
     832           0 :     s = (PySocketSockObject *)
     833             :         PyType_GenericNew(&sock_type, NULL, NULL);
     834           0 :     if (s != NULL)
     835           0 :         init_sockobject(s, fd, family, type, proto);
     836           0 :     return s;
     837             : }
     838             : 
     839             : 
     840             : /* Lock to allow python interpreter to continue, but only allow one
     841             :    thread to be in gethostbyname or getaddrinfo */
     842             : #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
     843             : static PyThread_type_lock netdb_lock;
     844             : #endif
     845             : 
     846             : 
     847             : /* Convert a string specifying a host name or one of a few symbolic
     848             :    names to a numeric IP address.  This usually calls gethostbyname()
     849             :    to do the work; the names "" and "<broadcast>" are special.
     850             :    Return the length (IPv4 should be 4 bytes), or negative if
     851             :    an error occurred; then an exception is raised. */
     852             : 
     853             : static int
     854           0 : setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
     855             : {
     856             :     struct addrinfo hints, *res;
     857             :     int error;
     858             :     int d1, d2, d3, d4;
     859             :     char ch;
     860             : 
     861           0 :     memset((void *) addr_ret, '\0', sizeof(*addr_ret));
     862           0 :     if (name[0] == '\0') {
     863             :         int siz;
     864           0 :         memset(&hints, 0, sizeof(hints));
     865           0 :         hints.ai_family = af;
     866           0 :         hints.ai_socktype = SOCK_DGRAM;         /*dummy*/
     867           0 :         hints.ai_flags = AI_PASSIVE;
     868           0 :         Py_BEGIN_ALLOW_THREADS
     869             :         ACQUIRE_GETADDRINFO_LOCK
     870           0 :         error = getaddrinfo(NULL, "0", &hints, &res);
     871           0 :         Py_END_ALLOW_THREADS
     872             :         /* We assume that those thread-unsafe getaddrinfo() versions
     873             :            *are* safe regarding their return value, ie. that a
     874             :            subsequent call to getaddrinfo() does not destroy the
     875             :            outcome of the first call. */
     876             :         RELEASE_GETADDRINFO_LOCK
     877           0 :         if (error) {
     878           0 :             set_gaierror(error);
     879           0 :             return -1;
     880             :         }
     881           0 :         switch (res->ai_family) {
     882             :         case AF_INET:
     883           0 :             siz = 4;
     884           0 :             break;
     885             : #ifdef ENABLE_IPV6
     886             :         case AF_INET6:
     887           0 :             siz = 16;
     888           0 :             break;
     889             : #endif
     890             :         default:
     891           0 :             freeaddrinfo(res);
     892           0 :             PyErr_SetString(PyExc_OSError,
     893             :                 "unsupported address family");
     894           0 :             return -1;
     895             :         }
     896           0 :         if (res->ai_next) {
     897           0 :             freeaddrinfo(res);
     898           0 :             PyErr_SetString(PyExc_OSError,
     899             :                 "wildcard resolved to multiple address");
     900           0 :             return -1;
     901             :         }
     902           0 :         if (res->ai_addrlen < addr_ret_size)
     903           0 :             addr_ret_size = res->ai_addrlen;
     904           0 :         memcpy(addr_ret, res->ai_addr, addr_ret_size);
     905           0 :         freeaddrinfo(res);
     906           0 :         return siz;
     907             :     }
     908           0 :     if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
     909             :         struct sockaddr_in *sin;
     910           0 :         if (af != AF_INET && af != AF_UNSPEC) {
     911           0 :             PyErr_SetString(PyExc_OSError,
     912             :                 "address family mismatched");
     913           0 :             return -1;
     914             :         }
     915           0 :         sin = (struct sockaddr_in *)addr_ret;
     916           0 :         memset((void *) sin, '\0', sizeof(*sin));
     917           0 :         sin->sin_family = AF_INET;
     918             : #ifdef HAVE_SOCKADDR_SA_LEN
     919             :         sin->sin_len = sizeof(*sin);
     920             : #endif
     921           0 :         sin->sin_addr.s_addr = INADDR_BROADCAST;
     922           0 :         return sizeof(sin->sin_addr);
     923             :     }
     924           0 :     if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
     925           0 :         0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
     926           0 :         0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
     927             :         struct sockaddr_in *sin;
     928           0 :         sin = (struct sockaddr_in *)addr_ret;
     929           0 :         sin->sin_addr.s_addr = htonl(
     930           0 :             ((long) d1 << 24) | ((long) d2 << 16) |
     931           0 :             ((long) d3 << 8) | ((long) d4 << 0));
     932           0 :         sin->sin_family = AF_INET;
     933             : #ifdef HAVE_SOCKADDR_SA_LEN
     934             :         sin->sin_len = sizeof(*sin);
     935             : #endif
     936           0 :         return 4;
     937             :     }
     938           0 :     memset(&hints, 0, sizeof(hints));
     939           0 :     hints.ai_family = af;
     940           0 :     Py_BEGIN_ALLOW_THREADS
     941             :     ACQUIRE_GETADDRINFO_LOCK
     942           0 :     error = getaddrinfo(name, NULL, &hints, &res);
     943             : #if defined(__digital__) && defined(__unix__)
     944             :     if (error == EAI_NONAME && af == AF_UNSPEC) {
     945             :         /* On Tru64 V5.1, numeric-to-addr conversion fails
     946             :            if no address family is given. Assume IPv4 for now.*/
     947             :         hints.ai_family = AF_INET;
     948             :         error = getaddrinfo(name, NULL, &hints, &res);
     949             :     }
     950             : #endif
     951           0 :     Py_END_ALLOW_THREADS
     952             :     RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
     953           0 :     if (error) {
     954           0 :         set_gaierror(error);
     955           0 :         return -1;
     956             :     }
     957           0 :     if (res->ai_addrlen < addr_ret_size)
     958           0 :         addr_ret_size = res->ai_addrlen;
     959           0 :     memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
     960           0 :     freeaddrinfo(res);
     961           0 :     switch (addr_ret->sa_family) {
     962             :     case AF_INET:
     963           0 :         return 4;
     964             : #ifdef ENABLE_IPV6
     965             :     case AF_INET6:
     966           0 :         return 16;
     967             : #endif
     968             :     default:
     969           0 :         PyErr_SetString(PyExc_OSError, "unknown address family");
     970           0 :         return -1;
     971             :     }
     972             : }
     973             : 
     974             : 
     975             : /* Create a string object representing an IP address.
     976             :    This is always a string of the form 'dd.dd.dd.dd' (with variable
     977             :    size numbers). */
     978             : 
     979             : static PyObject *
     980           0 : makeipaddr(struct sockaddr *addr, int addrlen)
     981             : {
     982             :     char buf[NI_MAXHOST];
     983             :     int error;
     984             : 
     985           0 :     error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
     986             :         NI_NUMERICHOST);
     987           0 :     if (error) {
     988           0 :         set_gaierror(error);
     989           0 :         return NULL;
     990             :     }
     991           0 :     return PyUnicode_FromString(buf);
     992             : }
     993             : 
     994             : 
     995             : #ifdef USE_BLUETOOTH
     996             : /* Convert a string representation of a Bluetooth address into a numeric
     997             :    address.  Returns the length (6), or raises an exception and returns -1 if
     998             :    an error occurred. */
     999             : 
    1000             : static int
    1001           0 : setbdaddr(char *name, bdaddr_t *bdaddr)
    1002             : {
    1003             :     unsigned int b0, b1, b2, b3, b4, b5;
    1004             :     char ch;
    1005             :     int n;
    1006             : 
    1007           0 :     n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
    1008             :                &b5, &b4, &b3, &b2, &b1, &b0, &ch);
    1009           0 :     if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
    1010           0 :         bdaddr->b[0] = b0;
    1011           0 :         bdaddr->b[1] = b1;
    1012           0 :         bdaddr->b[2] = b2;
    1013           0 :         bdaddr->b[3] = b3;
    1014           0 :         bdaddr->b[4] = b4;
    1015           0 :         bdaddr->b[5] = b5;
    1016           0 :         return 6;
    1017             :     } else {
    1018           0 :         PyErr_SetString(PyExc_OSError, "bad bluetooth address");
    1019           0 :         return -1;
    1020             :     }
    1021             : }
    1022             : 
    1023             : /* Create a string representation of the Bluetooth address.  This is always a
    1024             :    string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
    1025             :    value (zero padded if necessary). */
    1026             : 
    1027             : static PyObject *
    1028           0 : makebdaddr(bdaddr_t *bdaddr)
    1029             : {
    1030             :     char buf[(6 * 2) + 5 + 1];
    1031             : 
    1032           0 :     sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
    1033           0 :         bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
    1034           0 :         bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
    1035           0 :     return PyUnicode_FromString(buf);
    1036             : }
    1037             : #endif
    1038             : 
    1039             : 
    1040             : /* Create an object representing the given socket address,
    1041             :    suitable for passing it back to bind(), connect() etc.
    1042             :    The family field of the sockaddr structure is inspected
    1043             :    to determine what kind of address it really is. */
    1044             : 
    1045             : /*ARGSUSED*/
    1046             : static PyObject *
    1047           0 : makesockaddr(SOCKET_T sockfd, struct sockaddr *addr, size_t addrlen, int proto)
    1048             : {
    1049           0 :     if (addrlen == 0) {
    1050             :         /* No address -- may be recvfrom() from known socket */
    1051           0 :         Py_INCREF(Py_None);
    1052           0 :         return Py_None;
    1053             :     }
    1054             : 
    1055           0 :     switch (addr->sa_family) {
    1056             : 
    1057             :     case AF_INET:
    1058             :     {
    1059             :         struct sockaddr_in *a;
    1060           0 :         PyObject *addrobj = makeipaddr(addr, sizeof(*a));
    1061           0 :         PyObject *ret = NULL;
    1062           0 :         if (addrobj) {
    1063           0 :             a = (struct sockaddr_in *)addr;
    1064           0 :             ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
    1065           0 :             Py_DECREF(addrobj);
    1066             :         }
    1067           0 :         return ret;
    1068             :     }
    1069             : 
    1070             : #if defined(AF_UNIX)
    1071             :     case AF_UNIX:
    1072             :     {
    1073           0 :         struct sockaddr_un *a = (struct sockaddr_un *) addr;
    1074             : #ifdef linux
    1075           0 :         if (a->sun_path[0] == 0) {  /* Linux abstract namespace */
    1076           0 :             addrlen -= offsetof(struct sockaddr_un, sun_path);
    1077           0 :             return PyBytes_FromStringAndSize(a->sun_path, addrlen);
    1078             :         }
    1079             :         else
    1080             : #endif /* linux */
    1081             :         {
    1082             :             /* regular NULL-terminated string */
    1083           0 :             return PyUnicode_DecodeFSDefault(a->sun_path);
    1084             :         }
    1085             :     }
    1086             : #endif /* AF_UNIX */
    1087             : 
    1088             : #if defined(AF_NETLINK)
    1089             :        case AF_NETLINK:
    1090             :        {
    1091           0 :            struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
    1092           0 :            return Py_BuildValue("II", a->nl_pid, a->nl_groups);
    1093             :        }
    1094             : #endif /* AF_NETLINK */
    1095             : 
    1096             : #ifdef ENABLE_IPV6
    1097             :     case AF_INET6:
    1098             :     {
    1099             :         struct sockaddr_in6 *a;
    1100           0 :         PyObject *addrobj = makeipaddr(addr, sizeof(*a));
    1101           0 :         PyObject *ret = NULL;
    1102           0 :         if (addrobj) {
    1103           0 :             a = (struct sockaddr_in6 *)addr;
    1104           0 :             ret = Py_BuildValue("OiII",
    1105             :                                 addrobj,
    1106           0 :                                 ntohs(a->sin6_port),
    1107             :                                 ntohl(a->sin6_flowinfo),
    1108             :                                 a->sin6_scope_id);
    1109           0 :             Py_DECREF(addrobj);
    1110             :         }
    1111           0 :         return ret;
    1112             :     }
    1113             : #endif
    1114             : 
    1115             : #ifdef USE_BLUETOOTH
    1116             :     case AF_BLUETOOTH:
    1117           0 :         switch (proto) {
    1118             : 
    1119             :         case BTPROTO_L2CAP:
    1120             :         {
    1121           0 :             struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
    1122           0 :             PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
    1123           0 :             PyObject *ret = NULL;
    1124           0 :             if (addrobj) {
    1125           0 :                 ret = Py_BuildValue("Oi",
    1126             :                                     addrobj,
    1127           0 :                                     _BT_L2_MEMB(a, psm));
    1128           0 :                 Py_DECREF(addrobj);
    1129             :             }
    1130           0 :             return ret;
    1131             :         }
    1132             : 
    1133             :         case BTPROTO_RFCOMM:
    1134             :         {
    1135           0 :             struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
    1136           0 :             PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
    1137           0 :             PyObject *ret = NULL;
    1138           0 :             if (addrobj) {
    1139           0 :                 ret = Py_BuildValue("Oi",
    1140             :                                     addrobj,
    1141           0 :                                     _BT_RC_MEMB(a, channel));
    1142           0 :                 Py_DECREF(addrobj);
    1143             :             }
    1144           0 :             return ret;
    1145             :         }
    1146             : 
    1147             :         case BTPROTO_HCI:
    1148             :         {
    1149           0 :             struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
    1150             : #if defined(__NetBSD__) || defined(__DragonFly__)
    1151             :             return makebdaddr(&_BT_HCI_MEMB(a, bdaddr));
    1152             : #else
    1153           0 :             PyObject *ret = NULL;
    1154           0 :             ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
    1155           0 :             return ret;
    1156             : #endif
    1157             :         }
    1158             : 
    1159             : #if !defined(__FreeBSD__)
    1160             :         case BTPROTO_SCO:
    1161             :         {
    1162           0 :             struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
    1163           0 :             return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
    1164             :         }
    1165             : #endif
    1166             : 
    1167             :         default:
    1168           0 :             PyErr_SetString(PyExc_ValueError,
    1169             :                             "Unknown Bluetooth protocol");
    1170           0 :             return NULL;
    1171             :         }
    1172             : #endif
    1173             : 
    1174             : #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFNAME)
    1175             :     case AF_PACKET:
    1176             :     {
    1177           0 :         struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
    1178           0 :         char *ifname = "";
    1179             :         struct ifreq ifr;
    1180             :         /* need to look up interface name give index */
    1181           0 :         if (a->sll_ifindex) {
    1182           0 :             ifr.ifr_ifindex = a->sll_ifindex;
    1183           0 :             if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
    1184           0 :                 ifname = ifr.ifr_name;
    1185             :         }
    1186           0 :         return Py_BuildValue("shbhy#",
    1187             :                              ifname,
    1188           0 :                              ntohs(a->sll_protocol),
    1189           0 :                              a->sll_pkttype,
    1190           0 :                              a->sll_hatype,
    1191           0 :                              a->sll_addr,
    1192           0 :                              a->sll_halen);
    1193             :     }
    1194             : #endif
    1195             : 
    1196             : #ifdef HAVE_LINUX_TIPC_H
    1197             :     case AF_TIPC:
    1198             :     {
    1199           0 :         struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
    1200           0 :         if (a->addrtype == TIPC_ADDR_NAMESEQ) {
    1201           0 :             return Py_BuildValue("IIIII",
    1202           0 :                             a->addrtype,
    1203             :                             a->addr.nameseq.type,
    1204             :                             a->addr.nameseq.lower,
    1205             :                             a->addr.nameseq.upper,
    1206           0 :                             a->scope);
    1207           0 :         } else if (a->addrtype == TIPC_ADDR_NAME) {
    1208           0 :             return Py_BuildValue("IIIII",
    1209           0 :                             a->addrtype,
    1210             :                             a->addr.name.name.type,
    1211             :                             a->addr.name.name.instance,
    1212             :                             a->addr.name.name.instance,
    1213           0 :                             a->scope);
    1214           0 :         } else if (a->addrtype == TIPC_ADDR_ID) {
    1215           0 :             return Py_BuildValue("IIIII",
    1216           0 :                             a->addrtype,
    1217             :                             a->addr.id.node,
    1218             :                             a->addr.id.ref,
    1219             :                             0,
    1220           0 :                             a->scope);
    1221             :         } else {
    1222           0 :             PyErr_SetString(PyExc_ValueError,
    1223             :                             "Invalid address type");
    1224           0 :             return NULL;
    1225             :         }
    1226             :     }
    1227             : #endif
    1228             : 
    1229             : #ifdef AF_CAN
    1230             :     case AF_CAN:
    1231             :     {
    1232           0 :         struct sockaddr_can *a = (struct sockaddr_can *)addr;
    1233           0 :         char *ifname = "";
    1234             :         struct ifreq ifr;
    1235             :         /* need to look up interface name given index */
    1236           0 :         if (a->can_ifindex) {
    1237           0 :             ifr.ifr_ifindex = a->can_ifindex;
    1238           0 :             if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
    1239           0 :                 ifname = ifr.ifr_name;
    1240             :         }
    1241             : 
    1242           0 :         return Py_BuildValue("O&h", PyUnicode_DecodeFSDefault,
    1243             :                                     ifname,
    1244           0 :                                     a->can_family);
    1245             :     }
    1246             : #endif
    1247             : 
    1248             : #ifdef PF_SYSTEM
    1249             :     case PF_SYSTEM:
    1250             :         switch(proto) {
    1251             : #ifdef SYSPROTO_CONTROL
    1252             :         case SYSPROTO_CONTROL:
    1253             :         {
    1254             :             struct sockaddr_ctl *a = (struct sockaddr_ctl *)addr;
    1255             :             return Py_BuildValue("(II)", a->sc_id, a->sc_unit);
    1256             :         }
    1257             : #endif
    1258             :         default:
    1259             :             PyErr_SetString(PyExc_ValueError,
    1260             :                             "Invalid address type");
    1261             :             return 0;
    1262             :         }
    1263             : #endif
    1264             : 
    1265             :     /* More cases here... */
    1266             : 
    1267             :     default:
    1268             :         /* If we don't know the address family, don't raise an
    1269             :            exception -- return it as an (int, bytes) tuple. */
    1270           0 :         return Py_BuildValue("iy#",
    1271           0 :                              addr->sa_family,
    1272           0 :                              addr->sa_data,
    1273             :                              sizeof(addr->sa_data));
    1274             : 
    1275             :     }
    1276             : }
    1277             : 
    1278             : 
    1279             : /* Parse a socket address argument according to the socket object's
    1280             :    address family.  Return 1 if the address was in the proper format,
    1281             :    0 of not.  The address is returned through addr_ret, its length
    1282             :    through len_ret. */
    1283             : 
    1284             : static int
    1285           0 : getsockaddrarg(PySocketSockObject *s, PyObject *args,
    1286             :                struct sockaddr *addr_ret, int *len_ret)
    1287             : {
    1288           0 :     switch (s->sock_family) {
    1289             : 
    1290             : #if defined(AF_UNIX)
    1291             :     case AF_UNIX:
    1292             :     {
    1293             :         struct sockaddr_un* addr;
    1294             :         char *path;
    1295             :         int len;
    1296           0 :         int retval = 0;
    1297             : 
    1298             :         /* PEP 383.  Not using PyUnicode_FSConverter since we need to
    1299             :            allow embedded nulls on Linux. */
    1300           0 :         if (PyUnicode_Check(args)) {
    1301           0 :             if ((args = PyUnicode_EncodeFSDefault(args)) == NULL)
    1302           0 :                 return 0;
    1303             :         }
    1304             :         else
    1305           0 :             Py_INCREF(args);
    1306           0 :         if (!PyArg_Parse(args, "y#", &path, &len))
    1307           0 :             goto unix_out;
    1308             : 
    1309           0 :         addr = (struct sockaddr_un*)addr_ret;
    1310             : #ifdef linux
    1311           0 :         if (len > 0 && path[0] == 0) {
    1312             :             /* Linux abstract namespace extension */
    1313           0 :             if (len > sizeof addr->sun_path) {
    1314           0 :                 PyErr_SetString(PyExc_OSError,
    1315             :                                 "AF_UNIX path too long");
    1316           0 :                 goto unix_out;
    1317             :             }
    1318             :         }
    1319             :         else
    1320             : #endif /* linux */
    1321             :         {
    1322             :             /* regular NULL-terminated string */
    1323           0 :             if (len >= sizeof addr->sun_path) {
    1324           0 :                 PyErr_SetString(PyExc_OSError,
    1325             :                                 "AF_UNIX path too long");
    1326           0 :                 goto unix_out;
    1327             :             }
    1328           0 :             addr->sun_path[len] = 0;
    1329             :         }
    1330           0 :         addr->sun_family = s->sock_family;
    1331           0 :         memcpy(addr->sun_path, path, len);
    1332             : #if defined(PYOS_OS2)
    1333             :         *len_ret = sizeof(*addr);
    1334             : #else
    1335           0 :         *len_ret = len + offsetof(struct sockaddr_un, sun_path);
    1336             : #endif
    1337           0 :         retval = 1;
    1338             :     unix_out:
    1339           0 :         Py_DECREF(args);
    1340           0 :         return retval;
    1341             :     }
    1342             : #endif /* AF_UNIX */
    1343             : 
    1344             : #if defined(AF_NETLINK)
    1345             :     case AF_NETLINK:
    1346             :     {
    1347             :         struct sockaddr_nl* addr;
    1348             :         int pid, groups;
    1349           0 :         addr = (struct sockaddr_nl *)addr_ret;
    1350           0 :         if (!PyTuple_Check(args)) {
    1351           0 :             PyErr_Format(
    1352             :                 PyExc_TypeError,
    1353             :                 "getsockaddrarg: "
    1354             :                 "AF_NETLINK address must be tuple, not %.500s",
    1355           0 :                 Py_TYPE(args)->tp_name);
    1356           0 :             return 0;
    1357             :         }
    1358           0 :         if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
    1359           0 :             return 0;
    1360           0 :         addr->nl_family = AF_NETLINK;
    1361           0 :         addr->nl_pid = pid;
    1362           0 :         addr->nl_groups = groups;
    1363           0 :         *len_ret = sizeof(*addr);
    1364           0 :         return 1;
    1365             :     }
    1366             : #endif
    1367             : 
    1368             : #ifdef AF_RDS
    1369             :     case AF_RDS:
    1370             :         /* RDS sockets use sockaddr_in: fall-through */
    1371             : #endif
    1372             : 
    1373             :     case AF_INET:
    1374             :     {
    1375             :         struct sockaddr_in* addr;
    1376             :         char *host;
    1377             :         int port, result;
    1378           0 :         if (!PyTuple_Check(args)) {
    1379           0 :             PyErr_Format(
    1380             :                 PyExc_TypeError,
    1381             :                 "getsockaddrarg: "
    1382             :                 "AF_INET address must be tuple, not %.500s",
    1383           0 :                 Py_TYPE(args)->tp_name);
    1384           0 :             return 0;
    1385             :         }
    1386           0 :         if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
    1387             :                               "idna", &host, &port))
    1388           0 :             return 0;
    1389           0 :         addr=(struct sockaddr_in*)addr_ret;
    1390           0 :         result = setipaddr(host, (struct sockaddr *)addr,
    1391             :                            sizeof(*addr),  AF_INET);
    1392           0 :         PyMem_Free(host);
    1393           0 :         if (result < 0)
    1394           0 :             return 0;
    1395           0 :         if (port < 0 || port > 0xffff) {
    1396           0 :             PyErr_SetString(
    1397             :                 PyExc_OverflowError,
    1398             :                 "getsockaddrarg: port must be 0-65535.");
    1399           0 :             return 0;
    1400             :         }
    1401           0 :         addr->sin_family = AF_INET;
    1402           0 :         addr->sin_port = htons((short)port);
    1403           0 :         *len_ret = sizeof *addr;
    1404           0 :         return 1;
    1405             :     }
    1406             : 
    1407             : #ifdef ENABLE_IPV6
    1408             :     case AF_INET6:
    1409             :     {
    1410             :         struct sockaddr_in6* addr;
    1411             :         char *host;
    1412             :         int port, result;
    1413             :         unsigned int flowinfo, scope_id;
    1414           0 :         flowinfo = scope_id = 0;
    1415           0 :         if (!PyTuple_Check(args)) {
    1416           0 :             PyErr_Format(
    1417             :                 PyExc_TypeError,
    1418             :                 "getsockaddrarg: "
    1419             :                 "AF_INET6 address must be tuple, not %.500s",
    1420           0 :                 Py_TYPE(args)->tp_name);
    1421           0 :             return 0;
    1422             :         }
    1423           0 :         if (!PyArg_ParseTuple(args, "eti|II",
    1424             :                               "idna", &host, &port, &flowinfo,
    1425             :                               &scope_id)) {
    1426           0 :             return 0;
    1427             :         }
    1428           0 :         addr = (struct sockaddr_in6*)addr_ret;
    1429           0 :         result = setipaddr(host, (struct sockaddr *)addr,
    1430             :                            sizeof(*addr), AF_INET6);
    1431           0 :         PyMem_Free(host);
    1432           0 :         if (result < 0)
    1433           0 :             return 0;
    1434           0 :         if (port < 0 || port > 0xffff) {
    1435           0 :             PyErr_SetString(
    1436             :                 PyExc_OverflowError,
    1437             :                 "getsockaddrarg: port must be 0-65535.");
    1438           0 :             return 0;
    1439             :         }
    1440           0 :         if (flowinfo > 0xfffff) {
    1441           0 :             PyErr_SetString(
    1442             :                 PyExc_OverflowError,
    1443             :                 "getsockaddrarg: flowinfo must be 0-1048575.");
    1444           0 :             return 0;
    1445             :         }
    1446           0 :         addr->sin6_family = s->sock_family;
    1447           0 :         addr->sin6_port = htons((short)port);
    1448           0 :         addr->sin6_flowinfo = htonl(flowinfo);
    1449           0 :         addr->sin6_scope_id = scope_id;
    1450           0 :         *len_ret = sizeof *addr;
    1451           0 :         return 1;
    1452             :     }
    1453             : #endif
    1454             : 
    1455             : #ifdef USE_BLUETOOTH
    1456             :     case AF_BLUETOOTH:
    1457             :     {
    1458           0 :         switch (s->sock_proto) {
    1459             :         case BTPROTO_L2CAP:
    1460             :         {
    1461             :             struct sockaddr_l2 *addr;
    1462             :             char *straddr;
    1463             : 
    1464           0 :             addr = (struct sockaddr_l2 *)addr_ret;
    1465           0 :             memset(addr, 0, sizeof(struct sockaddr_l2));
    1466           0 :             _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
    1467           0 :             if (!PyArg_ParseTuple(args, "si", &straddr,
    1468             :                                   &_BT_L2_MEMB(addr, psm))) {
    1469           0 :                 PyErr_SetString(PyExc_OSError, "getsockaddrarg: "
    1470             :                                 "wrong format");
    1471           0 :                 return 0;
    1472             :             }
    1473           0 :             if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
    1474           0 :                 return 0;
    1475             : 
    1476           0 :             *len_ret = sizeof *addr;
    1477           0 :             return 1;
    1478             :         }
    1479             :         case BTPROTO_RFCOMM:
    1480             :         {
    1481             :             struct sockaddr_rc *addr;
    1482             :             char *straddr;
    1483             : 
    1484           0 :             addr = (struct sockaddr_rc *)addr_ret;
    1485           0 :             _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
    1486           0 :             if (!PyArg_ParseTuple(args, "si", &straddr,
    1487             :                                   &_BT_RC_MEMB(addr, channel))) {
    1488           0 :                 PyErr_SetString(PyExc_OSError, "getsockaddrarg: "
    1489             :                                 "wrong format");
    1490           0 :                 return 0;
    1491             :             }
    1492           0 :             if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
    1493           0 :                 return 0;
    1494             : 
    1495           0 :             *len_ret = sizeof *addr;
    1496           0 :             return 1;
    1497             :         }
    1498             :         case BTPROTO_HCI:
    1499             :         {
    1500           0 :             struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
    1501             : #if defined(__NetBSD__) || defined(__DragonFly__)
    1502             :                         char *straddr = PyBytes_AS_STRING(args);
    1503             : 
    1504             :                         _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
    1505             :             if (straddr == NULL) {
    1506             :                 PyErr_SetString(PyExc_OSError, "getsockaddrarg: "
    1507             :                     "wrong format");
    1508             :                 return 0;
    1509             :             }
    1510             :             if (setbdaddr(straddr, &_BT_HCI_MEMB(addr, bdaddr)) < 0)
    1511             :                 return 0;
    1512             : #else
    1513           0 :             _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
    1514           0 :             if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
    1515           0 :                 PyErr_SetString(PyExc_OSError, "getsockaddrarg: "
    1516             :                                 "wrong format");
    1517           0 :                 return 0;
    1518             :             }
    1519             : #endif
    1520           0 :             *len_ret = sizeof *addr;
    1521           0 :             return 1;
    1522             :         }
    1523             : #if !defined(__FreeBSD__)
    1524             :         case BTPROTO_SCO:
    1525             :         {
    1526             :             struct sockaddr_sco *addr;
    1527             :             char *straddr;
    1528             : 
    1529           0 :             addr = (struct sockaddr_sco *)addr_ret;
    1530           0 :             _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
    1531           0 :             if (!PyBytes_Check(args)) {
    1532           0 :                 PyErr_SetString(PyExc_OSError, "getsockaddrarg: "
    1533             :                                 "wrong format");
    1534           0 :                 return 0;
    1535             :             }
    1536           0 :             straddr = PyBytes_AS_STRING(args);
    1537           0 :             if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
    1538           0 :                 return 0;
    1539             : 
    1540           0 :             *len_ret = sizeof *addr;
    1541           0 :             return 1;
    1542             :         }
    1543             : #endif
    1544             :         default:
    1545           0 :             PyErr_SetString(PyExc_OSError, "getsockaddrarg: unknown Bluetooth protocol");
    1546           0 :             return 0;
    1547             :         }
    1548             :     }
    1549             : #endif
    1550             : 
    1551             : #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFINDEX)
    1552             :     case AF_PACKET:
    1553             :     {
    1554             :         struct sockaddr_ll* addr;
    1555             :         struct ifreq ifr;
    1556             :         char *interfaceName;
    1557             :         int protoNumber;
    1558           0 :         int hatype = 0;
    1559           0 :         int pkttype = 0;
    1560           0 :         char *haddr = NULL;
    1561           0 :         unsigned int halen = 0;
    1562             : 
    1563           0 :         if (!PyTuple_Check(args)) {
    1564           0 :             PyErr_Format(
    1565             :                 PyExc_TypeError,
    1566             :                 "getsockaddrarg: "
    1567             :                 "AF_PACKET address must be tuple, not %.500s",
    1568           0 :                 Py_TYPE(args)->tp_name);
    1569           0 :             return 0;
    1570             :         }
    1571           0 :         if (!PyArg_ParseTuple(args, "si|iiy#", &interfaceName,
    1572             :                               &protoNumber, &pkttype, &hatype,
    1573             :                               &haddr, &halen))
    1574           0 :             return 0;
    1575           0 :         strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
    1576           0 :         ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
    1577           0 :         if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
    1578           0 :             s->errorhandler();
    1579           0 :             return 0;
    1580             :         }
    1581           0 :         if (halen > 8) {
    1582           0 :           PyErr_SetString(PyExc_ValueError,
    1583             :                           "Hardware address must be 8 bytes or less");
    1584           0 :           return 0;
    1585             :         }
    1586           0 :         if (protoNumber < 0 || protoNumber > 0xffff) {
    1587           0 :             PyErr_SetString(
    1588             :                 PyExc_OverflowError,
    1589             :                 "getsockaddrarg: protoNumber must be 0-65535.");
    1590           0 :             return 0;
    1591             :         }
    1592           0 :         addr = (struct sockaddr_ll*)addr_ret;
    1593           0 :         addr->sll_family = AF_PACKET;
    1594           0 :         addr->sll_protocol = htons((short)protoNumber);
    1595           0 :         addr->sll_ifindex = ifr.ifr_ifindex;
    1596           0 :         addr->sll_pkttype = pkttype;
    1597           0 :         addr->sll_hatype = hatype;
    1598           0 :         if (halen != 0) {
    1599           0 :           memcpy(&addr->sll_addr, haddr, halen);
    1600             :         }
    1601           0 :         addr->sll_halen = halen;
    1602           0 :         *len_ret = sizeof *addr;
    1603           0 :         return 1;
    1604             :     }
    1605             : #endif
    1606             : 
    1607             : #ifdef HAVE_LINUX_TIPC_H
    1608             :     case AF_TIPC:
    1609             :     {
    1610             :         unsigned int atype, v1, v2, v3;
    1611           0 :         unsigned int scope = TIPC_CLUSTER_SCOPE;
    1612             :         struct sockaddr_tipc *addr;
    1613             : 
    1614           0 :         if (!PyTuple_Check(args)) {
    1615           0 :             PyErr_Format(
    1616             :                 PyExc_TypeError,
    1617             :                 "getsockaddrarg: "
    1618             :                 "AF_TIPC address must be tuple, not %.500s",
    1619           0 :                 Py_TYPE(args)->tp_name);
    1620           0 :             return 0;
    1621             :         }
    1622             : 
    1623           0 :         if (!PyArg_ParseTuple(args,
    1624             :                                 "IIII|I;Invalid TIPC address format",
    1625             :                                 &atype, &v1, &v2, &v3, &scope))
    1626           0 :             return 0;
    1627             : 
    1628           0 :         addr = (struct sockaddr_tipc *) addr_ret;
    1629           0 :         memset(addr, 0, sizeof(struct sockaddr_tipc));
    1630             : 
    1631           0 :         addr->family = AF_TIPC;
    1632           0 :         addr->scope = scope;
    1633           0 :         addr->addrtype = atype;
    1634             : 
    1635           0 :         if (atype == TIPC_ADDR_NAMESEQ) {
    1636           0 :             addr->addr.nameseq.type = v1;
    1637           0 :             addr->addr.nameseq.lower = v2;
    1638           0 :             addr->addr.nameseq.upper = v3;
    1639           0 :         } else if (atype == TIPC_ADDR_NAME) {
    1640           0 :             addr->addr.name.name.type = v1;
    1641           0 :             addr->addr.name.name.instance = v2;
    1642           0 :         } else if (atype == TIPC_ADDR_ID) {
    1643           0 :             addr->addr.id.node = v1;
    1644           0 :             addr->addr.id.ref = v2;
    1645             :         } else {
    1646             :             /* Shouldn't happen */
    1647           0 :             PyErr_SetString(PyExc_TypeError, "Invalid address type");
    1648           0 :             return 0;
    1649             :         }
    1650             : 
    1651           0 :         *len_ret = sizeof(*addr);
    1652             : 
    1653           0 :         return 1;
    1654             :     }
    1655             : #endif
    1656             : 
    1657             : #ifdef AF_CAN
    1658             :     case AF_CAN:
    1659           0 :         switch (s->sock_proto) {
    1660             :         case CAN_RAW:
    1661             :         {
    1662             :             struct sockaddr_can *addr;
    1663             :             PyObject *interfaceName;
    1664             :             struct ifreq ifr;
    1665           0 :             addr = (struct sockaddr_can *)addr_ret;
    1666             :             Py_ssize_t len;
    1667             : 
    1668           0 :             if (!PyArg_ParseTuple(args, "O&", PyUnicode_FSConverter,
    1669             :                                               &interfaceName))
    1670           0 :                 return 0;
    1671             : 
    1672           0 :             len = PyBytes_GET_SIZE(interfaceName);
    1673             : 
    1674           0 :             if (len == 0) {
    1675           0 :                 ifr.ifr_ifindex = 0;
    1676           0 :             } else if (len < sizeof(ifr.ifr_name)) {
    1677           0 :                 strcpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName));
    1678           0 :                 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
    1679           0 :                     s->errorhandler();
    1680           0 :                     Py_DECREF(interfaceName);
    1681           0 :                     return 0;
    1682             :                 }
    1683             :             } else {
    1684           0 :                 PyErr_SetString(PyExc_OSError,
    1685             :                                 "AF_CAN interface name too long");
    1686           0 :                 Py_DECREF(interfaceName);
    1687           0 :                 return 0;
    1688             :             }
    1689             : 
    1690           0 :             addr->can_family = AF_CAN;
    1691           0 :             addr->can_ifindex = ifr.ifr_ifindex;
    1692             : 
    1693           0 :             *len_ret = sizeof(*addr);
    1694           0 :             Py_DECREF(interfaceName);
    1695           0 :             return 1;
    1696             :         }
    1697             :         default:
    1698           0 :             PyErr_SetString(PyExc_OSError,
    1699             :                             "getsockaddrarg: unsupported CAN protocol");
    1700           0 :             return 0;
    1701             :         }
    1702             : #endif
    1703             :             
    1704             : #ifdef PF_SYSTEM
    1705             :     case PF_SYSTEM:
    1706             :         switch (s->sock_proto) {
    1707             : #ifdef SYSPROTO_CONTROL
    1708             :         case SYSPROTO_CONTROL:
    1709             :         {
    1710             :             struct sockaddr_ctl *addr;
    1711             :             
    1712             :             addr = (struct sockaddr_ctl *)addr_ret;
    1713             :             addr->sc_family = AF_SYSTEM;
    1714             :             addr->ss_sysaddr = AF_SYS_CONTROL; 
    1715             : 
    1716             :             if (PyUnicode_Check(args)) {
    1717             :                 struct ctl_info info;
    1718             :                 PyObject *ctl_name;
    1719             : 
    1720             :                 if (!PyArg_Parse(args, "O&",
    1721             :                                 PyUnicode_FSConverter, &ctl_name)) {
    1722             :                     return 0;
    1723             :                 }
    1724             : 
    1725             :                 if (PyBytes_GET_SIZE(ctl_name) > sizeof(info.ctl_name)) {
    1726             :                     PyErr_SetString(PyExc_ValueError,
    1727             :                                     "provided string is too long");
    1728             :                     Py_DECREF(ctl_name);
    1729             :                     return 0;
    1730             :                 }
    1731             :                 strncpy(info.ctl_name, PyBytes_AS_STRING(ctl_name),
    1732             :                         sizeof(info.ctl_name));
    1733             :                 Py_DECREF(ctl_name);
    1734             : 
    1735             :                 if (ioctl(s->sock_fd, CTLIOCGINFO, &info)) {
    1736             :                     PyErr_SetString(PyExc_OSError,
    1737             :                           "cannot find kernel control with provided name");
    1738             :                     return 0;
    1739             :                 }
    1740             :                 
    1741             :                 addr->sc_id = info.ctl_id;
    1742             :                 addr->sc_unit = 0;
    1743             :             } else if (!PyArg_ParseTuple(args, "II",
    1744             :                                          &(addr->sc_id), &(addr->sc_unit))) {
    1745             :                 PyErr_SetString(PyExc_TypeError, "getsockaddrarg: "
    1746             :                                 "expected str or tuple of two ints");
    1747             :                 
    1748             :                 return 0;
    1749             :             }
    1750             :               
    1751             :             *len_ret = sizeof(*addr);
    1752             :             return 1;
    1753             :         }
    1754             : #endif
    1755             :         default:
    1756             :             PyErr_SetString(PyExc_OSError,
    1757             :                             "getsockaddrarg: unsupported PF_SYSTEM protocol");
    1758             :             return 0;
    1759             :         }
    1760             : #endif
    1761             : 
    1762             :     /* More cases here... */
    1763             : 
    1764             :     default:
    1765           0 :         PyErr_SetString(PyExc_OSError, "getsockaddrarg: bad family");
    1766           0 :         return 0;
    1767             : 
    1768             :     }
    1769             : }
    1770             : 
    1771             : 
    1772             : /* Get the address length according to the socket object's address family.
    1773             :    Return 1 if the family is known, 0 otherwise.  The length is returned
    1774             :    through len_ret. */
    1775             : 
    1776             : static int
    1777           0 : getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
    1778             : {
    1779           0 :     switch (s->sock_family) {
    1780             : 
    1781             : #if defined(AF_UNIX)
    1782             :     case AF_UNIX:
    1783             :     {
    1784           0 :         *len_ret = sizeof (struct sockaddr_un);
    1785           0 :         return 1;
    1786             :     }
    1787             : #endif /* AF_UNIX */
    1788             : #if defined(AF_NETLINK)
    1789             :        case AF_NETLINK:
    1790             :        {
    1791           0 :            *len_ret = sizeof (struct sockaddr_nl);
    1792           0 :            return 1;
    1793             :        }
    1794             : #endif
    1795             : 
    1796             : #ifdef AF_RDS
    1797             :     case AF_RDS:
    1798             :         /* RDS sockets use sockaddr_in: fall-through */
    1799             : #endif
    1800             : 
    1801             :     case AF_INET:
    1802             :     {
    1803           0 :         *len_ret = sizeof (struct sockaddr_in);
    1804           0 :         return 1;
    1805             :     }
    1806             : 
    1807             : #ifdef ENABLE_IPV6
    1808             :     case AF_INET6:
    1809             :     {
    1810           0 :         *len_ret = sizeof (struct sockaddr_in6);
    1811           0 :         return 1;
    1812             :     }
    1813             : #endif
    1814             : 
    1815             : #ifdef USE_BLUETOOTH
    1816             :     case AF_BLUETOOTH:
    1817             :     {
    1818           0 :         switch(s->sock_proto)
    1819             :         {
    1820             : 
    1821             :         case BTPROTO_L2CAP:
    1822           0 :             *len_ret = sizeof (struct sockaddr_l2);
    1823           0 :             return 1;
    1824             :         case BTPROTO_RFCOMM:
    1825           0 :             *len_ret = sizeof (struct sockaddr_rc);
    1826           0 :             return 1;
    1827             :         case BTPROTO_HCI:
    1828           0 :             *len_ret = sizeof (struct sockaddr_hci);
    1829           0 :             return 1;
    1830             : #if !defined(__FreeBSD__)
    1831             :         case BTPROTO_SCO:
    1832           0 :             *len_ret = sizeof (struct sockaddr_sco);
    1833           0 :             return 1;
    1834             : #endif
    1835             :         default:
    1836           0 :             PyErr_SetString(PyExc_OSError, "getsockaddrlen: "
    1837             :                             "unknown BT protocol");
    1838           0 :             return 0;
    1839             : 
    1840             :         }
    1841             :     }
    1842             : #endif
    1843             : 
    1844             : #ifdef HAVE_NETPACKET_PACKET_H
    1845             :     case AF_PACKET:
    1846             :     {
    1847           0 :         *len_ret = sizeof (struct sockaddr_ll);
    1848           0 :         return 1;
    1849             :     }
    1850             : #endif
    1851             : 
    1852             : #ifdef HAVE_LINUX_TIPC_H
    1853             :     case AF_TIPC:
    1854             :     {
    1855           0 :         *len_ret = sizeof (struct sockaddr_tipc);
    1856           0 :         return 1;
    1857             :     }
    1858             : #endif
    1859             : 
    1860             : #ifdef AF_CAN
    1861             :     case AF_CAN:
    1862             :     {
    1863           0 :         *len_ret = sizeof (struct sockaddr_can);
    1864           0 :         return 1;
    1865             :     }
    1866             : #endif
    1867             :             
    1868             : #ifdef PF_SYSTEM
    1869             :     case PF_SYSTEM:
    1870             :         switch(s->sock_proto) {
    1871             : #ifdef SYSPROTO_CONTROL
    1872             :         case SYSPROTO_CONTROL:
    1873             :             *len_ret = sizeof (struct sockaddr_ctl);
    1874             :             return 1;
    1875             : #endif
    1876             :         default:
    1877             :             PyErr_SetString(PyExc_OSError, "getsockaddrlen: "
    1878             :                             "unknown PF_SYSTEM protocol");
    1879             :             return 0;
    1880             :         }
    1881             : #endif
    1882             : 
    1883             :     /* More cases here... */
    1884             : 
    1885             :     default:
    1886           0 :         PyErr_SetString(PyExc_OSError, "getsockaddrlen: bad family");
    1887           0 :         return 0;
    1888             : 
    1889             :     }
    1890             : }
    1891             : 
    1892             : 
    1893             : /* Support functions for the sendmsg() and recvmsg[_into]() methods.
    1894             :    Currently, these methods are only compiled if the RFC 2292/3542
    1895             :    CMSG_LEN() macro is available.  Older systems seem to have used
    1896             :    sizeof(struct cmsghdr) + (length) where CMSG_LEN() is used now, so
    1897             :    it may be possible to define CMSG_LEN() that way if it's not
    1898             :    provided.  Some architectures might need extra padding after the
    1899             :    cmsghdr, however, and CMSG_LEN() would have to take account of
    1900             :    this. */
    1901             : #ifdef CMSG_LEN
    1902             : /* If length is in range, set *result to CMSG_LEN(length) and return
    1903             :    true; otherwise, return false. */
    1904             : static int
    1905           0 : get_CMSG_LEN(size_t length, size_t *result)
    1906             : {
    1907             :     size_t tmp;
    1908             : 
    1909           0 :     if (length > (SOCKLEN_T_LIMIT - CMSG_LEN(0)))
    1910           0 :         return 0;
    1911           0 :     tmp = CMSG_LEN(length);
    1912           0 :     if (tmp > SOCKLEN_T_LIMIT || tmp < length)
    1913           0 :         return 0;
    1914           0 :     *result = tmp;
    1915           0 :     return 1;
    1916             : }
    1917             : 
    1918             : #ifdef CMSG_SPACE
    1919             : /* If length is in range, set *result to CMSG_SPACE(length) and return
    1920             :    true; otherwise, return false. */
    1921             : static int
    1922           0 : get_CMSG_SPACE(size_t length, size_t *result)
    1923             : {
    1924             :     size_t tmp;
    1925             : 
    1926             :     /* Use CMSG_SPACE(1) here in order to take account of the padding
    1927             :        necessary before *and* after the data. */
    1928           0 :     if (length > (SOCKLEN_T_LIMIT - CMSG_SPACE(1)))
    1929           0 :         return 0;
    1930           0 :     tmp = CMSG_SPACE(length);
    1931           0 :     if (tmp > SOCKLEN_T_LIMIT || tmp < length)
    1932           0 :         return 0;
    1933           0 :     *result = tmp;
    1934           0 :     return 1;
    1935             : }
    1936             : #endif
    1937             : 
    1938             : /* Return true iff msg->msg_controllen is valid, cmsgh is a valid
    1939             :    pointer in msg->msg_control with at least "space" bytes after it,
    1940             :    and its cmsg_len member inside the buffer. */
    1941             : static int
    1942           0 : cmsg_min_space(struct msghdr *msg, struct cmsghdr *cmsgh, size_t space)
    1943             : {
    1944             :     size_t cmsg_offset;
    1945             :     static const size_t cmsg_len_end = (offsetof(struct cmsghdr, cmsg_len) +
    1946             :                                         sizeof(cmsgh->cmsg_len));
    1947             : 
    1948             :     /* Note that POSIX allows msg_controllen to be of signed type. */
    1949           0 :     if (cmsgh == NULL || msg->msg_control == NULL || msg->msg_controllen < 0)
    1950           0 :         return 0;
    1951           0 :     if (space < cmsg_len_end)
    1952           0 :         space = cmsg_len_end;
    1953           0 :     cmsg_offset = (char *)cmsgh - (char *)msg->msg_control;
    1954           0 :     return (cmsg_offset <= (size_t)-1 - space &&
    1955           0 :             cmsg_offset + space <= msg->msg_controllen);
    1956             : }
    1957             : 
    1958             : /* If pointer CMSG_DATA(cmsgh) is in buffer msg->msg_control, set
    1959             :    *space to number of bytes following it in the buffer and return
    1960             :    true; otherwise, return false.  Assumes cmsgh, msg->msg_control and
    1961             :    msg->msg_controllen are valid. */
    1962             : static int
    1963           0 : get_cmsg_data_space(struct msghdr *msg, struct cmsghdr *cmsgh, size_t *space)
    1964             : {
    1965             :     size_t data_offset;
    1966             :     char *data_ptr;
    1967             : 
    1968           0 :     if ((data_ptr = (char *)CMSG_DATA(cmsgh)) == NULL)
    1969           0 :         return 0;
    1970           0 :     data_offset = data_ptr - (char *)msg->msg_control;
    1971           0 :     if (data_offset > msg->msg_controllen)
    1972           0 :         return 0;
    1973           0 :     *space = msg->msg_controllen - data_offset;
    1974           0 :     return 1;
    1975             : }
    1976             : 
    1977             : /* If cmsgh is invalid or not contained in the buffer pointed to by
    1978             :    msg->msg_control, return -1.  If cmsgh is valid and its associated
    1979             :    data is entirely contained in the buffer, set *data_len to the
    1980             :    length of the associated data and return 0.  If only part of the
    1981             :    associated data is contained in the buffer but cmsgh is otherwise
    1982             :    valid, set *data_len to the length contained in the buffer and
    1983             :    return 1. */
    1984             : static int
    1985           0 : get_cmsg_data_len(struct msghdr *msg, struct cmsghdr *cmsgh, size_t *data_len)
    1986             : {
    1987             :     size_t space, cmsg_data_len;
    1988             : 
    1989           0 :     if (!cmsg_min_space(msg, cmsgh, CMSG_LEN(0)) ||
    1990           0 :         cmsgh->cmsg_len < CMSG_LEN(0))
    1991           0 :         return -1;
    1992           0 :     cmsg_data_len = cmsgh->cmsg_len - CMSG_LEN(0);
    1993           0 :     if (!get_cmsg_data_space(msg, cmsgh, &space))
    1994           0 :         return -1;
    1995           0 :     if (space >= cmsg_data_len) {
    1996           0 :         *data_len = cmsg_data_len;
    1997           0 :         return 0;
    1998             :     }
    1999           0 :     *data_len = space;
    2000           0 :     return 1;
    2001             : }
    2002             : #endif    /* CMSG_LEN */
    2003             : 
    2004             : 
    2005             : /* s._accept() -> (fd, address) */
    2006             : 
    2007             : static PyObject *
    2008           0 : sock_accept(PySocketSockObject *s)
    2009             : {
    2010             :     sock_addr_t addrbuf;
    2011           0 :     SOCKET_T newfd = INVALID_SOCKET;
    2012             :     socklen_t addrlen;
    2013           0 :     PyObject *sock = NULL;
    2014           0 :     PyObject *addr = NULL;
    2015           0 :     PyObject *res = NULL;
    2016             :     int timeout;
    2017           0 :     if (!getsockaddrlen(s, &addrlen))
    2018           0 :         return NULL;
    2019           0 :     memset(&addrbuf, 0, addrlen);
    2020             : 
    2021             :     if (!IS_SELECTABLE(s))
    2022             :         return select_error();
    2023             : 
    2024           0 :     BEGIN_SELECT_LOOP(s)
    2025           0 :     Py_BEGIN_ALLOW_THREADS
    2026           0 :     timeout = internal_select_ex(s, 0, interval);
    2027           0 :     if (!timeout) {
    2028           0 :         newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
    2029             :     }
    2030           0 :     Py_END_ALLOW_THREADS
    2031             : 
    2032           0 :     if (timeout == 1) {
    2033           0 :         PyErr_SetString(socket_timeout, "timed out");
    2034           0 :         return NULL;
    2035             :     }
    2036           0 :     END_SELECT_LOOP(s)
    2037             : 
    2038           0 :     if (newfd == INVALID_SOCKET)
    2039           0 :         return s->errorhandler();
    2040             : 
    2041           0 :     sock = PyLong_FromSocket_t(newfd);
    2042           0 :     if (sock == NULL) {
    2043           0 :         SOCKETCLOSE(newfd);
    2044           0 :         goto finally;
    2045             :     }
    2046             : 
    2047           0 :     addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
    2048             :                         addrlen, s->sock_proto);
    2049           0 :     if (addr == NULL)
    2050           0 :         goto finally;
    2051             : 
    2052           0 :     res = PyTuple_Pack(2, sock, addr);
    2053             : 
    2054             : finally:
    2055           0 :     Py_XDECREF(sock);
    2056           0 :     Py_XDECREF(addr);
    2057           0 :     return res;
    2058             : }
    2059             : 
    2060             : PyDoc_STRVAR(accept_doc,
    2061             : "_accept() -> (integer, address info)\n\
    2062             : \n\
    2063             : Wait for an incoming connection.  Return a new socket file descriptor\n\
    2064             : representing the connection, and the address of the client.\n\
    2065             : For IP sockets, the address info is a pair (hostaddr, port).");
    2066             : 
    2067             : /* s.setblocking(flag) method.  Argument:
    2068             :    False -- non-blocking mode; same as settimeout(0)
    2069             :    True -- blocking mode; same as settimeout(None)
    2070             : */
    2071             : 
    2072             : static PyObject *
    2073           0 : sock_setblocking(PySocketSockObject *s, PyObject *arg)
    2074             : {
    2075             :     int block;
    2076             : 
    2077           0 :     block = PyLong_AsLong(arg);
    2078           0 :     if (block == -1 && PyErr_Occurred())
    2079           0 :         return NULL;
    2080             : 
    2081           0 :     s->sock_timeout = block ? -1.0 : 0.0;
    2082           0 :     internal_setblocking(s, block);
    2083             : 
    2084           0 :     Py_INCREF(Py_None);
    2085           0 :     return Py_None;
    2086             : }
    2087             : 
    2088             : PyDoc_STRVAR(setblocking_doc,
    2089             : "setblocking(flag)\n\
    2090             : \n\
    2091             : Set the socket to blocking (flag is true) or non-blocking (false).\n\
    2092             : setblocking(True) is equivalent to settimeout(None);\n\
    2093             : setblocking(False) is equivalent to settimeout(0.0).");
    2094             : 
    2095             : /* s.settimeout(timeout) method.  Argument:
    2096             :    None -- no timeout, blocking mode; same as setblocking(True)
    2097             :    0.0  -- non-blocking mode; same as setblocking(False)
    2098             :    > 0  -- timeout mode; operations time out after timeout seconds
    2099             :    < 0  -- illegal; raises an exception
    2100             : */
    2101             : static PyObject *
    2102           0 : sock_settimeout(PySocketSockObject *s, PyObject *arg)
    2103             : {
    2104             :     double timeout;
    2105             : 
    2106           0 :     if (arg == Py_None)
    2107           0 :         timeout = -1.0;
    2108             :     else {
    2109           0 :         timeout = PyFloat_AsDouble(arg);
    2110           0 :         if (timeout < 0.0) {
    2111           0 :             if (!PyErr_Occurred())
    2112           0 :                 PyErr_SetString(PyExc_ValueError,
    2113             :                                 "Timeout value out of range");
    2114           0 :             return NULL;
    2115             :         }
    2116             :     }
    2117             : 
    2118           0 :     s->sock_timeout = timeout;
    2119           0 :     internal_setblocking(s, timeout < 0.0);
    2120             : 
    2121           0 :     Py_INCREF(Py_None);
    2122           0 :     return Py_None;
    2123             : }
    2124             : 
    2125             : PyDoc_STRVAR(settimeout_doc,
    2126             : "settimeout(timeout)\n\
    2127             : \n\
    2128             : Set a timeout on socket operations.  'timeout' can be a float,\n\
    2129             : giving in seconds, or None.  Setting a timeout of None disables\n\
    2130             : the timeout feature and is equivalent to setblocking(1).\n\
    2131             : Setting a timeout of zero is the same as setblocking(0).");
    2132             : 
    2133             : /* s.gettimeout() method.
    2134             :    Returns the timeout associated with a socket. */
    2135             : static PyObject *
    2136           0 : sock_gettimeout(PySocketSockObject *s)
    2137             : {
    2138           0 :     if (s->sock_timeout < 0.0) {
    2139           0 :         Py_INCREF(Py_None);
    2140           0 :         return Py_None;
    2141             :     }
    2142             :     else
    2143           0 :         return PyFloat_FromDouble(s->sock_timeout);
    2144             : }
    2145             : 
    2146             : PyDoc_STRVAR(gettimeout_doc,
    2147             : "gettimeout() -> timeout\n\
    2148             : \n\
    2149             : Returns the timeout in seconds (float) associated with socket \n\
    2150             : operations. A timeout of None indicates that timeouts on socket \n\
    2151             : operations are disabled.");
    2152             : 
    2153             : /* s.setsockopt() method.
    2154             :    With an integer third argument, sets an integer option.
    2155             :    With a string third argument, sets an option from a buffer;
    2156             :    use optional built-in module 'struct' to encode the string. */
    2157             : 
    2158             : static PyObject *
    2159           0 : sock_setsockopt(PySocketSockObject *s, PyObject *args)
    2160             : {
    2161             :     int level;
    2162             :     int optname;
    2163             :     int res;
    2164             :     char *buf;
    2165             :     int buflen;
    2166             :     int flag;
    2167             : 
    2168           0 :     if (PyArg_ParseTuple(args, "iii:setsockopt",
    2169             :                          &level, &optname, &flag)) {
    2170           0 :         buf = (char *) &flag;
    2171           0 :         buflen = sizeof flag;
    2172             :     }
    2173             :     else {
    2174           0 :         PyErr_Clear();
    2175           0 :         if (!PyArg_ParseTuple(args, "iiy#:setsockopt",
    2176             :                               &level, &optname, &buf, &buflen))
    2177           0 :             return NULL;
    2178             :     }
    2179           0 :     res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
    2180           0 :     if (res < 0)
    2181           0 :         return s->errorhandler();
    2182           0 :     Py_INCREF(Py_None);
    2183           0 :     return Py_None;
    2184             : }
    2185             : 
    2186             : PyDoc_STRVAR(setsockopt_doc,
    2187             : "setsockopt(level, option, value)\n\
    2188             : \n\
    2189             : Set a socket option.  See the Unix manual for level and option.\n\
    2190             : The value argument can either be an integer or a string.");
    2191             : 
    2192             : 
    2193             : /* s.getsockopt() method.
    2194             :    With two arguments, retrieves an integer option.
    2195             :    With a third integer argument, retrieves a string buffer of that size;
    2196             :    use optional built-in module 'struct' to decode the string. */
    2197             : 
    2198             : static PyObject *
    2199           0 : sock_getsockopt(PySocketSockObject *s, PyObject *args)
    2200             : {
    2201             :     int level;
    2202             :     int optname;
    2203             :     int res;
    2204             :     PyObject *buf;
    2205           0 :     socklen_t buflen = 0;
    2206             : 
    2207           0 :     if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
    2208             :                           &level, &optname, &buflen))
    2209           0 :         return NULL;
    2210             : 
    2211           0 :     if (buflen == 0) {
    2212           0 :         int flag = 0;
    2213           0 :         socklen_t flagsize = sizeof flag;
    2214           0 :         res = getsockopt(s->sock_fd, level, optname,
    2215             :                          (void *)&flag, &flagsize);
    2216           0 :         if (res < 0)
    2217           0 :             return s->errorhandler();
    2218           0 :         return PyLong_FromLong(flag);
    2219             :     }
    2220             : #ifdef __VMS
    2221             :     /* socklen_t is unsigned so no negative test is needed,
    2222             :        test buflen == 0 is previously done */
    2223             :     if (buflen > 1024) {
    2224             : #else
    2225           0 :     if (buflen <= 0 || buflen > 1024) {
    2226             : #endif
    2227           0 :         PyErr_SetString(PyExc_OSError,
    2228             :                         "getsockopt buflen out of range");
    2229           0 :         return NULL;
    2230             :     }
    2231           0 :     buf = PyBytes_FromStringAndSize((char *)NULL, buflen);
    2232           0 :     if (buf == NULL)
    2233           0 :         return NULL;
    2234           0 :     res = getsockopt(s->sock_fd, level, optname,
    2235           0 :                      (void *)PyBytes_AS_STRING(buf), &buflen);
    2236           0 :     if (res < 0) {
    2237           0 :         Py_DECREF(buf);
    2238           0 :         return s->errorhandler();
    2239             :     }
    2240           0 :     _PyBytes_Resize(&buf, buflen);
    2241           0 :     return buf;
    2242             : }
    2243             : 
    2244             : PyDoc_STRVAR(getsockopt_doc,
    2245             : "getsockopt(level, option[, buffersize]) -> value\n\
    2246             : \n\
    2247             : Get a socket option.  See the Unix manual for level and option.\n\
    2248             : If a nonzero buffersize argument is given, the return value is a\n\
    2249             : string of that length; otherwise it is an integer.");
    2250             : 
    2251             : 
    2252             : /* s.bind(sockaddr) method */
    2253             : 
    2254             : static PyObject *
    2255           0 : sock_bind(PySocketSockObject *s, PyObject *addro)
    2256             : {
    2257             :     sock_addr_t addrbuf;
    2258             :     int addrlen;
    2259             :     int res;
    2260             : 
    2261           0 :     if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
    2262           0 :         return NULL;
    2263           0 :     Py_BEGIN_ALLOW_THREADS
    2264           0 :     res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
    2265           0 :     Py_END_ALLOW_THREADS
    2266           0 :     if (res < 0)
    2267           0 :         return s->errorhandler();
    2268           0 :     Py_INCREF(Py_None);
    2269           0 :     return Py_None;
    2270             : }
    2271             : 
    2272             : PyDoc_STRVAR(bind_doc,
    2273             : "bind(address)\n\
    2274             : \n\
    2275             : Bind the socket to a local address.  For IP sockets, the address is a\n\
    2276             : pair (host, port); the host must refer to the local host. For raw packet\n\
    2277             : sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
    2278             : 
    2279             : 
    2280             : /* s.close() method.
    2281             :    Set the file descriptor to -1 so operations tried subsequently
    2282             :    will surely fail. */
    2283             : 
    2284             : static PyObject *
    2285           0 : sock_close(PySocketSockObject *s)
    2286             : {
    2287             :     SOCKET_T fd;
    2288             : 
    2289           0 :     if ((fd = s->sock_fd) != -1) {
    2290           0 :         s->sock_fd = -1;
    2291           0 :         Py_BEGIN_ALLOW_THREADS
    2292           0 :         (void) SOCKETCLOSE(fd);
    2293           0 :         Py_END_ALLOW_THREADS
    2294             :     }
    2295           0 :     Py_INCREF(Py_None);
    2296           0 :     return Py_None;
    2297             : }
    2298             : 
    2299             : PyDoc_STRVAR(close_doc,
    2300             : "close()\n\
    2301             : \n\
    2302             : Close the socket.  It cannot be used after this call.");
    2303             : 
    2304             : static PyObject *
    2305           0 : sock_detach(PySocketSockObject *s)
    2306             : {
    2307           0 :     SOCKET_T fd = s->sock_fd;
    2308           0 :     s->sock_fd = -1;
    2309           0 :     return PyLong_FromSocket_t(fd);
    2310             : }
    2311             : 
    2312             : PyDoc_STRVAR(detach_doc,
    2313             : "detach()\n\
    2314             : \n\
    2315             : Close the socket object without closing the underlying file descriptor.\
    2316             : The object cannot be used after this call, but the file descriptor\
    2317             : can be reused for other purposes.  The file descriptor is returned.");
    2318             : 
    2319             : static int
    2320           0 : internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
    2321             :                  int *timeoutp)
    2322             : {
    2323             :     int res, timeout;
    2324             : 
    2325           0 :     timeout = 0;
    2326           0 :     res = connect(s->sock_fd, addr, addrlen);
    2327             : 
    2328             : #ifdef MS_WINDOWS
    2329             : 
    2330             :     if (s->sock_timeout > 0.0) {
    2331             :         if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
    2332             :             IS_SELECTABLE(s)) {
    2333             :             /* This is a mess.  Best solution: trust select */
    2334             :             fd_set fds;
    2335             :             fd_set fds_exc;
    2336             :             struct timeval tv;
    2337             :             tv.tv_sec = (int)s->sock_timeout;
    2338             :             tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
    2339             :             FD_ZERO(&fds);
    2340             :             FD_SET(s->sock_fd, &fds);
    2341             :             FD_ZERO(&fds_exc);
    2342             :             FD_SET(s->sock_fd, &fds_exc);
    2343             :             res = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
    2344             :                          NULL, &fds, &fds_exc, &tv);
    2345             :             if (res == 0) {
    2346             :                 res = WSAEWOULDBLOCK;
    2347             :                 timeout = 1;
    2348             :             } else if (res > 0) {
    2349             :                 if (FD_ISSET(s->sock_fd, &fds))
    2350             :                     /* The socket is in the writable set - this
    2351             :                        means connected */
    2352             :                     res = 0;
    2353             :                 else {
    2354             :                     /* As per MS docs, we need to call getsockopt()
    2355             :                        to get the underlying error */
    2356             :                     int res_size = sizeof res;
    2357             :                     /* It must be in the exception set */
    2358             :                     assert(FD_ISSET(s->sock_fd, &fds_exc));
    2359             :                     if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
    2360             :                                         (char *)&res, &res_size))
    2361             :                         /* getsockopt also clears WSAGetLastError,
    2362             :                            so reset it back. */
    2363             :                         WSASetLastError(res);
    2364             :                     else
    2365             :                         res = WSAGetLastError();
    2366             :                 }
    2367             :             }
    2368             :             /* else if (res < 0) an error occurred */
    2369             :         }
    2370             :     }
    2371             : 
    2372             :     if (res < 0)
    2373             :         res = WSAGetLastError();
    2374             : 
    2375             : #else
    2376             : 
    2377           0 :     if (s->sock_timeout > 0.0) {
    2378           0 :         if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
    2379           0 :             timeout = internal_select(s, 1);
    2380           0 :             if (timeout == 0) {
    2381             :                 /* Bug #1019808: in case of an EINPROGRESS,
    2382             :                    use getsockopt(SO_ERROR) to get the real
    2383             :                    error. */
    2384           0 :                 socklen_t res_size = sizeof res;
    2385           0 :                 (void)getsockopt(s->sock_fd, SOL_SOCKET,
    2386             :                                  SO_ERROR, &res, &res_size);
    2387           0 :                 if (res == EISCONN)
    2388           0 :                     res = 0;
    2389           0 :                 errno = res;
    2390             :             }
    2391           0 :             else if (timeout == -1) {
    2392           0 :                 res = errno;            /* had error */
    2393             :             }
    2394             :             else
    2395           0 :                 res = EWOULDBLOCK;                      /* timed out */
    2396             :         }
    2397             :     }
    2398             : 
    2399           0 :     if (res < 0)
    2400           0 :         res = errno;
    2401             : 
    2402             : #endif
    2403           0 :     *timeoutp = timeout;
    2404             : 
    2405           0 :     return res;
    2406             : }
    2407             : 
    2408             : /* s.connect(sockaddr) method */
    2409             : 
    2410             : static PyObject *
    2411           0 : sock_connect(PySocketSockObject *s, PyObject *addro)
    2412             : {
    2413             :     sock_addr_t addrbuf;
    2414             :     int addrlen;
    2415             :     int res;
    2416             :     int timeout;
    2417             : 
    2418           0 :     if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
    2419           0 :         return NULL;
    2420             : 
    2421           0 :     Py_BEGIN_ALLOW_THREADS
    2422           0 :     res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
    2423           0 :     Py_END_ALLOW_THREADS
    2424             : 
    2425           0 :     if (timeout == 1) {
    2426           0 :         PyErr_SetString(socket_timeout, "timed out");
    2427           0 :         return NULL;
    2428             :     }
    2429           0 :     if (res != 0)
    2430           0 :         return s->errorhandler();
    2431           0 :     Py_INCREF(Py_None);
    2432           0 :     return Py_None;
    2433             : }
    2434             : 
    2435             : PyDoc_STRVAR(connect_doc,
    2436             : "connect(address)\n\
    2437             : \n\
    2438             : Connect the socket to a remote address.  For IP sockets, the address\n\
    2439             : is a pair (host, port).");
    2440             : 
    2441             : 
    2442             : /* s.connect_ex(sockaddr) method */
    2443             : 
    2444             : static PyObject *
    2445           0 : sock_connect_ex(PySocketSockObject *s, PyObject *addro)
    2446             : {
    2447             :     sock_addr_t addrbuf;
    2448             :     int addrlen;
    2449             :     int res;
    2450             :     int timeout;
    2451             : 
    2452           0 :     if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
    2453           0 :         return NULL;
    2454             : 
    2455           0 :     Py_BEGIN_ALLOW_THREADS
    2456           0 :     res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
    2457           0 :     Py_END_ALLOW_THREADS
    2458             : 
    2459             :     /* Signals are not errors (though they may raise exceptions).  Adapted
    2460             :        from PyErr_SetFromErrnoWithFilenameObject(). */
    2461             : #ifdef EINTR
    2462           0 :     if (res == EINTR && PyErr_CheckSignals())
    2463           0 :         return NULL;
    2464             : #endif
    2465             : 
    2466           0 :     return PyLong_FromLong((long) res);
    2467             : }
    2468             : 
    2469             : PyDoc_STRVAR(connect_ex_doc,
    2470             : "connect_ex(address) -> errno\n\
    2471             : \n\
    2472             : This is like connect(address), but returns an error code (the errno value)\n\
    2473             : instead of raising an exception when an error occurs.");
    2474             : 
    2475             : 
    2476             : /* s.fileno() method */
    2477             : 
    2478             : static PyObject *
    2479           0 : sock_fileno(PySocketSockObject *s)
    2480             : {
    2481           0 :     return PyLong_FromSocket_t(s->sock_fd);
    2482             : }
    2483             : 
    2484             : PyDoc_STRVAR(fileno_doc,
    2485             : "fileno() -> integer\n\
    2486             : \n\
    2487             : Return the integer file descriptor of the socket.");
    2488             : 
    2489             : 
    2490             : /* s.getsockname() method */
    2491             : 
    2492             : static PyObject *
    2493           0 : sock_getsockname(PySocketSockObject *s)
    2494             : {
    2495             :     sock_addr_t addrbuf;
    2496             :     int res;
    2497             :     socklen_t addrlen;
    2498             : 
    2499           0 :     if (!getsockaddrlen(s, &addrlen))
    2500           0 :         return NULL;
    2501           0 :     memset(&addrbuf, 0, addrlen);
    2502           0 :     Py_BEGIN_ALLOW_THREADS
    2503           0 :     res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
    2504           0 :     Py_END_ALLOW_THREADS
    2505           0 :     if (res < 0)
    2506           0 :         return s->errorhandler();
    2507           0 :     return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
    2508             :                         s->sock_proto);
    2509             : }
    2510             : 
    2511             : PyDoc_STRVAR(getsockname_doc,
    2512             : "getsockname() -> address info\n\
    2513             : \n\
    2514             : Return the address of the local endpoint.  For IP sockets, the address\n\
    2515             : info is a pair (hostaddr, port).");
    2516             : 
    2517             : 
    2518             : #ifdef HAVE_GETPEERNAME         /* Cray APP doesn't have this :-( */
    2519             : /* s.getpeername() method */
    2520             : 
    2521             : static PyObject *
    2522           0 : sock_getpeername(PySocketSockObject *s)
    2523             : {
    2524             :     sock_addr_t addrbuf;
    2525             :     int res;
    2526             :     socklen_t addrlen;
    2527             : 
    2528           0 :     if (!getsockaddrlen(s, &addrlen))
    2529           0 :         return NULL;
    2530           0 :     memset(&addrbuf, 0, addrlen);
    2531           0 :     Py_BEGIN_ALLOW_THREADS
    2532           0 :     res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
    2533           0 :     Py_END_ALLOW_THREADS
    2534           0 :     if (res < 0)
    2535           0 :         return s->errorhandler();
    2536           0 :     return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
    2537             :                         s->sock_proto);
    2538             : }
    2539             : 
    2540             : PyDoc_STRVAR(getpeername_doc,
    2541             : "getpeername() -> address info\n\
    2542             : \n\
    2543             : Return the address of the remote endpoint.  For IP sockets, the address\n\
    2544             : info is a pair (hostaddr, port).");
    2545             : 
    2546             : #endif /* HAVE_GETPEERNAME */
    2547             : 
    2548             : 
    2549             : /* s.listen(n) method */
    2550             : 
    2551             : static PyObject *
    2552           0 : sock_listen(PySocketSockObject *s, PyObject *arg)
    2553             : {
    2554             :     int backlog;
    2555             :     int res;
    2556             : 
    2557           0 :     backlog = PyLong_AsLong(arg);
    2558           0 :     if (backlog == -1 && PyErr_Occurred())
    2559           0 :         return NULL;
    2560           0 :     Py_BEGIN_ALLOW_THREADS
    2561             :     /* To avoid problems on systems that don't allow a negative backlog
    2562             :      * (which doesn't make sense anyway) we force a minimum value of 0. */
    2563           0 :     if (backlog < 0)
    2564           0 :         backlog = 0;
    2565           0 :     res = listen(s->sock_fd, backlog);
    2566           0 :     Py_END_ALLOW_THREADS
    2567           0 :     if (res < 0)
    2568           0 :         return s->errorhandler();
    2569           0 :     Py_INCREF(Py_None);
    2570           0 :     return Py_None;
    2571             : }
    2572             : 
    2573             : PyDoc_STRVAR(listen_doc,
    2574             : "listen(backlog)\n\
    2575             : \n\
    2576             : Enable a server to accept connections.  The backlog argument must be at\n\
    2577             : least 0 (if it is lower, it is set to 0); it specifies the number of\n\
    2578             : unaccepted connections that the system will allow before refusing new\n\
    2579             : connections.");
    2580             : 
    2581             : 
    2582             : /*
    2583             :  * This is the guts of the recv() and recv_into() methods, which reads into a
    2584             :  * char buffer.  If you have any inc/dec ref to do to the objects that contain
    2585             :  * the buffer, do it in the caller.  This function returns the number of bytes
    2586             :  * successfully read.  If there was an error, it returns -1.  Note that it is
    2587             :  * also possible that we return a number of bytes smaller than the request
    2588             :  * bytes.
    2589             :  */
    2590             : 
    2591             : static Py_ssize_t
    2592           0 : sock_recv_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags)
    2593             : {
    2594           0 :     Py_ssize_t outlen = -1;
    2595             :     int timeout;
    2596             : #ifdef __VMS
    2597             :     int remaining;
    2598             :     char *read_buf;
    2599             : #endif
    2600             : 
    2601             :     if (!IS_SELECTABLE(s)) {
    2602             :         select_error();
    2603             :         return -1;
    2604             :     }
    2605           0 :     if (len == 0) {
    2606             :         /* If 0 bytes were requested, do nothing. */
    2607           0 :         return 0;
    2608             :     }
    2609             : 
    2610             : #ifndef __VMS
    2611           0 :     BEGIN_SELECT_LOOP(s)
    2612           0 :     Py_BEGIN_ALLOW_THREADS
    2613           0 :     timeout = internal_select_ex(s, 0, interval);
    2614           0 :     if (!timeout)
    2615           0 :         outlen = recv(s->sock_fd, cbuf, len, flags);
    2616           0 :     Py_END_ALLOW_THREADS
    2617             : 
    2618           0 :     if (timeout == 1) {
    2619           0 :         PyErr_SetString(socket_timeout, "timed out");
    2620           0 :         return -1;
    2621             :     }
    2622           0 :     END_SELECT_LOOP(s)
    2623           0 :     if (outlen < 0) {
    2624             :         /* Note: the call to errorhandler() ALWAYS indirectly returned
    2625             :            NULL, so ignore its return value */
    2626           0 :         s->errorhandler();
    2627           0 :         return -1;
    2628             :     }
    2629             : #else
    2630             :     read_buf = cbuf;
    2631             :     remaining = len;
    2632             :     while (remaining != 0) {
    2633             :         unsigned int segment;
    2634             :         int nread = -1;
    2635             : 
    2636             :         segment = remaining /SEGMENT_SIZE;
    2637             :         if (segment != 0) {
    2638             :             segment = SEGMENT_SIZE;
    2639             :         }
    2640             :         else {
    2641             :             segment = remaining;
    2642             :         }
    2643             : 
    2644             :         BEGIN_SELECT_LOOP(s)
    2645             :         Py_BEGIN_ALLOW_THREADS
    2646             :         timeout = internal_select_ex(s, 0, interval);
    2647             :         if (!timeout)
    2648             :             nread = recv(s->sock_fd, read_buf, segment, flags);
    2649             :         Py_END_ALLOW_THREADS
    2650             :         if (timeout == 1) {
    2651             :             PyErr_SetString(socket_timeout, "timed out");
    2652             :             return -1;
    2653             :         }
    2654             :         END_SELECT_LOOP(s)
    2655             : 
    2656             :         if (nread < 0) {
    2657             :             s->errorhandler();
    2658             :             return -1;
    2659             :         }
    2660             :         if (nread != remaining) {
    2661             :             read_buf += nread;
    2662             :             break;
    2663             :         }
    2664             : 
    2665             :         remaining -= segment;
    2666             :         read_buf += segment;
    2667             :     }
    2668             :     outlen = read_buf - cbuf;
    2669             : #endif /* !__VMS */
    2670             : 
    2671           0 :     return outlen;
    2672             : }
    2673             : 
    2674             : 
    2675             : /* s.recv(nbytes [,flags]) method */
    2676             : 
    2677             : static PyObject *
    2678           0 : sock_recv(PySocketSockObject *s, PyObject *args)
    2679             : {
    2680             :     Py_ssize_t recvlen, outlen;
    2681           0 :     int flags = 0;
    2682             :     PyObject *buf;
    2683             : 
    2684           0 :     if (!PyArg_ParseTuple(args, "n|i:recv", &recvlen, &flags))
    2685           0 :         return NULL;
    2686             : 
    2687           0 :     if (recvlen < 0) {
    2688           0 :         PyErr_SetString(PyExc_ValueError,
    2689             :                         "negative buffersize in recv");
    2690           0 :         return NULL;
    2691             :     }
    2692             : 
    2693             :     /* Allocate a new string. */
    2694           0 :     buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
    2695           0 :     if (buf == NULL)
    2696           0 :         return NULL;
    2697             : 
    2698             :     /* Call the guts */
    2699           0 :     outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags);
    2700           0 :     if (outlen < 0) {
    2701             :         /* An error occurred, release the string and return an
    2702             :            error. */
    2703           0 :         Py_DECREF(buf);
    2704           0 :         return NULL;
    2705             :     }
    2706           0 :     if (outlen != recvlen) {
    2707             :         /* We did not read as many bytes as we anticipated, resize the
    2708             :            string if possible and be successful. */
    2709           0 :         _PyBytes_Resize(&buf, outlen);
    2710             :     }
    2711             : 
    2712           0 :     return buf;
    2713             : }
    2714             : 
    2715             : PyDoc_STRVAR(recv_doc,
    2716             : "recv(buffersize[, flags]) -> data\n\
    2717             : \n\
    2718             : Receive up to buffersize bytes from the socket.  For the optional flags\n\
    2719             : argument, see the Unix manual.  When no data is available, block until\n\
    2720             : at least one byte is available or until the remote end is closed.  When\n\
    2721             : the remote end is closed and all data is read, return the empty string.");
    2722             : 
    2723             : 
    2724             : /* s.recv_into(buffer, [nbytes [,flags]]) method */
    2725             : 
    2726             : static PyObject*
    2727           0 : sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
    2728             : {
    2729             :     static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
    2730             : 
    2731           0 :     int flags = 0;
    2732             :     Py_buffer pbuf;
    2733             :     char *buf;
    2734           0 :     Py_ssize_t buflen, readlen, recvlen = 0;
    2735             : 
    2736             :     /* Get the buffer's memory */
    2737           0 :     if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ni:recv_into", kwlist,
    2738             :                                      &pbuf, &recvlen, &flags))
    2739           0 :         return NULL;
    2740           0 :     buf = pbuf.buf;
    2741           0 :     buflen = pbuf.len;
    2742             : 
    2743           0 :     if (recvlen < 0) {
    2744           0 :         PyBuffer_Release(&pbuf);
    2745           0 :         PyErr_SetString(PyExc_ValueError,
    2746             :                         "negative buffersize in recv_into");
    2747           0 :         return NULL;
    2748             :     }
    2749           0 :     if (recvlen == 0) {
    2750             :         /* If nbytes was not specified, use the buffer's length */
    2751           0 :         recvlen = buflen;
    2752             :     }
    2753             : 
    2754             :     /* Check if the buffer is large enough */
    2755           0 :     if (buflen < recvlen) {
    2756           0 :         PyBuffer_Release(&pbuf);
    2757           0 :         PyErr_SetString(PyExc_ValueError,
    2758             :                         "buffer too small for requested bytes");
    2759           0 :         return NULL;
    2760             :     }
    2761             : 
    2762             :     /* Call the guts */
    2763           0 :     readlen = sock_recv_guts(s, buf, recvlen, flags);
    2764           0 :     if (readlen < 0) {
    2765             :         /* Return an error. */
    2766           0 :         PyBuffer_Release(&pbuf);
    2767           0 :         return NULL;
    2768             :     }
    2769             : 
    2770           0 :     PyBuffer_Release(&pbuf);
    2771             :     /* Return the number of bytes read.  Note that we do not do anything
    2772             :        special here in the case that readlen < recvlen. */
    2773           0 :     return PyLong_FromSsize_t(readlen);
    2774             : }
    2775             : 
    2776             : PyDoc_STRVAR(recv_into_doc,
    2777             : "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
    2778             : \n\
    2779             : A version of recv() that stores its data into a buffer rather than creating \n\
    2780             : a new string.  Receive up to buffersize bytes from the socket.  If buffersize \n\
    2781             : is not specified (or 0), receive up to the size available in the given buffer.\n\
    2782             : \n\
    2783             : See recv() for documentation about the flags.");
    2784             : 
    2785             : 
    2786             : /*
    2787             :  * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
    2788             :  * into a char buffer.  If you have any inc/def ref to do to the objects that
    2789             :  * contain the buffer, do it in the caller.  This function returns the number
    2790             :  * of bytes successfully read.  If there was an error, it returns -1.  Note
    2791             :  * that it is also possible that we return a number of bytes smaller than the
    2792             :  * request bytes.
    2793             :  *
    2794             :  * 'addr' is a return value for the address object.  Note that you must decref
    2795             :  * it yourself.
    2796             :  */
    2797             : static Py_ssize_t
    2798           0 : sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags,
    2799             :                    PyObject** addr)
    2800             : {
    2801             :     sock_addr_t addrbuf;
    2802             :     int timeout;
    2803           0 :     Py_ssize_t n = -1;
    2804             :     socklen_t addrlen;
    2805             : 
    2806           0 :     *addr = NULL;
    2807             : 
    2808           0 :     if (!getsockaddrlen(s, &addrlen))
    2809           0 :         return -1;
    2810             : 
    2811             :     if (!IS_SELECTABLE(s)) {
    2812             :         select_error();
    2813             :         return -1;
    2814             :     }
    2815             : 
    2816           0 :     BEGIN_SELECT_LOOP(s)
    2817           0 :     Py_BEGIN_ALLOW_THREADS
    2818           0 :     memset(&addrbuf, 0, addrlen);
    2819           0 :     timeout = internal_select_ex(s, 0, interval);
    2820           0 :     if (!timeout) {
    2821             : #ifndef MS_WINDOWS
    2822             : #if defined(PYOS_OS2) && !defined(PYCC_GCC)
    2823             :         n = recvfrom(s->sock_fd, cbuf, len, flags,
    2824             :                      SAS2SA(&addrbuf), &addrlen);
    2825             : #else
    2826           0 :         n = recvfrom(s->sock_fd, cbuf, len, flags,
    2827             :                      (void *) &addrbuf, &addrlen);
    2828             : #endif
    2829             : #else
    2830             :         n = recvfrom(s->sock_fd, cbuf, len, flags,
    2831             :                      SAS2SA(&addrbuf), &addrlen);
    2832             : #endif
    2833             :     }
    2834           0 :     Py_END_ALLOW_THREADS
    2835             : 
    2836           0 :     if (timeout == 1) {
    2837           0 :         PyErr_SetString(socket_timeout, "timed out");
    2838           0 :         return -1;
    2839             :     }
    2840           0 :     END_SELECT_LOOP(s)
    2841           0 :     if (n < 0) {
    2842           0 :         s->errorhandler();
    2843           0 :         return -1;
    2844             :     }
    2845             : 
    2846           0 :     if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
    2847             :                                addrlen, s->sock_proto)))
    2848           0 :         return -1;
    2849             : 
    2850           0 :     return n;
    2851             : }
    2852             : 
    2853             : /* s.recvfrom(nbytes [,flags]) method */
    2854             : 
    2855             : static PyObject *
    2856           0 : sock_recvfrom(PySocketSockObject *s, PyObject *args)
    2857             : {
    2858           0 :     PyObject *buf = NULL;
    2859           0 :     PyObject *addr = NULL;
    2860           0 :     PyObject *ret = NULL;
    2861           0 :     int flags = 0;
    2862             :     Py_ssize_t recvlen, outlen;
    2863             : 
    2864           0 :     if (!PyArg_ParseTuple(args, "n|i:recvfrom", &recvlen, &flags))
    2865           0 :         return NULL;
    2866             : 
    2867           0 :     if (recvlen < 0) {
    2868           0 :         PyErr_SetString(PyExc_ValueError,
    2869             :                         "negative buffersize in recvfrom");
    2870           0 :         return NULL;
    2871             :     }
    2872             : 
    2873           0 :     buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
    2874           0 :     if (buf == NULL)
    2875           0 :         return NULL;
    2876             : 
    2877           0 :     outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf),
    2878             :                                 recvlen, flags, &addr);
    2879           0 :     if (outlen < 0) {
    2880           0 :         goto finally;
    2881             :     }
    2882             : 
    2883           0 :     if (outlen != recvlen) {
    2884             :         /* We did not read as many bytes as we anticipated, resize the
    2885             :            string if possible and be successful. */
    2886           0 :         if (_PyBytes_Resize(&buf, outlen) < 0)
    2887             :             /* Oopsy, not so successful after all. */
    2888           0 :             goto finally;
    2889             :     }
    2890             : 
    2891           0 :     ret = PyTuple_Pack(2, buf, addr);
    2892             : 
    2893             : finally:
    2894           0 :     Py_XDECREF(buf);
    2895           0 :     Py_XDECREF(addr);
    2896           0 :     return ret;
    2897             : }
    2898             : 
    2899             : PyDoc_STRVAR(recvfrom_doc,
    2900             : "recvfrom(buffersize[, flags]) -> (data, address info)\n\
    2901             : \n\
    2902             : Like recv(buffersize, flags) but also return the sender's address info.");
    2903             : 
    2904             : 
    2905             : /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
    2906             : 
    2907             : static PyObject *
    2908           0 : sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
    2909             : {
    2910             :     static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
    2911             : 
    2912           0 :     int flags = 0;
    2913             :     Py_buffer pbuf;
    2914             :     char *buf;
    2915           0 :     Py_ssize_t readlen, buflen, recvlen = 0;
    2916             : 
    2917           0 :     PyObject *addr = NULL;
    2918             : 
    2919           0 :     if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ni:recvfrom_into",
    2920             :                                      kwlist, &pbuf,
    2921             :                                      &recvlen, &flags))
    2922           0 :         return NULL;
    2923           0 :     buf = pbuf.buf;
    2924           0 :     buflen = pbuf.len;
    2925             :     assert(buf != 0 && buflen > 0);
    2926             : 
    2927           0 :     if (recvlen < 0) {
    2928           0 :         PyBuffer_Release(&pbuf);
    2929           0 :         PyErr_SetString(PyExc_ValueError,
    2930             :                         "negative buffersize in recvfrom_into");
    2931           0 :         return NULL;
    2932             :     }
    2933           0 :     if (recvlen == 0) {
    2934             :         /* If nbytes was not specified, use the buffer's length */
    2935           0 :         recvlen = buflen;
    2936             :     }
    2937             : 
    2938           0 :     readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
    2939           0 :     if (readlen < 0) {
    2940           0 :         PyBuffer_Release(&pbuf);
    2941             :         /* Return an error */
    2942           0 :         Py_XDECREF(addr);
    2943           0 :         return NULL;
    2944             :     }
    2945             : 
    2946           0 :     PyBuffer_Release(&pbuf);
    2947             :     /* Return the number of bytes read and the address.  Note that we do
    2948             :        not do anything special here in the case that readlen < recvlen. */
    2949           0 :     return Py_BuildValue("nN", readlen, addr);
    2950             : }
    2951             : 
    2952             : PyDoc_STRVAR(recvfrom_into_doc,
    2953             : "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
    2954             : \n\
    2955             : Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
    2956             : 
    2957             : 
    2958             : /* The sendmsg() and recvmsg[_into]() methods require a working
    2959             :    CMSG_LEN().  See the comment near get_CMSG_LEN(). */
    2960             : #ifdef CMSG_LEN
    2961             : /*
    2962             :  * Call recvmsg() with the supplied iovec structures, flags, and
    2963             :  * ancillary data buffer size (controllen).  Returns the tuple return
    2964             :  * value for recvmsg() or recvmsg_into(), with the first item provided
    2965             :  * by the supplied makeval() function.  makeval() will be called with
    2966             :  * the length read and makeval_data as arguments, and must return a
    2967             :  * new reference (which will be decrefed if there is a subsequent
    2968             :  * error).  On error, closes any file descriptors received via
    2969             :  * SCM_RIGHTS.
    2970             :  */
    2971             : static PyObject *
    2972           0 : sock_recvmsg_guts(PySocketSockObject *s, struct iovec *iov, int iovlen,
    2973             :                   int flags, Py_ssize_t controllen,
    2974             :                   PyObject *(*makeval)(ssize_t, void *), void *makeval_data)
    2975             : {
    2976           0 :     ssize_t bytes_received = -1;
    2977             :     int timeout;
    2978             :     sock_addr_t addrbuf;
    2979             :     socklen_t addrbuflen;
    2980           0 :     struct msghdr msg = {0};
    2981           0 :     PyObject *cmsg_list = NULL, *retval = NULL;
    2982           0 :     void *controlbuf = NULL;
    2983             :     struct cmsghdr *cmsgh;
    2984           0 :     size_t cmsgdatalen = 0;
    2985             :     int cmsg_status;
    2986             : 
    2987             :     /* XXX: POSIX says that msg_name and msg_namelen "shall be
    2988             :        ignored" when the socket is connected (Linux fills them in
    2989             :        anyway for AF_UNIX sockets at least).  Normally msg_namelen
    2990             :        seems to be set to 0 if there's no address, but try to
    2991             :        initialize msg_name to something that won't be mistaken for a
    2992             :        real address if that doesn't happen. */
    2993           0 :     if (!getsockaddrlen(s, &addrbuflen))
    2994           0 :         return NULL;
    2995           0 :     memset(&addrbuf, 0, addrbuflen);
    2996           0 :     SAS2SA(&addrbuf)->sa_family = AF_UNSPEC;
    2997             : 
    2998           0 :     if (controllen < 0 || controllen > SOCKLEN_T_LIMIT) {
    2999           0 :         PyErr_SetString(PyExc_ValueError,
    3000             :                         "invalid ancillary data buffer length");
    3001           0 :         return NULL;
    3002             :     }
    3003           0 :     if (controllen > 0 && (controlbuf = PyMem_Malloc(controllen)) == NULL)
    3004           0 :         return PyErr_NoMemory();
    3005             : 
    3006             :     /* Make the system call. */
    3007             :     if (!IS_SELECTABLE(s)) {
    3008             :         select_error();
    3009             :         goto finally;
    3010             :     }
    3011             : 
    3012           0 :     BEGIN_SELECT_LOOP(s)
    3013           0 :     Py_BEGIN_ALLOW_THREADS;
    3014           0 :     msg.msg_name = SAS2SA(&addrbuf);
    3015           0 :     msg.msg_namelen = addrbuflen;
    3016           0 :     msg.msg_iov = iov;
    3017           0 :     msg.msg_iovlen = iovlen;
    3018           0 :     msg.msg_control = controlbuf;
    3019           0 :     msg.msg_controllen = controllen;
    3020           0 :     timeout = internal_select_ex(s, 0, interval);
    3021           0 :     if (!timeout)
    3022           0 :         bytes_received = recvmsg(s->sock_fd, &msg, flags);
    3023           0 :     Py_END_ALLOW_THREADS;
    3024           0 :     if (timeout == 1) {
    3025           0 :         PyErr_SetString(socket_timeout, "timed out");
    3026             :         goto finally;
    3027             :     }
    3028           0 :     END_SELECT_LOOP(s)
    3029             : 
    3030           0 :     if (bytes_received < 0) {
    3031           0 :         s->errorhandler();
    3032           0 :         goto finally;
    3033             :     }
    3034             : 
    3035             :     /* Make list of (level, type, data) tuples from control messages. */
    3036           0 :     if ((cmsg_list = PyList_New(0)) == NULL)
    3037           0 :         goto err_closefds;
    3038             :     /* Check for empty ancillary data as old CMSG_FIRSTHDR()
    3039             :        implementations didn't do so. */
    3040           0 :     for (cmsgh = ((msg.msg_controllen > 0) ? CMSG_FIRSTHDR(&msg) : NULL);
    3041           0 :          cmsgh != NULL; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
    3042             :         PyObject *bytes, *tuple;
    3043             :         int tmp;
    3044             : 
    3045           0 :         cmsg_status = get_cmsg_data_len(&msg, cmsgh, &cmsgdatalen);
    3046           0 :         if (cmsg_status != 0) {
    3047           0 :             if (PyErr_WarnEx(PyExc_RuntimeWarning,
    3048             :                              "received malformed or improperly-truncated "
    3049             :                              "ancillary data", 1) == -1)
    3050           0 :                 goto err_closefds;
    3051             :         }
    3052           0 :         if (cmsg_status < 0)
    3053           0 :             break;
    3054           0 :         if (cmsgdatalen > PY_SSIZE_T_MAX) {
    3055           0 :             PyErr_SetString(PyExc_OSError, "control message too long");
    3056           0 :             goto err_closefds;
    3057             :         }
    3058             : 
    3059           0 :         bytes = PyBytes_FromStringAndSize((char *)CMSG_DATA(cmsgh),
    3060             :                                           cmsgdatalen);
    3061           0 :         tuple = Py_BuildValue("iiN", (int)cmsgh->cmsg_level,
    3062             :                               (int)cmsgh->cmsg_type, bytes);
    3063           0 :         if (tuple == NULL)
    3064           0 :             goto err_closefds;
    3065           0 :         tmp = PyList_Append(cmsg_list, tuple);
    3066           0 :         Py_DECREF(tuple);
    3067           0 :         if (tmp != 0)
    3068           0 :             goto err_closefds;
    3069             : 
    3070           0 :         if (cmsg_status != 0)
    3071           0 :             break;
    3072             :     }
    3073             : 
    3074           0 :     retval = Py_BuildValue("NOiN",
    3075             :                            (*makeval)(bytes_received, makeval_data),
    3076             :                            cmsg_list,
    3077             :                            (int)msg.msg_flags,
    3078             :                            makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
    3079             :                                         ((msg.msg_namelen > addrbuflen) ?
    3080           0 :                                          addrbuflen : msg.msg_namelen),
    3081             :                                         s->sock_proto));
    3082           0 :     if (retval == NULL)
    3083           0 :         goto err_closefds;
    3084             : 
    3085             : finally:
    3086           0 :     Py_XDECREF(cmsg_list);
    3087           0 :     PyMem_Free(controlbuf);
    3088           0 :     return retval;
    3089             : 
    3090             : err_closefds:
    3091             : #ifdef SCM_RIGHTS
    3092             :     /* Close all descriptors coming from SCM_RIGHTS, so they don't leak. */
    3093           0 :     for (cmsgh = ((msg.msg_controllen > 0) ? CMSG_FIRSTHDR(&msg) : NULL);
    3094           0 :          cmsgh != NULL; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
    3095           0 :         cmsg_status = get_cmsg_data_len(&msg, cmsgh, &cmsgdatalen);
    3096           0 :         if (cmsg_status < 0)
    3097           0 :             break;
    3098           0 :         if (cmsgh->cmsg_level == SOL_SOCKET &&
    3099           0 :             cmsgh->cmsg_type == SCM_RIGHTS) {
    3100             :             size_t numfds;
    3101             :             int *fdp;
    3102             : 
    3103           0 :             numfds = cmsgdatalen / sizeof(int);
    3104           0 :             fdp = (int *)CMSG_DATA(cmsgh);
    3105           0 :             while (numfds-- > 0)
    3106           0 :                 close(*fdp++);
    3107             :         }
    3108           0 :         if (cmsg_status != 0)
    3109           0 :             break;
    3110             :     }
    3111             : #endif /* SCM_RIGHTS */
    3112           0 :     goto finally;
    3113             : }
    3114             : 
    3115             : 
    3116             : static PyObject *
    3117           0 : makeval_recvmsg(ssize_t received, void *data)
    3118             : {
    3119           0 :     PyObject **buf = data;
    3120             : 
    3121           0 :     if (received < PyBytes_GET_SIZE(*buf))
    3122           0 :         _PyBytes_Resize(buf, received);
    3123           0 :     Py_XINCREF(*buf);
    3124           0 :     return *buf;
    3125             : }
    3126             : 
    3127             : /* s.recvmsg(bufsize[, ancbufsize[, flags]]) method */
    3128             : 
    3129             : static PyObject *
    3130           0 : sock_recvmsg(PySocketSockObject *s, PyObject *args)
    3131             : {
    3132           0 :     Py_ssize_t bufsize, ancbufsize = 0;
    3133           0 :     int flags = 0;
    3134             :     struct iovec iov;
    3135           0 :     PyObject *buf = NULL, *retval = NULL;
    3136             : 
    3137           0 :     if (!PyArg_ParseTuple(args, "n|ni:recvmsg", &bufsize, &ancbufsize, &flags))
    3138           0 :         return NULL;
    3139             : 
    3140           0 :     if (bufsize < 0) {
    3141           0 :         PyErr_SetString(PyExc_ValueError, "negative buffer size in recvmsg()");
    3142           0 :         return NULL;
    3143             :     }
    3144           0 :     if ((buf = PyBytes_FromStringAndSize(NULL, bufsize)) == NULL)
    3145           0 :         return NULL;
    3146           0 :     iov.iov_base = PyBytes_AS_STRING(buf);
    3147           0 :     iov.iov_len = bufsize;
    3148             : 
    3149             :     /* Note that we're passing a pointer to *our pointer* to the bytes
    3150             :        object here (&buf); makeval_recvmsg() may incref the object, or
    3151             :        deallocate it and set our pointer to NULL. */
    3152           0 :     retval = sock_recvmsg_guts(s, &iov, 1, flags, ancbufsize,
    3153             :                                &makeval_recvmsg, &buf);
    3154           0 :     Py_XDECREF(buf);
    3155           0 :     return retval;
    3156             : }
    3157             : 
    3158             : PyDoc_STRVAR(recvmsg_doc,
    3159             : "recvmsg(bufsize[, ancbufsize[, flags]]) -> (data, ancdata, msg_flags, address)\n\
    3160             : \n\
    3161             : Receive normal data (up to bufsize bytes) and ancillary data from the\n\
    3162             : socket.  The ancbufsize argument sets the size in bytes of the\n\
    3163             : internal buffer used to receive the ancillary data; it defaults to 0,\n\
    3164             : meaning that no ancillary data will be received.  Appropriate buffer\n\
    3165             : sizes for ancillary data can be calculated using CMSG_SPACE() or\n\
    3166             : CMSG_LEN(), and items which do not fit into the buffer might be\n\
    3167             : truncated or discarded.  The flags argument defaults to 0 and has the\n\
    3168             : same meaning as for recv().\n\
    3169             : \n\
    3170             : The return value is a 4-tuple: (data, ancdata, msg_flags, address).\n\
    3171             : The data item is a bytes object holding the non-ancillary data\n\
    3172             : received.  The ancdata item is a list of zero or more tuples\n\
    3173             : (cmsg_level, cmsg_type, cmsg_data) representing the ancillary data\n\
    3174             : (control messages) received: cmsg_level and cmsg_type are integers\n\
    3175             : specifying the protocol level and protocol-specific type respectively,\n\
    3176             : and cmsg_data is a bytes object holding the associated data.  The\n\
    3177             : msg_flags item is the bitwise OR of various flags indicating\n\
    3178             : conditions on the received message; see your system documentation for\n\
    3179             : details.  If the receiving socket is unconnected, address is the\n\
    3180             : address of the sending socket, if available; otherwise, its value is\n\
    3181             : unspecified.\n\
    3182             : \n\
    3183             : If recvmsg() raises an exception after the system call returns, it\n\
    3184             : will first attempt to close any file descriptors received via the\n\
    3185             : SCM_RIGHTS mechanism.");
    3186             : 
    3187             : 
    3188             : static PyObject *
    3189           0 : makeval_recvmsg_into(ssize_t received, void *data)
    3190             : {
    3191           0 :     return PyLong_FromSsize_t(received);
    3192             : }
    3193             : 
    3194             : /* s.recvmsg_into(buffers[, ancbufsize[, flags]]) method */
    3195             : 
    3196             : static PyObject *
    3197           0 : sock_recvmsg_into(PySocketSockObject *s, PyObject *args)
    3198             : {
    3199           0 :     Py_ssize_t ancbufsize = 0;
    3200           0 :     int flags = 0;
    3201           0 :     struct iovec *iovs = NULL;
    3202           0 :     Py_ssize_t i, nitems, nbufs = 0;
    3203           0 :     Py_buffer *bufs = NULL;
    3204           0 :     PyObject *buffers_arg, *fast, *retval = NULL;
    3205             : 
    3206           0 :     if (!PyArg_ParseTuple(args, "O|ni:recvmsg_into",
    3207             :                           &buffers_arg, &ancbufsize, &flags))
    3208           0 :         return NULL;
    3209             : 
    3210           0 :     if ((fast = PySequence_Fast(buffers_arg,
    3211             :                                 "recvmsg_into() argument 1 must be an "
    3212             :                                 "iterable")) == NULL)
    3213           0 :         return NULL;
    3214           0 :     nitems = PySequence_Fast_GET_SIZE(fast);
    3215             :     if (nitems > INT_MAX) {
    3216             :         PyErr_SetString(PyExc_OSError, "recvmsg_into() argument 1 is too long");
    3217             :         goto finally;
    3218             :     }
    3219             : 
    3220             :     /* Fill in an iovec for each item, and save the Py_buffer
    3221             :        structs to release afterwards. */
    3222           0 :     if (nitems > 0 && ((iovs = PyMem_New(struct iovec, nitems)) == NULL ||
    3223           0 :                        (bufs = PyMem_New(Py_buffer, nitems)) == NULL)) {
    3224           0 :         PyErr_NoMemory();
    3225           0 :         goto finally;
    3226             :     }
    3227           0 :     for (; nbufs < nitems; nbufs++) {
    3228           0 :         if (!PyArg_Parse(PySequence_Fast_GET_ITEM(fast, nbufs),
    3229             :                          "w*;recvmsg_into() argument 1 must be an iterable "
    3230             :                          "of single-segment read-write buffers",
    3231           0 :                          &bufs[nbufs]))
    3232           0 :             goto finally;
    3233           0 :         iovs[nbufs].iov_base = bufs[nbufs].buf;
    3234           0 :         iovs[nbufs].iov_len = bufs[nbufs].len;
    3235             :     }
    3236             : 
    3237           0 :     retval = sock_recvmsg_guts(s, iovs, nitems, flags, ancbufsize,
    3238             :                                &makeval_recvmsg_into, NULL);
    3239             : finally:
    3240           0 :     for (i = 0; i < nbufs; i++)
    3241           0 :         PyBuffer_Release(&bufs[i]);
    3242           0 :     PyMem_Free(bufs);
    3243           0 :     PyMem_Free(iovs);
    3244           0 :     Py_DECREF(fast);
    3245           0 :     return retval;
    3246             : }
    3247             : 
    3248             : PyDoc_STRVAR(recvmsg_into_doc,
    3249             : "recvmsg_into(buffers[, ancbufsize[, flags]]) -> (nbytes, ancdata, msg_flags, address)\n\
    3250             : \n\
    3251             : Receive normal data and ancillary data from the socket, scattering the\n\
    3252             : non-ancillary data into a series of buffers.  The buffers argument\n\
    3253             : must be an iterable of objects that export writable buffers\n\
    3254             : (e.g. bytearray objects); these will be filled with successive chunks\n\
    3255             : of the non-ancillary data until it has all been written or there are\n\
    3256             : no more buffers.  The ancbufsize argument sets the size in bytes of\n\
    3257             : the internal buffer used to receive the ancillary data; it defaults to\n\
    3258             : 0, meaning that no ancillary data will be received.  Appropriate\n\
    3259             : buffer sizes for ancillary data can be calculated using CMSG_SPACE()\n\
    3260             : or CMSG_LEN(), and items which do not fit into the buffer might be\n\
    3261             : truncated or discarded.  The flags argument defaults to 0 and has the\n\
    3262             : same meaning as for recv().\n\
    3263             : \n\
    3264             : The return value is a 4-tuple: (nbytes, ancdata, msg_flags, address).\n\
    3265             : The nbytes item is the total number of bytes of non-ancillary data\n\
    3266             : written into the buffers.  The ancdata item is a list of zero or more\n\
    3267             : tuples (cmsg_level, cmsg_type, cmsg_data) representing the ancillary\n\
    3268             : data (control messages) received: cmsg_level and cmsg_type are\n\
    3269             : integers specifying the protocol level and protocol-specific type\n\
    3270             : respectively, and cmsg_data is a bytes object holding the associated\n\
    3271             : data.  The msg_flags item is the bitwise OR of various flags\n\
    3272             : indicating conditions on the received message; see your system\n\
    3273             : documentation for details.  If the receiving socket is unconnected,\n\
    3274             : address is the address of the sending socket, if available; otherwise,\n\
    3275             : its value is unspecified.\n\
    3276             : \n\
    3277             : If recvmsg_into() raises an exception after the system call returns,\n\
    3278             : it will first attempt to close any file descriptors received via the\n\
    3279             : SCM_RIGHTS mechanism.");
    3280             : #endif    /* CMSG_LEN */
    3281             : 
    3282             : 
    3283             : /* s.send(data [,flags]) method */
    3284             : 
    3285             : static PyObject *
    3286           0 : sock_send(PySocketSockObject *s, PyObject *args)
    3287             : {
    3288             :     char *buf;
    3289           0 :     Py_ssize_t len, n = -1;
    3290           0 :     int flags = 0, timeout;
    3291             :     Py_buffer pbuf;
    3292             : 
    3293           0 :     if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags))
    3294           0 :         return NULL;
    3295             : 
    3296             :     if (!IS_SELECTABLE(s)) {
    3297             :         PyBuffer_Release(&pbuf);
    3298             :         return select_error();
    3299             :     }
    3300           0 :     buf = pbuf.buf;
    3301           0 :     len = pbuf.len;
    3302             : 
    3303           0 :     BEGIN_SELECT_LOOP(s)
    3304           0 :     Py_BEGIN_ALLOW_THREADS
    3305           0 :     timeout = internal_select_ex(s, 1, interval);
    3306           0 :     if (!timeout)
    3307             : #ifdef __VMS
    3308             :         n = sendsegmented(s->sock_fd, buf, len, flags);
    3309             : #else
    3310           0 :         n = send(s->sock_fd, buf, len, flags);
    3311             : #endif
    3312           0 :     Py_END_ALLOW_THREADS
    3313           0 :     if (timeout == 1) {
    3314           0 :         PyBuffer_Release(&pbuf);
    3315           0 :         PyErr_SetString(socket_timeout, "timed out");
    3316           0 :         return NULL;
    3317             :     }
    3318           0 :     END_SELECT_LOOP(s)
    3319             : 
    3320           0 :     PyBuffer_Release(&pbuf);
    3321           0 :     if (n < 0)
    3322           0 :         return s->errorhandler();
    3323           0 :     return PyLong_FromSsize_t(n);
    3324             : }
    3325             : 
    3326             : PyDoc_STRVAR(send_doc,
    3327             : "send(data[, flags]) -> count\n\
    3328             : \n\
    3329             : Send a data string to the socket.  For the optional flags\n\
    3330             : argument, see the Unix manual.  Return the number of bytes\n\
    3331             : sent; this may be less than len(data) if the network is busy.");
    3332             : 
    3333             : 
    3334             : /* s.sendall(data [,flags]) method */
    3335             : 
    3336             : static PyObject *
    3337           0 : sock_sendall(PySocketSockObject *s, PyObject *args)
    3338             : {
    3339             :     char *buf;
    3340           0 :     Py_ssize_t len, n = -1;
    3341           0 :     int flags = 0, timeout, saved_errno;
    3342             :     Py_buffer pbuf;
    3343             : 
    3344           0 :     if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags))
    3345           0 :         return NULL;
    3346           0 :     buf = pbuf.buf;
    3347           0 :     len = pbuf.len;
    3348             : 
    3349             :     if (!IS_SELECTABLE(s)) {
    3350             :         PyBuffer_Release(&pbuf);
    3351             :         return select_error();
    3352             :     }
    3353             : 
    3354             :     do {
    3355           0 :         Py_BEGIN_ALLOW_THREADS
    3356           0 :         timeout = internal_select(s, 1);
    3357           0 :         n = -1;
    3358           0 :         if (!timeout) {
    3359             : #ifdef __VMS
    3360             :             n = sendsegmented(s->sock_fd, buf, len, flags);
    3361             : #else
    3362           0 :             n = send(s->sock_fd, buf, len, flags);
    3363             : #endif
    3364             :         }
    3365           0 :         Py_END_ALLOW_THREADS
    3366           0 :         if (timeout == 1) {
    3367           0 :             PyBuffer_Release(&pbuf);
    3368           0 :             PyErr_SetString(socket_timeout, "timed out");
    3369           0 :             return NULL;
    3370             :         }
    3371             :         /* PyErr_CheckSignals() might change errno */
    3372           0 :         saved_errno = errno;
    3373             :         /* We must run our signal handlers before looping again.
    3374             :            send() can return a successful partial write when it is
    3375             :            interrupted, so we can't restrict ourselves to EINTR. */
    3376           0 :         if (PyErr_CheckSignals()) {
    3377           0 :             PyBuffer_Release(&pbuf);
    3378           0 :             return NULL;
    3379             :         }
    3380           0 :         if (n < 0) {
    3381             :             /* If interrupted, try again */
    3382           0 :             if (saved_errno == EINTR)
    3383           0 :                 continue;
    3384             :             else
    3385           0 :                 break;
    3386             :         }
    3387           0 :         buf += n;
    3388           0 :         len -= n;
    3389           0 :     } while (len > 0);
    3390           0 :     PyBuffer_Release(&pbuf);
    3391             : 
    3392           0 :     if (n < 0)
    3393           0 :         return s->errorhandler();
    3394             : 
    3395           0 :     Py_INCREF(Py_None);
    3396           0 :     return Py_None;
    3397             : }
    3398             : 
    3399             : PyDoc_STRVAR(sendall_doc,
    3400             : "sendall(data[, flags])\n\
    3401             : \n\
    3402             : Send a data string to the socket.  For the optional flags\n\
    3403             : argument, see the Unix manual.  This calls send() repeatedly\n\
    3404             : until all data is sent.  If an error occurs, it's impossible\n\
    3405             : to tell how much data has been sent.");
    3406             : 
    3407             : 
    3408             : /* s.sendto(data, [flags,] sockaddr) method */
    3409             : 
    3410             : static PyObject *
    3411           0 : sock_sendto(PySocketSockObject *s, PyObject *args)
    3412             : {
    3413             :     Py_buffer pbuf;
    3414             :     PyObject *addro;
    3415             :     char *buf;
    3416             :     Py_ssize_t len, arglen;
    3417             :     sock_addr_t addrbuf;
    3418           0 :     int addrlen, n = -1, flags, timeout;
    3419             : 
    3420           0 :     flags = 0;
    3421           0 :     arglen = PyTuple_Size(args);
    3422           0 :     switch (arglen) {
    3423             :         case 2:
    3424           0 :             PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro);
    3425           0 :             break;
    3426             :         case 3:
    3427           0 :             PyArg_ParseTuple(args, "y*iO:sendto",
    3428             :                              &pbuf, &flags, &addro);
    3429           0 :             break;
    3430             :         default:
    3431           0 :             PyErr_Format(PyExc_TypeError,
    3432             :                          "sendto() takes 2 or 3 arguments (%d given)",
    3433             :                          arglen);
    3434           0 :             return NULL;
    3435             :     }
    3436           0 :     if (PyErr_Occurred())
    3437           0 :         return NULL;
    3438             : 
    3439           0 :     buf = pbuf.buf;
    3440           0 :     len = pbuf.len;
    3441             : 
    3442             :     if (!IS_SELECTABLE(s)) {
    3443             :         PyBuffer_Release(&pbuf);
    3444             :         return select_error();
    3445             :     }
    3446             : 
    3447           0 :     if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
    3448           0 :         PyBuffer_Release(&pbuf);
    3449           0 :         return NULL;
    3450             :     }
    3451             : 
    3452           0 :     BEGIN_SELECT_LOOP(s)
    3453           0 :     Py_BEGIN_ALLOW_THREADS
    3454           0 :     timeout = internal_select_ex(s, 1, interval);
    3455           0 :     if (!timeout)
    3456           0 :         n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
    3457           0 :     Py_END_ALLOW_THREADS
    3458             : 
    3459           0 :     if (timeout == 1) {
    3460           0 :         PyBuffer_Release(&pbuf);
    3461           0 :         PyErr_SetString(socket_timeout, "timed out");
    3462           0 :         return NULL;
    3463             :     }
    3464           0 :     END_SELECT_LOOP(s)
    3465           0 :     PyBuffer_Release(&pbuf);
    3466           0 :     if (n < 0)
    3467           0 :         return s->errorhandler();
    3468           0 :     return PyLong_FromSsize_t(n);
    3469             : }
    3470             : 
    3471             : PyDoc_STRVAR(sendto_doc,
    3472             : "sendto(data[, flags], address) -> count\n\
    3473             : \n\
    3474             : Like send(data, flags) but allows specifying the destination address.\n\
    3475             : For IP sockets, the address is a pair (hostaddr, port).");
    3476             : 
    3477             : 
    3478             : /* The sendmsg() and recvmsg[_into]() methods require a working
    3479             :    CMSG_LEN().  See the comment near get_CMSG_LEN(). */
    3480             : #ifdef CMSG_LEN
    3481             : /* s.sendmsg(buffers[, ancdata[, flags[, address]]]) method */
    3482             : 
    3483             : static PyObject *
    3484           0 : sock_sendmsg(PySocketSockObject *s, PyObject *args)
    3485             : {
    3486           0 :     Py_ssize_t i, ndataparts, ndatabufs = 0, ncmsgs, ncmsgbufs = 0;
    3487           0 :     Py_buffer *databufs = NULL;
    3488           0 :     struct iovec *iovs = NULL;
    3489             :     sock_addr_t addrbuf;
    3490           0 :     struct msghdr msg = {0};
    3491             :     struct cmsginfo {
    3492             :         int level;
    3493             :         int type;
    3494             :         Py_buffer data;
    3495           0 :     } *cmsgs = NULL;
    3496           0 :     void *controlbuf = NULL;
    3497             :     size_t controllen, controllen_last;
    3498           0 :     ssize_t bytes_sent = -1;
    3499           0 :     int addrlen, timeout, flags = 0;
    3500           0 :     PyObject *data_arg, *cmsg_arg = NULL, *addr_arg = NULL, *data_fast = NULL,
    3501           0 :         *cmsg_fast = NULL, *retval = NULL;
    3502             : 
    3503           0 :     if (!PyArg_ParseTuple(args, "O|OiO:sendmsg",
    3504             :                           &data_arg, &cmsg_arg, &flags, &addr_arg))
    3505           0 :         return NULL;
    3506             : 
    3507             :     /* Parse destination address. */
    3508           0 :     if (addr_arg != NULL && addr_arg != Py_None) {
    3509           0 :         if (!getsockaddrarg(s, addr_arg, SAS2SA(&addrbuf), &addrlen))
    3510           0 :             goto finally;
    3511           0 :         msg.msg_name = &addrbuf;
    3512           0 :         msg.msg_namelen = addrlen;
    3513             :     }
    3514             : 
    3515             :     /* Fill in an iovec for each message part, and save the Py_buffer
    3516             :        structs to release afterwards. */
    3517           0 :     if ((data_fast = PySequence_Fast(data_arg,
    3518             :                                      "sendmsg() argument 1 must be an "
    3519             :                                      "iterable")) == NULL)
    3520           0 :         goto finally;
    3521           0 :     ndataparts = PySequence_Fast_GET_SIZE(data_fast);
    3522             :     if (ndataparts > INT_MAX) {
    3523             :         PyErr_SetString(PyExc_OSError, "sendmsg() argument 1 is too long");
    3524             :         goto finally;
    3525             :     }
    3526           0 :     msg.msg_iovlen = ndataparts;
    3527           0 :     if (ndataparts > 0 &&
    3528           0 :         ((msg.msg_iov = iovs = PyMem_New(struct iovec, ndataparts)) == NULL ||
    3529           0 :          (databufs = PyMem_New(Py_buffer, ndataparts)) == NULL)) {
    3530           0 :         PyErr_NoMemory();
    3531           0 :         goto finally;
    3532             :     }
    3533           0 :     for (; ndatabufs < ndataparts; ndatabufs++) {
    3534           0 :         if (!PyArg_Parse(PySequence_Fast_GET_ITEM(data_fast, ndatabufs),
    3535             :                          "y*;sendmsg() argument 1 must be an iterable of "
    3536             :                          "buffer-compatible objects",
    3537           0 :                          &databufs[ndatabufs]))
    3538           0 :             goto finally;
    3539           0 :         iovs[ndatabufs].iov_base = databufs[ndatabufs].buf;
    3540           0 :         iovs[ndatabufs].iov_len = databufs[ndatabufs].len;
    3541             :     }
    3542             : 
    3543           0 :     if (cmsg_arg == NULL)
    3544           0 :         ncmsgs = 0;
    3545             :     else {
    3546           0 :         if ((cmsg_fast = PySequence_Fast(cmsg_arg,
    3547             :                                          "sendmsg() argument 2 must be an "
    3548             :                                          "iterable")) == NULL)
    3549           0 :             goto finally;
    3550           0 :         ncmsgs = PySequence_Fast_GET_SIZE(cmsg_fast);
    3551             :     }
    3552             : 
    3553             : #ifndef CMSG_SPACE
    3554             :     if (ncmsgs > 1) {
    3555             :         PyErr_SetString(PyExc_OSError,
    3556             :                         "sending multiple control messages is not supported "
    3557             :                         "on this system");
    3558             :         goto finally;
    3559             :     }
    3560             : #endif
    3561             :     /* Save level, type and Py_buffer for each control message,
    3562             :        and calculate total size. */
    3563           0 :     if (ncmsgs > 0 && (cmsgs = PyMem_New(struct cmsginfo, ncmsgs)) == NULL) {
    3564           0 :         PyErr_NoMemory();
    3565           0 :         goto finally;
    3566             :     }
    3567           0 :     controllen = controllen_last = 0;
    3568           0 :     while (ncmsgbufs < ncmsgs) {
    3569             :         size_t bufsize, space;
    3570             : 
    3571           0 :         if (!PyArg_Parse(PySequence_Fast_GET_ITEM(cmsg_fast, ncmsgbufs),
    3572             :                          "(iiy*):[sendmsg() ancillary data items]",
    3573           0 :                          &cmsgs[ncmsgbufs].level,
    3574           0 :                          &cmsgs[ncmsgbufs].type,
    3575           0 :                          &cmsgs[ncmsgbufs].data))
    3576             :             goto finally;
    3577           0 :         bufsize = cmsgs[ncmsgbufs++].data.len;
    3578             : 
    3579             : #ifdef CMSG_SPACE
    3580           0 :         if (!get_CMSG_SPACE(bufsize, &space)) {
    3581             : #else
    3582             :         if (!get_CMSG_LEN(bufsize, &space)) {
    3583             : #endif
    3584           0 :             PyErr_SetString(PyExc_OSError, "ancillary data item too large");
    3585             :             goto finally;
    3586             :         }
    3587           0 :         controllen += space;
    3588           0 :         if (controllen > SOCKLEN_T_LIMIT || controllen < controllen_last) {
    3589           0 :             PyErr_SetString(PyExc_OSError, "too much ancillary data");
    3590             :             goto finally;
    3591             :         }
    3592           0 :         controllen_last = controllen;
    3593             :     }
    3594             : 
    3595             :     /* Construct ancillary data block from control message info. */
    3596           0 :     if (ncmsgbufs > 0) {
    3597           0 :         struct cmsghdr *cmsgh = NULL;
    3598             : 
    3599           0 :         if ((msg.msg_control = controlbuf =
    3600             :              PyMem_Malloc(controllen)) == NULL) {
    3601           0 :             PyErr_NoMemory();
    3602           0 :             goto finally;
    3603             :         }
    3604           0 :         msg.msg_controllen = controllen;
    3605             : 
    3606             :         /* Need to zero out the buffer as a workaround for glibc's
    3607             :            CMSG_NXTHDR() implementation.  After getting the pointer to
    3608             :            the next header, it checks its (uninitialized) cmsg_len
    3609             :            member to see if the "message" fits in the buffer, and
    3610             :            returns NULL if it doesn't.  Zero-filling the buffer
    3611             :            ensures that that doesn't happen. */
    3612           0 :         memset(controlbuf, 0, controllen);
    3613             : 
    3614           0 :         for (i = 0; i < ncmsgbufs; i++) {
    3615           0 :             size_t msg_len, data_len = cmsgs[i].data.len;
    3616           0 :             int enough_space = 0;
    3617             : 
    3618           0 :             cmsgh = (i == 0) ? CMSG_FIRSTHDR(&msg) : CMSG_NXTHDR(&msg, cmsgh);
    3619           0 :             if (cmsgh == NULL) {
    3620           0 :                 PyErr_Format(PyExc_RuntimeError,
    3621             :                              "unexpected NULL result from %s()",
    3622             :                              (i == 0) ? "CMSG_FIRSTHDR" : "CMSG_NXTHDR");
    3623             :                 goto finally;
    3624             :             }
    3625           0 :             if (!get_CMSG_LEN(data_len, &msg_len)) {
    3626           0 :                 PyErr_SetString(PyExc_RuntimeError,
    3627             :                                 "item size out of range for CMSG_LEN()");
    3628             :                 goto finally;
    3629             :             }
    3630           0 :             if (cmsg_min_space(&msg, cmsgh, msg_len)) {
    3631             :                 size_t space;
    3632             : 
    3633           0 :                 cmsgh->cmsg_len = msg_len;
    3634           0 :                 if (get_cmsg_data_space(&msg, cmsgh, &space))
    3635           0 :                     enough_space = (space >= data_len);
    3636             :             }
    3637           0 :             if (!enough_space) {
    3638           0 :                 PyErr_SetString(PyExc_RuntimeError,
    3639             :                                 "ancillary data does not fit in calculated "
    3640             :                                 "space");
    3641             :                 goto finally;
    3642             :             }
    3643           0 :             cmsgh->cmsg_level = cmsgs[i].level;
    3644           0 :             cmsgh->cmsg_type = cmsgs[i].type;
    3645           0 :             memcpy(CMSG_DATA(cmsgh), cmsgs[i].data.buf, data_len);
    3646             :         }
    3647             :     }
    3648             : 
    3649             :     /* Make the system call. */
    3650             :     if (!IS_SELECTABLE(s)) {
    3651             :         select_error();
    3652             :         goto finally;
    3653             :     }
    3654             : 
    3655           0 :     BEGIN_SELECT_LOOP(s)
    3656           0 :     Py_BEGIN_ALLOW_THREADS;
    3657           0 :     timeout = internal_select_ex(s, 1, interval);
    3658           0 :     if (!timeout)
    3659           0 :         bytes_sent = sendmsg(s->sock_fd, &msg, flags);
    3660           0 :     Py_END_ALLOW_THREADS;
    3661           0 :     if (timeout == 1) {
    3662           0 :         PyErr_SetString(socket_timeout, "timed out");
    3663             :         goto finally;
    3664             :     }
    3665           0 :     END_SELECT_LOOP(s)
    3666             : 
    3667           0 :     if (bytes_sent < 0) {
    3668           0 :         s->errorhandler();
    3669           0 :         goto finally;
    3670             :     }
    3671           0 :     retval = PyLong_FromSsize_t(bytes_sent);
    3672             : 
    3673             : finally:
    3674           0 :     PyMem_Free(controlbuf);
    3675           0 :     for (i = 0; i < ncmsgbufs; i++)
    3676           0 :         PyBuffer_Release(&cmsgs[i].data);
    3677           0 :     PyMem_Free(cmsgs);
    3678           0 :     Py_XDECREF(cmsg_fast);
    3679           0 :     for (i = 0; i < ndatabufs; i++)
    3680           0 :         PyBuffer_Release(&databufs[i]);
    3681           0 :     PyMem_Free(databufs);
    3682           0 :     PyMem_Free(iovs);
    3683           0 :     Py_XDECREF(data_fast);
    3684           0 :     return retval;
    3685             : }
    3686             : 
    3687             : PyDoc_STRVAR(sendmsg_doc,
    3688             : "sendmsg(buffers[, ancdata[, flags[, address]]]) -> count\n\
    3689             : \n\
    3690             : Send normal and ancillary data to the socket, gathering the\n\
    3691             : non-ancillary data from a series of buffers and concatenating it into\n\
    3692             : a single message.  The buffers argument specifies the non-ancillary\n\
    3693             : data as an iterable of buffer-compatible objects (e.g. bytes objects).\n\
    3694             : The ancdata argument specifies the ancillary data (control messages)\n\
    3695             : as an iterable of zero or more tuples (cmsg_level, cmsg_type,\n\
    3696             : cmsg_data), where cmsg_level and cmsg_type are integers specifying the\n\
    3697             : protocol level and protocol-specific type respectively, and cmsg_data\n\
    3698             : is a buffer-compatible object holding the associated data.  The flags\n\
    3699             : argument defaults to 0 and has the same meaning as for send().  If\n\
    3700             : address is supplied and not None, it sets a destination address for\n\
    3701             : the message.  The return value is the number of bytes of non-ancillary\n\
    3702             : data sent.");
    3703             : #endif    /* CMSG_LEN */
    3704             : 
    3705             : 
    3706             : /* s.shutdown(how) method */
    3707             : 
    3708             : static PyObject *
    3709           0 : sock_shutdown(PySocketSockObject *s, PyObject *arg)
    3710             : {
    3711             :     int how;
    3712             :     int res;
    3713             : 
    3714           0 :     how = PyLong_AsLong(arg);
    3715           0 :     if (how == -1 && PyErr_Occurred())
    3716           0 :         return NULL;
    3717           0 :     Py_BEGIN_ALLOW_THREADS
    3718           0 :     res = shutdown(s->sock_fd, how);
    3719           0 :     Py_END_ALLOW_THREADS
    3720           0 :     if (res < 0)
    3721           0 :         return s->errorhandler();
    3722           0 :     Py_INCREF(Py_None);
    3723           0 :     return Py_None;
    3724             : }
    3725             : 
    3726             : PyDoc_STRVAR(shutdown_doc,
    3727             : "shutdown(flag)\n\
    3728             : \n\
    3729             : Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
    3730             : of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
    3731             : 
    3732             : #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
    3733             : static PyObject*
    3734             : sock_ioctl(PySocketSockObject *s, PyObject *arg)
    3735             : {
    3736             :     unsigned long cmd = SIO_RCVALL;
    3737             :     PyObject *argO;
    3738             :     DWORD recv;
    3739             : 
    3740             :     if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
    3741             :         return NULL;
    3742             : 
    3743             :     switch (cmd) {
    3744             :     case SIO_RCVALL: {
    3745             :         unsigned int option = RCVALL_ON;
    3746             :         if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
    3747             :             return NULL;
    3748             :         if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
    3749             :                          NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
    3750             :             return set_error();
    3751             :         }
    3752             :         return PyLong_FromUnsignedLong(recv); }
    3753             :     case SIO_KEEPALIVE_VALS: {
    3754             :         struct tcp_keepalive ka;
    3755             :         if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
    3756             :                         &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
    3757             :             return NULL;
    3758             :         if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
    3759             :                          NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
    3760             :             return set_error();
    3761             :         }
    3762             :         return PyLong_FromUnsignedLong(recv); }
    3763             :     default:
    3764             :         PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd);
    3765             :         return NULL;
    3766             :     }
    3767             : }
    3768             : PyDoc_STRVAR(sock_ioctl_doc,
    3769             : "ioctl(cmd, option) -> long\n\
    3770             : \n\
    3771             : Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
    3772             : SIO_RCVALL:  'option' must be one of the socket.RCVALL_* constants.\n\
    3773             : SIO_KEEPALIVE_VALS:  'option' is a tuple of (onoff, timeout, interval).");
    3774             : #endif
    3775             : 
    3776             : #if defined(MS_WINDOWS)
    3777             : static PyObject*
    3778             : sock_share(PySocketSockObject *s, PyObject *arg)
    3779             : {
    3780             :     WSAPROTOCOL_INFO info;
    3781             :     DWORD processId;
    3782             :     int result;
    3783             : 
    3784             :     if (!PyArg_ParseTuple(arg, "I", &processId))
    3785             :         return NULL;
    3786             : 
    3787             :     Py_BEGIN_ALLOW_THREADS
    3788             :     result = WSADuplicateSocket(s->sock_fd, processId, &info);
    3789             :     Py_END_ALLOW_THREADS
    3790             :     if (result == SOCKET_ERROR)
    3791             :         return set_error();
    3792             :     return PyBytes_FromStringAndSize((const char*)&info, sizeof(info));
    3793             : }
    3794             : PyDoc_STRVAR(sock_share_doc,
    3795             : "share(process_id) -> bytes\n\
    3796             : \n\
    3797             : Share the socket with another process.  The target process id\n\
    3798             : must be provided and the resulting bytes object passed to the target\n\
    3799             : process.  There the shared socket can be instantiated by calling\n\
    3800             : socket.fromshare().");
    3801             : 
    3802             : 
    3803             : #endif
    3804             : 
    3805             : /* List of methods for socket objects */
    3806             : 
    3807             : static PyMethodDef sock_methods[] = {
    3808             :     {"_accept",           (PyCFunction)sock_accept, METH_NOARGS,
    3809             :                       accept_doc},
    3810             :     {"bind",              (PyCFunction)sock_bind, METH_O,
    3811             :                       bind_doc},
    3812             :     {"close",             (PyCFunction)sock_close, METH_NOARGS,
    3813             :                       close_doc},
    3814             :     {"connect",           (PyCFunction)sock_connect, METH_O,
    3815             :                       connect_doc},
    3816             :     {"connect_ex",        (PyCFunction)sock_connect_ex, METH_O,
    3817             :                       connect_ex_doc},
    3818             :     {"detach",            (PyCFunction)sock_detach, METH_NOARGS,
    3819             :                       detach_doc},
    3820             :     {"fileno",            (PyCFunction)sock_fileno, METH_NOARGS,
    3821             :                       fileno_doc},
    3822             : #ifdef HAVE_GETPEERNAME
    3823             :     {"getpeername",       (PyCFunction)sock_getpeername,
    3824             :                       METH_NOARGS, getpeername_doc},
    3825             : #endif
    3826             :     {"getsockname",       (PyCFunction)sock_getsockname,
    3827             :                       METH_NOARGS, getsockname_doc},
    3828             :     {"getsockopt",        (PyCFunction)sock_getsockopt, METH_VARARGS,
    3829             :                       getsockopt_doc},
    3830             : #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
    3831             :     {"ioctl",             (PyCFunction)sock_ioctl, METH_VARARGS,
    3832             :                       sock_ioctl_doc},
    3833             : #endif
    3834             : #if defined(MS_WINDOWS)
    3835             :     {"share",         (PyCFunction)sock_share, METH_VARARGS,
    3836             :                       sock_share_doc},
    3837             : #endif
    3838             :     {"listen",            (PyCFunction)sock_listen, METH_O,
    3839             :                       listen_doc},
    3840             :     {"recv",              (PyCFunction)sock_recv, METH_VARARGS,
    3841             :                       recv_doc},
    3842             :     {"recv_into",         (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
    3843             :                       recv_into_doc},
    3844             :     {"recvfrom",          (PyCFunction)sock_recvfrom, METH_VARARGS,
    3845             :                       recvfrom_doc},
    3846             :     {"recvfrom_into",  (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
    3847             :                       recvfrom_into_doc},
    3848             :     {"send",              (PyCFunction)sock_send, METH_VARARGS,
    3849             :                       send_doc},
    3850             :     {"sendall",           (PyCFunction)sock_sendall, METH_VARARGS,
    3851             :                       sendall_doc},
    3852             :     {"sendto",            (PyCFunction)sock_sendto, METH_VARARGS,
    3853             :                       sendto_doc},
    3854             :     {"setblocking",       (PyCFunction)sock_setblocking, METH_O,
    3855             :                       setblocking_doc},
    3856             :     {"settimeout",    (PyCFunction)sock_settimeout, METH_O,
    3857             :                       settimeout_doc},
    3858             :     {"gettimeout",    (PyCFunction)sock_gettimeout, METH_NOARGS,
    3859             :                       gettimeout_doc},
    3860             :     {"setsockopt",        (PyCFunction)sock_setsockopt, METH_VARARGS,
    3861             :                       setsockopt_doc},
    3862             :     {"shutdown",          (PyCFunction)sock_shutdown, METH_O,
    3863             :                       shutdown_doc},
    3864             : #ifdef CMSG_LEN
    3865             :     {"recvmsg",           (PyCFunction)sock_recvmsg, METH_VARARGS,
    3866             :                       recvmsg_doc},
    3867             :     {"recvmsg_into",      (PyCFunction)sock_recvmsg_into, METH_VARARGS,
    3868             :                       recvmsg_into_doc,},
    3869             :     {"sendmsg",           (PyCFunction)sock_sendmsg, METH_VARARGS,
    3870             :                       sendmsg_doc},
    3871             : #endif
    3872             :     {NULL,                      NULL}           /* sentinel */
    3873             : };
    3874             : 
    3875             : /* SockObject members */
    3876             : static PyMemberDef sock_memberlist[] = {
    3877             :        {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
    3878             :        {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
    3879             :        {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
    3880             :        {"timeout", T_DOUBLE, offsetof(PySocketSockObject, sock_timeout), READONLY, "the socket timeout"},
    3881             :        {0},
    3882             : };
    3883             : 
    3884             : /* Deallocate a socket object in response to the last Py_DECREF().
    3885             :    First close the file description. */
    3886             : 
    3887             : static void
    3888           0 : sock_dealloc(PySocketSockObject *s)
    3889             : {
    3890           0 :     if (s->sock_fd != -1) {
    3891             :         PyObject *exc, *val, *tb;
    3892           0 :         Py_ssize_t old_refcount = Py_REFCNT(s);
    3893           0 :         ++Py_REFCNT(s);
    3894           0 :         PyErr_Fetch(&exc, &val, &tb);
    3895           0 :         if (PyErr_WarnFormat(PyExc_ResourceWarning, 1,
    3896             :                              "unclosed %R", s))
    3897             :             /* Spurious errors can appear at shutdown */
    3898           0 :             if (PyErr_ExceptionMatches(PyExc_Warning))
    3899           0 :                 PyErr_WriteUnraisable((PyObject *) s);
    3900           0 :         PyErr_Restore(exc, val, tb);
    3901           0 :         (void) SOCKETCLOSE(s->sock_fd);
    3902           0 :         Py_REFCNT(s) = old_refcount;
    3903             :     }
    3904           0 :     Py_TYPE(s)->tp_free((PyObject *)s);
    3905           0 : }
    3906             : 
    3907             : 
    3908             : static PyObject *
    3909           0 : sock_repr(PySocketSockObject *s)
    3910             : {
    3911             : #if SIZEOF_SOCKET_T > SIZEOF_LONG
    3912             :     if (s->sock_fd > LONG_MAX) {
    3913             :         /* this can occur on Win64, and actually there is a special
    3914             :            ugly printf formatter for decimal pointer length integer
    3915             :            printing, only bother if necessary*/
    3916             :         PyErr_SetString(PyExc_OverflowError,
    3917             :                         "no printf formatter to display "
    3918             :                         "the socket descriptor in decimal");
    3919             :         return NULL;
    3920             :     }
    3921             : #endif
    3922           0 :     return PyUnicode_FromFormat(
    3923             :         "<socket object, fd=%ld, family=%d, type=%d, proto=%d>",
    3924           0 :         (long)s->sock_fd, s->sock_family,
    3925             :         s->sock_type,
    3926             :         s->sock_proto);
    3927             : }
    3928             : 
    3929             : 
    3930             : /* Create a new, uninitialized socket object. */
    3931             : 
    3932             : static PyObject *
    3933           0 : sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    3934             : {
    3935             :     PyObject *new;
    3936             : 
    3937           0 :     new = type->tp_alloc(type, 0);
    3938           0 :     if (new != NULL) {
    3939           0 :         ((PySocketSockObject *)new)->sock_fd = -1;
    3940           0 :         ((PySocketSockObject *)new)->sock_timeout = -1.0;
    3941           0 :         ((PySocketSockObject *)new)->errorhandler = &set_error;
    3942             :     }
    3943           0 :     return new;
    3944             : }
    3945             : 
    3946             : 
    3947             : /* Initialize a new socket object. */
    3948             : 
    3949             : /*ARGSUSED*/
    3950             : static int
    3951           0 : sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
    3952             : {
    3953           0 :     PySocketSockObject *s = (PySocketSockObject *)self;
    3954           0 :     PyObject *fdobj = NULL;
    3955           0 :     SOCKET_T fd = INVALID_SOCKET;
    3956           0 :     int family = AF_INET, type = SOCK_STREAM, proto = 0;
    3957             :     static char *keywords[] = {"family", "type", "proto", "fileno", 0};
    3958             : 
    3959           0 :     if (!PyArg_ParseTupleAndKeywords(args, kwds,
    3960             :                                      "|iiiO:socket", keywords,
    3961             :                                      &family, &type, &proto, &fdobj))
    3962           0 :         return -1;
    3963             : 
    3964           0 :     if (fdobj != NULL && fdobj != Py_None) {
    3965             : #ifdef MS_WINDOWS
    3966             :         /* recreate a socket that was duplicated */
    3967             :         if (PyBytes_Check(fdobj)) {
    3968             :             WSAPROTOCOL_INFO info;
    3969             :             if (PyBytes_GET_SIZE(fdobj) != sizeof(info)) {
    3970             :                 PyErr_Format(PyExc_ValueError,
    3971             :                     "socket descriptor string has wrong size, "
    3972             :                     "should be %zu bytes.", sizeof(info));
    3973             :                 return -1;
    3974             :             }
    3975             :             memcpy(&info, PyBytes_AS_STRING(fdobj), sizeof(info));
    3976             :             Py_BEGIN_ALLOW_THREADS
    3977             :             fd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
    3978             :                      FROM_PROTOCOL_INFO, &info, 0, WSA_FLAG_OVERLAPPED);
    3979             :             Py_END_ALLOW_THREADS
    3980             :             if (fd == INVALID_SOCKET) {
    3981             :                 set_error();
    3982             :                 return -1;
    3983             :             }
    3984             :             family = info.iAddressFamily;
    3985             :             type = info.iSocketType;
    3986             :             proto = info.iProtocol;
    3987             :         }
    3988             :         else
    3989             : #endif
    3990             :         {
    3991           0 :             fd = PyLong_AsSocket_t(fdobj);
    3992           0 :             if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
    3993           0 :                 return -1;
    3994           0 :             if (fd == INVALID_SOCKET) {
    3995           0 :                 PyErr_SetString(PyExc_ValueError,
    3996             :                                 "can't use invalid socket value");
    3997           0 :                 return -1;
    3998             :             }
    3999             :         }
    4000             :     }
    4001             :     else {
    4002           0 :         Py_BEGIN_ALLOW_THREADS
    4003           0 :         fd = socket(family, type, proto);
    4004           0 :         Py_END_ALLOW_THREADS
    4005             : 
    4006           0 :         if (fd == INVALID_SOCKET) {
    4007           0 :             set_error();
    4008           0 :             return -1;
    4009             :         }
    4010             :     }
    4011           0 :     init_sockobject(s, fd, family, type, proto);
    4012             : 
    4013           0 :     return 0;
    4014             : 
    4015             : }
    4016             : 
    4017             : 
    4018             : /* Type object for socket objects. */
    4019             : 
    4020             : static PyTypeObject sock_type = {
    4021             :     PyVarObject_HEAD_INIT(0, 0)         /* Must fill in type value later */
    4022             :     "_socket.socket",                           /* tp_name */
    4023             :     sizeof(PySocketSockObject),                 /* tp_basicsize */
    4024             :     0,                                          /* tp_itemsize */
    4025             :     (destructor)sock_dealloc,                   /* tp_dealloc */
    4026             :     0,                                          /* tp_print */
    4027             :     0,                                          /* tp_getattr */
    4028             :     0,                                          /* tp_setattr */
    4029             :     0,                                          /* tp_reserved */
    4030             :     (reprfunc)sock_repr,                        /* tp_repr */
    4031             :     0,                                          /* tp_as_number */
    4032             :     0,                                          /* tp_as_sequence */
    4033             :     0,                                          /* tp_as_mapping */
    4034             :     0,                                          /* tp_hash */
    4035             :     0,                                          /* tp_call */
    4036             :     0,                                          /* tp_str */
    4037             :     PyObject_GenericGetAttr,                    /* tp_getattro */
    4038             :     0,                                          /* tp_setattro */
    4039             :     0,                                          /* tp_as_buffer */
    4040             :     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
    4041             :     sock_doc,                                   /* tp_doc */
    4042             :     0,                                          /* tp_traverse */
    4043             :     0,                                          /* tp_clear */
    4044             :     0,                                          /* tp_richcompare */
    4045             :     0,                                          /* tp_weaklistoffset */
    4046             :     0,                                          /* tp_iter */
    4047             :     0,                                          /* tp_iternext */
    4048             :     sock_methods,                               /* tp_methods */
    4049             :     sock_memberlist,                            /* tp_members */
    4050             :     0,                                          /* tp_getset */
    4051             :     0,                                          /* tp_base */
    4052             :     0,                                          /* tp_dict */
    4053             :     0,                                          /* tp_descr_get */
    4054             :     0,                                          /* tp_descr_set */
    4055             :     0,                                          /* tp_dictoffset */
    4056             :     sock_initobj,                               /* tp_init */
    4057             :     PyType_GenericAlloc,                        /* tp_alloc */
    4058             :     sock_new,                                   /* tp_new */
    4059             :     PyObject_Del,                               /* tp_free */
    4060             : };
    4061             : 
    4062             : 
    4063             : /* Python interface to gethostname(). */
    4064             : 
    4065             : /*ARGSUSED*/
    4066             : static PyObject *
    4067           0 : socket_gethostname(PyObject *self, PyObject *unused)
    4068             : {
    4069             : #ifdef MS_WINDOWS
    4070             :     /* Don't use winsock's gethostname, as this returns the ANSI
    4071             :        version of the hostname, whereas we need a Unicode string.
    4072             :        Otherwise, gethostname apparently also returns the DNS name. */
    4073             :     wchar_t buf[MAX_COMPUTERNAME_LENGTH + 1];
    4074             :     DWORD size = Py_ARRAY_LENGTH(buf);
    4075             :     wchar_t *name;
    4076             :     PyObject *result;
    4077             : 
    4078             :     if (GetComputerNameExW(ComputerNamePhysicalDnsHostname, buf, &size))
    4079             :         return PyUnicode_FromWideChar(buf, size);
    4080             : 
    4081             :     if (GetLastError() != ERROR_MORE_DATA)
    4082             :         return PyErr_SetFromWindowsErr(0);
    4083             : 
    4084             :     if (size == 0)
    4085             :         return PyUnicode_New(0, 0);
    4086             : 
    4087             :     /* MSDN says ERROR_MORE_DATA may occur because DNS allows longer
    4088             :        names */
    4089             :     name = PyMem_Malloc(size * sizeof(wchar_t));
    4090             :     if (!name)
    4091             :         return NULL;
    4092             :     if (!GetComputerNameExW(ComputerNamePhysicalDnsHostname,
    4093             :                            name,
    4094             :                            &size))
    4095             :     {
    4096             :         PyMem_Free(name);
    4097             :         return PyErr_SetFromWindowsErr(0);
    4098             :     }
    4099             : 
    4100             :     result = PyUnicode_FromWideChar(name, size);
    4101             :     PyMem_Free(name);
    4102             :     return result;
    4103             : #else
    4104             :     char buf[1024];
    4105             :     int res;
    4106           0 :     Py_BEGIN_ALLOW_THREADS
    4107           0 :     res = gethostname(buf, (int) sizeof buf - 1);
    4108           0 :     Py_END_ALLOW_THREADS
    4109           0 :     if (res < 0)
    4110           0 :         return set_error();
    4111           0 :     buf[sizeof buf - 1] = '\0';
    4112           0 :     return PyUnicode_FromString(buf);
    4113             : #endif
    4114             : }
    4115             : 
    4116             : PyDoc_STRVAR(gethostname_doc,
    4117             : "gethostname() -> string\n\
    4118             : \n\
    4119             : Return the current host name.");
    4120             : 
    4121             : #ifdef HAVE_SETHOSTNAME
    4122             : PyDoc_STRVAR(sethostname_doc,
    4123             : "sethostname(name)\n\n\
    4124             : Sets the hostname to name.");
    4125             : 
    4126             : static PyObject *
    4127           0 : socket_sethostname(PyObject *self, PyObject *args)
    4128             : {
    4129             :     PyObject *hnobj;
    4130             :     Py_buffer buf;
    4131           0 :     int res, flag = 0;
    4132             : 
    4133           0 :     if (!PyArg_ParseTuple(args, "S:sethostname", &hnobj)) {
    4134           0 :         PyErr_Clear();
    4135           0 :         if (!PyArg_ParseTuple(args, "O&:sethostname",
    4136             :                 PyUnicode_FSConverter, &hnobj))
    4137           0 :             return NULL;
    4138           0 :         flag = 1;
    4139             :     }
    4140           0 :     res = PyObject_GetBuffer(hnobj, &buf, PyBUF_SIMPLE);
    4141           0 :     if (!res) {
    4142           0 :         res = sethostname(buf.buf, buf.len);
    4143           0 :         PyBuffer_Release(&buf);
    4144             :     }
    4145           0 :     if (flag)
    4146           0 :         Py_DECREF(hnobj);
    4147           0 :     if (res)
    4148           0 :         return set_error();
    4149           0 :     Py_RETURN_NONE;
    4150             : }
    4151             : #endif
    4152             : 
    4153             : /* Python interface to gethostbyname(name). */
    4154             : 
    4155             : /*ARGSUSED*/
    4156             : static PyObject *
    4157           0 : socket_gethostbyname(PyObject *self, PyObject *args)
    4158             : {
    4159             :     char *name;
    4160             :     sock_addr_t addrbuf;
    4161           0 :     PyObject *ret = NULL;
    4162             : 
    4163           0 :     if (!PyArg_ParseTuple(args, "et:gethostbyname", "idna", &name))
    4164           0 :         return NULL;
    4165           0 :     if (setipaddr(name, SAS2SA(&addrbuf),  sizeof(addrbuf), AF_INET) < 0)
    4166           0 :         goto finally;
    4167           0 :     ret = makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
    4168             : finally:
    4169           0 :     PyMem_Free(name);
    4170           0 :     return ret;
    4171             : }
    4172             : 
    4173             : PyDoc_STRVAR(gethostbyname_doc,
    4174             : "gethostbyname(host) -> address\n\
    4175             : \n\
    4176             : Return the IP address (a string of the form '255.255.255.255') for a host.");
    4177             : 
    4178             : 
    4179             : /* Convenience function common to gethostbyname_ex and gethostbyaddr */
    4180             : 
    4181             : static PyObject *
    4182           0 : gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
    4183             : {
    4184             :     char **pch;
    4185           0 :     PyObject *rtn_tuple = (PyObject *)NULL;
    4186           0 :     PyObject *name_list = (PyObject *)NULL;
    4187           0 :     PyObject *addr_list = (PyObject *)NULL;
    4188             :     PyObject *tmp;
    4189             : 
    4190           0 :     if (h == NULL) {
    4191             :         /* Let's get real error message to return */
    4192           0 :         set_herror(h_errno);
    4193           0 :         return NULL;
    4194             :     }
    4195             : 
    4196           0 :     if (h->h_addrtype != af) {
    4197             :         /* Let's get real error message to return */
    4198           0 :         errno = EAFNOSUPPORT;
    4199           0 :         PyErr_SetFromErrno(PyExc_OSError);
    4200           0 :         return NULL;
    4201             :     }
    4202             : 
    4203           0 :     switch (af) {
    4204             : 
    4205             :     case AF_INET:
    4206           0 :         if (alen < sizeof(struct sockaddr_in))
    4207           0 :             return NULL;
    4208           0 :         break;
    4209             : 
    4210             : #ifdef ENABLE_IPV6
    4211             :     case AF_INET6:
    4212           0 :         if (alen < sizeof(struct sockaddr_in6))
    4213           0 :             return NULL;
    4214           0 :         break;
    4215             : #endif
    4216             : 
    4217             :     }
    4218             : 
    4219           0 :     if ((name_list = PyList_New(0)) == NULL)
    4220           0 :         goto err;
    4221             : 
    4222           0 :     if ((addr_list = PyList_New(0)) == NULL)
    4223           0 :         goto err;
    4224             : 
    4225             :     /* SF #1511317: h_aliases can be NULL */
    4226           0 :     if (h->h_aliases) {
    4227           0 :         for (pch = h->h_aliases; *pch != NULL; pch++) {
    4228             :             int status;
    4229           0 :             tmp = PyUnicode_FromString(*pch);
    4230           0 :             if (tmp == NULL)
    4231           0 :                 goto err;
    4232             : 
    4233           0 :             status = PyList_Append(name_list, tmp);
    4234           0 :             Py_DECREF(tmp);
    4235             : 
    4236           0 :             if (status)
    4237           0 :                 goto err;
    4238             :         }
    4239             :     }
    4240             : 
    4241           0 :     for (pch = h->h_addr_list; *pch != NULL; pch++) {
    4242             :         int status;
    4243             : 
    4244           0 :         switch (af) {
    4245             : 
    4246             :         case AF_INET:
    4247             :             {
    4248             :             struct sockaddr_in sin;
    4249           0 :             memset(&sin, 0, sizeof(sin));
    4250           0 :             sin.sin_family = af;
    4251             : #ifdef HAVE_SOCKADDR_SA_LEN
    4252             :             sin.sin_len = sizeof(sin);
    4253             : #endif
    4254           0 :             memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
    4255           0 :             tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
    4256             : 
    4257           0 :             if (pch == h->h_addr_list && alen >= sizeof(sin))
    4258           0 :                 memcpy((char *) addr, &sin, sizeof(sin));
    4259             :             break;
    4260             :             }
    4261             : 
    4262             : #ifdef ENABLE_IPV6
    4263             :         case AF_INET6:
    4264             :             {
    4265             :             struct sockaddr_in6 sin6;
    4266           0 :             memset(&sin6, 0, sizeof(sin6));
    4267           0 :             sin6.sin6_family = af;
    4268             : #ifdef HAVE_SOCKADDR_SA_LEN
    4269             :             sin6.sin6_len = sizeof(sin6);
    4270             : #endif
    4271           0 :             memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
    4272           0 :             tmp = makeipaddr((struct sockaddr *)&sin6,
    4273             :                 sizeof(sin6));
    4274             : 
    4275           0 :             if (pch == h->h_addr_list && alen >= sizeof(sin6))
    4276           0 :                 memcpy((char *) addr, &sin6, sizeof(sin6));
    4277             :             break;
    4278             :             }
    4279             : #endif
    4280             : 
    4281             :         default:                /* can't happen */
    4282           0 :             PyErr_SetString(PyExc_OSError,
    4283             :                             "unsupported address family");
    4284           0 :             return NULL;
    4285             :         }
    4286             : 
    4287           0 :         if (tmp == NULL)
    4288           0 :             goto err;
    4289             : 
    4290           0 :         status = PyList_Append(addr_list, tmp);
    4291           0 :         Py_DECREF(tmp);
    4292             : 
    4293           0 :         if (status)
    4294           0 :             goto err;
    4295             :     }
    4296             : 
    4297           0 :     rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
    4298             : 
    4299             :  err:
    4300           0 :     Py_XDECREF(name_list);
    4301           0 :     Py_XDECREF(addr_list);
    4302           0 :     return rtn_tuple;
    4303             : }
    4304             : 
    4305             : 
    4306             : /* Python interface to gethostbyname_ex(name). */
    4307             : 
    4308             : /*ARGSUSED*/
    4309             : static PyObject *
    4310           0 : socket_gethostbyname_ex(PyObject *self, PyObject *args)
    4311             : {
    4312             :     char *name;
    4313             :     struct hostent *h;
    4314             :     sock_addr_t addr;
    4315             :     struct sockaddr *sa;
    4316           0 :     PyObject *ret = NULL;
    4317             : #ifdef HAVE_GETHOSTBYNAME_R
    4318             :     struct hostent hp_allocated;
    4319             : #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
    4320             :     struct hostent_data data;
    4321             : #else
    4322             :     char buf[16384];
    4323           0 :     int buf_len = (sizeof buf) - 1;
    4324             :     int errnop;
    4325             : #endif
    4326             : #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
    4327             :     int result;
    4328             : #endif
    4329             : #endif /* HAVE_GETHOSTBYNAME_R */
    4330             : 
    4331           0 :     if (!PyArg_ParseTuple(args, "et:gethostbyname_ex", "idna", &name))
    4332           0 :         return NULL;
    4333           0 :     if (setipaddr(name, SAS2SA(&addr), sizeof(addr), AF_INET) < 0)
    4334           0 :         goto finally;
    4335           0 :     Py_BEGIN_ALLOW_THREADS
    4336             : #ifdef HAVE_GETHOSTBYNAME_R
    4337             : #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
    4338           0 :     gethostbyname_r(name, &hp_allocated, buf, buf_len,
    4339             :                              &h, &errnop);
    4340             : #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
    4341             :     h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
    4342             : #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
    4343             :     memset((void *) &data, '\0', sizeof(data));
    4344             :     result = gethostbyname_r(name, &hp_allocated, &data);
    4345             :     h = (result != 0) ? NULL : &hp_allocated;
    4346             : #endif
    4347             : #else /* not HAVE_GETHOSTBYNAME_R */
    4348             : #ifdef USE_GETHOSTBYNAME_LOCK
    4349             :     PyThread_acquire_lock(netdb_lock, 1);
    4350             : #endif
    4351             :     h = gethostbyname(name);
    4352             : #endif /* HAVE_GETHOSTBYNAME_R */
    4353           0 :     Py_END_ALLOW_THREADS
    4354             :     /* Some C libraries would require addr.__ss_family instead of
    4355             :        addr.ss_family.
    4356             :        Therefore, we cast the sockaddr_storage into sockaddr to
    4357             :        access sa_family. */
    4358           0 :     sa = SAS2SA(&addr);
    4359           0 :     ret = gethost_common(h, SAS2SA(&addr), sizeof(addr),
    4360           0 :                          sa->sa_family);
    4361             : #ifdef USE_GETHOSTBYNAME_LOCK
    4362             :     PyThread_release_lock(netdb_lock);
    4363             : #endif
    4364             : finally:
    4365           0 :     PyMem_Free(name);
    4366           0 :     return ret;
    4367             : }
    4368             : 
    4369             : PyDoc_STRVAR(ghbn_ex_doc,
    4370             : "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
    4371             : \n\
    4372             : Return the true host name, a list of aliases, and a list of IP addresses,\n\
    4373             : for a host.  The host argument is a string giving a host name or IP number.");
    4374             : 
    4375             : 
    4376             : /* Python interface to gethostbyaddr(IP). */
    4377             : 
    4378             : /*ARGSUSED*/
    4379             : static PyObject *
    4380           0 : socket_gethostbyaddr(PyObject *self, PyObject *args)
    4381             : {
    4382             :     sock_addr_t addr;
    4383           0 :     struct sockaddr *sa = SAS2SA(&addr);
    4384             :     char *ip_num;
    4385             :     struct hostent *h;
    4386           0 :     PyObject *ret = NULL;
    4387             : #ifdef HAVE_GETHOSTBYNAME_R
    4388             :     struct hostent hp_allocated;
    4389             : #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
    4390             :     struct hostent_data data;
    4391             : #else
    4392             :     /* glibcs up to 2.10 assume that the buf argument to
    4393             :        gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
    4394             :        does not ensure. The attribute below instructs the compiler
    4395             :        to maintain this alignment. */
    4396             :     char buf[16384] Py_ALIGNED(8);
    4397           0 :     int buf_len = (sizeof buf) - 1;
    4398             :     int errnop;
    4399             : #endif
    4400             : #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
    4401             :     int result;
    4402             : #endif
    4403             : #endif /* HAVE_GETHOSTBYNAME_R */
    4404             :     char *ap;
    4405             :     int al;
    4406             :     int af;
    4407             : 
    4408           0 :     if (!PyArg_ParseTuple(args, "et:gethostbyaddr", "idna", &ip_num))
    4409           0 :         return NULL;
    4410           0 :     af = AF_UNSPEC;
    4411           0 :     if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
    4412           0 :         goto finally;
    4413           0 :     af = sa->sa_family;
    4414           0 :     ap = NULL;
    4415             :     /* al = 0; */
    4416           0 :     switch (af) {
    4417             :     case AF_INET:
    4418           0 :         ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
    4419           0 :         al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
    4420           0 :         break;
    4421             : #ifdef ENABLE_IPV6
    4422             :     case AF_INET6:
    4423           0 :         ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
    4424           0 :         al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
    4425           0 :         break;
    4426             : #endif
    4427             :     default:
    4428           0 :         PyErr_SetString(PyExc_OSError, "unsupported address family");
    4429           0 :         goto finally;
    4430             :     }
    4431           0 :     Py_BEGIN_ALLOW_THREADS
    4432             : #ifdef HAVE_GETHOSTBYNAME_R
    4433             : #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
    4434           0 :     gethostbyaddr_r(ap, al, af,
    4435             :         &hp_allocated, buf, buf_len,
    4436             :         &h, &errnop);
    4437             : #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
    4438             :     h = gethostbyaddr_r(ap, al, af,
    4439             :                         &hp_allocated, buf, buf_len, &errnop);
    4440             : #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
    4441             :     memset((void *) &data, '\0', sizeof(data));
    4442             :     result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
    4443             :     h = (result != 0) ? NULL : &hp_allocated;
    4444             : #endif
    4445             : #else /* not HAVE_GETHOSTBYNAME_R */
    4446             : #ifdef USE_GETHOSTBYNAME_LOCK
    4447             :     PyThread_acquire_lock(netdb_lock, 1);
    4448             : #endif
    4449             :     h = gethostbyaddr(ap, al, af);
    4450             : #endif /* HAVE_GETHOSTBYNAME_R */
    4451           0 :     Py_END_ALLOW_THREADS
    4452           0 :     ret = gethost_common(h, SAS2SA(&addr), sizeof(addr), af);
    4453             : #ifdef USE_GETHOSTBYNAME_LOCK
    4454             :     PyThread_release_lock(netdb_lock);
    4455             : #endif
    4456             : finally:
    4457           0 :     PyMem_Free(ip_num);
    4458           0 :     return ret;
    4459             : }
    4460             : 
    4461             : PyDoc_STRVAR(gethostbyaddr_doc,
    4462             : "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
    4463             : \n\
    4464             : Return the true host name, a list of aliases, and a list of IP addresses,\n\
    4465             : for a host.  The host argument is a string giving a host name or IP number.");
    4466             : 
    4467             : 
    4468             : /* Python interface to getservbyname(name).
    4469             :    This only returns the port number, since the other info is already
    4470             :    known or not useful (like the list of aliases). */
    4471             : 
    4472             : /*ARGSUSED*/
    4473             : static PyObject *
    4474           0 : socket_getservbyname(PyObject *self, PyObject *args)
    4475             : {
    4476           0 :     char *name, *proto=NULL;
    4477             :     struct servent *sp;
    4478           0 :     if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
    4479           0 :         return NULL;
    4480           0 :     Py_BEGIN_ALLOW_THREADS
    4481           0 :     sp = getservbyname(name, proto);
    4482           0 :     Py_END_ALLOW_THREADS
    4483           0 :     if (sp == NULL) {
    4484           0 :         PyErr_SetString(PyExc_OSError, "service/proto not found");
    4485           0 :         return NULL;
    4486             :     }
    4487           0 :     return PyLong_FromLong((long) ntohs(sp->s_port));
    4488             : }
    4489             : 
    4490             : PyDoc_STRVAR(getservbyname_doc,
    4491             : "getservbyname(servicename[, protocolname]) -> integer\n\
    4492             : \n\
    4493             : Return a port number from a service name and protocol name.\n\
    4494             : The optional protocol name, if given, should be 'tcp' or 'udp',\n\
    4495             : otherwise any protocol will match.");
    4496             : 
    4497             : 
    4498             : /* Python interface to getservbyport(port).
    4499             :    This only returns the service name, since the other info is already
    4500             :    known or not useful (like the list of aliases). */
    4501             : 
    4502             : /*ARGSUSED*/
    4503             : static PyObject *
    4504           0 : socket_getservbyport(PyObject *self, PyObject *args)
    4505             : {
    4506             :     int port;
    4507           0 :     char *proto=NULL;
    4508             :     struct servent *sp;
    4509           0 :     if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
    4510           0 :         return NULL;
    4511           0 :     if (port < 0 || port > 0xffff) {
    4512           0 :         PyErr_SetString(
    4513             :             PyExc_OverflowError,
    4514             :             "getservbyport: port must be 0-65535.");
    4515           0 :         return NULL;
    4516             :     }
    4517           0 :     Py_BEGIN_ALLOW_THREADS
    4518           0 :     sp = getservbyport(htons((short)port), proto);
    4519           0 :     Py_END_ALLOW_THREADS
    4520           0 :     if (sp == NULL) {
    4521           0 :         PyErr_SetString(PyExc_OSError, "port/proto not found");
    4522           0 :         return NULL;
    4523             :     }
    4524           0 :     return PyUnicode_FromString(sp->s_name);
    4525             : }
    4526             : 
    4527             : PyDoc_STRVAR(getservbyport_doc,
    4528             : "getservbyport(port[, protocolname]) -> string\n\
    4529             : \n\
    4530             : Return the service name from a port number and protocol name.\n\
    4531             : The optional protocol name, if given, should be 'tcp' or 'udp',\n\
    4532             : otherwise any protocol will match.");
    4533             : 
    4534             : /* Python interface to getprotobyname(name).
    4535             :    This only returns the protocol number, since the other info is
    4536             :    already known or not useful (like the list of aliases). */
    4537             : 
    4538             : /*ARGSUSED*/
    4539             : static PyObject *
    4540           0 : socket_getprotobyname(PyObject *self, PyObject *args)
    4541             : {
    4542             :     char *name;
    4543             :     struct protoent *sp;
    4544           0 :     if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
    4545           0 :         return NULL;
    4546           0 :     Py_BEGIN_ALLOW_THREADS
    4547           0 :     sp = getprotobyname(name);
    4548           0 :     Py_END_ALLOW_THREADS
    4549           0 :     if (sp == NULL) {
    4550           0 :         PyErr_SetString(PyExc_OSError, "protocol not found");
    4551           0 :         return NULL;
    4552             :     }
    4553           0 :     return PyLong_FromLong((long) sp->p_proto);
    4554             : }
    4555             : 
    4556             : PyDoc_STRVAR(getprotobyname_doc,
    4557             : "getprotobyname(name) -> integer\n\
    4558             : \n\
    4559             : Return the protocol number for the named protocol.  (Rarely used.)");
    4560             : 
    4561             : 
    4562             : #ifndef NO_DUP
    4563             : /* dup() function for socket fds */
    4564             : 
    4565             : static PyObject *
    4566           0 : socket_dup(PyObject *self, PyObject *fdobj)
    4567             : {
    4568             :     SOCKET_T fd, newfd;
    4569             :     PyObject *newfdobj;
    4570             : 
    4571             : 
    4572           0 :     fd = PyLong_AsSocket_t(fdobj);
    4573           0 :     if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
    4574           0 :         return NULL;
    4575             : 
    4576           0 :     newfd = dup_socket(fd);
    4577           0 :     if (newfd == INVALID_SOCKET)
    4578           0 :         return set_error();
    4579             : 
    4580           0 :     newfdobj = PyLong_FromSocket_t(newfd);
    4581           0 :     if (newfdobj == NULL)
    4582           0 :         SOCKETCLOSE(newfd);
    4583           0 :     return newfdobj;
    4584             : }
    4585             : 
    4586             : PyDoc_STRVAR(dup_doc,
    4587             : "dup(integer) -> integer\n\
    4588             : \n\
    4589             : Duplicate an integer socket file descriptor.  This is like os.dup(), but for\n\
    4590             : sockets; on some platforms os.dup() won't work for socket file descriptors.");
    4591             : #endif
    4592             : 
    4593             : 
    4594             : #ifdef HAVE_SOCKETPAIR
    4595             : /* Create a pair of sockets using the socketpair() function.
    4596             :    Arguments as for socket() except the default family is AF_UNIX if
    4597             :    defined on the platform; otherwise, the default is AF_INET. */
    4598             : 
    4599             : /*ARGSUSED*/
    4600             : static PyObject *
    4601           0 : socket_socketpair(PyObject *self, PyObject *args)
    4602             : {
    4603           0 :     PySocketSockObject *s0 = NULL, *s1 = NULL;
    4604             :     SOCKET_T sv[2];
    4605           0 :     int family, type = SOCK_STREAM, proto = 0;
    4606           0 :     PyObject *res = NULL;
    4607             : 
    4608             : #if defined(AF_UNIX)
    4609           0 :     family = AF_UNIX;
    4610             : #else
    4611             :     family = AF_INET;
    4612             : #endif
    4613           0 :     if (!PyArg_ParseTuple(args, "|iii:socketpair",
    4614             :                           &family, &type, &proto))
    4615           0 :         return NULL;
    4616             :     /* Create a pair of socket fds */
    4617           0 :     if (socketpair(family, type, proto, sv) < 0)
    4618           0 :         return set_error();
    4619           0 :     s0 = new_sockobject(sv[0], family, type, proto);
    4620           0 :     if (s0 == NULL)
    4621           0 :         goto finally;
    4622           0 :     s1 = new_sockobject(sv[1], family, type, proto);
    4623           0 :     if (s1 == NULL)
    4624           0 :         goto finally;
    4625           0 :     res = PyTuple_Pack(2, s0, s1);
    4626             : 
    4627             : finally:
    4628           0 :     if (res == NULL) {
    4629           0 :         if (s0 == NULL)
    4630           0 :             SOCKETCLOSE(sv[0]);
    4631           0 :         if (s1 == NULL)
    4632           0 :             SOCKETCLOSE(sv[1]);
    4633             :     }
    4634           0 :     Py_XDECREF(s0);
    4635           0 :     Py_XDECREF(s1);
    4636           0 :     return res;
    4637             : }
    4638             : 
    4639             : PyDoc_STRVAR(socketpair_doc,
    4640             : "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
    4641             : \n\
    4642             : Create a pair of socket objects from the sockets returned by the platform\n\
    4643             : socketpair() function.\n\
    4644             : The arguments are the same as for socket() except the default family is\n\
    4645             : AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
    4646             : 
    4647             : #endif /* HAVE_SOCKETPAIR */
    4648             : 
    4649             : 
    4650             : static PyObject *
    4651           0 : socket_ntohs(PyObject *self, PyObject *args)
    4652             : {
    4653             :     int x1, x2;
    4654             : 
    4655           0 :     if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
    4656           0 :         return NULL;
    4657             :     }
    4658           0 :     if (x1 < 0) {
    4659           0 :         PyErr_SetString(PyExc_OverflowError,
    4660             :             "can't convert negative number to unsigned long");
    4661           0 :         return NULL;
    4662             :     }
    4663           0 :     x2 = (unsigned int)ntohs((unsigned short)x1);
    4664           0 :     return PyLong_FromLong(x2);
    4665             : }
    4666             : 
    4667             : PyDoc_STRVAR(ntohs_doc,
    4668             : "ntohs(integer) -> integer\n\
    4669             : \n\
    4670             : Convert a 16-bit integer from network to host byte order.");
    4671             : 
    4672             : 
    4673             : static PyObject *
    4674           0 : socket_ntohl(PyObject *self, PyObject *arg)
    4675             : {
    4676             :     unsigned long x;
    4677             : 
    4678           0 :     if (PyLong_Check(arg)) {
    4679           0 :         x = PyLong_AsUnsignedLong(arg);
    4680           0 :         if (x == (unsigned long) -1 && PyErr_Occurred())
    4681           0 :             return NULL;
    4682             : #if SIZEOF_LONG > 4
    4683             :         {
    4684             :             unsigned long y;
    4685             :             /* only want the trailing 32 bits */
    4686             :             y = x & 0xFFFFFFFFUL;
    4687             :             if (y ^ x)
    4688             :                 return PyErr_Format(PyExc_OverflowError,
    4689             :                             "long int larger than 32 bits");
    4690             :             x = y;
    4691             :         }
    4692             : #endif
    4693             :     }
    4694             :     else
    4695           0 :         return PyErr_Format(PyExc_TypeError,
    4696             :                             "expected int/long, %s found",
    4697           0 :                             Py_TYPE(arg)->tp_name);
    4698           0 :     if (x == (unsigned long) -1 && PyErr_Occurred())
    4699           0 :         return NULL;
    4700           0 :     return PyLong_FromUnsignedLong(ntohl(x));
    4701             : }
    4702             : 
    4703             : PyDoc_STRVAR(ntohl_doc,
    4704             : "ntohl(integer) -> integer\n\
    4705             : \n\
    4706             : Convert a 32-bit integer from network to host byte order.");
    4707             : 
    4708             : 
    4709             : static PyObject *
    4710           0 : socket_htons(PyObject *self, PyObject *args)
    4711             : {
    4712             :     int x1, x2;
    4713             : 
    4714           0 :     if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
    4715           0 :         return NULL;
    4716             :     }
    4717           0 :     if (x1 < 0) {
    4718           0 :         PyErr_SetString(PyExc_OverflowError,
    4719             :             "can't convert negative number to unsigned long");
    4720           0 :         return NULL;
    4721             :     }
    4722           0 :     x2 = (unsigned int)htons((unsigned short)x1);
    4723           0 :     return PyLong_FromLong(x2);
    4724             : }
    4725             : 
    4726             : PyDoc_STRVAR(htons_doc,
    4727             : "htons(integer) -> integer\n\
    4728             : \n\
    4729             : Convert a 16-bit integer from host to network byte order.");
    4730             : 
    4731             : 
    4732             : static PyObject *
    4733           0 : socket_htonl(PyObject *self, PyObject *arg)
    4734             : {
    4735             :     unsigned long x;
    4736             : 
    4737           0 :     if (PyLong_Check(arg)) {
    4738           0 :         x = PyLong_AsUnsignedLong(arg);
    4739           0 :         if (x == (unsigned long) -1 && PyErr_Occurred())
    4740           0 :             return NULL;
    4741             : #if SIZEOF_LONG > 4
    4742             :         {
    4743             :             unsigned long y;
    4744             :             /* only want the trailing 32 bits */
    4745             :             y = x & 0xFFFFFFFFUL;
    4746             :             if (y ^ x)
    4747             :                 return PyErr_Format(PyExc_OverflowError,
    4748             :                             "long int larger than 32 bits");
    4749             :             x = y;
    4750             :         }
    4751             : #endif
    4752             :     }
    4753             :     else
    4754           0 :         return PyErr_Format(PyExc_TypeError,
    4755             :                             "expected int/long, %s found",
    4756           0 :                             Py_TYPE(arg)->tp_name);
    4757           0 :     return PyLong_FromUnsignedLong(htonl((unsigned long)x));
    4758             : }
    4759             : 
    4760             : PyDoc_STRVAR(htonl_doc,
    4761             : "htonl(integer) -> integer\n\
    4762             : \n\
    4763             : Convert a 32-bit integer from host to network byte order.");
    4764             : 
    4765             : /* socket.inet_aton() and socket.inet_ntoa() functions. */
    4766             : 
    4767             : PyDoc_STRVAR(inet_aton_doc,
    4768             : "inet_aton(string) -> bytes giving packed 32-bit IP representation\n\
    4769             : \n\
    4770             : Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
    4771             : binary format used in low-level network functions.");
    4772             : 
    4773             : static PyObject*
    4774           0 : socket_inet_aton(PyObject *self, PyObject *args)
    4775             : {
    4776             : #ifndef INADDR_NONE
    4777             : #define INADDR_NONE (-1)
    4778             : #endif
    4779             : #ifdef HAVE_INET_ATON
    4780             :     struct in_addr buf;
    4781             : #endif
    4782             : 
    4783             : #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
    4784             : #if (SIZEOF_INT != 4)
    4785             : #error "Not sure if in_addr_t exists and int is not 32-bits."
    4786             : #endif
    4787             :     /* Have to use inet_addr() instead */
    4788             :     unsigned int packed_addr;
    4789             : #endif
    4790             :     char *ip_addr;
    4791             : 
    4792           0 :     if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
    4793           0 :         return NULL;
    4794             : 
    4795             : 
    4796             : #ifdef HAVE_INET_ATON
    4797             : 
    4798             : #ifdef USE_INET_ATON_WEAKLINK
    4799             :     if (inet_aton != NULL) {
    4800             : #endif
    4801           0 :     if (inet_aton(ip_addr, &buf))
    4802           0 :         return PyBytes_FromStringAndSize((char *)(&buf),
    4803             :                                           sizeof(buf));
    4804             : 
    4805           0 :     PyErr_SetString(PyExc_OSError,
    4806             :                     "illegal IP address string passed to inet_aton");
    4807           0 :     return NULL;
    4808             : 
    4809             : #ifdef USE_INET_ATON_WEAKLINK
    4810             :    } else {
    4811             : #endif
    4812             : 
    4813             : #endif
    4814             : 
    4815             : #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
    4816             : 
    4817             :     /* special-case this address as inet_addr might return INADDR_NONE
    4818             :      * for this */
    4819             :     if (strcmp(ip_addr, "255.255.255.255") == 0) {
    4820             :         packed_addr = 0xFFFFFFFF;
    4821             :     } else {
    4822             : 
    4823             :         packed_addr = inet_addr(ip_addr);
    4824             : 
    4825             :         if (packed_addr == INADDR_NONE) {               /* invalid address */
    4826             :             PyErr_SetString(PyExc_OSError,
    4827             :                 "illegal IP address string passed to inet_aton");
    4828             :             return NULL;
    4829             :         }
    4830             :     }
    4831             :     return PyBytes_FromStringAndSize((char *) &packed_addr,
    4832             :                                       sizeof(packed_addr));
    4833             : 
    4834             : #ifdef USE_INET_ATON_WEAKLINK
    4835             :    }
    4836             : #endif
    4837             : 
    4838             : #endif
    4839             : }
    4840             : 
    4841             : PyDoc_STRVAR(inet_ntoa_doc,
    4842             : "inet_ntoa(packed_ip) -> ip_address_string\n\
    4843             : \n\
    4844             : Convert an IP address from 32-bit packed binary format to string format");
    4845             : 
    4846             : static PyObject*
    4847           0 : socket_inet_ntoa(PyObject *self, PyObject *args)
    4848             : {
    4849             :     char *packed_str;
    4850             :     int addr_len;
    4851             :     struct in_addr packed_addr;
    4852             : 
    4853           0 :     if (!PyArg_ParseTuple(args, "y#:inet_ntoa", &packed_str, &addr_len)) {
    4854           0 :         return NULL;
    4855             :     }
    4856             : 
    4857           0 :     if (addr_len != sizeof(packed_addr)) {
    4858           0 :         PyErr_SetString(PyExc_OSError,
    4859             :             "packed IP wrong length for inet_ntoa");
    4860           0 :         return NULL;
    4861             :     }
    4862             : 
    4863           0 :     memcpy(&packed_addr, packed_str, addr_len);
    4864             : 
    4865           0 :     return PyUnicode_FromString(inet_ntoa(packed_addr));
    4866             : }
    4867             : 
    4868             : #ifdef HAVE_INET_PTON
    4869             : 
    4870             : PyDoc_STRVAR(inet_pton_doc,
    4871             : "inet_pton(af, ip) -> packed IP address string\n\
    4872             : \n\
    4873             : Convert an IP address from string format to a packed string suitable\n\
    4874             : for use with low-level network functions.");
    4875             : 
    4876             : static PyObject *
    4877           0 : socket_inet_pton(PyObject *self, PyObject *args)
    4878             : {
    4879             :     int af;
    4880             :     char* ip;
    4881             :     int retval;
    4882             : #ifdef ENABLE_IPV6
    4883             :     char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
    4884             : #else
    4885             :     char packed[sizeof(struct in_addr)];
    4886             : #endif
    4887           0 :     if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
    4888           0 :         return NULL;
    4889             :     }
    4890             : 
    4891             : #if !defined(ENABLE_IPV6) && defined(AF_INET6)
    4892             :     if(af == AF_INET6) {
    4893             :         PyErr_SetString(PyExc_OSError,
    4894             :                         "can't use AF_INET6, IPv6 is disabled");
    4895             :         return NULL;
    4896             :     }
    4897             : #endif
    4898             : 
    4899           0 :     retval = inet_pton(af, ip, packed);
    4900           0 :     if (retval < 0) {
    4901           0 :         PyErr_SetFromErrno(PyExc_OSError);
    4902           0 :         return NULL;
    4903           0 :     } else if (retval == 0) {
    4904           0 :         PyErr_SetString(PyExc_OSError,
    4905             :             "illegal IP address string passed to inet_pton");
    4906           0 :         return NULL;
    4907           0 :     } else if (af == AF_INET) {
    4908           0 :         return PyBytes_FromStringAndSize(packed,
    4909             :                                           sizeof(struct in_addr));
    4910             : #ifdef ENABLE_IPV6
    4911           0 :     } else if (af == AF_INET6) {
    4912           0 :         return PyBytes_FromStringAndSize(packed,
    4913             :                                           sizeof(struct in6_addr));
    4914             : #endif
    4915             :     } else {
    4916           0 :         PyErr_SetString(PyExc_OSError, "unknown address family");
    4917           0 :         return NULL;
    4918             :     }
    4919             : }
    4920             : 
    4921             : PyDoc_STRVAR(inet_ntop_doc,
    4922             : "inet_ntop(af, packed_ip) -> string formatted IP address\n\
    4923             : \n\
    4924             : Convert a packed IP address of the given family to string format.");
    4925             : 
    4926             : static PyObject *
    4927           0 : socket_inet_ntop(PyObject *self, PyObject *args)
    4928             : {
    4929             :     int af;
    4930             :     char* packed;
    4931             :     int len;
    4932             :     const char* retval;
    4933             : #ifdef ENABLE_IPV6
    4934             :     char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
    4935             : #else
    4936             :     char ip[INET_ADDRSTRLEN + 1];
    4937             : #endif
    4938             : 
    4939             :     /* Guarantee NUL-termination for PyUnicode_FromString() below */
    4940           0 :     memset((void *) &ip[0], '\0', sizeof(ip));
    4941             : 
    4942           0 :     if (!PyArg_ParseTuple(args, "iy#:inet_ntop", &af, &packed, &len)) {
    4943           0 :         return NULL;
    4944             :     }
    4945             : 
    4946           0 :     if (af == AF_INET) {
    4947           0 :         if (len != sizeof(struct in_addr)) {
    4948           0 :             PyErr_SetString(PyExc_ValueError,
    4949             :                 "invalid length of packed IP address string");
    4950           0 :             return NULL;
    4951             :         }
    4952             : #ifdef ENABLE_IPV6
    4953           0 :     } else if (af == AF_INET6) {
    4954           0 :         if (len != sizeof(struct in6_addr)) {
    4955           0 :             PyErr_SetString(PyExc_ValueError,
    4956             :                 "invalid length of packed IP address string");
    4957           0 :             return NULL;
    4958             :         }
    4959             : #endif
    4960             :     } else {
    4961           0 :         PyErr_Format(PyExc_ValueError,
    4962             :             "unknown address family %d", af);
    4963           0 :         return NULL;
    4964             :     }
    4965             : 
    4966           0 :     retval = inet_ntop(af, packed, ip, sizeof(ip));
    4967           0 :     if (!retval) {
    4968           0 :         PyErr_SetFromErrno(PyExc_OSError);
    4969           0 :         return NULL;
    4970             :     } else {
    4971           0 :         return PyUnicode_FromString(retval);
    4972             :     }
    4973             : 
    4974             :     /* NOTREACHED */
    4975             :     PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
    4976             :     return NULL;
    4977             : }
    4978             : 
    4979             : #endif /* HAVE_INET_PTON */
    4980             : 
    4981             : /* Python interface to getaddrinfo(host, port). */
    4982             : 
    4983             : /*ARGSUSED*/
    4984             : static PyObject *
    4985           0 : socket_getaddrinfo(PyObject *self, PyObject *args, PyObject* kwargs)
    4986             : {
    4987             :     static char* kwnames[] = {"host", "port", "family", "type", "proto",
    4988             :                               "flags", 0};
    4989             :     struct addrinfo hints, *res;
    4990           0 :     struct addrinfo *res0 = NULL;
    4991           0 :     PyObject *hobj = NULL;
    4992           0 :     PyObject *pobj = (PyObject *)NULL;
    4993             :     char pbuf[30];
    4994             :     char *hptr, *pptr;
    4995             :     int family, socktype, protocol, flags;
    4996             :     int error;
    4997           0 :     PyObject *all = (PyObject *)NULL;
    4998           0 :     PyObject *idna = NULL;
    4999             : 
    5000           0 :     family = socktype = protocol = flags = 0;
    5001           0 :     family = AF_UNSPEC;
    5002           0 :     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|iiii:getaddrinfo",
    5003             :                           kwnames, &hobj, &pobj, &family, &socktype,
    5004             :                           &protocol, &flags)) {
    5005           0 :         return NULL;
    5006             :     }
    5007           0 :     if (hobj == Py_None) {
    5008           0 :         hptr = NULL;
    5009           0 :     } else if (PyUnicode_Check(hobj)) {
    5010             :         _Py_IDENTIFIER(encode);
    5011             : 
    5012           0 :         idna = _PyObject_CallMethodId(hobj, &PyId_encode, "s", "idna");
    5013           0 :         if (!idna)
    5014           0 :             return NULL;
    5015             :         assert(PyBytes_Check(idna));
    5016           0 :         hptr = PyBytes_AS_STRING(idna);
    5017           0 :     } else if (PyBytes_Check(hobj)) {
    5018           0 :         hptr = PyBytes_AsString(hobj);
    5019             :     } else {
    5020           0 :         PyErr_SetString(PyExc_TypeError,
    5021             :                         "getaddrinfo() argument 1 must be string or None");
    5022           0 :         return NULL;
    5023             :     }
    5024           0 :     if (PyLong_CheckExact(pobj)) {
    5025           0 :         long value = PyLong_AsLong(pobj);
    5026           0 :         if (value == -1 && PyErr_Occurred())
    5027           0 :             goto err;
    5028           0 :         PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", value);
    5029           0 :         pptr = pbuf;
    5030           0 :     } else if (PyUnicode_Check(pobj)) {
    5031           0 :         pptr = _PyUnicode_AsString(pobj);
    5032           0 :         if (pptr == NULL)
    5033           0 :             goto err;
    5034           0 :     } else if (PyBytes_Check(pobj)) {
    5035           0 :         pptr = PyBytes_AS_STRING(pobj);
    5036           0 :     } else if (pobj == Py_None) {
    5037           0 :         pptr = (char *)NULL;
    5038             :     } else {
    5039           0 :         PyErr_SetString(PyExc_OSError, "Int or String expected");
    5040           0 :         goto err;
    5041             :     }
    5042           0 :     memset(&hints, 0, sizeof(hints));
    5043           0 :     hints.ai_family = family;
    5044           0 :     hints.ai_socktype = socktype;
    5045           0 :     hints.ai_protocol = protocol;
    5046           0 :     hints.ai_flags = flags;
    5047           0 :     Py_BEGIN_ALLOW_THREADS
    5048             :     ACQUIRE_GETADDRINFO_LOCK
    5049           0 :     error = getaddrinfo(hptr, pptr, &hints, &res0);
    5050           0 :     Py_END_ALLOW_THREADS
    5051             :     RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
    5052           0 :     if (error) {
    5053           0 :         set_gaierror(error);
    5054           0 :         goto err;
    5055             :     }
    5056             : 
    5057           0 :     if ((all = PyList_New(0)) == NULL)
    5058           0 :         goto err;
    5059           0 :     for (res = res0; res; res = res->ai_next) {
    5060             :         PyObject *single;
    5061           0 :         PyObject *addr =
    5062           0 :             makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
    5063           0 :         if (addr == NULL)
    5064           0 :             goto err;
    5065           0 :         single = Py_BuildValue("iiisO", res->ai_family,
    5066             :             res->ai_socktype, res->ai_protocol,
    5067           0 :             res->ai_canonname ? res->ai_canonname : "",
    5068             :             addr);
    5069           0 :         Py_DECREF(addr);
    5070           0 :         if (single == NULL)
    5071           0 :             goto err;
    5072             : 
    5073           0 :         if (PyList_Append(all, single))
    5074           0 :             goto err;
    5075           0 :         Py_XDECREF(single);
    5076             :     }
    5077           0 :     Py_XDECREF(idna);
    5078           0 :     if (res0)
    5079           0 :         freeaddrinfo(res0);
    5080           0 :     return all;
    5081             :  err:
    5082           0 :     Py_XDECREF(all);
    5083           0 :     Py_XDECREF(idna);
    5084           0 :     if (res0)
    5085           0 :         freeaddrinfo(res0);
    5086           0 :     return (PyObject *)NULL;
    5087             : }
    5088             : 
    5089             : PyDoc_STRVAR(getaddrinfo_doc,
    5090             : "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
    5091             :     -> list of (family, socktype, proto, canonname, sockaddr)\n\
    5092             : \n\
    5093             : Resolve host and port into addrinfo struct.");
    5094             : 
    5095             : /* Python interface to getnameinfo(sa, flags). */
    5096             : 
    5097             : /*ARGSUSED*/
    5098             : static PyObject *
    5099           0 : socket_getnameinfo(PyObject *self, PyObject *args)
    5100             : {
    5101           0 :     PyObject *sa = (PyObject *)NULL;
    5102             :     int flags;
    5103             :     char *hostp;
    5104             :     int port;
    5105             :     unsigned int flowinfo, scope_id;
    5106             :     char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
    5107           0 :     struct addrinfo hints, *res = NULL;
    5108             :     int error;
    5109           0 :     PyObject *ret = (PyObject *)NULL;
    5110             : 
    5111           0 :     flags = flowinfo = scope_id = 0;
    5112           0 :     if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
    5113           0 :         return NULL;
    5114           0 :     if (!PyTuple_Check(sa)) {
    5115           0 :         PyErr_SetString(PyExc_TypeError,
    5116             :                         "getnameinfo() argument 1 must be a tuple");
    5117           0 :         return NULL;
    5118             :     }
    5119           0 :     if (!PyArg_ParseTuple(sa, "si|II",
    5120             :                           &hostp, &port, &flowinfo, &scope_id))
    5121           0 :         return NULL;
    5122           0 :     if (flowinfo > 0xfffff) {
    5123           0 :         PyErr_SetString(PyExc_OverflowError,
    5124             :                         "getsockaddrarg: flowinfo must be 0-1048575.");
    5125           0 :         return NULL;
    5126             :     }
    5127           0 :     PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
    5128           0 :     memset(&hints, 0, sizeof(hints));
    5129           0 :     hints.ai_family = AF_UNSPEC;
    5130           0 :     hints.ai_socktype = SOCK_DGRAM;     /* make numeric port happy */
    5131           0 :     hints.ai_flags = AI_NUMERICHOST;    /* don't do any name resolution */
    5132           0 :     Py_BEGIN_ALLOW_THREADS
    5133             :     ACQUIRE_GETADDRINFO_LOCK
    5134           0 :     error = getaddrinfo(hostp, pbuf, &hints, &res);
    5135           0 :     Py_END_ALLOW_THREADS
    5136             :     RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
    5137           0 :     if (error) {
    5138           0 :         set_gaierror(error);
    5139           0 :         goto fail;
    5140             :     }
    5141           0 :     if (res->ai_next) {
    5142           0 :         PyErr_SetString(PyExc_OSError,
    5143             :             "sockaddr resolved to multiple addresses");
    5144           0 :         goto fail;
    5145             :     }
    5146           0 :     switch (res->ai_family) {
    5147             :     case AF_INET:
    5148             :         {
    5149           0 :         if (PyTuple_GET_SIZE(sa) != 2) {
    5150           0 :             PyErr_SetString(PyExc_OSError,
    5151             :                 "IPv4 sockaddr must be 2 tuple");
    5152           0 :             goto fail;
    5153             :         }
    5154           0 :         break;
    5155             :         }
    5156             : #ifdef ENABLE_IPV6
    5157             :     case AF_INET6:
    5158             :         {
    5159             :         struct sockaddr_in6 *sin6;
    5160           0 :         sin6 = (struct sockaddr_in6 *)res->ai_addr;
    5161           0 :         sin6->sin6_flowinfo = htonl(flowinfo);
    5162           0 :         sin6->sin6_scope_id = scope_id;
    5163           0 :         break;
    5164             :         }
    5165             : #endif
    5166             :     }
    5167           0 :     error = getnameinfo(res->ai_addr, (socklen_t) res->ai_addrlen,
    5168             :                     hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
    5169           0 :     if (error) {
    5170           0 :         set_gaierror(error);
    5171           0 :         goto fail;
    5172             :     }
    5173           0 :     ret = Py_BuildValue("ss", hbuf, pbuf);
    5174             : 
    5175             : fail:
    5176           0 :     if (res)
    5177           0 :         freeaddrinfo(res);
    5178           0 :     return ret;
    5179             : }
    5180             : 
    5181             : PyDoc_STRVAR(getnameinfo_doc,
    5182             : "getnameinfo(sockaddr, flags) --> (host, port)\n\
    5183             : \n\
    5184             : Get host and port for a sockaddr.");
    5185             : 
    5186             : 
    5187             : /* Python API to getting and setting the default timeout value. */
    5188             : 
    5189             : static PyObject *
    5190           0 : socket_getdefaulttimeout(PyObject *self)
    5191             : {
    5192           0 :     if (defaulttimeout < 0.0) {
    5193           0 :         Py_INCREF(Py_None);
    5194           0 :         return Py_None;
    5195             :     }
    5196             :     else
    5197           0 :         return PyFloat_FromDouble(defaulttimeout);
    5198             : }
    5199             : 
    5200             : PyDoc_STRVAR(getdefaulttimeout_doc,
    5201             : "getdefaulttimeout() -> timeout\n\
    5202             : \n\
    5203             : Returns the default timeout in seconds (float) for new socket objects.\n\
    5204             : A value of None indicates that new socket objects have no timeout.\n\
    5205             : When the socket module is first imported, the default is None.");
    5206             : 
    5207             : static PyObject *
    5208           0 : socket_setdefaulttimeout(PyObject *self, PyObject *arg)
    5209             : {
    5210             :     double timeout;
    5211             : 
    5212           0 :     if (arg == Py_None)
    5213           0 :         timeout = -1.0;
    5214             :     else {
    5215           0 :         timeout = PyFloat_AsDouble(arg);
    5216           0 :         if (timeout < 0.0) {
    5217           0 :             if (!PyErr_Occurred())
    5218           0 :                 PyErr_SetString(PyExc_ValueError,
    5219             :                                 "Timeout value out of range");
    5220           0 :             return NULL;
    5221             :         }
    5222             :     }
    5223             : 
    5224           0 :     defaulttimeout = timeout;
    5225             : 
    5226           0 :     Py_INCREF(Py_None);
    5227           0 :     return Py_None;
    5228             : }
    5229             : 
    5230             : PyDoc_STRVAR(setdefaulttimeout_doc,
    5231             : "setdefaulttimeout(timeout)\n\
    5232             : \n\
    5233             : Set the default timeout in seconds (float) for new socket objects.\n\
    5234             : A value of None indicates that new socket objects have no timeout.\n\
    5235             : When the socket module is first imported, the default is None.");
    5236             : 
    5237             : #ifdef HAVE_IF_NAMEINDEX
    5238             : /* Python API for getting interface indices and names */
    5239             : 
    5240             : static PyObject *
    5241           0 : socket_if_nameindex(PyObject *self, PyObject *arg)
    5242             : {
    5243             :     PyObject *list;
    5244             :     int i;
    5245             :     struct if_nameindex *ni;
    5246             : 
    5247           0 :     ni = if_nameindex();
    5248           0 :     if (ni == NULL) {
    5249           0 :         PyErr_SetFromErrno(PyExc_OSError);
    5250           0 :         return NULL;
    5251             :     }
    5252             : 
    5253           0 :     list = PyList_New(0);
    5254           0 :     if (list == NULL) {
    5255           0 :         if_freenameindex(ni);
    5256           0 :         return NULL;
    5257             :     }
    5258             : 
    5259           0 :     for (i = 0; ni[i].if_index != 0 && i < INT_MAX; i++) {
    5260           0 :         PyObject *ni_tuple = Py_BuildValue("IO&",
    5261           0 :                 ni[i].if_index, PyUnicode_DecodeFSDefault, ni[i].if_name);
    5262             : 
    5263           0 :         if (ni_tuple == NULL || PyList_Append(list, ni_tuple) == -1) {
    5264           0 :             Py_XDECREF(ni_tuple);
    5265           0 :             Py_DECREF(list);
    5266           0 :             if_freenameindex(ni);
    5267           0 :             return NULL;
    5268             :         }
    5269           0 :         Py_DECREF(ni_tuple);
    5270             :     }
    5271             : 
    5272           0 :     if_freenameindex(ni);
    5273           0 :     return list;
    5274             : }
    5275             : 
    5276             : PyDoc_STRVAR(if_nameindex_doc,
    5277             : "if_nameindex()\n\
    5278             : \n\
    5279             : Returns a list of network interface information (index, name) tuples.");
    5280             : 
    5281             : static PyObject *
    5282           0 : socket_if_nametoindex(PyObject *self, PyObject *args)
    5283             : {
    5284             :     PyObject *oname;
    5285             :     unsigned long index;
    5286             : 
    5287           0 :     if (!PyArg_ParseTuple(args, "O&:if_nametoindex",
    5288             :                           PyUnicode_FSConverter, &oname))
    5289           0 :         return NULL;
    5290             : 
    5291           0 :     index = if_nametoindex(PyBytes_AS_STRING(oname));
    5292           0 :     Py_DECREF(oname);
    5293           0 :     if (index == 0) {
    5294             :         /* if_nametoindex() doesn't set errno */
    5295           0 :         PyErr_SetString(PyExc_OSError, "no interface with this name");
    5296           0 :         return NULL;
    5297             :     }
    5298             : 
    5299           0 :     return PyLong_FromUnsignedLong(index);
    5300             : }
    5301             : 
    5302             : PyDoc_STRVAR(if_nametoindex_doc,
    5303             : "if_nametoindex(if_name)\n\
    5304             : \n\
    5305             : Returns the interface index corresponding to the interface name if_name.");
    5306             : 
    5307             : static PyObject *
    5308           0 : socket_if_indextoname(PyObject *self, PyObject *arg)
    5309             : {
    5310             :     unsigned long index;
    5311             :     char name[IF_NAMESIZE + 1];
    5312             : 
    5313           0 :     index = PyLong_AsUnsignedLong(arg);
    5314           0 :     if (index == (unsigned long) -1)
    5315           0 :         return NULL;
    5316             : 
    5317           0 :     if (if_indextoname(index, name) == NULL) {
    5318           0 :         PyErr_SetFromErrno(PyExc_OSError);
    5319           0 :         return NULL;
    5320             :     }
    5321             : 
    5322           0 :     return PyUnicode_DecodeFSDefault(name);
    5323             : }
    5324             : 
    5325             : PyDoc_STRVAR(if_indextoname_doc,
    5326             : "if_indextoname(if_index)\n\
    5327             : \n\
    5328             : Returns the interface name corresponding to the interface index if_index.");
    5329             : 
    5330             : #endif  /* HAVE_IF_NAMEINDEX */
    5331             : 
    5332             : 
    5333             : #ifdef CMSG_LEN
    5334             : /* Python interface to CMSG_LEN(length). */
    5335             : 
    5336             : static PyObject *
    5337           0 : socket_CMSG_LEN(PyObject *self, PyObject *args)
    5338             : {
    5339             :     Py_ssize_t length;
    5340             :     size_t result;
    5341             : 
    5342           0 :     if (!PyArg_ParseTuple(args, "n:CMSG_LEN", &length))
    5343           0 :         return NULL;
    5344           0 :     if (length < 0 || !get_CMSG_LEN(length, &result)) {
    5345           0 :         PyErr_Format(PyExc_OverflowError, "CMSG_LEN() argument out of range");
    5346           0 :         return NULL;
    5347             :     }
    5348           0 :     return PyLong_FromSize_t(result);
    5349             : }
    5350             : 
    5351             : PyDoc_STRVAR(CMSG_LEN_doc,
    5352             : "CMSG_LEN(length) -> control message length\n\
    5353             : \n\
    5354             : Return the total length, without trailing padding, of an ancillary\n\
    5355             : data item with associated data of the given length.  This value can\n\
    5356             : often be used as the buffer size for recvmsg() to receive a single\n\
    5357             : item of ancillary data, but RFC 3542 requires portable applications to\n\
    5358             : use CMSG_SPACE() and thus include space for padding, even when the\n\
    5359             : item will be the last in the buffer.  Raises OverflowError if length\n\
    5360             : is outside the permissible range of values.");
    5361             : 
    5362             : 
    5363             : #ifdef CMSG_SPACE
    5364             : /* Python interface to CMSG_SPACE(length). */
    5365             : 
    5366             : static PyObject *
    5367           0 : socket_CMSG_SPACE(PyObject *self, PyObject *args)
    5368             : {
    5369             :     Py_ssize_t length;
    5370             :     size_t result;
    5371             : 
    5372           0 :     if (!PyArg_ParseTuple(args, "n:CMSG_SPACE", &length))
    5373           0 :         return NULL;
    5374           0 :     if (length < 0 || !get_CMSG_SPACE(length, &result)) {
    5375           0 :         PyErr_SetString(PyExc_OverflowError,
    5376             :                         "CMSG_SPACE() argument out of range");
    5377           0 :         return NULL;
    5378             :     }
    5379           0 :     return PyLong_FromSize_t(result);
    5380             : }
    5381             : 
    5382             : PyDoc_STRVAR(CMSG_SPACE_doc,
    5383             : "CMSG_SPACE(length) -> buffer size\n\
    5384             : \n\
    5385             : Return the buffer size needed for recvmsg() to receive an ancillary\n\
    5386             : data item with associated data of the given length, along with any\n\
    5387             : trailing padding.  The buffer space needed to receive multiple items\n\
    5388             : is the sum of the CMSG_SPACE() values for their associated data\n\
    5389             : lengths.  Raises OverflowError if length is outside the permissible\n\
    5390             : range of values.");
    5391             : #endif    /* CMSG_SPACE */
    5392             : #endif    /* CMSG_LEN */
    5393             : 
    5394             : 
    5395             : /* List of functions exported by this module. */
    5396             : 
    5397             : static PyMethodDef socket_methods[] = {
    5398             :     {"gethostbyname",           socket_gethostbyname,
    5399             :      METH_VARARGS, gethostbyname_doc},
    5400             :     {"gethostbyname_ex",        socket_gethostbyname_ex,
    5401             :      METH_VARARGS, ghbn_ex_doc},
    5402             :     {"gethostbyaddr",           socket_gethostbyaddr,
    5403             :      METH_VARARGS, gethostbyaddr_doc},
    5404             :     {"gethostname",             socket_gethostname,
    5405             :      METH_NOARGS,  gethostname_doc},
    5406             : #ifdef HAVE_SETHOSTNAME
    5407             :     {"sethostname",             socket_sethostname,
    5408             :      METH_VARARGS,  sethostname_doc},
    5409             : #endif
    5410             :     {"getservbyname",           socket_getservbyname,
    5411             :      METH_VARARGS, getservbyname_doc},
    5412             :     {"getservbyport",           socket_getservbyport,
    5413             :      METH_VARARGS, getservbyport_doc},
    5414             :     {"getprotobyname",          socket_getprotobyname,
    5415             :      METH_VARARGS, getprotobyname_doc},
    5416             : #ifndef NO_DUP
    5417             :     {"dup",                     socket_dup,
    5418             :      METH_O, dup_doc},
    5419             : #endif
    5420             : #ifdef HAVE_SOCKETPAIR
    5421             :     {"socketpair",              socket_socketpair,
    5422             :      METH_VARARGS, socketpair_doc},
    5423             : #endif
    5424             :     {"ntohs",                   socket_ntohs,
    5425             :      METH_VARARGS, ntohs_doc},
    5426             :     {"ntohl",                   socket_ntohl,
    5427             :      METH_O, ntohl_doc},
    5428             :     {"htons",                   socket_htons,
    5429             :      METH_VARARGS, htons_doc},
    5430             :     {"htonl",                   socket_htonl,
    5431             :      METH_O, htonl_doc},
    5432             :     {"inet_aton",               socket_inet_aton,
    5433             :      METH_VARARGS, inet_aton_doc},
    5434             :     {"inet_ntoa",               socket_inet_ntoa,
    5435             :      METH_VARARGS, inet_ntoa_doc},
    5436             : #ifdef HAVE_INET_PTON
    5437             :     {"inet_pton",               socket_inet_pton,
    5438             :      METH_VARARGS, inet_pton_doc},
    5439             :     {"inet_ntop",               socket_inet_ntop,
    5440             :      METH_VARARGS, inet_ntop_doc},
    5441             : #endif
    5442             :     {"getaddrinfo",             (PyCFunction)socket_getaddrinfo,
    5443             :      METH_VARARGS | METH_KEYWORDS, getaddrinfo_doc},
    5444             :     {"getnameinfo",             socket_getnameinfo,
    5445             :      METH_VARARGS, getnameinfo_doc},
    5446             :     {"getdefaulttimeout",       (PyCFunction)socket_getdefaulttimeout,
    5447             :      METH_NOARGS, getdefaulttimeout_doc},
    5448             :     {"setdefaulttimeout",       socket_setdefaulttimeout,
    5449             :      METH_O, setdefaulttimeout_doc},
    5450             : #ifdef HAVE_IF_NAMEINDEX
    5451             :     {"if_nameindex", socket_if_nameindex,
    5452             :      METH_NOARGS, if_nameindex_doc},
    5453             :     {"if_nametoindex", socket_if_nametoindex,
    5454             :      METH_VARARGS, if_nametoindex_doc},
    5455             :     {"if_indextoname", socket_if_indextoname,
    5456             :      METH_O, if_indextoname_doc},
    5457             : #endif
    5458             : #ifdef CMSG_LEN
    5459             :     {"CMSG_LEN",                socket_CMSG_LEN,
    5460             :      METH_VARARGS, CMSG_LEN_doc},
    5461             : #ifdef CMSG_SPACE
    5462             :     {"CMSG_SPACE",              socket_CMSG_SPACE,
    5463             :      METH_VARARGS, CMSG_SPACE_doc},
    5464             : #endif
    5465             : #endif
    5466             :     {NULL,                      NULL}            /* Sentinel */
    5467             : };
    5468             : 
    5469             : 
    5470             : #ifdef MS_WINDOWS
    5471             : #define OS_INIT_DEFINED
    5472             : 
    5473             : /* Additional initialization and cleanup for Windows */
    5474             : 
    5475             : static void
    5476             : os_cleanup(void)
    5477             : {
    5478             :     WSACleanup();
    5479             : }
    5480             : 
    5481             : static int
    5482             : os_init(void)
    5483             : {
    5484             :     WSADATA WSAData;
    5485             :     int ret;
    5486             :     ret = WSAStartup(0x0101, &WSAData);
    5487             :     switch (ret) {
    5488             :     case 0:     /* No error */
    5489             :         Py_AtExit(os_cleanup);
    5490             :         return 1; /* Success */
    5491             :     case WSASYSNOTREADY:
    5492             :         PyErr_SetString(PyExc_ImportError,
    5493             :                         "WSAStartup failed: network not ready");
    5494             :         break;
    5495             :     case WSAVERNOTSUPPORTED:
    5496             :     case WSAEINVAL:
    5497             :         PyErr_SetString(
    5498             :             PyExc_ImportError,
    5499             :             "WSAStartup failed: requested version not supported");
    5500             :         break;
    5501             :     default:
    5502             :         PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret);
    5503             :         break;
    5504             :     }
    5505             :     return 0; /* Failure */
    5506             : }
    5507             : 
    5508             : #endif /* MS_WINDOWS */
    5509             : 
    5510             : 
    5511             : #ifdef PYOS_OS2
    5512             : #define OS_INIT_DEFINED
    5513             : 
    5514             : /* Additional initialization for OS/2 */
    5515             : 
    5516             : static int
    5517             : os_init(void)
    5518             : {
    5519             : #ifndef PYCC_GCC
    5520             :     int rc = sock_init();
    5521             : 
    5522             :     if (rc == 0) {
    5523             :         return 1; /* Success */
    5524             :     }
    5525             : 
    5526             :     PyErr_Format(PyExc_ImportError, "OS/2 TCP/IP Error# %d", sock_errno());
    5527             : 
    5528             :     return 0;  /* Failure */
    5529             : #else
    5530             :     /* No need to initialize sockets with GCC/EMX */
    5531             :     return 1; /* Success */
    5532             : #endif
    5533             : }
    5534             : 
    5535             : #endif /* PYOS_OS2 */
    5536             : 
    5537             : 
    5538             : #ifndef OS_INIT_DEFINED
    5539             : static int
    5540           1 : os_init(void)
    5541             : {
    5542           1 :     return 1; /* Success */
    5543             : }
    5544             : #endif
    5545             : 
    5546             : 
    5547             : /* C API table - always add new things to the end for binary
    5548             :    compatibility. */
    5549             : static
    5550             : PySocketModule_APIObject PySocketModuleAPI =
    5551             : {
    5552             :     &sock_type,
    5553             :     NULL,
    5554             :     NULL
    5555             : };
    5556             : 
    5557             : 
    5558             : /* Initialize the _socket module.
    5559             : 
    5560             :    This module is actually called "_socket", and there's a wrapper
    5561             :    "socket.py" which implements some additional functionality.
    5562             :    The import of "_socket" may fail with an ImportError exception if
    5563             :    os-specific initialization fails.  On Windows, this does WINSOCK
    5564             :    initialization.  When WINSOCK is initialized successfully, a call to
    5565             :    WSACleanup() is scheduled to be made at exit time.
    5566             : */
    5567             : 
    5568             : PyDoc_STRVAR(socket_doc,
    5569             : "Implementation module for socket operations.\n\
    5570             : \n\
    5571             : See the socket module for documentation.");
    5572             : 
    5573             : static struct PyModuleDef socketmodule = {
    5574             :     PyModuleDef_HEAD_INIT,
    5575             :     PySocket_MODULE_NAME,
    5576             :     socket_doc,
    5577             :     -1,
    5578             :     socket_methods,
    5579             :     NULL,
    5580             :     NULL,
    5581             :     NULL,
    5582             :     NULL
    5583             : };
    5584             : 
    5585             : PyMODINIT_FUNC
    5586           1 : PyInit__socket(void)
    5587             : {
    5588             :     PyObject *m, *has_ipv6;
    5589             : 
    5590           1 :     if (!os_init())
    5591           0 :         return NULL;
    5592             : 
    5593           1 :     Py_TYPE(&sock_type) = &PyType_Type;
    5594           1 :     m = PyModule_Create(&socketmodule);
    5595           1 :     if (m == NULL)
    5596           0 :         return NULL;
    5597             : 
    5598           1 :     Py_INCREF(PyExc_OSError);
    5599           1 :     PySocketModuleAPI.error = PyExc_OSError;
    5600           1 :     Py_INCREF(PyExc_OSError);
    5601           1 :     PyModule_AddObject(m, "error", PyExc_OSError);
    5602           1 :     socket_herror = PyErr_NewException("socket.herror",
    5603             :                                        PyExc_OSError, NULL);
    5604           1 :     if (socket_herror == NULL)
    5605           0 :         return NULL;
    5606           1 :     Py_INCREF(socket_herror);
    5607           1 :     PyModule_AddObject(m, "herror", socket_herror);
    5608           1 :     socket_gaierror = PyErr_NewException("socket.gaierror", PyExc_OSError,
    5609             :         NULL);
    5610           1 :     if (socket_gaierror == NULL)
    5611           0 :         return NULL;
    5612           1 :     Py_INCREF(socket_gaierror);
    5613           1 :     PyModule_AddObject(m, "gaierror", socket_gaierror);
    5614           1 :     socket_timeout = PyErr_NewException("socket.timeout",
    5615             :                                         PyExc_OSError, NULL);
    5616           1 :     if (socket_timeout == NULL)
    5617           0 :         return NULL;
    5618           1 :     PySocketModuleAPI.timeout_error = socket_timeout;
    5619           1 :     Py_INCREF(socket_timeout);
    5620           1 :     PyModule_AddObject(m, "timeout", socket_timeout);
    5621           1 :     Py_INCREF((PyObject *)&sock_type);
    5622           1 :     if (PyModule_AddObject(m, "SocketType",
    5623             :                            (PyObject *)&sock_type) != 0)
    5624           0 :         return NULL;
    5625           1 :     Py_INCREF((PyObject *)&sock_type);
    5626           1 :     if (PyModule_AddObject(m, "socket",
    5627             :                            (PyObject *)&sock_type) != 0)
    5628           0 :         return NULL;
    5629             : 
    5630             : #ifdef ENABLE_IPV6
    5631           1 :     has_ipv6 = Py_True;
    5632             : #else
    5633             :     has_ipv6 = Py_False;
    5634             : #endif
    5635           1 :     Py_INCREF(has_ipv6);
    5636           1 :     PyModule_AddObject(m, "has_ipv6", has_ipv6);
    5637             : 
    5638             :     /* Export C API */
    5639           1 :     if (PyModule_AddObject(m, PySocket_CAPI_NAME,
    5640             :            PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL)
    5641             :                              ) != 0)
    5642           0 :         return NULL;
    5643             : 
    5644             :     /* Address families (we only support AF_INET and AF_UNIX) */
    5645             : #ifdef AF_UNSPEC
    5646           1 :     PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
    5647             : #endif
    5648           1 :     PyModule_AddIntConstant(m, "AF_INET", AF_INET);
    5649             : #ifdef AF_INET6
    5650           1 :     PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
    5651             : #endif /* AF_INET6 */
    5652             : #if defined(AF_UNIX)
    5653           1 :     PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
    5654             : #endif /* AF_UNIX */
    5655             : #ifdef AF_AX25
    5656             :     /* Amateur Radio AX.25 */
    5657           1 :     PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
    5658             : #endif
    5659             : #ifdef AF_IPX
    5660           1 :     PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
    5661             : #endif
    5662             : #ifdef AF_APPLETALK
    5663             :     /* Appletalk DDP */
    5664           1 :     PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
    5665             : #endif
    5666             : #ifdef AF_NETROM
    5667             :     /* Amateur radio NetROM */
    5668           1 :     PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
    5669             : #endif
    5670             : #ifdef AF_BRIDGE
    5671             :     /* Multiprotocol bridge */
    5672           1 :     PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
    5673             : #endif
    5674             : #ifdef AF_ATMPVC
    5675             :     /* ATM PVCs */
    5676           1 :     PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
    5677             : #endif
    5678             : #ifdef AF_AAL5
    5679             :     /* Reserved for Werner's ATM */
    5680             :     PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
    5681             : #endif
    5682             : #ifdef AF_X25
    5683             :     /* Reserved for X.25 project */
    5684           1 :     PyModule_AddIntConstant(m, "AF_X25", AF_X25);
    5685             : #endif
    5686             : #ifdef AF_INET6
    5687           1 :     PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
    5688             : #endif
    5689             : #ifdef AF_ROSE
    5690             :     /* Amateur Radio X.25 PLP */
    5691           1 :     PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
    5692             : #endif
    5693             : #ifdef AF_DECnet
    5694             :     /* Reserved for DECnet project */
    5695           1 :     PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
    5696             : #endif
    5697             : #ifdef AF_NETBEUI
    5698             :     /* Reserved for 802.2LLC project */
    5699           1 :     PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
    5700             : #endif
    5701             : #ifdef AF_SECURITY
    5702             :     /* Security callback pseudo AF */
    5703           1 :     PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
    5704             : #endif
    5705             : #ifdef AF_KEY
    5706             :     /* PF_KEY key management API */
    5707           1 :     PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
    5708             : #endif
    5709             : #ifdef AF_NETLINK
    5710             :     /*  */
    5711           1 :     PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
    5712           1 :     PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
    5713             : #ifdef NETLINK_SKIP
    5714             :     PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
    5715             : #endif
    5716             : #ifdef NETLINK_W1
    5717             :     PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
    5718             : #endif
    5719           1 :     PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
    5720           1 :     PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
    5721             : #ifdef NETLINK_TCPDIAG
    5722             :     PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
    5723             : #endif
    5724             : #ifdef NETLINK_NFLOG
    5725           1 :     PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
    5726             : #endif
    5727             : #ifdef NETLINK_XFRM
    5728           1 :     PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
    5729             : #endif
    5730             : #ifdef NETLINK_ARPD
    5731             :     PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
    5732             : #endif
    5733             : #ifdef NETLINK_ROUTE6
    5734             :     PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
    5735             : #endif
    5736           1 :     PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
    5737             : #ifdef NETLINK_DNRTMSG
    5738           1 :     PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
    5739             : #endif
    5740             : #ifdef NETLINK_TAPBASE
    5741             :     PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
    5742             : #endif
    5743             : #endif /* AF_NETLINK */
    5744             : #ifdef AF_ROUTE
    5745             :     /* Alias to emulate 4.4BSD */
    5746           1 :     PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
    5747             : #endif
    5748             : #ifdef AF_ASH
    5749             :     /* Ash */
    5750           1 :     PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
    5751             : #endif
    5752             : #ifdef AF_ECONET
    5753             :     /* Acorn Econet */
    5754           1 :     PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
    5755             : #endif
    5756             : #ifdef AF_ATMSVC
    5757             :     /* ATM SVCs */
    5758           1 :     PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
    5759             : #endif
    5760             : #ifdef AF_SNA
    5761             :     /* Linux SNA Project (nutters!) */
    5762           1 :     PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
    5763             : #endif
    5764             : #ifdef AF_IRDA
    5765             :     /* IRDA sockets */
    5766           1 :     PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
    5767             : #endif
    5768             : #ifdef AF_PPPOX
    5769             :     /* PPPoX sockets */
    5770           1 :     PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
    5771             : #endif
    5772             : #ifdef AF_WANPIPE
    5773             :     /* Wanpipe API Sockets */
    5774           1 :     PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
    5775             : #endif
    5776             : #ifdef AF_LLC
    5777             :     /* Linux LLC */
    5778           1 :     PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
    5779             : #endif
    5780             : 
    5781             : #ifdef USE_BLUETOOTH
    5782           1 :     PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
    5783           1 :     PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
    5784           1 :     PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
    5785           1 :     PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
    5786             : #if !defined(__NetBSD__) && !defined(__DragonFly__)
    5787           1 :     PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
    5788             : #endif
    5789             : #if !defined(__FreeBSD__)
    5790             : #if !defined(__NetBSD__) && !defined(__DragonFly__)
    5791           1 :     PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
    5792             : #endif
    5793           1 :     PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
    5794           1 :     PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
    5795             : #endif
    5796           1 :     PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
    5797           1 :     PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
    5798           1 :     PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
    5799             : #endif
    5800             : 
    5801             : #ifdef AF_CAN
    5802             :     /* Controller Area Network */
    5803           1 :     PyModule_AddIntConstant(m, "AF_CAN", AF_CAN);
    5804             : #endif
    5805             : #ifdef PF_CAN
    5806             :     /* Controller Area Network */
    5807           1 :     PyModule_AddIntConstant(m, "PF_CAN", PF_CAN);
    5808             : #endif
    5809             : 
    5810             : /* Reliable Datagram Sockets */
    5811             : #ifdef AF_RDS
    5812           1 :     PyModule_AddIntConstant(m, "AF_RDS", AF_RDS);
    5813             : #endif
    5814             : #ifdef PF_RDS
    5815           1 :     PyModule_AddIntConstant(m, "PF_RDS", PF_RDS);
    5816             : #endif
    5817             : 
    5818             : /* Kernel event messages */
    5819             : #ifdef PF_SYSTEM
    5820             :     PyModule_AddIntConstant(m, "PF_SYSTEM", PF_SYSTEM);
    5821             : #endif
    5822             : #ifdef AF_SYSTEM
    5823             :     PyModule_AddIntConstant(m, "AF_SYSTEM", AF_SYSTEM);
    5824             : #endif
    5825             : 
    5826             : #ifdef AF_PACKET
    5827           1 :     PyModule_AddIntMacro(m, AF_PACKET);
    5828             : #endif
    5829             : #ifdef PF_PACKET
    5830           1 :     PyModule_AddIntMacro(m, PF_PACKET);
    5831             : #endif
    5832             : #ifdef PACKET_HOST
    5833           1 :     PyModule_AddIntMacro(m, PACKET_HOST);
    5834             : #endif
    5835             : #ifdef PACKET_BROADCAST
    5836           1 :     PyModule_AddIntMacro(m, PACKET_BROADCAST);
    5837             : #endif
    5838             : #ifdef PACKET_MULTICAST
    5839           1 :     PyModule_AddIntMacro(m, PACKET_MULTICAST);
    5840             : #endif
    5841             : #ifdef PACKET_OTHERHOST
    5842           1 :     PyModule_AddIntMacro(m, PACKET_OTHERHOST);
    5843             : #endif
    5844             : #ifdef PACKET_OUTGOING
    5845           1 :     PyModule_AddIntMacro(m, PACKET_OUTGOING);
    5846             : #endif
    5847             : #ifdef PACKET_LOOPBACK
    5848           1 :     PyModule_AddIntMacro(m, PACKET_LOOPBACK);
    5849             : #endif
    5850             : #ifdef PACKET_FASTROUTE
    5851           1 :     PyModule_AddIntMacro(m, PACKET_FASTROUTE);
    5852             : #endif
    5853             : 
    5854             : #ifdef HAVE_LINUX_TIPC_H
    5855           1 :     PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
    5856             : 
    5857             :     /* for addresses */
    5858           1 :     PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
    5859           1 :     PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
    5860           1 :     PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
    5861             : 
    5862           1 :     PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
    5863           1 :     PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
    5864           1 :     PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
    5865             : 
    5866             :     /* for setsockopt() */
    5867           1 :     PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
    5868           1 :     PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
    5869           1 :     PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
    5870           1 :     PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
    5871             :                     TIPC_DEST_DROPPABLE);
    5872           1 :     PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
    5873             : 
    5874           1 :     PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
    5875             :                     TIPC_LOW_IMPORTANCE);
    5876           1 :     PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
    5877             :                     TIPC_MEDIUM_IMPORTANCE);
    5878           1 :     PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
    5879             :                     TIPC_HIGH_IMPORTANCE);
    5880           1 :     PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
    5881             :                     TIPC_CRITICAL_IMPORTANCE);
    5882             : 
    5883             :     /* for subscriptions */
    5884           1 :     PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
    5885           1 :     PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
    5886             : #ifdef TIPC_SUB_CANCEL
    5887             :     /* doesn't seem to be available everywhere */
    5888           1 :     PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
    5889             : #endif
    5890           1 :     PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
    5891           1 :     PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
    5892           1 :     PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
    5893           1 :     PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
    5894           1 :     PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
    5895           1 :     PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
    5896             : #endif
    5897             : 
    5898             :     /* Socket types */
    5899           1 :     PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
    5900           1 :     PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
    5901             : /* We have incomplete socket support. */
    5902           1 :     PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
    5903           1 :     PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
    5904             : #if defined(SOCK_RDM)
    5905           1 :     PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
    5906             : #endif
    5907             : #ifdef SOCK_CLOEXEC
    5908           1 :     PyModule_AddIntConstant(m, "SOCK_CLOEXEC", SOCK_CLOEXEC);
    5909             : #endif
    5910             : #ifdef SOCK_NONBLOCK
    5911           1 :     PyModule_AddIntConstant(m, "SOCK_NONBLOCK", SOCK_NONBLOCK);
    5912             : #endif
    5913             : 
    5914             : #ifdef  SO_DEBUG
    5915           1 :     PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
    5916             : #endif
    5917             : #ifdef  SO_ACCEPTCONN
    5918           1 :     PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
    5919             : #endif
    5920             : #ifdef  SO_REUSEADDR
    5921           1 :     PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
    5922             : #endif
    5923             : #ifdef SO_EXCLUSIVEADDRUSE
    5924             :     PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
    5925             : #endif
    5926             : 
    5927             : #ifdef  SO_KEEPALIVE
    5928           1 :     PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
    5929             : #endif
    5930             : #ifdef  SO_DONTROUTE
    5931           1 :     PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
    5932             : #endif
    5933             : #ifdef  SO_BROADCAST
    5934           1 :     PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
    5935             : #endif
    5936             : #ifdef  SO_USELOOPBACK
    5937             :     PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
    5938             : #endif
    5939             : #ifdef  SO_LINGER
    5940           1 :     PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
    5941             : #endif
    5942             : #ifdef  SO_OOBINLINE
    5943           1 :     PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
    5944             : #endif
    5945             : #ifdef  SO_REUSEPORT
    5946             :     PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
    5947             : #endif
    5948             : #ifdef  SO_SNDBUF
    5949           1 :     PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
    5950             : #endif
    5951             : #ifdef  SO_RCVBUF
    5952           1 :     PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
    5953             : #endif
    5954             : #ifdef  SO_SNDLOWAT
    5955           1 :     PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
    5956             : #endif
    5957             : #ifdef  SO_RCVLOWAT
    5958           1 :     PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
    5959             : #endif
    5960             : #ifdef  SO_SNDTIMEO
    5961           1 :     PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
    5962             : #endif
    5963             : #ifdef  SO_RCVTIMEO
    5964           1 :     PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
    5965             : #endif
    5966             : #ifdef  SO_ERROR
    5967           1 :     PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
    5968             : #endif
    5969             : #ifdef  SO_TYPE
    5970           1 :     PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
    5971             : #endif
    5972             : #ifdef  SO_SETFIB
    5973             :     PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB);
    5974             : #endif
    5975             : #ifdef  SO_PASSCRED
    5976           1 :     PyModule_AddIntConstant(m, "SO_PASSCRED", SO_PASSCRED);
    5977             : #endif
    5978             : #ifdef  SO_PEERCRED
    5979           1 :     PyModule_AddIntConstant(m, "SO_PEERCRED", SO_PEERCRED);
    5980             : #endif
    5981             : #ifdef  LOCAL_PEERCRED
    5982             :     PyModule_AddIntConstant(m, "LOCAL_PEERCRED", LOCAL_PEERCRED);
    5983             : #endif
    5984             : #ifdef  SO_BINDTODEVICE
    5985           1 :     PyModule_AddIntMacro(m, SO_BINDTODEVICE);
    5986             : #endif
    5987             : 
    5988             :     /* Maximum number of connections for "listen" */
    5989             : #ifdef  SOMAXCONN
    5990           1 :     PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
    5991             : #else
    5992             :     PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
    5993             : #endif
    5994             : 
    5995             :     /* Ancilliary message types */
    5996             : #ifdef  SCM_RIGHTS
    5997           1 :     PyModule_AddIntConstant(m, "SCM_RIGHTS", SCM_RIGHTS);
    5998             : #endif
    5999             : #ifdef  SCM_CREDENTIALS
    6000           1 :     PyModule_AddIntConstant(m, "SCM_CREDENTIALS", SCM_CREDENTIALS);
    6001             : #endif
    6002             : #ifdef  SCM_CREDS
    6003             :     PyModule_AddIntConstant(m, "SCM_CREDS", SCM_CREDS);
    6004             : #endif
    6005             : 
    6006             :     /* Flags for send, recv */
    6007             : #ifdef  MSG_OOB
    6008           1 :     PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
    6009             : #endif
    6010             : #ifdef  MSG_PEEK
    6011           1 :     PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
    6012             : #endif
    6013             : #ifdef  MSG_DONTROUTE
    6014           1 :     PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
    6015             : #endif
    6016             : #ifdef  MSG_DONTWAIT
    6017           1 :     PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
    6018             : #endif
    6019             : #ifdef  MSG_EOR
    6020           1 :     PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
    6021             : #endif
    6022             : #ifdef  MSG_TRUNC
    6023           1 :     PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
    6024             : #endif
    6025             : #ifdef  MSG_CTRUNC
    6026           1 :     PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
    6027             : #endif
    6028             : #ifdef  MSG_WAITALL
    6029           1 :     PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
    6030             : #endif
    6031             : #ifdef  MSG_BTAG
    6032             :     PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
    6033             : #endif
    6034             : #ifdef  MSG_ETAG
    6035             :     PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
    6036             : #endif
    6037             : #ifdef  MSG_NOSIGNAL
    6038           1 :     PyModule_AddIntConstant(m, "MSG_NOSIGNAL", MSG_NOSIGNAL);
    6039             : #endif
    6040             : #ifdef  MSG_NOTIFICATION
    6041             :     PyModule_AddIntConstant(m, "MSG_NOTIFICATION", MSG_NOTIFICATION);
    6042             : #endif
    6043             : #ifdef  MSG_CMSG_CLOEXEC
    6044           1 :     PyModule_AddIntConstant(m, "MSG_CMSG_CLOEXEC", MSG_CMSG_CLOEXEC);
    6045             : #endif
    6046             : #ifdef  MSG_ERRQUEUE
    6047           1 :     PyModule_AddIntConstant(m, "MSG_ERRQUEUE", MSG_ERRQUEUE);
    6048             : #endif
    6049             : #ifdef  MSG_CONFIRM
    6050           1 :     PyModule_AddIntConstant(m, "MSG_CONFIRM", MSG_CONFIRM);
    6051             : #endif
    6052             : #ifdef  MSG_MORE
    6053           1 :     PyModule_AddIntConstant(m, "MSG_MORE", MSG_MORE);
    6054             : #endif
    6055             : #ifdef  MSG_EOF
    6056             :     PyModule_AddIntConstant(m, "MSG_EOF", MSG_EOF);
    6057             : #endif
    6058             : #ifdef  MSG_BCAST
    6059             :     PyModule_AddIntConstant(m, "MSG_BCAST", MSG_BCAST);
    6060             : #endif
    6061             : #ifdef  MSG_MCAST
    6062             :     PyModule_AddIntConstant(m, "MSG_MCAST", MSG_MCAST);
    6063             : #endif
    6064             : 
    6065             :     /* Protocol level and numbers, usable for [gs]etsockopt */
    6066             : #ifdef  SOL_SOCKET
    6067           1 :     PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
    6068             : #endif
    6069             : #ifdef  SOL_IP
    6070           1 :     PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
    6071             : #else
    6072             :     PyModule_AddIntConstant(m, "SOL_IP", 0);
    6073             : #endif
    6074             : #ifdef  SOL_IPX
    6075             :     PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
    6076             : #endif
    6077             : #ifdef  SOL_AX25
    6078             :     PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
    6079             : #endif
    6080             : #ifdef  SOL_ATALK
    6081             :     PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
    6082             : #endif
    6083             : #ifdef  SOL_NETROM
    6084             :     PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
    6085             : #endif
    6086             : #ifdef  SOL_ROSE
    6087             :     PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
    6088             : #endif
    6089             : #ifdef  SOL_TCP
    6090           1 :     PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
    6091             : #else
    6092             :     PyModule_AddIntConstant(m, "SOL_TCP", 6);
    6093             : #endif
    6094             : #ifdef  SOL_UDP
    6095             :     PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
    6096             : #else
    6097           1 :     PyModule_AddIntConstant(m, "SOL_UDP", 17);
    6098             : #endif
    6099             : #ifdef SOL_CAN_BASE
    6100           1 :     PyModule_AddIntConstant(m, "SOL_CAN_BASE", SOL_CAN_BASE);
    6101             : #endif
    6102             : #ifdef SOL_CAN_RAW
    6103           1 :     PyModule_AddIntConstant(m, "SOL_CAN_RAW", SOL_CAN_RAW);
    6104           1 :     PyModule_AddIntConstant(m, "CAN_RAW", CAN_RAW);
    6105             : #endif
    6106             : #ifdef HAVE_LINUX_CAN_H
    6107           1 :     PyModule_AddIntConstant(m, "CAN_EFF_FLAG", CAN_EFF_FLAG);
    6108           1 :     PyModule_AddIntConstant(m, "CAN_RTR_FLAG", CAN_RTR_FLAG);
    6109           1 :     PyModule_AddIntConstant(m, "CAN_ERR_FLAG", CAN_ERR_FLAG);
    6110             : 
    6111           1 :     PyModule_AddIntConstant(m, "CAN_SFF_MASK", CAN_SFF_MASK);
    6112           1 :     PyModule_AddIntConstant(m, "CAN_EFF_MASK", CAN_EFF_MASK);
    6113           1 :     PyModule_AddIntConstant(m, "CAN_ERR_MASK", CAN_ERR_MASK);
    6114             : #endif
    6115             : #ifdef HAVE_LINUX_CAN_RAW_H
    6116           1 :     PyModule_AddIntConstant(m, "CAN_RAW_FILTER", CAN_RAW_FILTER);
    6117           1 :     PyModule_AddIntConstant(m, "CAN_RAW_ERR_FILTER", CAN_RAW_ERR_FILTER);
    6118           1 :     PyModule_AddIntConstant(m, "CAN_RAW_LOOPBACK", CAN_RAW_LOOPBACK);
    6119           1 :     PyModule_AddIntConstant(m, "CAN_RAW_RECV_OWN_MSGS", CAN_RAW_RECV_OWN_MSGS);
    6120             : #endif
    6121             : #ifdef SOL_RDS
    6122             :     PyModule_AddIntConstant(m, "SOL_RDS", SOL_RDS);
    6123             : #endif
    6124             : #ifdef RDS_CANCEL_SENT_TO
    6125             :     PyModule_AddIntConstant(m, "RDS_CANCEL_SENT_TO", RDS_CANCEL_SENT_TO);
    6126             : #endif
    6127             : #ifdef RDS_GET_MR
    6128             :     PyModule_AddIntConstant(m, "RDS_GET_MR", RDS_GET_MR);
    6129             : #endif
    6130             : #ifdef RDS_FREE_MR
    6131             :     PyModule_AddIntConstant(m, "RDS_FREE_MR", RDS_FREE_MR);
    6132             : #endif
    6133             : #ifdef RDS_RECVERR
    6134             :     PyModule_AddIntConstant(m, "RDS_RECVERR", RDS_RECVERR);
    6135             : #endif
    6136             : #ifdef RDS_CONG_MONITOR
    6137             :     PyModule_AddIntConstant(m, "RDS_CONG_MONITOR", RDS_CONG_MONITOR);
    6138             : #endif
    6139             : #ifdef RDS_GET_MR_FOR_DEST
    6140             :     PyModule_AddIntConstant(m, "RDS_GET_MR_FOR_DEST", RDS_GET_MR_FOR_DEST);
    6141             : #endif
    6142             : #ifdef  IPPROTO_IP
    6143           1 :     PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
    6144             : #else
    6145             :     PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
    6146             : #endif
    6147             : #ifdef  IPPROTO_HOPOPTS
    6148           1 :     PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
    6149             : #endif
    6150             : #ifdef  IPPROTO_ICMP
    6151           1 :     PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
    6152             : #else
    6153             :     PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
    6154             : #endif
    6155             : #ifdef  IPPROTO_IGMP
    6156           1 :     PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
    6157             : #endif
    6158             : #ifdef  IPPROTO_GGP
    6159             :     PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
    6160             : #endif
    6161             : #ifdef  IPPROTO_IPV4
    6162             :     PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
    6163             : #endif
    6164             : #ifdef  IPPROTO_IPV6
    6165           1 :     PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
    6166             : #endif
    6167             : #ifdef  IPPROTO_IPIP
    6168           1 :     PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
    6169             : #endif
    6170             : #ifdef  IPPROTO_TCP
    6171           1 :     PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
    6172             : #else
    6173             :     PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
    6174             : #endif
    6175             : #ifdef  IPPROTO_EGP
    6176           1 :     PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
    6177             : #endif
    6178             : #ifdef  IPPROTO_PUP
    6179           1 :     PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
    6180             : #endif
    6181             : #ifdef  IPPROTO_UDP
    6182           1 :     PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
    6183             : #else
    6184             :     PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
    6185             : #endif
    6186             : #ifdef  IPPROTO_IDP
    6187           1 :     PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
    6188             : #endif
    6189             : #ifdef  IPPROTO_HELLO
    6190             :     PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
    6191             : #endif
    6192             : #ifdef  IPPROTO_ND
    6193             :     PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
    6194             : #endif
    6195             : #ifdef  IPPROTO_TP
    6196           1 :     PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
    6197             : #endif
    6198             : #ifdef  IPPROTO_IPV6
    6199           1 :     PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
    6200             : #endif
    6201             : #ifdef  IPPROTO_ROUTING
    6202           1 :     PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
    6203             : #endif
    6204             : #ifdef  IPPROTO_FRAGMENT
    6205           1 :     PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
    6206             : #endif
    6207             : #ifdef  IPPROTO_RSVP
    6208           1 :     PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
    6209             : #endif
    6210             : #ifdef  IPPROTO_GRE
    6211           1 :     PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
    6212             : #endif
    6213             : #ifdef  IPPROTO_ESP
    6214           1 :     PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
    6215             : #endif
    6216             : #ifdef  IPPROTO_AH
    6217           1 :     PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
    6218             : #endif
    6219             : #ifdef  IPPROTO_MOBILE
    6220             :     PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
    6221             : #endif
    6222             : #ifdef  IPPROTO_ICMPV6
    6223           1 :     PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
    6224             : #endif
    6225             : #ifdef  IPPROTO_NONE
    6226           1 :     PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
    6227             : #endif
    6228             : #ifdef  IPPROTO_DSTOPTS
    6229           1 :     PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
    6230             : #endif
    6231             : #ifdef  IPPROTO_XTP
    6232             :     PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
    6233             : #endif
    6234             : #ifdef  IPPROTO_EON
    6235             :     PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
    6236             : #endif
    6237             : #ifdef  IPPROTO_PIM
    6238           1 :     PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
    6239             : #endif
    6240             : #ifdef  IPPROTO_IPCOMP
    6241             :     PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
    6242             : #endif
    6243             : #ifdef  IPPROTO_VRRP
    6244             :     PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
    6245             : #endif
    6246             : #ifdef  IPPROTO_SCTP
    6247           1 :     PyModule_AddIntConstant(m, "IPPROTO_SCTP", IPPROTO_SCTP);
    6248             : #endif
    6249             : #ifdef  IPPROTO_BIP
    6250             :     PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
    6251             : #endif
    6252             : /**/
    6253             : #ifdef  IPPROTO_RAW
    6254           1 :     PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
    6255             : #else
    6256             :     PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
    6257             : #endif
    6258             : #ifdef  IPPROTO_MAX
    6259             :     PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
    6260             : #endif
    6261             : 
    6262             : #ifdef  SYSPROTO_CONTROL
    6263             :     PyModule_AddIntConstant(m, "SYSPROTO_CONTROL", SYSPROTO_CONTROL);
    6264             : #endif
    6265             : 
    6266             :     /* Some port configuration */
    6267             : #ifdef  IPPORT_RESERVED
    6268           1 :     PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
    6269             : #else
    6270             :     PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
    6271             : #endif
    6272             : #ifdef  IPPORT_USERRESERVED
    6273             :     PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
    6274             : #else
    6275           1 :     PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
    6276             : #endif
    6277             : 
    6278             :     /* Some reserved IP v.4 addresses */
    6279             : #ifdef  INADDR_ANY
    6280           1 :     PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
    6281             : #else
    6282             :     PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
    6283             : #endif
    6284             : #ifdef  INADDR_BROADCAST
    6285           1 :     PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
    6286             : #else
    6287             :     PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
    6288             : #endif
    6289             : #ifdef  INADDR_LOOPBACK
    6290           1 :     PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
    6291             : #else
    6292             :     PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
    6293             : #endif
    6294             : #ifdef  INADDR_UNSPEC_GROUP
    6295           1 :     PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
    6296             : #else
    6297             :     PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
    6298             : #endif
    6299             : #ifdef  INADDR_ALLHOSTS_GROUP
    6300           1 :     PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
    6301             :                             INADDR_ALLHOSTS_GROUP);
    6302             : #else
    6303             :     PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
    6304             : #endif
    6305             : #ifdef  INADDR_MAX_LOCAL_GROUP
    6306           1 :     PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
    6307             :                             INADDR_MAX_LOCAL_GROUP);
    6308             : #else
    6309             :     PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
    6310             : #endif
    6311             : #ifdef  INADDR_NONE
    6312           1 :     PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
    6313             : #else
    6314             :     PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
    6315             : #endif
    6316             : 
    6317             :     /* IPv4 [gs]etsockopt options */
    6318             : #ifdef  IP_OPTIONS
    6319           1 :     PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
    6320             : #endif
    6321             : #ifdef  IP_HDRINCL
    6322           1 :     PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
    6323             : #endif
    6324             : #ifdef  IP_TOS
    6325           1 :     PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
    6326             : #endif
    6327             : #ifdef  IP_TTL
    6328           1 :     PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
    6329             : #endif
    6330             : #ifdef  IP_RECVOPTS
    6331           1 :     PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
    6332             : #endif
    6333             : #ifdef  IP_RECVRETOPTS
    6334           1 :     PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
    6335             : #endif
    6336             : #ifdef  IP_RECVDSTADDR
    6337             :     PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
    6338             : #endif
    6339             : #ifdef  IP_RETOPTS
    6340           1 :     PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
    6341             : #endif
    6342             : #ifdef  IP_MULTICAST_IF
    6343           1 :     PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
    6344             : #endif
    6345             : #ifdef  IP_MULTICAST_TTL
    6346           1 :     PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
    6347             : #endif
    6348             : #ifdef  IP_MULTICAST_LOOP
    6349           1 :     PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
    6350             : #endif
    6351             : #ifdef  IP_ADD_MEMBERSHIP
    6352           1 :     PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
    6353             : #endif
    6354             : #ifdef  IP_DROP_MEMBERSHIP
    6355           1 :     PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
    6356             : #endif
    6357             : #ifdef  IP_DEFAULT_MULTICAST_TTL
    6358           1 :     PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
    6359             :                             IP_DEFAULT_MULTICAST_TTL);
    6360             : #endif
    6361             : #ifdef  IP_DEFAULT_MULTICAST_LOOP
    6362           1 :     PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
    6363             :                             IP_DEFAULT_MULTICAST_LOOP);
    6364             : #endif
    6365             : #ifdef  IP_MAX_MEMBERSHIPS
    6366           1 :     PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
    6367             : #endif
    6368             : #ifdef  IP_TRANSPARENT
    6369           1 :     PyModule_AddIntConstant(m, "IP_TRANSPARENT", IP_TRANSPARENT);
    6370             : #endif
    6371             : 
    6372             :     /* IPv6 [gs]etsockopt options, defined in RFC2553 */
    6373             : #ifdef  IPV6_JOIN_GROUP
    6374           1 :     PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
    6375             : #endif
    6376             : #ifdef  IPV6_LEAVE_GROUP
    6377           1 :     PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
    6378             : #endif
    6379             : #ifdef  IPV6_MULTICAST_HOPS
    6380           1 :     PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
    6381             : #endif
    6382             : #ifdef  IPV6_MULTICAST_IF
    6383           1 :     PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
    6384             : #endif
    6385             : #ifdef  IPV6_MULTICAST_LOOP
    6386           1 :     PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
    6387             : #endif
    6388             : #ifdef  IPV6_UNICAST_HOPS
    6389           1 :     PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
    6390             : #endif
    6391             :     /* Additional IPV6 socket options, defined in RFC 3493 */
    6392             : #ifdef IPV6_V6ONLY
    6393           1 :     PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
    6394             : #endif
    6395             :     /* Advanced IPV6 socket options, from RFC 3542 */
    6396             : #ifdef IPV6_CHECKSUM
    6397           1 :     PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
    6398             : #endif
    6399             : #ifdef IPV6_DONTFRAG
    6400             :     PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
    6401             : #endif
    6402             : #ifdef IPV6_DSTOPTS
    6403           1 :     PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
    6404             : #endif
    6405             : #ifdef IPV6_HOPLIMIT
    6406           1 :     PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
    6407             : #endif
    6408             : #ifdef IPV6_HOPOPTS
    6409           1 :     PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
    6410             : #endif
    6411             : #ifdef IPV6_NEXTHOP
    6412           1 :     PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
    6413             : #endif
    6414             : #ifdef IPV6_PATHMTU
    6415             :     PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
    6416             : #endif
    6417             : #ifdef IPV6_PKTINFO
    6418           1 :     PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
    6419             : #endif
    6420             : #ifdef IPV6_RECVDSTOPTS
    6421           1 :     PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
    6422             : #endif
    6423             : #ifdef IPV6_RECVHOPLIMIT
    6424           1 :     PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
    6425             : #endif
    6426             : #ifdef IPV6_RECVHOPOPTS
    6427           1 :     PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
    6428             : #endif
    6429             : #ifdef IPV6_RECVPKTINFO
    6430           1 :     PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
    6431             : #endif
    6432             : #ifdef IPV6_RECVRTHDR
    6433           1 :     PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
    6434             : #endif
    6435             : #ifdef IPV6_RECVTCLASS
    6436           1 :     PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
    6437             : #endif
    6438             : #ifdef IPV6_RTHDR
    6439           1 :     PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
    6440             : #endif
    6441             : #ifdef IPV6_RTHDRDSTOPTS
    6442           1 :     PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
    6443             : #endif
    6444             : #ifdef IPV6_RTHDR_TYPE_0
    6445           1 :     PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
    6446             : #endif
    6447             : #ifdef IPV6_RECVPATHMTU
    6448             :     PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
    6449             : #endif
    6450             : #ifdef IPV6_TCLASS
    6451           1 :     PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
    6452             : #endif
    6453             : #ifdef IPV6_USE_MIN_MTU
    6454             :     PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
    6455             : #endif
    6456             : 
    6457             :     /* TCP options */
    6458             : #ifdef  TCP_NODELAY
    6459           1 :     PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
    6460             : #endif
    6461             : #ifdef  TCP_MAXSEG
    6462           1 :     PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
    6463             : #endif
    6464             : #ifdef  TCP_CORK
    6465           1 :     PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
    6466             : #endif
    6467             : #ifdef  TCP_KEEPIDLE
    6468           1 :     PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
    6469             : #endif
    6470             : #ifdef  TCP_KEEPINTVL
    6471           1 :     PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
    6472             : #endif
    6473             : #ifdef  TCP_KEEPCNT
    6474           1 :     PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
    6475             : #endif
    6476             : #ifdef  TCP_SYNCNT
    6477           1 :     PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
    6478             : #endif
    6479             : #ifdef  TCP_LINGER2
    6480           1 :     PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
    6481             : #endif
    6482             : #ifdef  TCP_DEFER_ACCEPT
    6483           1 :     PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
    6484             : #endif
    6485             : #ifdef  TCP_WINDOW_CLAMP
    6486           1 :     PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
    6487             : #endif
    6488             : #ifdef  TCP_INFO
    6489           1 :     PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
    6490             : #endif
    6491             : #ifdef  TCP_QUICKACK
    6492           1 :     PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
    6493             : #endif
    6494             : 
    6495             : 
    6496             :     /* IPX options */
    6497             : #ifdef  IPX_TYPE
    6498             :     PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
    6499             : #endif
    6500             : 
    6501             : /* Reliable Datagram Sockets */
    6502             : #ifdef RDS_CMSG_RDMA_ARGS
    6503             :     PyModule_AddIntConstant(m, "RDS_CMSG_RDMA_ARGS", RDS_CMSG_RDMA_ARGS);
    6504             : #endif
    6505             : #ifdef RDS_CMSG_RDMA_DEST
    6506             :     PyModule_AddIntConstant(m, "RDS_CMSG_RDMA_DEST", RDS_CMSG_RDMA_DEST);
    6507             : #endif
    6508             : #ifdef RDS_CMSG_RDMA_MAP
    6509             :     PyModule_AddIntConstant(m, "RDS_CMSG_RDMA_MAP", RDS_CMSG_RDMA_MAP);
    6510             : #endif
    6511             : #ifdef RDS_CMSG_RDMA_STATUS
    6512             :     PyModule_AddIntConstant(m, "RDS_CMSG_RDMA_STATUS", RDS_CMSG_RDMA_STATUS);
    6513             : #endif
    6514             : #ifdef RDS_CMSG_RDMA_UPDATE
    6515             :     PyModule_AddIntConstant(m, "RDS_CMSG_RDMA_UPDATE", RDS_CMSG_RDMA_UPDATE);
    6516             : #endif
    6517             : #ifdef RDS_RDMA_READWRITE
    6518             :     PyModule_AddIntConstant(m, "RDS_RDMA_READWRITE", RDS_RDMA_READWRITE);
    6519             : #endif
    6520             : #ifdef RDS_RDMA_FENCE
    6521             :     PyModule_AddIntConstant(m, "RDS_RDMA_FENCE", RDS_RDMA_FENCE);
    6522             : #endif
    6523             : #ifdef RDS_RDMA_INVALIDATE
    6524             :     PyModule_AddIntConstant(m, "RDS_RDMA_INVALIDATE", RDS_RDMA_INVALIDATE);
    6525             : #endif
    6526             : #ifdef RDS_RDMA_USE_ONCE
    6527             :     PyModule_AddIntConstant(m, "RDS_RDMA_USE_ONCE", RDS_RDMA_USE_ONCE);
    6528             : #endif
    6529             : #ifdef RDS_RDMA_DONTWAIT
    6530             :     PyModule_AddIntConstant(m, "RDS_RDMA_DONTWAIT", RDS_RDMA_DONTWAIT);
    6531             : #endif
    6532             : #ifdef RDS_RDMA_NOTIFY_ME
    6533             :     PyModule_AddIntConstant(m, "RDS_RDMA_NOTIFY_ME", RDS_RDMA_NOTIFY_ME);
    6534             : #endif
    6535             : #ifdef RDS_RDMA_SILENT
    6536             :     PyModule_AddIntConstant(m, "RDS_RDMA_SILENT", RDS_RDMA_SILENT);
    6537             : #endif
    6538             : 
    6539             :     /* get{addr,name}info parameters */
    6540             : #ifdef EAI_ADDRFAMILY
    6541           1 :     PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
    6542             : #endif
    6543             : #ifdef EAI_AGAIN
    6544           1 :     PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
    6545             : #endif
    6546             : #ifdef EAI_BADFLAGS
    6547           1 :     PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
    6548             : #endif
    6549             : #ifdef EAI_FAIL
    6550           1 :     PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
    6551             : #endif
    6552             : #ifdef EAI_FAMILY
    6553           1 :     PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
    6554             : #endif
    6555             : #ifdef EAI_MEMORY
    6556           1 :     PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
    6557             : #endif
    6558             : #ifdef EAI_NODATA
    6559           1 :     PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
    6560             : #endif
    6561             : #ifdef EAI_NONAME
    6562           1 :     PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
    6563             : #endif
    6564             : #ifdef EAI_OVERFLOW
    6565           1 :     PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
    6566             : #endif
    6567             : #ifdef EAI_SERVICE
    6568           1 :     PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
    6569             : #endif
    6570             : #ifdef EAI_SOCKTYPE
    6571           1 :     PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
    6572             : #endif
    6573             : #ifdef EAI_SYSTEM
    6574           1 :     PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
    6575             : #endif
    6576             : #ifdef EAI_BADHINTS
    6577             :     PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
    6578             : #endif
    6579             : #ifdef EAI_PROTOCOL
    6580             :     PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
    6581             : #endif
    6582             : #ifdef EAI_MAX
    6583             :     PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
    6584             : #endif
    6585             : #ifdef AI_PASSIVE
    6586           1 :     PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
    6587             : #endif
    6588             : #ifdef AI_CANONNAME
    6589           1 :     PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
    6590             : #endif
    6591             : #ifdef AI_NUMERICHOST
    6592           1 :     PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
    6593             : #endif
    6594             : #ifdef AI_NUMERICSERV
    6595           1 :     PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
    6596             : #endif
    6597             : #ifdef AI_MASK
    6598             :     PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
    6599             : #endif
    6600             : #ifdef AI_ALL
    6601           1 :     PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
    6602             : #endif
    6603             : #ifdef AI_V4MAPPED_CFG
    6604             :     PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
    6605             : #endif
    6606             : #ifdef AI_ADDRCONFIG
    6607           1 :     PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
    6608             : #endif
    6609             : #ifdef AI_V4MAPPED
    6610           1 :     PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
    6611             : #endif
    6612             : #ifdef AI_DEFAULT
    6613             :     PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
    6614             : #endif
    6615             : #ifdef NI_MAXHOST
    6616           1 :     PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
    6617             : #endif
    6618             : #ifdef NI_MAXSERV
    6619           1 :     PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
    6620             : #endif
    6621             : #ifdef NI_NOFQDN
    6622           1 :     PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
    6623             : #endif
    6624             : #ifdef NI_NUMERICHOST
    6625           1 :     PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
    6626             : #endif
    6627             : #ifdef NI_NAMEREQD
    6628           1 :     PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
    6629             : #endif
    6630             : #ifdef NI_NUMERICSERV
    6631           1 :     PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
    6632             : #endif
    6633             : #ifdef NI_DGRAM
    6634           1 :     PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
    6635             : #endif
    6636             : 
    6637             :     /* shutdown() parameters */
    6638             : #ifdef SHUT_RD
    6639           1 :     PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
    6640             : #elif defined(SD_RECEIVE)
    6641             :     PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
    6642             : #else
    6643             :     PyModule_AddIntConstant(m, "SHUT_RD", 0);
    6644             : #endif
    6645             : #ifdef SHUT_WR
    6646           1 :     PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
    6647             : #elif defined(SD_SEND)
    6648             :     PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
    6649             : #else
    6650             :     PyModule_AddIntConstant(m, "SHUT_WR", 1);
    6651             : #endif
    6652             : #ifdef SHUT_RDWR
    6653           1 :     PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
    6654             : #elif defined(SD_BOTH)
    6655             :     PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
    6656             : #else
    6657             :     PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
    6658             : #endif
    6659             : 
    6660             : #ifdef SIO_RCVALL
    6661             :     {
    6662             :         DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS};
    6663             :         const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
    6664             :         int i;
    6665             :         for(i = 0; i<Py_ARRAY_LENGTH(codes); ++i) {
    6666             :             PyObject *tmp;
    6667             :             tmp = PyLong_FromUnsignedLong(codes[i]);
    6668             :             if (tmp == NULL)
    6669             :                 return NULL;
    6670             :             PyModule_AddObject(m, names[i], tmp);
    6671             :         }
    6672             :     }
    6673             :     PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
    6674             :     PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
    6675             :     PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
    6676             : #ifdef RCVALL_IPLEVEL
    6677             :     PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
    6678             : #endif
    6679             : #ifdef RCVALL_MAX
    6680             :     PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
    6681             : #endif
    6682             : #endif /* _MSTCPIP_ */
    6683             : 
    6684             :     /* Initialize gethostbyname lock */
    6685             : #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
    6686             :     netdb_lock = PyThread_allocate_lock();
    6687             : #endif
    6688           1 :     return m;
    6689             : }
    6690             : 
    6691             : 
    6692             : #ifndef HAVE_INET_PTON
    6693             : #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
    6694             : 
    6695             : /* Simplistic emulation code for inet_pton that only works for IPv4 */
    6696             : /* These are not exposed because they do not set errno properly */
    6697             : 
    6698             : int
    6699             : inet_pton(int af, const char *src, void *dst)
    6700             : {
    6701             :     if (af == AF_INET) {
    6702             : #if (SIZEOF_INT != 4)
    6703             : #error "Not sure if in_addr_t exists and int is not 32-bits."
    6704             : #endif
    6705             :         unsigned int packed_addr;
    6706             :         packed_addr = inet_addr(src);
    6707             :         if (packed_addr == INADDR_NONE)
    6708             :             return 0;
    6709             :         memcpy(dst, &packed_addr, 4);
    6710             :         return 1;
    6711             :     }
    6712             :     /* Should set errno to EAFNOSUPPORT */
    6713             :     return -1;
    6714             : }
    6715             : 
    6716             : const char *
    6717             : inet_ntop(int af, const void *src, char *dst, socklen_t size)
    6718             : {
    6719             :     if (af == AF_INET) {
    6720             :         struct in_addr packed_addr;
    6721             :         if (size < 16)
    6722             :             /* Should set errno to ENOSPC. */
    6723             :             return NULL;
    6724             :         memcpy(&packed_addr, src, sizeof(packed_addr));
    6725             :         return strncpy(dst, inet_ntoa(packed_addr), size);
    6726             :     }
    6727             :     /* Should set errno to EAFNOSUPPORT */
    6728             :     return NULL;
    6729             : }
    6730             : 
    6731             : #endif
    6732             : #endif

Generated by: LCOV version 1.10