cpython/Modules/socketmodule.c

/* Socket module */

/*

This module provides an interface to Berkeley socket IPC.

Limitations:

- Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
  portable manner, though AF_PACKET, AF_NETLINK, AF_QIPCRTR and AF_TIPC are
  supported under Linux.
- No read/write operations (use sendall/recv or makefile instead).
- Additional restrictions apply on some non-Unix platforms (compensated
  for by socket.py).

Module interface:

- socket.error: exception raised for socket specific errors, alias for OSError
- socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
    a subclass of socket.error
- socket.herror: exception raised for gethostby* errors,
    a subclass of socket.error
- socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
- socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
- socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
- socket.getprotobyname(protocolname) --> protocol number
- socket.getservbyname(servicename[, protocolname]) --> port number
- socket.getservbyport(portnumber[, protocolname]) --> service name
- socket.socket([family[, type [, proto, fileno]]]) --> new socket object
    (fileno specifies a pre-existing socket file descriptor)
- socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
- socket.ntohs(16 bit value) --> new int object
- socket.ntohl(32 bit value) --> new int object
- socket.htons(16 bit value) --> new int object
- socket.htonl(32 bit value) --> new int object
- socket.getaddrinfo(host, port [, family, type, proto, flags])
    --> List of (family, type, proto, canonname, sockaddr)
- socket.getnameinfo(sockaddr, flags) --> (host, port)
- socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
- socket.has_ipv6: boolean value indicating if IPv6 is supported
- socket.inet_aton(IP address) -> 32-bit packed IP representation
- socket.inet_ntoa(packed IP) -> IP address string
- socket.getdefaulttimeout() -> None | float
- socket.setdefaulttimeout(None | float)
- socket.if_nameindex() -> list of tuples (if_index, if_name)
- socket.if_nametoindex(name) -> corresponding interface index
- socket.if_indextoname(index) -> corresponding interface name
- an internet socket address is a pair (hostname, port)
  where hostname can be anything recognized by gethostbyname()
  (including the dd.dd.dd.dd notation) and port is in host byte order
- where a hostname is returned, the dd.dd.dd.dd notation is used
- a UNIX domain socket address is a string specifying the pathname
- an AF_PACKET socket address is a tuple containing a string
  specifying the ethernet interface and an integer specifying
  the Ethernet protocol number to be received. For example:
  ("eth0",0x1234).  Optional 3rd,4th,5th elements in the tuple
  specify packet-type and ha-type/addr.
- an AF_QIPCRTR socket address is a (node, port) tuple where the
  node and port are non-negative integers.
- an AF_TIPC socket address is expressed as
 (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
    TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
  and scope can be one of:
    TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
  The meaning of v1, v2 and v3 depends on the value of addr_type:
    if addr_type is TIPC_ADDR_NAME:
        v1 is the server type
        v2 is the port identifier
        v3 is ignored
    if addr_type is TIPC_ADDR_NAMESEQ:
        v1 is the server type
        v2 is the lower port number
        v3 is the upper port number
    if addr_type is TIPC_ADDR_ID:
        v1 is the node
        v2 is the ref
        v3 is ignored


Local naming conventions:

- names starting with sock_ are socket object methods
- names starting with socket_ are module-level functions
- names starting with PySocket are exported through socketmodule.h

*/

#ifndef Py_BUILD_CORE_BUILTIN
#define Py_BUILD_CORE_MODULE
#endif

#ifdef __APPLE__
// Issue #35569: Expose RFC 3542 socket options.
#define __APPLE_USE_RFC_3542
#include <AvailabilityMacros.h>
/* for getaddrinfo thread safety test on old versions of OS X */
#ifndef MAC_OS_X_VERSION_10_5
#define MAC_OS_X_VERSION_10_5
#endif
  /*
   * inet_aton is not available on OSX 10.3, yet we want to use a binary
   * that was build on 10.4 or later to work on that release, weak linking
   * comes to the rescue.
   */
# pragma weak inet_aton
#endif

#include "Python.h"
#include "pycore_capsule.h"       // _PyCapsule_SetTraverse()
#include "pycore_fileutils.h"     // _Py_set_inheritable()
#include "pycore_moduleobject.h"  // _PyModule_GetState
#include "pycore_time.h"          // _PyTime_AsMilliseconds()

#ifdef _Py_MEMORY_SANITIZER
#  include <sanitizer/msan_interface.h>
#endif

/* Socket object documentation */
PyDoc_STRVAR(sock_doc,
"socket(family=AF_INET, type=SOCK_STREAM, proto=0) -> socket object\n\
socket(family=-1, type=-1, proto=-1, fileno=None) -> socket object\n\
\n\
Open a socket of the given type.  The family argument specifies the\n\
address family; it defaults to AF_INET.  The type argument specifies\n\
whether this is a stream (SOCK_STREAM, this is the default)\n\
or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,\n\
specifying the default protocol.  Keyword arguments are accepted.\n\
The socket is created as non-inheritable.\n\
\n\
When a fileno is passed in, family, type and proto are auto-detected,\n\
unless they are explicitly set.\n\
\n\
A socket object represents one endpoint of a network connection.\n\
\n\
Methods of socket objects (keyword arguments not allowed):\n\
\n\
_accept() -- accept connection, returning new socket fd and client address\n\
bind(addr) -- bind the socket to a local address\n\
close() -- close the socket\n\
connect(addr) -- connect the socket to a remote address\n\
connect_ex(addr) -- connect, return an error code instead of an exception\n\
dup() -- return a new socket fd duplicated from fileno()\n\
fileno() -- return underlying file descriptor\n\
getpeername() -- return remote address [*]\n\
getsockname() -- return local address\n\
getsockopt(level, optname[, buflen]) -- get socket options\n\
gettimeout() -- return timeout or None\n\
listen([n]) -- start listening for incoming connections\n\
recv(buflen[, flags]) -- receive data\n\
recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
recvfrom_into(buffer[, nbytes, [, flags])\n\
  -- receive data and sender\'s address (into a buffer)\n\
sendall(data[, flags]) -- send all data\n\
send(data[, flags]) -- send data, may not send all of it\n\
sendto(data[, flags], addr) -- send data to a given address\n\
setblocking(bool) -- set or clear the blocking I/O flag\n\
getblocking() -- return True if socket is blocking, False if non-blocking\n\
setsockopt(level, optname, value[, optlen]) -- set socket options\n\
settimeout(None | float) -- set or clear the timeout\n\
shutdown(how) -- shut down traffic in one or both directions\n\
\n\
 [*] not available on all platforms!");

/* XXX This is a terrible mess of platform-dependent preprocessor hacks.
   I hope some day someone can clean this up please... */

/* Hacks for gethostbyname_r().  On some non-Linux platforms, the configure
   script doesn't get this right, so we hardcode some platform checks below.
   On the other hand, not all Linux versions agree, so there the settings
   computed by the configure script are needed! */

#ifndef __linux__
# undef HAVE_GETHOSTBYNAME_R_3_ARG
# undef HAVE_GETHOSTBYNAME_R_5_ARG
# undef HAVE_GETHOSTBYNAME_R_6_ARG
#endif

#if defined(__OpenBSD__)
# include <sys/uio.h>
#endif

#if defined(__ANDROID__) && __ANDROID_API__ < 23
# undef HAVE_GETHOSTBYNAME_R
#endif

#ifdef HAVE_GETHOSTBYNAME_R
# if defined(_AIX) && !defined(_LINUX_SOURCE_COMPAT)
#define HAVE_GETHOSTBYNAME_R_3_ARG
# elif defined(__sun) || defined(__sgi)
#define HAVE_GETHOSTBYNAME_R_5_ARG
# elif defined(__linux__)
/* Rely on the configure script */
# elif defined(_LINUX_SOURCE_COMPAT) /* Linux compatibility on AIX */
#define HAVE_GETHOSTBYNAME_R_6_ARG
# else
#  undef HAVE_GETHOSTBYNAME_R
# endif
#endif

#if !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
#define USE_GETHOSTBYNAME_LOCK
#endif

#if defined(__APPLE__) || defined(__CYGWIN__) || defined(__NetBSD__)
#  include <sys/ioctl.h>
#endif


#if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
/* make sure that the reentrant (gethostbyaddr_r etc)
   functions are declared correctly if compiling with
   MIPSPro 7.x in ANSI C mode (default) */

/* XXX Using _SGIAPI is the wrong thing,
   but I don't know what the right thing is. */
#undef _SGIAPI /* to avoid warning */
#define _SGIAPI

#undef _XOPEN_SOURCE
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#ifdef _SS_ALIGNSIZE
#define HAVE_GETADDRINFO
#define HAVE_GETNAMEINFO
#endif

#define HAVE_INET_PTON
#include <netdb.h>
#endif // __sgi

/* Solaris fails to define this variable at all. */
#if (defined(__sun) && defined(__SVR4)) && !defined(INET_ADDRSTRLEN)
#define INET_ADDRSTRLEN
#endif

/* Generic includes */
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif

#ifdef HAVE_NET_IF_H
#include <net/if.h>
#endif

#ifdef HAVE_NET_ETHERNET_H
#include <net/ethernet.h>
#endif

/* Generic socket object definitions and includes */
#define PySocket_BUILDING_SOCKET
#include "socketmodule.h"

/* Addressing includes */

#ifndef MS_WINDOWS

/* Non-MS WINDOWS includes */
#ifdef HAVE_NETDB_H
#  include <netdb.h>
#endif
#include <unistd.h>               // close()

/* Headers needed for inet_ntoa() and inet_addr() */
#   include <arpa/inet.h>

#  include <fcntl.h>

#else /* MS_WINDOWS */

/* MS_WINDOWS includes */
# ifdef HAVE_FCNTL_H
#  include <fcntl.h>
# endif

/* Helpers needed for AF_HYPERV */
# include <Rpc.h>

/* Macros based on the IPPROTO enum, see: https://bugs.python.org/issue29515 */
#define IPPROTO_ICMP
#define IPPROTO_IGMP
#define IPPROTO_GGP
#define IPPROTO_TCP
#define IPPROTO_PUP
#define IPPROTO_UDP
#define IPPROTO_IDP
#define IPPROTO_ND
#define IPPROTO_RAW
#define IPPROTO_MAX
#define IPPROTO_HOPOPTS
#define IPPROTO_IPV4
#define IPPROTO_IPV6
#define IPPROTO_ROUTING
#define IPPROTO_FRAGMENT
#define IPPROTO_ESP
#define IPPROTO_AH
#define IPPROTO_ICMPV6
#define IPPROTO_NONE
#define IPPROTO_DSTOPTS
#define IPPROTO_EGP
#define IPPROTO_PIM
#define IPPROTO_ICLFXBM
#define IPPROTO_ST
#define IPPROTO_CBT
#define IPPROTO_IGP
#define IPPROTO_RDP
#define IPPROTO_PGM
#define IPPROTO_L2TP
#define IPPROTO_SCTP

/* Provides the IsWindows7SP1OrGreater() function */
#include <versionhelpers.h>
// For if_nametoindex() and if_indextoname()
#include <iphlpapi.h>

/* remove some flags on older version Windows during run-time.
   https://msdn.microsoft.com/en-us/library/windows/desktop/ms738596.aspx */
typedef struct {
    DWORD build_number;  /* available starting with this Win10 BuildNumber */
    const char flag_name[20];
} FlagRuntimeInfo;

/* IMPORTANT: make sure the list ordered by descending build_number */
static FlagRuntimeInfo win_runtime_flags[] = {
    /* available starting with Windows 10 1709 */
    {16299, "TCP_KEEPIDLE"},
    {16299, "TCP_KEEPINTVL"},
    /* available starting with Windows 10 1703 */
    {15063, "TCP_KEEPCNT"},
    /* available starting with Windows 10 1607 */
    {14393, "TCP_FASTOPEN"}
};

/*[clinic input]
module _socket
class _socket.socket "PySocketSockObject *" "clinic_state()->sock_type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=2db2489bd2219fd8]*/

static int
remove_unusable_flags(PyObject *m)
{
    PyObject *dict;
    OSVERSIONINFOEX info;

    dict = PyModule_GetDict(m);
    if (dict == NULL) {
        return -1;
    }
#ifndef MS_WINDOWS_DESKTOP
    info.dwOSVersionInfoSize = sizeof(info);
    if (!GetVersionEx((OSVERSIONINFO*) &info)) {
        PyErr_SetFromWindowsErr(0);
        return -1;
    }
#else
    /* set to Windows 10, except BuildNumber. */
    memset(&info, 0, sizeof(info));
    info.dwOSVersionInfoSize = sizeof(info);
    info.dwMajorVersion = 10;
    info.dwMinorVersion = 0;

    /* set Condition Mask */
    DWORDLONG dwlConditionMask = 0;
    VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
    VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
    VER_SET_CONDITION(dwlConditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
#endif

    for (int i=0; i<sizeof(win_runtime_flags)/sizeof(FlagRuntimeInfo); i++) {
#ifdef MS_WINDOWS_DESKTOP
        info.dwBuildNumber = win_runtime_flags[i].build_number;
        /* greater than or equal to the specified version?
           Compatibility Mode will not cheat VerifyVersionInfo(...) */
        BOOL isSupported = VerifyVersionInfo(
            &info,
            VER_MAJORVERSION|VER_MINORVERSION|VER_BUILDNUMBER,
            dwlConditionMask);
#else
        /* note in this case 'info' is the actual OS version, whereas above
           it is the version to compare against. */
        BOOL isSupported = info.dwMajorVersion > 10 ||
            (info.dwMajorVersion == 10 && info.dwMinorVersion > 0) ||
            (info.dwMajorVersion == 10 && info.dwMinorVersion == 0 &&
            info.dwBuildNumber >= win_runtime_flags[i].build_number);
#endif
        if (isSupported) {
            break;
        }
        else {
            if (PyDict_PopString(dict, win_runtime_flags[i].flag_name,
                                 NULL) < 0) {
                return -1;
            }
        }
    }
    return 0;
}

#endif

#include <stddef.h>

#ifndef O_NONBLOCK
#define O_NONBLOCK
#endif

/* include Python's addrinfo.h unless it causes trouble */
#if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
  /* Do not include addinfo.h on some newer IRIX versions.
   * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
   * for example, but not by 6.5.10.
   */
#elif defined(_MSC_VER) && _MSC_VER>1201
  /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
   * EAI_* constants are defined in (the already included) ws2tcpip.h.
   */
#else
#  include "addrinfo.h"
#endif

#ifdef __APPLE__
/* On OS X, getaddrinfo returns no error indication of lookup
   failure, so we must use the emulation instead of the libinfo
   implementation. Unfortunately, performing an autoconf test
   for this bug would require DNS access for the machine performing
   the configuration, which is not acceptable. Therefore, we
   determine the bug just by checking for __APPLE__. If this bug
   gets ever fixed, perhaps checking for sys/version.h would be
   appropriate, which is 10/0 on the system with the bug. */
#ifndef HAVE_GETNAMEINFO
/* This bug seems to be fixed in Jaguar. The easiest way I could
   Find to check for Jaguar is that it has getnameinfo(), which
   older releases don't have */
#undef HAVE_GETADDRINFO
#endif

#ifdef HAVE_INET_ATON
#define USE_INET_ATON_WEAKLINK
#endif

#endif

/* I know this is a bad practice, but it is the easiest... */
#if !defined(HAVE_GETADDRINFO)
/* avoid clashes with the C library definition of the symbol. */
#define getaddrinfo
#define gai_strerror
#define freeaddrinfo
#include "getaddrinfo.c"
#endif

#if !defined(HAVE_GETNAMEINFO)
#define getnameinfo
#include "getnameinfo.c"
#endif // HAVE_GETNAMEINFO

#ifdef MS_WINDOWS
#define SOCKETCLOSE
#endif

#ifdef MS_WIN32
#  undef EAFNOSUPPORT
#define EAFNOSUPPORT
#endif

#ifndef SOCKETCLOSE
#define SOCKETCLOSE
#endif

#if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
#define USE_BLUETOOTH
#if defined(__FreeBSD__)
#define BTPROTO_L2CAP
#define BTPROTO_RFCOMM
#define BTPROTO_HCI
#define SOL_HCI
#define HCI_FILTER
#define sockaddr_l2
#define sockaddr_rc
#define hci_dev
#define _BT_L2_MEMB
#define _BT_RC_MEMB
#define _BT_HCI_MEMB
#elif defined(__NetBSD__) || defined(__DragonFly__)
#define sockaddr_l2
#define sockaddr_rc
#define sockaddr_hci
#define sockaddr_sco
#define SOL_HCI
#define HCI_DATA_DIR
#define _BT_L2_MEMB
#define _BT_RC_MEMB
#define _BT_HCI_MEMB
#define _BT_SCO_MEMB
#else
#define _BT_L2_MEMB
#define _BT_RC_MEMB
#define _BT_HCI_MEMB
#define _BT_SCO_MEMB
#endif
#endif

#ifdef MS_WINDOWS_DESKTOP
#define sockaddr_rc

#define USE_BLUETOOTH
#define AF_BLUETOOTH
#define BTPROTO_RFCOMM
#define _BT_RC_MEMB
#endif /* MS_WINDOWS_DESKTOP */

/* Convert "sock_addr_t *" to "struct sockaddr *". */
#define SAS2SA(x)

/*
 * Constants for getnameinfo()
 */
#if !defined(NI_MAXHOST)
#define NI_MAXHOST
#endif
#if !defined(NI_MAXSERV)
#define NI_MAXSERV
#endif

#ifndef INVALID_SOCKET /* MS defines this */
#define INVALID_SOCKET
#endif

#ifndef INADDR_NONE
#define INADDR_NONE
#endif

socket_state;

static inline socket_state *
get_module_state(PyObject *mod)
{}

static struct PyModuleDef socketmodule;

static inline socket_state *
find_module_state_by_def(PyTypeObject *type)
{}

#define clinic_state
#include "clinic/socketmodule.c.h"
#undef clinic_state

/* XXX There's a problem here: *static* functions are not supposed to have
   a Py prefix (or use CapitalizedWords).  Later... */

#if defined(HAVE_POLL_H)
#include <poll.h>
#elif defined(HAVE_SYS_POLL_H)
#include <sys/poll.h>
#endif

/* Largest value to try to store in a socklen_t (used when handling
   ancillary data).  POSIX requires socklen_t to hold at least
   (2**31)-1 and recommends against storing larger values, but
   socklen_t was originally int in the BSD interface, so to be on the
   safe side we use the smaller of (2**31)-1 and INT_MAX. */
#if INT_MAX > 0x7fffffff
#define SOCKLEN_T_LIMIT
#else
#define SOCKLEN_T_LIMIT
#endif

#ifdef HAVE_POLL
/* Instead of select(), we'll use poll() since poll() works on any fd. */
#define IS_SELECTABLE(s)
/* Can we call select() with this socket without a buffer overrun? */
#else
/* If there's no timeout left, we don't have to call select, so it's a safe,
 * little white lie. */
#define IS_SELECTABLE
#endif

static PyObject*
select_error(void)
{}

#ifdef MS_WINDOWS
#ifndef WSAEAGAIN
#define WSAEAGAIN
#endif
#define CHECK_ERRNO
#else
#define CHECK_ERRNO(expected)
#endif

#ifdef MS_WINDOWS
#define GET_SOCK_ERROR
#define SET_SOCK_ERROR
#define SOCK_TIMEOUT_ERR
#define SOCK_INPROGRESS_ERR
#else
#define GET_SOCK_ERROR
#define SET_SOCK_ERROR(err)
#define SOCK_TIMEOUT_ERR
#define SOCK_INPROGRESS_ERR
#endif

#ifdef _MSC_VER
#define SUPPRESS_DEPRECATED_CALL
#else
#define SUPPRESS_DEPRECATED_CALL
#endif

/* Convenience function to raise an error according to errno
   and return a NULL pointer from a function. */

static PyObject *
set_error(void)
{}


#if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME) || defined (HAVE_GETHOSTBYADDR)
static PyObject *
set_herror(socket_state *state, int h_error)
{}
#endif


#ifdef HAVE_GETADDRINFO
static PyObject *
set_gaierror(socket_state *state, int error)
{}
#endif

/* Function to perform the setting of socket blocking mode
   internally. block = (1 | 0). */
static int
internal_setblocking(PySocketSockObject *s, int block)
{}

static int
internal_select(PySocketSockObject *s, int writing, PyTime_t interval,
                int connect)
{}

/* Call a socket function.

   On error, raise an exception and return -1 if err is set, or fill err and
   return -1 otherwise. If a signal was received and the signal handler raised
   an exception, return -1, and set err to -1 if err is set.

   On success, return 0, and set err to 0 if err is set.

   If the socket has a timeout, wait until the socket is ready before calling
   the function: wait until the socket is writable if writing is nonzero, wait
   until the socket received data otherwise.

   If the socket function is interrupted by a signal (failed with EINTR): retry
   the function, except if the signal handler raised an exception (PEP 475).

   When the function is retried, recompute the timeout using a monotonic clock.

   sock_call_ex() must be called with the GIL held. The socket function is
   called with the GIL released. */
static int
sock_call_ex(PySocketSockObject *s,
             int writing,
             int (*sock_func) (PySocketSockObject *s, void *data),
             void *data,
             int connect,
             int *err,
             PyTime_t timeout)
{}

static int
sock_call(PySocketSockObject *s,
          int writing,
          int (*func) (PySocketSockObject *s, void *data),
          void *data)
{}


/* Initialize a new socket object. */

static int
init_sockobject(socket_state *state, PySocketSockObject *s,
                SOCKET_T fd, int family, int type, int proto)
{}


#ifdef HAVE_SOCKETPAIR
/* Create a new socket object.
   This just creates the object and initializes it.
   If the creation fails, return NULL and set an exception (implicit
   in NEWOBJ()). */

static PySocketSockObject *
new_sockobject(socket_state *state, SOCKET_T fd, int family, int type,
               int proto)
{}
#endif


/* Lock to allow python interpreter to continue, but only allow one
   thread to be in gethostbyname or getaddrinfo */
#if defined(USE_GETHOSTBYNAME_LOCK)
static PyThread_type_lock netdb_lock;
#endif


#ifdef HAVE_GETADDRINFO
/* Convert a string specifying a host name or one of a few symbolic
   names to a numeric IP address.  This usually calls gethostbyname()
   to do the work; the names "" and "<broadcast>" are special.
   Return the length (IPv4 should be 4 bytes), or negative if
   an error occurred; then an exception is raised. */

static int
setipaddr(socket_state *state, const char *name, struct sockaddr *addr_ret,
          size_t addr_ret_size, int af)
{}
#endif // HAVE_GETADDRINFO

/* Convert IPv4 sockaddr to a Python str. */

static PyObject *
make_ipv4_addr(const struct sockaddr_in *addr)
{}

#ifdef ENABLE_IPV6
/* Convert IPv6 sockaddr to a Python str. */

static PyObject *
make_ipv6_addr(const struct sockaddr_in6 *addr)
{}
#endif

#ifdef USE_BLUETOOTH
/* Convert a string representation of a Bluetooth address into a numeric
   address.  Returns the length (6), or raises an exception and returns -1 if
   an error occurred. */

static int
setbdaddr(const char *name, bdaddr_t *bdaddr)
{
    unsigned int b0, b1, b2, b3, b4, b5;
    char ch;
    int n;

    n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
               &b5, &b4, &b3, &b2, &b1, &b0, &ch);
    if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {

#ifdef MS_WINDOWS
        *bdaddr = (ULONGLONG)(b0 & 0xFF);
        *bdaddr |= ((ULONGLONG)(b1 & 0xFF) << 8);
        *bdaddr |= ((ULONGLONG)(b2 & 0xFF) << 16);
        *bdaddr |= ((ULONGLONG)(b3 & 0xFF) << 24);
        *bdaddr |= ((ULONGLONG)(b4 & 0xFF) << 32);
        *bdaddr |= ((ULONGLONG)(b5 & 0xFF) << 40);
#else
        bdaddr->b[0] = b0;
        bdaddr->b[1] = b1;
        bdaddr->b[2] = b2;
        bdaddr->b[3] = b3;
        bdaddr->b[4] = b4;
        bdaddr->b[5] = b5;
#endif

        return 6;
    } else {
        PyErr_SetString(PyExc_OSError, "bad bluetooth address");
        return -1;
    }
}

/* Create a string representation of the Bluetooth address.  This is always a
   string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
   value (zero padded if necessary). */

static PyObject *
makebdaddr(bdaddr_t *bdaddr)
{
#ifdef MS_WINDOWS
    int i;
    unsigned int octets[6];

    for (i = 0; i < 6; ++i) {
        octets[i] = ((*bdaddr) >> (8 * i)) & 0xFF;
    }

    return PyUnicode_FromFormat("%02X:%02X:%02X:%02X:%02X:%02X",
        octets[5], octets[4], octets[3],
        octets[2], octets[1], octets[0]);
#else
    return PyUnicode_FromFormat("%02X:%02X:%02X:%02X:%02X:%02X",
        bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
        bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
#endif
}
#endif


/* Create an object representing the given socket address,
   suitable for passing it back to bind(), connect() etc.
   The family field of the sockaddr structure is inspected
   to determine what kind of address it really is. */

/*ARGSUSED*/
static PyObject *
makesockaddr(SOCKET_T sockfd, struct sockaddr *addr, size_t addrlen, int proto)
{}

#if defined(HAVE_BIND) || defined(HAVE_CONNECTTO) || defined(CMSG_LEN)
/* Helper for getsockaddrarg: bypass IDNA for ASCII-only host names
   (in particular, numeric IP addresses). */
struct maybe_idna {};

static void
idna_cleanup(struct maybe_idna *data)
{}

static int
idna_converter(PyObject *obj, struct maybe_idna *data)
{}

/* Parse a socket address argument according to the socket object's
   address family.  Return 1 if the address was in the proper format,
   0 of not.  The address is returned through addr_ret, its length
   through len_ret. */

static int
getsockaddrarg(PySocketSockObject *s, PyObject *args,
               sock_addr_t *addrbuf, int *len_ret, const char *caller)
{}
#endif // defined(HAVE_BIND) || defined(HAVE_CONNECTTO) || defined(CMSG_LEN)


/* Get the address length according to the socket object's address family.
   Return 1 if the family is known, 0 otherwise.  The length is returned
   through len_ret. */

static int
getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
{}


/* Support functions for the sendmsg() and recvmsg[_into]() methods.
   Currently, these methods are only compiled if the RFC 2292/3542
   CMSG_LEN() macro is available.  Older systems seem to have used
   sizeof(struct cmsghdr) + (length) where CMSG_LEN() is used now, so
   it may be possible to define CMSG_LEN() that way if it's not
   provided.  Some architectures might need extra padding after the
   cmsghdr, however, and CMSG_LEN() would have to take account of
   this. */
#ifdef CMSG_LEN
/* If length is in range, set *result to CMSG_LEN(length) and return
   true; otherwise, return false. */
static int
get_CMSG_LEN(size_t length, size_t *result)
{}

#ifdef CMSG_SPACE
/* If length is in range, set *result to CMSG_SPACE(length) and return
   true; otherwise, return false. */
static int
get_CMSG_SPACE(size_t length, size_t *result)
{}
#endif

/* Return true iff msg->msg_controllen is valid, cmsgh is a valid
   pointer in msg->msg_control with at least "space" bytes after it,
   and its cmsg_len member inside the buffer. */
static int
cmsg_min_space(struct msghdr *msg, struct cmsghdr *cmsgh, size_t space)
{}

/* If pointer CMSG_DATA(cmsgh) is in buffer msg->msg_control, set
   *space to number of bytes following it in the buffer and return
   true; otherwise, return false.  Assumes cmsgh, msg->msg_control and
   msg->msg_controllen are valid. */
static int
get_cmsg_data_space(struct msghdr *msg, struct cmsghdr *cmsgh, size_t *space)
{}

/* If cmsgh is invalid or not contained in the buffer pointed to by
   msg->msg_control, return -1.  If cmsgh is valid and its associated
   data is entirely contained in the buffer, set *data_len to the
   length of the associated data and return 0.  If only part of the
   associated data is contained in the buffer but cmsgh is otherwise
   valid, set *data_len to the length contained in the buffer and
   return 1. */
static int
get_cmsg_data_len(struct msghdr *msg, struct cmsghdr *cmsgh, size_t *data_len)
{}
#endif    /* CMSG_LEN */


struct sock_accept {};

#if defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)

static int
sock_accept_impl(PySocketSockObject *s, void *data)
{}

/* s._accept() -> (fd, address) */

static PyObject *
sock_accept(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
{}

PyDoc_STRVAR(accept_doc,
"_accept() -> (integer, address info)\n\
\n\
Wait for an incoming connection.  Return a new socket file descriptor\n\
representing the connection, and the address of the client.\n\
For IP sockets, the address info is a pair (hostaddr, port).");
#endif // defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)


/* s.setblocking(flag) method.  Argument:
   False -- non-blocking mode; same as settimeout(0)
   True -- blocking mode; same as settimeout(None)
*/

static PyObject *
sock_setblocking(PySocketSockObject *s, PyObject *arg)
{}

PyDoc_STRVAR(setblocking_doc,
"setblocking(flag)\n\
\n\
Set the socket to blocking (flag is true) or non-blocking (false).\n\
setblocking(True) is equivalent to settimeout(None);\n\
setblocking(False) is equivalent to settimeout(0.0).");

/* s.getblocking() method.
   Returns True if socket is in blocking mode,
   False if it is in non-blocking mode.
*/
static PyObject *
sock_getblocking(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
{}

PyDoc_STRVAR(getblocking_doc,
"getblocking()\n\
\n\
Returns True if socket is in blocking mode, or False if it\n\
is in non-blocking mode.");

static int
socket_parse_timeout(PyTime_t *timeout, PyObject *timeout_obj)
{}

/* s.settimeout(timeout) method.  Argument:
   None -- no timeout, blocking mode; same as setblocking(True)
   0.0  -- non-blocking mode; same as setblocking(False)
   > 0  -- timeout mode; operations time out after timeout seconds
   < 0  -- illegal; raises an exception
*/
static PyObject *
sock_settimeout(PySocketSockObject *s, PyObject *arg)
{}

PyDoc_STRVAR(settimeout_doc,
"settimeout(timeout)\n\
\n\
Set a timeout on socket operations.  'timeout' can be a float,\n\
giving in seconds, or None.  Setting a timeout of None disables\n\
the timeout feature and is equivalent to setblocking(1).\n\
Setting a timeout of zero is the same as setblocking(0).");

/* s.gettimeout() method.
   Returns the timeout associated with a socket. */
static PyObject *
sock_gettimeout(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
{}

PyDoc_STRVAR(gettimeout_doc,
"gettimeout() -> timeout\n\
\n\
Returns the timeout in seconds (float) associated with socket\n\
operations. A timeout of None indicates that timeouts on socket\n\
operations are disabled.");

#ifdef HAVE_SETSOCKOPT
/* s.setsockopt() method.
   With an integer third argument, sets an integer optval with optlen=4.
   With None as third argument and an integer fourth argument, set
   optval=NULL with unsigned int as optlen.
   With a string third argument, sets an option from a buffer;
   use optional built-in module 'struct' to encode the string.
*/

static PyObject *
sock_setsockopt(PySocketSockObject *s, PyObject *args)
{}

PyDoc_STRVAR(setsockopt_doc,
"setsockopt(level, option, value: int)\n\
setsockopt(level, option, value: buffer)\n\
setsockopt(level, option, None, optlen: int)\n\
\n\
Set a socket option.  See the Unix manual for level and option.\n\
The value argument can either be an integer, a string buffer, or\n\
None, optlen.");
#endif

/* s.getsockopt() method.
   With two arguments, retrieves an integer option.
   With a third integer argument, retrieves a string buffer of that size;
   use optional built-in module 'struct' to decode the string. */

static PyObject *
sock_getsockopt(PySocketSockObject *s, PyObject *args)
{}

PyDoc_STRVAR(getsockopt_doc,
"getsockopt(level, option[, buffersize]) -> value\n\
\n\
Get a socket option.  See the Unix manual for level and option.\n\
If a nonzero buffersize argument is given, the return value is a\n\
string of that length; otherwise it is an integer.");


#ifdef HAVE_BIND
/* s.bind(sockaddr) method */

static PyObject *
sock_bind(PySocketSockObject *s, PyObject *addro)
{}

PyDoc_STRVAR(bind_doc,
"bind(address)\n\
\n\
Bind the socket to a local address.  For IP sockets, the address is a\n\
pair (host, port); the host must refer to the local host. For raw packet\n\
sockets the address is a tuple (ifname, proto [,pkttype [,hatype [,addr]]])");
#endif


/* s.close() method.
   Set the file descriptor to -1 so operations tried subsequently
   will surely fail. */

/*[clinic input]
@critical_section
_socket.socket.close
    self as s: self(type="PySocketSockObject *")

close()

Close the socket.  It cannot be used after this call.
[clinic start generated code]*/

static PyObject *
_socket_socket_close_impl(PySocketSockObject *s)
/*[clinic end generated code: output=038b2418e07f6f6c input=9839a261e05bcb97]*/
{}

static PyObject *
sock_detach(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
{}

PyDoc_STRVAR(detach_doc,
"detach()\n\
\n\
Close the socket object without closing the underlying file descriptor.\n\
The object cannot be used after this call, but the file descriptor\n\
can be reused for other purposes.  The file descriptor is returned.");

#ifdef HAVE_CONNECT
static int
sock_connect_impl(PySocketSockObject *s, void* Py_UNUSED(data))
{}

/* Common functionality for socket.connect and socket.connect_ex.
 *
 * If *raise* is set:
 * - On success, return 0.
 * - On any failure, return -1 with an exception set.
 * If *raise* is zero:
 * - On success, return 0.
 * - On connect() failure, return errno (without an exception set)
 * - On other error, return -1 with an exception set.
 *
 *   Note that -1 is a valid errno value on some systems.
 */
static int
internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
                 int raise)
{}

/* s.connect(sockaddr) method */

static PyObject *
sock_connect(PySocketSockObject *s, PyObject *addro)
{}

PyDoc_STRVAR(connect_doc,
"connect(address)\n\
\n\
Connect the socket to a remote address.  For IP sockets, the address\n\
is a pair (host, port).");


/* s.connect_ex(sockaddr) method */

static PyObject *
sock_connect_ex(PySocketSockObject *s, PyObject *addro)
{}

PyDoc_STRVAR(connect_ex_doc,
"connect_ex(address) -> errno\n\
\n\
This is like connect(address), but returns an error code (the errno value)\n\
instead of raising an exception when an error occurs.");
#endif // HAVE_CONNECT


/* s.fileno() method */

static PyObject *
sock_fileno(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
{}

PyDoc_STRVAR(fileno_doc,
"fileno() -> integer\n\
\n\
Return the integer file descriptor of the socket.");


#ifdef HAVE_GETSOCKNAME
/* s.getsockname() method */

static PyObject *
sock_getsockname(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
{}

PyDoc_STRVAR(getsockname_doc,
"getsockname() -> address info\n\
\n\
Return the address of the local endpoint. The format depends on the\n\
address family. For IPv4 sockets, the address info is a pair\n\
(hostaddr, port). For IPv6 sockets, the address info is a 4-tuple\n\
(hostaddr, port, flowinfo, scope_id).");
#endif


#ifdef HAVE_GETPEERNAME         /* Cray APP doesn't have this :-( */
/* s.getpeername() method */

static PyObject *
sock_getpeername(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
{}

PyDoc_STRVAR(getpeername_doc,
"getpeername() -> address info\n\
\n\
Return the address of the remote endpoint.  For IP sockets, the address\n\
info is a pair (hostaddr, port).");

#endif /* HAVE_GETPEERNAME */


#ifdef HAVE_LISTEN
/* s.listen(n) method */

static PyObject *
sock_listen(PySocketSockObject *s, PyObject *args)
{}

PyDoc_STRVAR(listen_doc,
"listen([backlog])\n\
\n\
Enable a server to accept connections.  If backlog is specified, it must be\n\
at least 0 (if it is lower, it is set to 0); it specifies the number of\n\
unaccepted connections that the system will allow before refusing new\n\
connections. If not specified, a default reasonable value is chosen.");
#endif

struct sock_recv {};

static int
sock_recv_impl(PySocketSockObject *s, void *data)
{}


/*
 * This is the guts of the recv() and recv_into() methods, which reads into a
 * char buffer.  If you have any inc/dec ref to do to the objects that contain
 * the buffer, do it in the caller.  This function returns the number of bytes
 * successfully read.  If there was an error, it returns -1.  Note that it is
 * also possible that we return a number of bytes smaller than the request
 * bytes.
 */

static Py_ssize_t
sock_recv_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags)
{}


/* s.recv(nbytes [,flags]) method */

static PyObject *
sock_recv(PySocketSockObject *s, PyObject *args)
{}

PyDoc_STRVAR(recv_doc,
"recv(buffersize[, flags]) -> data\n\
\n\
Receive up to buffersize bytes from the socket.  For the optional flags\n\
argument, see the Unix manual.  When no data is available, block until\n\
at least one byte is available or until the remote end is closed.  When\n\
the remote end is closed and all data is read, return the empty string.");


/* s.recv_into(buffer, [nbytes [,flags]]) method */

static PyObject*
sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
{}

PyDoc_STRVAR(recv_into_doc,
"recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
\n\
A version of recv() that stores its data into a buffer rather than creating\n\
a new string.  Receive up to buffersize bytes from the socket.  If buffersize\n\
is not specified (or 0), receive up to the size available in the given buffer.\n\
\n\
See recv() for documentation about the flags.");

struct sock_recvfrom {};

#ifdef HAVE_RECVFROM
static int
sock_recvfrom_impl(PySocketSockObject *s, void *data)
{}


/*
 * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
 * into a char buffer.  If you have any inc/def ref to do to the objects that
 * contain the buffer, do it in the caller.  This function returns the number
 * of bytes successfully read.  If there was an error, it returns -1.  Note
 * that it is also possible that we return a number of bytes smaller than the
 * request bytes.
 *
 * 'addr' is a return value for the address object.  Note that you must decref
 * it yourself.
 */
static Py_ssize_t
sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags,
                   PyObject** addr)
{}

/* s.recvfrom(nbytes [,flags]) method */

static PyObject *
sock_recvfrom(PySocketSockObject *s, PyObject *args)
{}

PyDoc_STRVAR(recvfrom_doc,
"recvfrom(buffersize[, flags]) -> (data, address info)\n\
\n\
Like recv(buffersize, flags) but also return the sender's address info.");


/* s.recvfrom_into(buffer[, nbytes [,flags]]) method */

static PyObject *
sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
{}

PyDoc_STRVAR(recvfrom_into_doc,
"recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
\n\
Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
#endif

/* The sendmsg() and recvmsg[_into]() methods require a working
   CMSG_LEN().  See the comment near get_CMSG_LEN(). */
#ifdef CMSG_LEN
struct sock_recvmsg {};

static int
sock_recvmsg_impl(PySocketSockObject *s, void *data)
{}

/*
 * Call recvmsg() with the supplied iovec structures, flags, and
 * ancillary data buffer size (controllen).  Returns the tuple return
 * value for recvmsg() or recvmsg_into(), with the first item provided
 * by the supplied makeval() function.  makeval() will be called with
 * the length read and makeval_data as arguments, and must return a
 * new reference (which will be decrefed if there is a subsequent
 * error).  On error, closes any file descriptors received via
 * SCM_RIGHTS.
 */
static PyObject *
sock_recvmsg_guts(PySocketSockObject *s, struct iovec *iov, int iovlen,
                  int flags, Py_ssize_t controllen,
                  PyObject *(*makeval)(ssize_t, void *), void *makeval_data)
{}


static PyObject *
makeval_recvmsg(ssize_t received, void *data)
{}

/* s.recvmsg(bufsize[, ancbufsize[, flags]]) method */

static PyObject *
sock_recvmsg(PySocketSockObject *s, PyObject *args)
{}

PyDoc_STRVAR(recvmsg_doc,
"recvmsg(bufsize[, ancbufsize[, flags]]) -> (data, ancdata, msg_flags, address)\n\
\n\
Receive normal data (up to bufsize bytes) and ancillary data from the\n\
socket.  The ancbufsize argument sets the size in bytes of the\n\
internal buffer used to receive the ancillary data; it defaults to 0,\n\
meaning that no ancillary data will be received.  Appropriate buffer\n\
sizes for ancillary data can be calculated using CMSG_SPACE() or\n\
CMSG_LEN(), and items which do not fit into the buffer might be\n\
truncated or discarded.  The flags argument defaults to 0 and has the\n\
same meaning as for recv().\n\
\n\
The return value is a 4-tuple: (data, ancdata, msg_flags, address).\n\
The data item is a bytes object holding the non-ancillary data\n\
received.  The ancdata item is a list of zero or more tuples\n\
(cmsg_level, cmsg_type, cmsg_data) representing the ancillary data\n\
(control messages) received: cmsg_level and cmsg_type are integers\n\
specifying the protocol level and protocol-specific type respectively,\n\
and cmsg_data is a bytes object holding the associated data.  The\n\
msg_flags item is the bitwise OR of various flags indicating\n\
conditions on the received message; see your system documentation for\n\
details.  If the receiving socket is unconnected, address is the\n\
address of the sending socket, if available; otherwise, its value is\n\
unspecified.\n\
\n\
If recvmsg() raises an exception after the system call returns, it\n\
will first attempt to close any file descriptors received via the\n\
SCM_RIGHTS mechanism.");


static PyObject *
makeval_recvmsg_into(ssize_t received, void *data)
{}

/* s.recvmsg_into(buffers[, ancbufsize[, flags]]) method */

static PyObject *
sock_recvmsg_into(PySocketSockObject *s, PyObject *args)
{}

PyDoc_STRVAR(recvmsg_into_doc,
"recvmsg_into(buffers[, ancbufsize[, flags]]) -> (nbytes, ancdata, msg_flags, address)\n\
\n\
Receive normal data and ancillary data from the socket, scattering the\n\
non-ancillary data into a series of buffers.  The buffers argument\n\
must be an iterable of objects that export writable buffers\n\
(e.g. bytearray objects); these will be filled with successive chunks\n\
of the non-ancillary data until it has all been written or there are\n\
no more buffers.  The ancbufsize argument sets the size in bytes of\n\
the internal buffer used to receive the ancillary data; it defaults to\n\
0, meaning that no ancillary data will be received.  Appropriate\n\
buffer sizes for ancillary data can be calculated using CMSG_SPACE()\n\
or CMSG_LEN(), and items which do not fit into the buffer might be\n\
truncated or discarded.  The flags argument defaults to 0 and has the\n\
same meaning as for recv().\n\
\n\
The return value is a 4-tuple: (nbytes, ancdata, msg_flags, address).\n\
The nbytes item is the total number of bytes of non-ancillary data\n\
written into the buffers.  The ancdata item is a list of zero or more\n\
tuples (cmsg_level, cmsg_type, cmsg_data) representing the ancillary\n\
data (control messages) received: cmsg_level and cmsg_type are\n\
integers specifying the protocol level and protocol-specific type\n\
respectively, and cmsg_data is a bytes object holding the associated\n\
data.  The msg_flags item is the bitwise OR of various flags\n\
indicating conditions on the received message; see your system\n\
documentation for details.  If the receiving socket is unconnected,\n\
address is the address of the sending socket, if available; otherwise,\n\
its value is unspecified.\n\
\n\
If recvmsg_into() raises an exception after the system call returns,\n\
it will first attempt to close any file descriptors received via the\n\
SCM_RIGHTS mechanism.");
#endif    /* CMSG_LEN */


struct sock_send {};

static int
sock_send_impl(PySocketSockObject *s, void *data)
{}

/* s.send(data [,flags]) method */

static PyObject *
sock_send(PySocketSockObject *s, PyObject *args)
{}

PyDoc_STRVAR(send_doc,
"send(data[, flags]) -> count\n\
\n\
Send a data string to the socket.  For the optional flags\n\
argument, see the Unix manual.  Return the number of bytes\n\
sent; this may be less than len(data) if the network is busy.");


/* s.sendall(data [,flags]) method */

static PyObject *
sock_sendall(PySocketSockObject *s, PyObject *args)
{}

PyDoc_STRVAR(sendall_doc,
"sendall(data[, flags])\n\
\n\
Send a data string to the socket.  For the optional flags\n\
argument, see the Unix manual.  This calls send() repeatedly\n\
until all data is sent.  If an error occurs, it's impossible\n\
to tell how much data has been sent.");


#ifdef HAVE_SENDTO
struct sock_sendto {};

static int
sock_sendto_impl(PySocketSockObject *s, void *data)
{}

/* s.sendto(data, [flags,] sockaddr) method */

static PyObject *
sock_sendto(PySocketSockObject *s, PyObject *args)
{}

PyDoc_STRVAR(sendto_doc,
"sendto(data[, flags], address) -> count\n\
\n\
Like send(data, flags) but allows specifying the destination address.\n\
For IP sockets, the address is a pair (hostaddr, port).");
#endif


/* The sendmsg() and recvmsg[_into]() methods require a working
   CMSG_LEN().  See the comment near get_CMSG_LEN(). */
#ifdef CMSG_LEN
struct sock_sendmsg {};

static int
sock_sendmsg_iovec(PySocketSockObject *s, PyObject *data_arg,
                   struct msghdr *msg,
                   Py_buffer **databufsout, Py_ssize_t *ndatabufsout) {}

static int
sock_sendmsg_impl(PySocketSockObject *s, void *data)
{}

/* s.sendmsg(buffers[, ancdata[, flags[, address]]]) method */

static PyObject *
sock_sendmsg(PySocketSockObject *s, PyObject *args)
{}

PyDoc_STRVAR(sendmsg_doc,
"sendmsg(buffers[, ancdata[, flags[, address]]]) -> count\n\
\n\
Send normal and ancillary data to the socket, gathering the\n\
non-ancillary data from a series of buffers and concatenating it into\n\
a single message.  The buffers argument specifies the non-ancillary\n\
data as an iterable of bytes-like objects (e.g. bytes objects).\n\
The ancdata argument specifies the ancillary data (control messages)\n\
as an iterable of zero or more tuples (cmsg_level, cmsg_type,\n\
cmsg_data), where cmsg_level and cmsg_type are integers specifying the\n\
protocol level and protocol-specific type respectively, and cmsg_data\n\
is a bytes-like object holding the associated data.  The flags\n\
argument defaults to 0 and has the same meaning as for send().  If\n\
address is supplied and not None, it sets a destination address for\n\
the message.  The return value is the number of bytes of non-ancillary\n\
data sent.");
#endif    /* CMSG_LEN */

#ifdef HAVE_SOCKADDR_ALG
static PyObject*
sock_sendmsg_afalg(PySocketSockObject *self, PyObject *args, PyObject *kwds)
{}

PyDoc_STRVAR(sendmsg_afalg_doc,
"sendmsg_afalg([msg], *, op[, iv[, assoclen[, flags=MSG_MORE]]])\n\
\n\
Set operation mode, IV and length of associated data for an AF_ALG\n\
operation socket.");
#endif

#ifdef HAVE_SHUTDOWN
/* s.shutdown(how) method */

static PyObject *
sock_shutdown(PySocketSockObject *s, PyObject *arg)
{}

PyDoc_STRVAR(shutdown_doc,
"shutdown(flag)\n\
\n\
Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
#endif

#if defined(MS_WINDOWS) && defined(SIO_RCVALL)
static PyObject*
sock_ioctl(PySocketSockObject *s, PyObject *arg)
{
    unsigned long cmd = SIO_RCVALL;
    PyObject *argO;
    DWORD recv;

    if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
        return NULL;

    switch (cmd) {
    case SIO_RCVALL: {
        unsigned int option = RCVALL_ON;
        if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
            return NULL;
        if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
                         NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
            return set_error();
        }
        return PyLong_FromUnsignedLong(recv); }
    case SIO_KEEPALIVE_VALS: {
        struct tcp_keepalive ka;
        if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
                        &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
            return NULL;
        if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
                         NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
            return set_error();
        }
        return PyLong_FromUnsignedLong(recv); }
#if defined(SIO_LOOPBACK_FAST_PATH)
    case SIO_LOOPBACK_FAST_PATH: {
        unsigned int option;
        if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
            return NULL;
        if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
                         NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
            return set_error();
        }
        return PyLong_FromUnsignedLong(recv); }
#endif
    default:
        PyErr_Format(PyExc_ValueError, "invalid ioctl command %lu", cmd);
        return NULL;
    }
}
PyDoc_STRVAR(sock_ioctl_doc,
"ioctl(cmd, option) -> long\n\
\n\
Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
SIO_RCVALL:  'option' must be one of the socket.RCVALL_* constants.\n\
SIO_KEEPALIVE_VALS:  'option' is a tuple of (onoff, timeout, interval).\n\
SIO_LOOPBACK_FAST_PATH: 'option' is a boolean value, and is disabled by default");
#endif

#if defined(MS_WINDOWS)
static PyObject*
sock_share(PySocketSockObject *s, PyObject *arg)
{
    WSAPROTOCOL_INFOW info;
    DWORD processId;
    int result;

    if (!PyArg_ParseTuple(arg, "I", &processId))
        return NULL;

    Py_BEGIN_ALLOW_THREADS
    result = WSADuplicateSocketW(s->sock_fd, processId, &info);
    Py_END_ALLOW_THREADS
    if (result == SOCKET_ERROR)
        return set_error();
    return PyBytes_FromStringAndSize((const char*)&info, sizeof(info));
}
PyDoc_STRVAR(sock_share_doc,
"share(process_id) -> bytes\n\
\n\
Share the socket with another process.  The target process id\n\
must be provided and the resulting bytes object passed to the target\n\
process.  There the shared socket can be instantiated by calling\n\
socket.fromshare().");


#endif

/* List of methods for socket objects */

static PyMethodDef sock_methods[] =;

/* SockObject members */
static PyMemberDef sock_memberlist[] =;

static PyGetSetDef sock_getsetlist[] =;

/* Deallocate a socket object in response to the last Py_DECREF().
   First close the file description. */

static void
sock_finalize(PySocketSockObject *s)
{}

static int
sock_traverse(PySocketSockObject *s, visitproc visit, void *arg)
{}

static void
sock_dealloc(PySocketSockObject *s)
{}


static PyObject *
sock_repr(PySocketSockObject *s)
{}


/* Create a new, uninitialized socket object. */

static PyObject *
sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{}


/* Initialize a new socket object. */

/*ARGSUSED*/

#ifndef HAVE_SOCKET
#define socket
static int
socket(int domain, int type, int protocol)
{
    errno = ENOTSUP;
    return INVALID_SOCKET;
}
#endif

/*[clinic input]
_socket.socket.__init__ as sock_initobj
    family: int = -1
    type: int = -1
    proto: int = -1
    fileno as fdobj: object = NULL
[clinic start generated code]*/

static int
sock_initobj_impl(PySocketSockObject *self, int family, int type, int proto,
                  PyObject *fdobj)
/*[clinic end generated code: output=d114d026b9a9a810 input=04cfc32953f5cc25]*/
{}


/* Type object for socket objects. */

static PyType_Slot sock_slots[] =;

static PyType_Spec sock_spec =;


#ifdef HAVE_GETHOSTNAME
/* Python interface to gethostname(). */

/*ARGSUSED*/
static PyObject *
socket_gethostname(PyObject *self, PyObject *unused)
{}

PyDoc_STRVAR(gethostname_doc,
"gethostname() -> string\n\
\n\
Return the current host name.");
#endif

#ifdef HAVE_SETHOSTNAME
PyDoc_STRVAR(sethostname_doc,
"sethostname(name)\n\n\
Sets the hostname to name.");

static PyObject *
socket_sethostname(PyObject *self, PyObject *args)
{}
#endif

#ifdef HAVE_GETADDRINFO
/* Python interface to gethostbyname(name). */

/*ARGSUSED*/
static PyObject *
socket_gethostbyname(PyObject *self, PyObject *args)
{}

PyDoc_STRVAR(gethostbyname_doc,
"gethostbyname(host) -> address\n\
\n\
Return the IP address (a string of the form '255.255.255.255') for a host.");
#endif


#if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME) || defined (HAVE_GETHOSTBYADDR)
static PyObject*
sock_decode_hostname(const char *name)
{}

/* Convenience function common to gethostbyname_ex and gethostbyaddr */

static PyObject *
gethost_common(socket_state *state, struct hostent *h, struct sockaddr *addr,
               size_t alen, int af)
{}
#endif

#if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME)
/* Python interface to gethostbyname_ex(name). */

/*ARGSUSED*/
static PyObject *
socket_gethostbyname_ex(PyObject *self, PyObject *args)
{}

PyDoc_STRVAR(ghbn_ex_doc,
"gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
\n\
Return the true host name, a list of aliases, and a list of IP addresses,\n\
for a host.  The host argument is a string giving a host name or IP number.");
#endif

#if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYADDR)
/* Python interface to gethostbyaddr(IP). */

/*ARGSUSED*/
static PyObject *
socket_gethostbyaddr(PyObject *self, PyObject *args)
{}

PyDoc_STRVAR(gethostbyaddr_doc,
"gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
\n\
Return the true host name, a list of aliases, and a list of IP addresses,\n\
for a host.  The host argument is a string giving a host name or IP number.");
#endif

#ifdef HAVE_GETSERVBYNAME
/* Python interface to getservbyname(name).
   This only returns the port number, since the other info is already
   known or not useful (like the list of aliases). */

/*ARGSUSED*/
static PyObject *
socket_getservbyname(PyObject *self, PyObject *args)
{}

PyDoc_STRVAR(getservbyname_doc,
"getservbyname(servicename[, protocolname]) -> integer\n\
\n\
Return a port number from a service name and protocol name.\n\
The optional protocol name, if given, should be 'tcp' or 'udp',\n\
otherwise any protocol will match.");
#endif

#ifdef HAVE_GETSERVBYPORT
/* Python interface to getservbyport(port).
   This only returns the service name, since the other info is already
   known or not useful (like the list of aliases). */

/*ARGSUSED*/
static PyObject *
socket_getservbyport(PyObject *self, PyObject *args)
{}

PyDoc_STRVAR(getservbyport_doc,
"getservbyport(port[, protocolname]) -> string\n\
\n\
Return the service name from a port number and protocol name.\n\
The optional protocol name, if given, should be 'tcp' or 'udp',\n\
otherwise any protocol will match.");
#endif

#ifdef HAVE_GETPROTOBYNAME
/* Python interface to getprotobyname(name).
   This only returns the protocol number, since the other info is
   already known or not useful (like the list of aliases). */

/*ARGSUSED*/
static PyObject *
socket_getprotobyname(PyObject *self, PyObject *args)
{}

PyDoc_STRVAR(getprotobyname_doc,
"getprotobyname(name) -> integer\n\
\n\
Return the protocol number for the named protocol.  (Rarely used.)");
#endif

static PyObject *
socket_close(PyObject *self, PyObject *fdobj)
{}

PyDoc_STRVAR(close_doc,
"close(integer) -> None\n\
\n\
Close an integer socket file descriptor.  This is like os.close(), but for\n\
sockets; on some platforms os.close() won't work for socket file descriptors.");

#ifndef NO_DUP
/* dup() function for socket fds */

static PyObject *
socket_dup(PyObject *self, PyObject *fdobj)
{}

PyDoc_STRVAR(dup_doc,
"dup(integer) -> integer\n\
\n\
Duplicate an integer socket file descriptor.  This is like os.dup(), but for\n\
sockets; on some platforms os.dup() won't work for socket file descriptors.");
#endif


#ifdef HAVE_SOCKETPAIR
/* Create a pair of sockets using the socketpair() function.
   Arguments as for socket() except the default family is AF_UNIX if
   defined on the platform; otherwise, the default is AF_INET. */

/*ARGSUSED*/
static PyObject *
socket_socketpair(PyObject *self, PyObject *args)
{}

PyDoc_STRVAR(socketpair_doc,
"socketpair([family[, type [, proto]]]) -> (socket object, socket object)\n\
\n\
Create a pair of socket objects from the sockets returned by the platform\n\
socketpair() function.\n\
The arguments are the same as for socket() except the default family is\n\
AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");

#endif /* HAVE_SOCKETPAIR */


/*[clinic input]
_socket.socket.ntohs
    x: int
    /

Convert a 16-bit unsigned integer from network to host byte order.
[clinic start generated code]*/

static PyObject *
_socket_socket_ntohs_impl(PySocketSockObject *self, int x)
/*[clinic end generated code: output=a828a61a9fb205b2 input=9a79cb3a71652147]*/
{}


static PyObject *
socket_ntohl(PyObject *self, PyObject *arg)
{}

PyDoc_STRVAR(ntohl_doc,
"ntohl(integer) -> integer\n\
\n\
Convert a 32-bit integer from network to host byte order.");


/*[clinic input]
_socket.socket.htons
    x: int
    /

Convert a 16-bit unsigned integer from host to network byte order.
[clinic start generated code]*/

static PyObject *
_socket_socket_htons_impl(PySocketSockObject *self, int x)
/*[clinic end generated code: output=d785ee692312da47 input=053252d8416f4337]*/
{}


static PyObject *
socket_htonl(PyObject *self, PyObject *arg)
{}

PyDoc_STRVAR(htonl_doc,
"htonl(integer) -> integer\n\
\n\
Convert a 32-bit integer from host to network byte order.");

/* socket.inet_aton() and socket.inet_ntoa() functions. */

/*[clinic input]
_socket.socket.inet_aton
    ip_addr: str
    /

Convert an IP address in string format (123.45.67.89) to the 32-bit packed binary format used in low-level network functions.
[clinic start generated code]*/

static PyObject *
_socket_socket_inet_aton_impl(PySocketSockObject *self, const char *ip_addr)
/*[clinic end generated code: output=5bfe11a255423d8c input=a120e20cb52b9488]*/
{}

#ifdef HAVE_INET_NTOA
/*[clinic input]
_socket.socket.inet_ntoa
    packed_ip: Py_buffer
    /

Convert an IP address from 32-bit packed binary format to string format.
[clinic start generated code]*/

static PyObject *
_socket_socket_inet_ntoa_impl(PySocketSockObject *self, Py_buffer *packed_ip)
/*[clinic end generated code: output=b671880a3f62461b input=95c2c4a1b2ee957c]*/
{}
#endif // HAVE_INET_NTOA

#ifdef HAVE_INET_PTON

PyDoc_STRVAR(inet_pton_doc,
"inet_pton(af, ip) -> packed IP address string\n\
\n\
Convert an IP address from string format to a packed string suitable\n\
for use with low-level network functions.");

static PyObject *
socket_inet_pton(PyObject *self, PyObject *args)
{}

PyDoc_STRVAR(inet_ntop_doc,
"inet_ntop(af, packed_ip) -> string formatted IP address\n\
\n\
Convert a packed IP address of the given family to string format.");

static PyObject *
socket_inet_ntop(PyObject *self, PyObject *args)
{}

#endif /* HAVE_INET_PTON */

#ifdef HAVE_GETADDRINFO
/* Python interface to getaddrinfo(host, port). */

/*ARGSUSED*/
static PyObject *
socket_getaddrinfo(PyObject *self, PyObject *args, PyObject* kwargs)
{}

PyDoc_STRVAR(getaddrinfo_doc,
"getaddrinfo(host, port [, family, type, proto, flags])\n\
    -> list of (family, type, proto, canonname, sockaddr)\n\
\n\
Resolve host and port into addrinfo struct.");
#endif // HAVE_GETADDRINFO

#ifdef HAVE_GETNAMEINFO
/* Python interface to getnameinfo(sa, flags). */

/*ARGSUSED*/
static PyObject *
socket_getnameinfo(PyObject *self, PyObject *args)
{}

PyDoc_STRVAR(getnameinfo_doc,
"getnameinfo(sockaddr, flags) --> (host, port)\n\
\n\
Get host and port for a sockaddr.");
#endif // HAVE_GETNAMEINFO

/* Python API to getting and setting the default timeout value. */

static PyObject *
socket_getdefaulttimeout(PyObject *self, PyObject *Py_UNUSED(ignored))
{}

PyDoc_STRVAR(getdefaulttimeout_doc,
"getdefaulttimeout() -> timeout\n\
\n\
Returns the default timeout in seconds (float) for new socket objects.\n\
A value of None indicates that new socket objects have no timeout.\n\
When the socket module is first imported, the default is None.");

static PyObject *
socket_setdefaulttimeout(PyObject *self, PyObject *arg)
{}

PyDoc_STRVAR(setdefaulttimeout_doc,
"setdefaulttimeout(timeout)\n\
\n\
Set the default timeout in seconds (float) for new socket objects.\n\
A value of None indicates that new socket objects have no timeout.\n\
When the socket module is first imported, the default is None.");

#if defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
/* Python API for getting interface indices and names */

static PyObject *
socket_if_nameindex(PyObject *self, PyObject *arg)
{}

PyDoc_STRVAR(if_nameindex_doc,
"if_nameindex()\n\
\n\
Returns a list of network interface information (index, name) tuples.");

/*[clinic input]
_socket.socket.if_nametoindex
    oname: object(converter="PyUnicode_FSConverter")
    /

Returns the interface index corresponding to the interface name if_name.
[clinic start generated code]*/

static PyObject *
_socket_socket_if_nametoindex_impl(PySocketSockObject *self, PyObject *oname)
/*[clinic end generated code: output=f7fc00511a309a8e input=662688054482cd46]*/
{}


static PyObject *
socket_if_indextoname(PyObject *self, PyObject *arg)
{}

PyDoc_STRVAR(if_indextoname_doc,
"if_indextoname(if_index)\n\
\n\
Returns the interface name corresponding to the interface index if_index.");

#endif // defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)


#ifdef CMSG_LEN
/* Python interface to CMSG_LEN(length). */

static PyObject *
socket_CMSG_LEN(PyObject *self, PyObject *args)
{}

PyDoc_STRVAR(CMSG_LEN_doc,
"CMSG_LEN(length) -> control message length\n\
\n\
Return the total length, without trailing padding, of an ancillary\n\
data item with associated data of the given length.  This value can\n\
often be used as the buffer size for recvmsg() to receive a single\n\
item of ancillary data, but RFC 3542 requires portable applications to\n\
use CMSG_SPACE() and thus include space for padding, even when the\n\
item will be the last in the buffer.  Raises OverflowError if length\n\
is outside the permissible range of values.");


#ifdef CMSG_SPACE
/* Python interface to CMSG_SPACE(length). */

static PyObject *
socket_CMSG_SPACE(PyObject *self, PyObject *args)
{}

PyDoc_STRVAR(CMSG_SPACE_doc,
"CMSG_SPACE(length) -> buffer size\n\
\n\
Return the buffer size needed for recvmsg() to receive an ancillary\n\
data item with associated data of the given length, along with any\n\
trailing padding.  The buffer space needed to receive multiple items\n\
is the sum of the CMSG_SPACE() values for their associated data\n\
lengths.  Raises OverflowError if length is outside the permissible\n\
range of values.");
#endif    /* CMSG_SPACE */
#endif    /* CMSG_LEN */


/* List of functions exported by this module. */

static PyMethodDef socket_methods[] =;


#ifdef MS_WINDOWS
#define OS_INIT_DEFINED

/* Additional initialization and cleanup for Windows */

static void
os_cleanup(void)
{
    WSACleanup();
}

static int
os_init(void)
{
    WSADATA WSAData;
    int ret;
    ret = WSAStartup(0x0101, &WSAData);
    switch (ret) {
    case 0:     /* No error */
        Py_AtExit(os_cleanup);
        return 1; /* Success */
    case WSASYSNOTREADY:
        PyErr_SetString(PyExc_ImportError,
                        "WSAStartup failed: network not ready");
        break;
    case WSAVERNOTSUPPORTED:
    case WSAEINVAL:
        PyErr_SetString(
            PyExc_ImportError,
            "WSAStartup failed: requested version not supported");
        break;
    default:
        PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret);
        break;
    }
    return 0; /* Failure */
}

#endif /* MS_WINDOWS */



#ifndef OS_INIT_DEFINED
static int
os_init(void)
{}
#endif

static int
sock_capi_traverse(PyObject *capsule, visitproc visit, void *arg)
{}

static int
sock_capi_clear(PyObject *capsule)
{}

static void
sock_capi_free(PySocketModule_APIObject *capi)
{}

static void
sock_capi_destroy(PyObject *capsule)
{}

static PySocketModule_APIObject *
sock_get_api(socket_state *state)
{}


/* Initialize the _socket module.

   This module is actually called "_socket", and there's a wrapper
   "socket.py" which implements some additional functionality.
   The import of "_socket" may fail with an ImportError exception if
   os-specific initialization fails.  On Windows, this does WINSOCK
   initialization.  When WINSOCK is initialized successfully, a call to
   WSACleanup() is scheduled to be made at exit time.
*/

PyDoc_STRVAR(socket_doc,
"Implementation module for socket operations.\n\
\n\
See the socket module for documentation.");

static int
socket_exec(PyObject *m)
{}

static struct PyModuleDef_Slot socket_slots[] =;

static int
socket_traverse(PyObject *mod, visitproc visit, void *arg)
{}

static int
socket_clear(PyObject *mod)
{}

static void
socket_free(void *mod)
{}

static struct PyModuleDef socketmodule =;

PyMODINIT_FUNC
PyInit__socket(void)
{}