1/* Socket module */
2
3/*
4
5This module provides an interface to Berkeley socket IPC.
6
7Limitations:
8
9- Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
10  portable manner, though AF_PACKET, AF_NETLINK 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
16Module 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.fromfd(fd, family, type[, proto]) --> new socket object (created
24    from an existing file descriptor)
25- socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
26- socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
27- socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
28- socket.getprotobyname(protocolname) --> protocol number
29- socket.getservbyname(servicename[, protocolname]) --> port number
30- socket.getservbyport(portnumber[, protocolname]) --> service name
31- socket.socket([family[, type [, proto]]]) --> new socket object
32- socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
33- socket.ntohs(16 bit value) --> new int object
34- socket.ntohl(32 bit value) --> new int object
35- socket.htons(16 bit value) --> new int object
36- socket.htonl(32 bit value) --> new int object
37- socket.getaddrinfo(host, port [, family, socktype, proto, flags])
38    --> List of (family, socktype, proto, canonname, sockaddr)
39- socket.getnameinfo(sockaddr, flags) --> (host, port)
40- socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
41- socket.has_ipv6: boolean value indicating if IPv6 is supported
42- socket.inet_aton(IP address) -> 32-bit packed IP representation
43- socket.inet_ntoa(packed IP) -> IP address string
44- socket.getdefaulttimeout() -> None | float
45- socket.setdefaulttimeout(None | float)
46- an Internet socket address is a pair (hostname, port)
47  where hostname can be anything recognized by gethostbyname()
48  (including the dd.dd.dd.dd notation) and port is in host byte order
49- where a hostname is returned, the dd.dd.dd.dd notation is used
50- a UNIX domain socket address is a string specifying the pathname
51- an AF_PACKET socket address is a tuple containing a string
52  specifying the ethernet interface and an integer specifying
53  the Ethernet protocol number to be received. For example:
54  ("eth0",0x1234).  Optional 3rd,4th,5th elements in the tuple
55  specify packet-type and ha-type/addr.
56- an AF_TIPC socket address is expressed as
57 (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
58    TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
59  and scope can be one of:
60    TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
61  The meaning of v1, v2 and v3 depends on the value of addr_type:
62    if addr_type is TIPC_ADDR_NAME:
63        v1 is the server type
64        v2 is the port identifier
65        v3 is ignored
66    if addr_type is TIPC_ADDR_NAMESEQ:
67        v1 is the server type
68        v2 is the lower port number
69        v3 is the upper port number
70    if addr_type is TIPC_ADDR_ID:
71        v1 is the node
72        v2 is the ref
73        v3 is ignored
74
75
76Local naming conventions:
77
78- names starting with sock_ are socket object methods
79- names starting with socket_ are module-level functions
80- names starting with PySocket are exported through socketmodule.h
81
82*/
83
84#ifdef __APPLE__
85  /*
86   * inet_aton is not available on OSX 10.3, yet we want to use a binary
87   * that was build on 10.4 or later to work on that release, weak linking
88   * comes to the rescue.
89   */
90# pragma weak inet_aton
91#endif
92
93#include "Python.h"
94#include "structmember.h"
95
96#undef MAX
97#define MAX(x, y) ((x) < (y) ? (y) : (x))
98
99/* Socket object documentation */
100PyDoc_STRVAR(sock_doc,
101"socket([family[, type[, proto]]]) -> socket object\n\
102\n\
103Open a socket of the given type.  The family argument specifies the\n\
104address family; it defaults to AF_INET.  The type argument specifies\n\
105whether this is a stream (SOCK_STREAM, this is the default)\n\
106or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,\n\
107specifying the default protocol.  Keyword arguments are accepted.\n\
108\n\
109A socket object represents one endpoint of a network connection.\n\
110\n\
111Methods of socket objects (keyword arguments not allowed):\n\
112\n\
113accept() -- accept a connection, returning new socket and client address\n\
114bind(addr) -- bind the socket to a local address\n\
115close() -- close the socket\n\
116connect(addr) -- connect the socket to a remote address\n\
117connect_ex(addr) -- connect, return an error code instead of an exception\n\
118dup() -- return a new socket object identical to the current one [*]\n\
119fileno() -- return underlying file descriptor\n\
120getpeername() -- return remote address [*]\n\
121getsockname() -- return local address\n\
122getsockopt(level, optname[, buflen]) -- get socket options\n\
123gettimeout() -- return timeout or None\n\
124listen(n) -- start listening for incoming connections\n\
125makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
126recv(buflen[, flags]) -- receive data\n\
127recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
128recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
129recvfrom_into(buffer[, nbytes, [, flags])\n\
130  -- receive data and sender\'s address (into a buffer)\n\
131sendall(data[, flags]) -- send all data\n\
132send(data[, flags]) -- send data, may not send all of it\n\
133sendto(data[, flags], addr) -- send data to a given address\n\
134setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
135setsockopt(level, optname, value) -- set socket options\n\
136settimeout(None | float) -- set or clear the timeout\n\
137shutdown(how) -- shut down traffic in one or both directions\n\
138\n\
139 [*] not available on all platforms!");
140
141/* XXX This is a terrible mess of platform-dependent preprocessor hacks.
142   I hope some day someone can clean this up please... */
143
144/* Hacks for gethostbyname_r().  On some non-Linux platforms, the configure
145   script doesn't get this right, so we hardcode some platform checks below.
146   On the other hand, not all Linux versions agree, so there the settings
147   computed by the configure script are needed! */
148
149#ifndef linux
150# undef HAVE_GETHOSTBYNAME_R_3_ARG
151# undef HAVE_GETHOSTBYNAME_R_5_ARG
152# undef HAVE_GETHOSTBYNAME_R_6_ARG
153#endif
154
155#ifndef WITH_THREAD
156# undef HAVE_GETHOSTBYNAME_R
157#endif
158
159#ifdef HAVE_GETHOSTBYNAME_R
160# if defined(_AIX) || defined(__osf__)
161#  define HAVE_GETHOSTBYNAME_R_3_ARG
162# elif defined(__sun) || defined(__sgi)
163#  define HAVE_GETHOSTBYNAME_R_5_ARG
164# elif defined(linux)
165/* Rely on the configure script */
166# else
167#  undef HAVE_GETHOSTBYNAME_R
168# endif
169#endif
170
171#if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
172    !defined(MS_WINDOWS)
173# define USE_GETHOSTBYNAME_LOCK
174#endif
175
176/* To use __FreeBSD_version */
177#ifdef HAVE_SYS_PARAM_H
178#include <sys/param.h>
179#endif
180/* On systems on which getaddrinfo() is believed to not be thread-safe,
181   (this includes the getaddrinfo emulation) protect access with a lock. */
182#if defined(WITH_THREAD) && (defined(__APPLE__) || \
183    (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
184    defined(__OpenBSD__) || defined(__NetBSD__) || \
185    defined(__VMS) || !defined(HAVE_GETADDRINFO))
186#define USE_GETADDRINFO_LOCK
187#endif
188
189#ifdef USE_GETADDRINFO_LOCK
190#define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
191#define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
192#else
193#define ACQUIRE_GETADDRINFO_LOCK
194#define RELEASE_GETADDRINFO_LOCK
195#endif
196
197#if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
198# include "pythread.h"
199#endif
200
201#if defined(PYCC_VACPP)
202# include <types.h>
203# include <io.h>
204# include <sys/ioctl.h>
205# include <utils.h>
206# include <ctype.h>
207#endif
208
209#if defined(__VMS)
210#  include <ioctl.h>
211#endif
212
213#if defined(PYOS_OS2)
214# define  INCL_DOS
215# define  INCL_DOSERRORS
216# define  INCL_NOPMAPI
217# include <os2.h>
218#endif
219
220#if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
221/* make sure that the reentrant (gethostbyaddr_r etc)
222   functions are declared correctly if compiling with
223   MIPSPro 7.x in ANSI C mode (default) */
224
225/* XXX Using _SGIAPI is the wrong thing,
226   but I don't know what the right thing is. */
227#undef _SGIAPI /* to avoid warning */
228#define _SGIAPI 1
229
230#undef _XOPEN_SOURCE
231#include <sys/socket.h>
232#include <sys/types.h>
233#include <netinet/in.h>
234#ifdef _SS_ALIGNSIZE
235#define HAVE_GETADDRINFO 1
236#define HAVE_GETNAMEINFO 1
237#endif
238
239#define HAVE_INET_PTON
240#include <netdb.h>
241#endif
242
243/* Irix 6.5 fails to define this variable at all. This is needed
244   for both GCC and SGI's compiler. I'd say that the SGI headers
245   are just busted. Same thing for Solaris. */
246#if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
247#define INET_ADDRSTRLEN 16
248#endif
249
250/* Generic includes */
251#ifdef HAVE_SYS_TYPES_H
252#include <sys/types.h>
253#endif
254
255/* Generic socket object definitions and includes */
256#define PySocket_BUILDING_SOCKET
257#include "socketmodule.h"
258
259/* Addressing includes */
260
261#ifndef MS_WINDOWS
262
263/* Non-MS WINDOWS includes */
264# include <netdb.h>
265
266/* Headers needed for inet_ntoa() and inet_addr() */
267# ifdef __BEOS__
268#  include <net/netdb.h>
269# elif defined(PYOS_OS2) && defined(PYCC_VACPP)
270#  include <netdb.h>
271typedef size_t socklen_t;
272# else
273#   include <arpa/inet.h>
274# endif
275
276# ifndef RISCOS
277#  include <fcntl.h>
278# else
279#  include <sys/ioctl.h>
280#  include <socklib.h>
281#  define NO_DUP
282int h_errno; /* not used */
283#  define INET_ADDRSTRLEN 16
284# endif
285
286#else
287
288/* MS_WINDOWS includes */
289# ifdef HAVE_FCNTL_H
290#  include <fcntl.h>
291# endif
292
293#endif
294
295#include <stddef.h>
296
297#ifndef offsetof
298# define offsetof(type, member) ((size_t)(&((type *)0)->member))
299#endif
300
301#ifndef O_NONBLOCK
302# define O_NONBLOCK O_NDELAY
303#endif
304
305/* include Python's addrinfo.h unless it causes trouble */
306#if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
307  /* Do not include addinfo.h on some newer IRIX versions.
308   * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
309   * for example, but not by 6.5.10.
310   */
311#elif defined(_MSC_VER) && _MSC_VER>1201
312  /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
313   * EAI_* constants are defined in (the already included) ws2tcpip.h.
314   */
315#else
316#  include "addrinfo.h"
317#endif
318
319#ifndef HAVE_INET_PTON
320#if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
321int inet_pton(int af, const char *src, void *dst);
322const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
323#endif
324#endif
325
326#ifdef __APPLE__
327/* On OS X, getaddrinfo returns no error indication of lookup
328   failure, so we must use the emulation instead of the libinfo
329   implementation. Unfortunately, performing an autoconf test
330   for this bug would require DNS access for the machine performing
331   the configuration, which is not acceptable. Therefore, we
332   determine the bug just by checking for __APPLE__. If this bug
333   gets ever fixed, perhaps checking for sys/version.h would be
334   appropriate, which is 10/0 on the system with the bug. */
335#ifndef HAVE_GETNAMEINFO
336/* This bug seems to be fixed in Jaguar. Ths easiest way I could
337   Find to check for Jaguar is that it has getnameinfo(), which
338   older releases don't have */
339#undef HAVE_GETADDRINFO
340#endif
341
342#ifdef HAVE_INET_ATON
343#define USE_INET_ATON_WEAKLINK
344#endif
345
346#endif
347
348/* I know this is a bad practice, but it is the easiest... */
349#if !defined(HAVE_GETADDRINFO)
350/* avoid clashes with the C library definition of the symbol. */
351#define getaddrinfo fake_getaddrinfo
352#define gai_strerror fake_gai_strerror
353#define freeaddrinfo fake_freeaddrinfo
354#include "getaddrinfo.c"
355#endif
356#if !defined(HAVE_GETNAMEINFO)
357#define getnameinfo fake_getnameinfo
358#include "getnameinfo.c"
359#endif
360
361#if defined(MS_WINDOWS) || defined(__BEOS__)
362/* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
363/* seem to be a few differences in the API */
364#define SOCKETCLOSE closesocket
365#define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
366#endif
367
368#ifdef MS_WIN32
369#define EAFNOSUPPORT WSAEAFNOSUPPORT
370#define snprintf _snprintf
371#endif
372
373#if defined(PYOS_OS2) && !defined(PYCC_GCC)
374#define SOCKETCLOSE soclose
375#define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
376#endif
377
378#ifndef SOCKETCLOSE
379#define SOCKETCLOSE close
380#endif
381
382#if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
383#define USE_BLUETOOTH 1
384#if defined(__FreeBSD__)
385#define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
386#define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
387#define BTPROTO_HCI BLUETOOTH_PROTO_HCI
388#define SOL_HCI SOL_HCI_RAW
389#define HCI_FILTER SO_HCI_RAW_FILTER
390#define sockaddr_l2 sockaddr_l2cap
391#define sockaddr_rc sockaddr_rfcomm
392#define hci_dev hci_node
393#define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
394#define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
395#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
396#elif defined(__NetBSD__) || defined(__DragonFly__)
397#define sockaddr_l2 sockaddr_bt
398#define sockaddr_rc sockaddr_bt
399#define sockaddr_hci sockaddr_bt
400#define sockaddr_sco sockaddr_bt
401#define SOL_HCI BTPROTO_HCI
402#define HCI_DATA_DIR SO_HCI_DIRECTION
403#define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
404#define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
405#define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
406#define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
407#else
408#define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
409#define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
410#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
411#define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
412#endif
413#endif
414
415#ifdef __VMS
416/* TCP/IP Services for VMS uses a maximum send/recv buffer length */
417#define SEGMENT_SIZE (32 * 1024 -1)
418#endif
419
420#define SAS2SA(x)       ((struct sockaddr *)(x))
421
422/*
423 * Constants for getnameinfo()
424 */
425#if !defined(NI_MAXHOST)
426#define NI_MAXHOST 1025
427#endif
428#if !defined(NI_MAXSERV)
429#define NI_MAXSERV 32
430#endif
431
432/* XXX There's a problem here: *static* functions are not supposed to have
433   a Py prefix (or use CapitalizedWords).  Later... */
434
435/* Global variable holding the exception type for errors detected
436   by this module (but not argument type or memory errors, etc.). */
437static PyObject *socket_error;
438static PyObject *socket_herror;
439static PyObject *socket_gaierror;
440static PyObject *socket_timeout;
441
442#ifdef RISCOS
443/* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
444static int taskwindow;
445#endif
446
447/* A forward reference to the socket type object.
448   The sock_type variable contains pointers to various functions,
449   some of which call new_sockobject(), which uses sock_type, so
450   there has to be a circular reference. */
451static PyTypeObject sock_type;
452
453#if defined(HAVE_POLL_H)
454#include <poll.h>
455#elif defined(HAVE_SYS_POLL_H)
456#include <sys/poll.h>
457#endif
458
459#ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
460/* Platform can select file descriptors beyond FD_SETSIZE */
461#define IS_SELECTABLE(s) 1
462#elif defined(HAVE_POLL)
463/* Instead of select(), we'll use poll() since poll() works on any fd. */
464#define IS_SELECTABLE(s) 1
465/* Can we call select() with this socket without a buffer overrun? */
466#else
467/* POSIX says selecting file descriptors beyond FD_SETSIZE
468   has undefined behaviour.  If there's no timeout left, we don't have to
469   call select, so it's a safe, little white lie. */
470#define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
471#endif
472
473static PyObject*
474select_error(void)
475{
476    PyErr_SetString(socket_error, "unable to select on socket");
477    return NULL;
478}
479
480/* Convenience function to raise an error according to errno
481   and return a NULL pointer from a function. */
482
483static PyObject *
484set_error(void)
485{
486#ifdef MS_WINDOWS
487    int err_no = WSAGetLastError();
488    /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
489       recognizes the error codes used by both GetLastError() and
490       WSAGetLastError */
491    if (err_no)
492        return PyErr_SetExcFromWindowsErr(socket_error, err_no);
493#endif
494
495#if defined(PYOS_OS2) && !defined(PYCC_GCC)
496    if (sock_errno() != NO_ERROR) {
497        APIRET rc;
498        ULONG  msglen;
499        char outbuf[100];
500        int myerrorcode = sock_errno();
501
502        /* Retrieve socket-related error message from MPTN.MSG file */
503        rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
504                           myerrorcode - SOCBASEERR + 26,
505                           "mptn.msg",
506                           &msglen);
507        if (rc == NO_ERROR) {
508            PyObject *v;
509
510            /* OS/2 doesn't guarantee a terminator */
511            outbuf[msglen] = '\0';
512            if (strlen(outbuf) > 0) {
513                /* If non-empty msg, trim CRLF */
514                char *lastc = &outbuf[ strlen(outbuf)-1 ];
515                while (lastc > outbuf &&
516                       isspace(Py_CHARMASK(*lastc))) {
517                    /* Trim trailing whitespace (CRLF) */
518                    *lastc-- = '\0';
519                }
520            }
521            v = Py_BuildValue("(is)", myerrorcode, outbuf);
522            if (v != NULL) {
523                PyErr_SetObject(socket_error, v);
524                Py_DECREF(v);
525            }
526            return NULL;
527        }
528    }
529#endif
530
531#if defined(RISCOS)
532    if (_inet_error.errnum != NULL) {
533        PyObject *v;
534        v = Py_BuildValue("(is)", errno, _inet_err());
535        if (v != NULL) {
536            PyErr_SetObject(socket_error, v);
537            Py_DECREF(v);
538        }
539        return NULL;
540    }
541#endif
542
543    return PyErr_SetFromErrno(socket_error);
544}
545
546
547static PyObject *
548set_herror(int h_error)
549{
550    PyObject *v;
551
552#ifdef HAVE_HSTRERROR
553    v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
554#else
555    v = Py_BuildValue("(is)", h_error, "host not found");
556#endif
557    if (v != NULL) {
558        PyErr_SetObject(socket_herror, v);
559        Py_DECREF(v);
560    }
561
562    return NULL;
563}
564
565
566static PyObject *
567set_gaierror(int error)
568{
569    PyObject *v;
570
571#ifdef EAI_SYSTEM
572    /* EAI_SYSTEM is not available on Windows XP. */
573    if (error == EAI_SYSTEM)
574        return set_error();
575#endif
576
577#ifdef HAVE_GAI_STRERROR
578    v = Py_BuildValue("(is)", error, gai_strerror(error));
579#else
580    v = Py_BuildValue("(is)", error, "getaddrinfo failed");
581#endif
582    if (v != NULL) {
583        PyErr_SetObject(socket_gaierror, v);
584        Py_DECREF(v);
585    }
586
587    return NULL;
588}
589
590#ifdef __VMS
591/* Function to send in segments */
592static int
593sendsegmented(int sock_fd, char *buf, int len, int flags)
594{
595    int n = 0;
596    int remaining = len;
597
598    while (remaining > 0) {
599        unsigned int segment;
600
601        segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
602        n = send(sock_fd, buf, segment, flags);
603        if (n < 0) {
604            return n;
605        }
606        remaining -= segment;
607        buf += segment;
608    } /* end while */
609
610    return len;
611}
612#endif
613
614/* Function to perform the setting of socket blocking mode
615   internally. block = (1 | 0). */
616static int
617internal_setblocking(PySocketSockObject *s, int block)
618{
619#ifndef RISCOS
620#ifndef MS_WINDOWS
621    int delay_flag;
622#endif
623#endif
624
625    Py_BEGIN_ALLOW_THREADS
626#ifdef __BEOS__
627    block = !block;
628    setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
629               (void *)(&block), sizeof(int));
630#else
631#ifndef RISCOS
632#ifndef MS_WINDOWS
633#if defined(PYOS_OS2) && !defined(PYCC_GCC)
634    block = !block;
635    ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
636#elif defined(__VMS)
637    block = !block;
638    ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
639#else  /* !PYOS_OS2 && !__VMS */
640    delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
641    if (block)
642        delay_flag &= (~O_NONBLOCK);
643    else
644        delay_flag |= O_NONBLOCK;
645    fcntl(s->sock_fd, F_SETFL, delay_flag);
646#endif /* !PYOS_OS2 */
647#else /* MS_WINDOWS */
648    block = !block;
649    ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
650#endif /* MS_WINDOWS */
651#else /* RISCOS */
652    block = !block;
653    socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
654#endif /* RISCOS */
655#endif /* __BEOS__ */
656    Py_END_ALLOW_THREADS
657
658    /* Since these don't return anything */
659    return 1;
660}
661
662/* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
663   The argument writing indicates the direction.
664   This does not raise an exception; we'll let our caller do that
665   after they've reacquired the interpreter lock.
666   Returns 1 on timeout, -1 on error, 0 otherwise. */
667static int
668internal_select(PySocketSockObject *s, int writing)
669{
670    int n;
671
672    /* Nothing to do unless we're in timeout mode (not non-blocking) */
673    if (s->sock_timeout <= 0.0)
674        return 0;
675
676    /* Guard against closed socket */
677    if (s->sock_fd < 0)
678        return 0;
679
680    /* Prefer poll, if available, since you can poll() any fd
681     * which can't be done with select(). */
682#ifdef HAVE_POLL
683    {
684        struct pollfd pollfd;
685        int timeout;
686
687        pollfd.fd = s->sock_fd;
688        pollfd.events = writing ? POLLOUT : POLLIN;
689
690        /* s->sock_timeout is in seconds, timeout in ms */
691        timeout = (int)(s->sock_timeout * 1000 + 0.5);
692        n = poll(&pollfd, 1, timeout);
693    }
694#else
695    {
696        /* Construct the arguments to select */
697        fd_set fds;
698        struct timeval tv;
699        tv.tv_sec = (int)s->sock_timeout;
700        tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
701        FD_ZERO(&fds);
702        FD_SET(s->sock_fd, &fds);
703
704        /* See if the socket is ready */
705        if (writing)
706            n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
707        else
708            n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
709    }
710#endif
711
712    if (n < 0)
713        return -1;
714    if (n == 0)
715        return 1;
716    return 0;
717}
718
719/* Initialize a new socket object. */
720
721static double defaulttimeout = -1.0; /* Default timeout for new sockets */
722
723PyMODINIT_FUNC
724init_sockobject(PySocketSockObject *s,
725                SOCKET_T fd, int family, int type, int proto)
726{
727#ifdef RISCOS
728    int block = 1;
729#endif
730    s->sock_fd = fd;
731    s->sock_family = family;
732    s->sock_type = type;
733    s->sock_proto = proto;
734    s->sock_timeout = defaulttimeout;
735
736    s->errorhandler = &set_error;
737
738    if (defaulttimeout >= 0.0)
739        internal_setblocking(s, 0);
740
741#ifdef RISCOS
742    if (taskwindow)
743        socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
744#endif
745}
746
747
748/* Create a new socket object.
749   This just creates the object and initializes it.
750   If the creation fails, return NULL and set an exception (implicit
751   in NEWOBJ()). */
752
753static PySocketSockObject *
754new_sockobject(SOCKET_T fd, int family, int type, int proto)
755{
756    PySocketSockObject *s;
757    s = (PySocketSockObject *)
758        PyType_GenericNew(&sock_type, NULL, NULL);
759    if (s != NULL)
760        init_sockobject(s, fd, family, type, proto);
761    return s;
762}
763
764
765/* Lock to allow python interpreter to continue, but only allow one
766   thread to be in gethostbyname or getaddrinfo */
767#if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
768PyThread_type_lock netdb_lock;
769#endif
770
771
772/* Convert a string specifying a host name or one of a few symbolic
773   names to a numeric IP address.  This usually calls gethostbyname()
774   to do the work; the names "" and "<broadcast>" are special.
775   Return the length (IPv4 should be 4 bytes), or negative if
776   an error occurred; then an exception is raised. */
777
778static int
779setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
780{
781    struct addrinfo hints, *res;
782    int error;
783    int d1, d2, d3, d4;
784    char ch;
785
786    memset((void *) addr_ret, '\0', sizeof(*addr_ret));
787    if (name[0] == '\0') {
788        int siz;
789        memset(&hints, 0, sizeof(hints));
790        hints.ai_family = af;
791        hints.ai_socktype = SOCK_DGRAM;         /*dummy*/
792        hints.ai_flags = AI_PASSIVE;
793        Py_BEGIN_ALLOW_THREADS
794        ACQUIRE_GETADDRINFO_LOCK
795        error = getaddrinfo(NULL, "0", &hints, &res);
796        Py_END_ALLOW_THREADS
797        /* We assume that those thread-unsafe getaddrinfo() versions
798           *are* safe regarding their return value, ie. that a
799           subsequent call to getaddrinfo() does not destroy the
800           outcome of the first call. */
801        RELEASE_GETADDRINFO_LOCK
802        if (error) {
803            set_gaierror(error);
804            return -1;
805        }
806        switch (res->ai_family) {
807        case AF_INET:
808            siz = 4;
809            break;
810#ifdef ENABLE_IPV6
811        case AF_INET6:
812            siz = 16;
813            break;
814#endif
815        default:
816            freeaddrinfo(res);
817            PyErr_SetString(socket_error,
818                "unsupported address family");
819            return -1;
820        }
821        if (res->ai_next) {
822            freeaddrinfo(res);
823            PyErr_SetString(socket_error,
824                "wildcard resolved to multiple address");
825            return -1;
826        }
827        if (res->ai_addrlen < addr_ret_size)
828            addr_ret_size = res->ai_addrlen;
829        memcpy(addr_ret, res->ai_addr, addr_ret_size);
830        freeaddrinfo(res);
831        return siz;
832    }
833    if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
834        struct sockaddr_in *sin;
835        if (af != AF_INET && af != AF_UNSPEC) {
836            PyErr_SetString(socket_error,
837                "address family mismatched");
838            return -1;
839        }
840        sin = (struct sockaddr_in *)addr_ret;
841        memset((void *) sin, '\0', sizeof(*sin));
842        sin->sin_family = AF_INET;
843#ifdef HAVE_SOCKADDR_SA_LEN
844        sin->sin_len = sizeof(*sin);
845#endif
846        sin->sin_addr.s_addr = INADDR_BROADCAST;
847        return sizeof(sin->sin_addr);
848    }
849    if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
850        0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
851        0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
852        struct sockaddr_in *sin;
853        sin = (struct sockaddr_in *)addr_ret;
854        sin->sin_addr.s_addr = htonl(
855            ((long) d1 << 24) | ((long) d2 << 16) |
856            ((long) d3 << 8) | ((long) d4 << 0));
857        sin->sin_family = AF_INET;
858#ifdef HAVE_SOCKADDR_SA_LEN
859        sin->sin_len = sizeof(*sin);
860#endif
861        return 4;
862    }
863    memset(&hints, 0, sizeof(hints));
864    hints.ai_family = af;
865    Py_BEGIN_ALLOW_THREADS
866    ACQUIRE_GETADDRINFO_LOCK
867    error = getaddrinfo(name, NULL, &hints, &res);
868#if defined(__digital__) && defined(__unix__)
869    if (error == EAI_NONAME && af == AF_UNSPEC) {
870        /* On Tru64 V5.1, numeric-to-addr conversion fails
871           if no address family is given. Assume IPv4 for now.*/
872        hints.ai_family = AF_INET;
873        error = getaddrinfo(name, NULL, &hints, &res);
874    }
875#endif
876    Py_END_ALLOW_THREADS
877    RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
878    if (error) {
879        set_gaierror(error);
880        return -1;
881    }
882    if (res->ai_addrlen < addr_ret_size)
883        addr_ret_size = res->ai_addrlen;
884    memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
885    freeaddrinfo(res);
886    switch (addr_ret->sa_family) {
887    case AF_INET:
888        return 4;
889#ifdef ENABLE_IPV6
890    case AF_INET6:
891        return 16;
892#endif
893    default:
894        PyErr_SetString(socket_error, "unknown address family");
895        return -1;
896    }
897}
898
899
900/* Create a string object representing an IP address.
901   This is always a string of the form 'dd.dd.dd.dd' (with variable
902   size numbers). */
903
904static PyObject *
905makeipaddr(struct sockaddr *addr, int addrlen)
906{
907    char buf[NI_MAXHOST];
908    int error;
909
910    error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
911        NI_NUMERICHOST);
912    if (error) {
913        set_gaierror(error);
914        return NULL;
915    }
916    return PyString_FromString(buf);
917}
918
919
920#ifdef USE_BLUETOOTH
921/* Convert a string representation of a Bluetooth address into a numeric
922   address.  Returns the length (6), or raises an exception and returns -1 if
923   an error occurred. */
924
925static int
926setbdaddr(char *name, bdaddr_t *bdaddr)
927{
928    unsigned int b0, b1, b2, b3, b4, b5;
929    char ch;
930    int n;
931
932    n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
933               &b5, &b4, &b3, &b2, &b1, &b0, &ch);
934    if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
935        bdaddr->b[0] = b0;
936        bdaddr->b[1] = b1;
937        bdaddr->b[2] = b2;
938        bdaddr->b[3] = b3;
939        bdaddr->b[4] = b4;
940        bdaddr->b[5] = b5;
941        return 6;
942    } else {
943        PyErr_SetString(socket_error, "bad bluetooth address");
944        return -1;
945    }
946}
947
948/* Create a string representation of the Bluetooth address.  This is always a
949   string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
950   value (zero padded if necessary). */
951
952static PyObject *
953makebdaddr(bdaddr_t *bdaddr)
954{
955    char buf[(6 * 2) + 5 + 1];
956
957    sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
958        bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
959        bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
960    return PyString_FromString(buf);
961}
962#endif
963
964
965/* Create an object representing the given socket address,
966   suitable for passing it back to bind(), connect() etc.
967   The family field of the sockaddr structure is inspected
968   to determine what kind of address it really is. */
969
970/*ARGSUSED*/
971static PyObject *
972makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
973{
974    if (addrlen == 0) {
975        /* No address -- may be recvfrom() from known socket */
976        Py_INCREF(Py_None);
977        return Py_None;
978    }
979
980#ifdef __BEOS__
981    /* XXX: BeOS version of accept() doesn't set family correctly */
982    addr->sa_family = AF_INET;
983#endif
984
985    switch (addr->sa_family) {
986
987    case AF_INET:
988    {
989        struct sockaddr_in *a;
990        PyObject *addrobj = makeipaddr(addr, sizeof(*a));
991        PyObject *ret = NULL;
992        if (addrobj) {
993            a = (struct sockaddr_in *)addr;
994            ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
995            Py_DECREF(addrobj);
996        }
997        return ret;
998    }
999
1000#if defined(AF_UNIX)
1001    case AF_UNIX:
1002    {
1003        struct sockaddr_un *a = (struct sockaddr_un *) addr;
1004#ifdef linux
1005        if (a->sun_path[0] == 0) {  /* Linux abstract namespace */
1006            addrlen -= offsetof(struct sockaddr_un, sun_path);
1007            return PyString_FromStringAndSize(a->sun_path,
1008                                              addrlen);
1009        }
1010        else
1011#endif /* linux */
1012        {
1013            /* regular NULL-terminated string */
1014            return PyString_FromString(a->sun_path);
1015        }
1016    }
1017#endif /* AF_UNIX */
1018
1019#if defined(AF_NETLINK)
1020       case AF_NETLINK:
1021       {
1022           struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
1023           return Py_BuildValue("II", a->nl_pid, a->nl_groups);
1024       }
1025#endif /* AF_NETLINK */
1026
1027#ifdef ENABLE_IPV6
1028    case AF_INET6:
1029    {
1030        struct sockaddr_in6 *a;
1031        PyObject *addrobj = makeipaddr(addr, sizeof(*a));
1032        PyObject *ret = NULL;
1033        if (addrobj) {
1034            a = (struct sockaddr_in6 *)addr;
1035            ret = Py_BuildValue("Oiii",
1036                                addrobj,
1037                                ntohs(a->sin6_port),
1038                                a->sin6_flowinfo,
1039                                a->sin6_scope_id);
1040            Py_DECREF(addrobj);
1041        }
1042        return ret;
1043    }
1044#endif
1045
1046#ifdef USE_BLUETOOTH
1047    case AF_BLUETOOTH:
1048        switch (proto) {
1049
1050        case BTPROTO_L2CAP:
1051        {
1052            struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
1053            PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
1054            PyObject *ret = NULL;
1055            if (addrobj) {
1056                ret = Py_BuildValue("Oi",
1057                                    addrobj,
1058                                    _BT_L2_MEMB(a, psm));
1059                Py_DECREF(addrobj);
1060            }
1061            return ret;
1062        }
1063
1064        case BTPROTO_RFCOMM:
1065        {
1066            struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
1067            PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
1068            PyObject *ret = NULL;
1069            if (addrobj) {
1070                ret = Py_BuildValue("Oi",
1071                                    addrobj,
1072                                    _BT_RC_MEMB(a, channel));
1073                Py_DECREF(addrobj);
1074            }
1075            return ret;
1076        }
1077
1078        case BTPROTO_HCI:
1079        {
1080            struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
1081#if defined(__NetBSD__) || defined(__DragonFly__)
1082            return makebdaddr(&_BT_HCI_MEMB(a, bdaddr));
1083#else
1084            PyObject *ret = NULL;
1085            ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
1086            return ret;
1087#endif
1088        }
1089
1090#if !defined(__FreeBSD__)
1091        case BTPROTO_SCO:
1092        {
1093            struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1094            return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1095        }
1096#endif
1097
1098        default:
1099            PyErr_SetString(PyExc_ValueError,
1100                            "Unknown Bluetooth protocol");
1101            return NULL;
1102        }
1103#endif
1104
1105#if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFNAME)
1106    case AF_PACKET:
1107    {
1108        struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1109        char *ifname = "";
1110        struct ifreq ifr;
1111        /* need to look up interface name give index */
1112        if (a->sll_ifindex) {
1113            ifr.ifr_ifindex = a->sll_ifindex;
1114            if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1115                ifname = ifr.ifr_name;
1116        }
1117        return Py_BuildValue("shbhs#",
1118                             ifname,
1119                             ntohs(a->sll_protocol),
1120                             a->sll_pkttype,
1121                             a->sll_hatype,
1122                             a->sll_addr,
1123                             a->sll_halen);
1124    }
1125#endif
1126
1127#ifdef HAVE_LINUX_TIPC_H
1128    case AF_TIPC:
1129    {
1130        struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
1131        if (a->addrtype == TIPC_ADDR_NAMESEQ) {
1132            return Py_BuildValue("IIIII",
1133                            a->addrtype,
1134                            a->addr.nameseq.type,
1135                            a->addr.nameseq.lower,
1136                            a->addr.nameseq.upper,
1137                            a->scope);
1138        } else if (a->addrtype == TIPC_ADDR_NAME) {
1139            return Py_BuildValue("IIIII",
1140                            a->addrtype,
1141                            a->addr.name.name.type,
1142                            a->addr.name.name.instance,
1143                            a->addr.name.name.instance,
1144                            a->scope);
1145        } else if (a->addrtype == TIPC_ADDR_ID) {
1146            return Py_BuildValue("IIIII",
1147                            a->addrtype,
1148                            a->addr.id.node,
1149                            a->addr.id.ref,
1150                            0,
1151                            a->scope);
1152        } else {
1153            PyErr_SetString(PyExc_ValueError,
1154                            "Invalid address type");
1155            return NULL;
1156        }
1157    }
1158#endif
1159
1160    /* More cases here... */
1161
1162    default:
1163        /* If we don't know the address family, don't raise an
1164           exception -- return it as a tuple. */
1165        return Py_BuildValue("is#",
1166                             addr->sa_family,
1167                             addr->sa_data,
1168                             sizeof(addr->sa_data));
1169
1170    }
1171}
1172
1173
1174/* Parse a socket address argument according to the socket object's
1175   address family.  Return 1 if the address was in the proper format,
1176   0 of not.  The address is returned through addr_ret, its length
1177   through len_ret. */
1178
1179static int
1180getsockaddrarg(PySocketSockObject *s, PyObject *args,
1181               struct sockaddr *addr_ret, int *len_ret)
1182{
1183    switch (s->sock_family) {
1184
1185#if defined(AF_UNIX)
1186    case AF_UNIX:
1187    {
1188        struct sockaddr_un* addr;
1189        char *path;
1190        int len;
1191        if (!PyArg_Parse(args, "t#", &path, &len))
1192            return 0;
1193
1194        addr = (struct sockaddr_un*)addr_ret;
1195#ifdef linux
1196        if (len > 0 && path[0] == 0) {
1197            /* Linux abstract namespace extension */
1198            if (len > sizeof addr->sun_path) {
1199                PyErr_SetString(socket_error,
1200                                "AF_UNIX path too long");
1201                return 0;
1202            }
1203        }
1204        else
1205#endif /* linux */
1206        {
1207            /* regular NULL-terminated string */
1208            if (len >= sizeof addr->sun_path) {
1209                PyErr_SetString(socket_error,
1210                                "AF_UNIX path too long");
1211                return 0;
1212            }
1213            addr->sun_path[len] = 0;
1214        }
1215        addr->sun_family = s->sock_family;
1216        memcpy(addr->sun_path, path, len);
1217#if defined(PYOS_OS2)
1218        *len_ret = sizeof(*addr);
1219#else
1220        *len_ret = len + offsetof(struct sockaddr_un, sun_path);
1221#endif
1222        return 1;
1223    }
1224#endif /* AF_UNIX */
1225
1226#if defined(AF_NETLINK)
1227    case AF_NETLINK:
1228    {
1229        struct sockaddr_nl* addr;
1230        int pid, groups;
1231        addr = (struct sockaddr_nl *)addr_ret;
1232        if (!PyTuple_Check(args)) {
1233            PyErr_Format(
1234                PyExc_TypeError,
1235                "getsockaddrarg: "
1236                "AF_NETLINK address must be tuple, not %.500s",
1237                Py_TYPE(args)->tp_name);
1238            return 0;
1239        }
1240        if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
1241            return 0;
1242        addr->nl_family = AF_NETLINK;
1243        addr->nl_pid = pid;
1244        addr->nl_groups = groups;
1245        *len_ret = sizeof(*addr);
1246        return 1;
1247    }
1248#endif
1249
1250    case AF_INET:
1251    {
1252        struct sockaddr_in* addr;
1253        char *host;
1254        int port, result;
1255        if (!PyTuple_Check(args)) {
1256            PyErr_Format(
1257                PyExc_TypeError,
1258                "getsockaddrarg: "
1259                "AF_INET address must be tuple, not %.500s",
1260                Py_TYPE(args)->tp_name);
1261            return 0;
1262        }
1263        if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
1264                              "idna", &host, &port))
1265            return 0;
1266        addr=(struct sockaddr_in*)addr_ret;
1267        result = setipaddr(host, (struct sockaddr *)addr,
1268                           sizeof(*addr),  AF_INET);
1269        PyMem_Free(host);
1270        if (result < 0)
1271            return 0;
1272        if (port < 0 || port > 0xffff) {
1273            PyErr_SetString(
1274                PyExc_OverflowError,
1275                "getsockaddrarg: port must be 0-65535.");
1276            return 0;
1277        }
1278        addr->sin_family = AF_INET;
1279        addr->sin_port = htons((short)port);
1280        *len_ret = sizeof *addr;
1281        return 1;
1282    }
1283
1284#ifdef ENABLE_IPV6
1285    case AF_INET6:
1286    {
1287        struct sockaddr_in6* addr;
1288        char *host;
1289        int port, flowinfo, scope_id, result;
1290        flowinfo = scope_id = 0;
1291        if (!PyTuple_Check(args)) {
1292            PyErr_Format(
1293                PyExc_TypeError,
1294                "getsockaddrarg: "
1295                "AF_INET6 address must be tuple, not %.500s",
1296                Py_TYPE(args)->tp_name);
1297            return 0;
1298        }
1299        if (!PyArg_ParseTuple(args, "eti|ii",
1300                              "idna", &host, &port, &flowinfo,
1301                              &scope_id)) {
1302            return 0;
1303        }
1304        addr = (struct sockaddr_in6*)addr_ret;
1305        result = setipaddr(host, (struct sockaddr *)addr,
1306                           sizeof(*addr), AF_INET6);
1307        PyMem_Free(host);
1308        if (result < 0)
1309            return 0;
1310        if (port < 0 || port > 0xffff) {
1311            PyErr_SetString(
1312                PyExc_OverflowError,
1313                "getsockaddrarg: port must be 0-65535.");
1314            return 0;
1315        }
1316        addr->sin6_family = s->sock_family;
1317        addr->sin6_port = htons((short)port);
1318        addr->sin6_flowinfo = flowinfo;
1319        addr->sin6_scope_id = scope_id;
1320        *len_ret = sizeof *addr;
1321        return 1;
1322    }
1323#endif
1324
1325#ifdef USE_BLUETOOTH
1326    case AF_BLUETOOTH:
1327    {
1328        switch (s->sock_proto) {
1329        case BTPROTO_L2CAP:
1330        {
1331            struct sockaddr_l2 *addr;
1332            char *straddr;
1333
1334            addr = (struct sockaddr_l2 *)addr_ret;
1335            memset(addr, 0, sizeof(struct sockaddr_l2));
1336            _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1337            if (!PyArg_ParseTuple(args, "si", &straddr,
1338                                  &_BT_L2_MEMB(addr, psm))) {
1339                PyErr_SetString(socket_error, "getsockaddrarg: "
1340                                "wrong format");
1341                return 0;
1342            }
1343            if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1344                return 0;
1345
1346            *len_ret = sizeof *addr;
1347            return 1;
1348        }
1349        case BTPROTO_RFCOMM:
1350        {
1351            struct sockaddr_rc *addr;
1352            char *straddr;
1353
1354            addr = (struct sockaddr_rc *)addr_ret;
1355            _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1356            if (!PyArg_ParseTuple(args, "si", &straddr,
1357                                  &_BT_RC_MEMB(addr, channel))) {
1358                PyErr_SetString(socket_error, "getsockaddrarg: "
1359                                "wrong format");
1360                return 0;
1361            }
1362            if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
1363                return 0;
1364
1365            *len_ret = sizeof *addr;
1366            return 1;
1367        }
1368        case BTPROTO_HCI:
1369        {
1370            struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
1371#if defined(__NetBSD__) || defined(__DragonFly__)
1372			char *straddr = PyBytes_AS_STRING(args);
1373
1374			_BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
1375            if (straddr == NULL) {
1376                PyErr_SetString(socket_error, "getsockaddrarg: "
1377                    "wrong format");
1378                return 0;
1379            }
1380            if (setbdaddr(straddr, &_BT_HCI_MEMB(addr, bdaddr)) < 0)
1381                return 0;
1382#else
1383            _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
1384            if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
1385                PyErr_SetString(socket_error, "getsockaddrarg: "
1386                                "wrong format");
1387                return 0;
1388            }
1389#endif
1390            *len_ret = sizeof *addr;
1391            return 1;
1392        }
1393#if !defined(__FreeBSD__)
1394        case BTPROTO_SCO:
1395        {
1396            struct sockaddr_sco *addr;
1397            char *straddr;
1398
1399            addr = (struct sockaddr_sco *)addr_ret;
1400            _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
1401            straddr = PyString_AsString(args);
1402            if (straddr == NULL) {
1403                PyErr_SetString(socket_error, "getsockaddrarg: "
1404                                "wrong format");
1405                return 0;
1406            }
1407            if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
1408                return 0;
1409
1410            *len_ret = sizeof *addr;
1411            return 1;
1412        }
1413#endif
1414        default:
1415            PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
1416            return 0;
1417        }
1418    }
1419#endif
1420
1421#if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFINDEX)
1422    case AF_PACKET:
1423    {
1424        struct sockaddr_ll* addr;
1425        struct ifreq ifr;
1426        char *interfaceName;
1427        int protoNumber;
1428        int hatype = 0;
1429        int pkttype = 0;
1430        char *haddr = NULL;
1431        unsigned int halen = 0;
1432
1433        if (!PyTuple_Check(args)) {
1434            PyErr_Format(
1435                PyExc_TypeError,
1436                "getsockaddrarg: "
1437                "AF_PACKET address must be tuple, not %.500s",
1438                Py_TYPE(args)->tp_name);
1439            return 0;
1440        }
1441        if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
1442                              &protoNumber, &pkttype, &hatype,
1443                              &haddr, &halen))
1444            return 0;
1445        strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1446        ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1447        if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1448            s->errorhandler();
1449            return 0;
1450        }
1451        if (halen > 8) {
1452          PyErr_SetString(PyExc_ValueError,
1453                          "Hardware address must be 8 bytes or less");
1454          return 0;
1455        }
1456        if (protoNumber < 0 || protoNumber > 0xffff) {
1457            PyErr_SetString(
1458                PyExc_OverflowError,
1459                "getsockaddrarg: protoNumber must be 0-65535.");
1460            return 0;
1461        }
1462        addr = (struct sockaddr_ll*)addr_ret;
1463        addr->sll_family = AF_PACKET;
1464        addr->sll_protocol = htons((short)protoNumber);
1465        addr->sll_ifindex = ifr.ifr_ifindex;
1466        addr->sll_pkttype = pkttype;
1467        addr->sll_hatype = hatype;
1468        if (halen != 0) {
1469          memcpy(&addr->sll_addr, haddr, halen);
1470        }
1471        addr->sll_halen = halen;
1472        *len_ret = sizeof *addr;
1473        return 1;
1474    }
1475#endif
1476
1477#ifdef HAVE_LINUX_TIPC_H
1478    case AF_TIPC:
1479    {
1480        unsigned int atype, v1, v2, v3;
1481        unsigned int scope = TIPC_CLUSTER_SCOPE;
1482        struct sockaddr_tipc *addr;
1483
1484        if (!PyTuple_Check(args)) {
1485            PyErr_Format(
1486                PyExc_TypeError,
1487                "getsockaddrarg: "
1488                "AF_TIPC address must be tuple, not %.500s",
1489                Py_TYPE(args)->tp_name);
1490            return 0;
1491        }
1492
1493        if (!PyArg_ParseTuple(args,
1494                                "IIII|I;Invalid TIPC address format",
1495                                &atype, &v1, &v2, &v3, &scope))
1496            return 0;
1497
1498        addr = (struct sockaddr_tipc *) addr_ret;
1499        memset(addr, 0, sizeof(struct sockaddr_tipc));
1500
1501        addr->family = AF_TIPC;
1502        addr->scope = scope;
1503        addr->addrtype = atype;
1504
1505        if (atype == TIPC_ADDR_NAMESEQ) {
1506            addr->addr.nameseq.type = v1;
1507            addr->addr.nameseq.lower = v2;
1508            addr->addr.nameseq.upper = v3;
1509        } else if (atype == TIPC_ADDR_NAME) {
1510            addr->addr.name.name.type = v1;
1511            addr->addr.name.name.instance = v2;
1512        } else if (atype == TIPC_ADDR_ID) {
1513            addr->addr.id.node = v1;
1514            addr->addr.id.ref = v2;
1515        } else {
1516            /* Shouldn't happen */
1517            PyErr_SetString(PyExc_TypeError, "Invalid address type");
1518            return 0;
1519        }
1520
1521        *len_ret = sizeof(*addr);
1522
1523        return 1;
1524    }
1525#endif
1526
1527    /* More cases here... */
1528
1529    default:
1530        PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1531        return 0;
1532
1533    }
1534}
1535
1536
1537/* Get the address length according to the socket object's address family.
1538   Return 1 if the family is known, 0 otherwise.  The length is returned
1539   through len_ret. */
1540
1541static int
1542getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1543{
1544    switch (s->sock_family) {
1545
1546#if defined(AF_UNIX)
1547    case AF_UNIX:
1548    {
1549        *len_ret = sizeof (struct sockaddr_un);
1550        return 1;
1551    }
1552#endif /* AF_UNIX */
1553#if defined(AF_NETLINK)
1554       case AF_NETLINK:
1555       {
1556           *len_ret = sizeof (struct sockaddr_nl);
1557           return 1;
1558       }
1559#endif
1560
1561    case AF_INET:
1562    {
1563        *len_ret = sizeof (struct sockaddr_in);
1564        return 1;
1565    }
1566
1567#ifdef ENABLE_IPV6
1568    case AF_INET6:
1569    {
1570        *len_ret = sizeof (struct sockaddr_in6);
1571        return 1;
1572    }
1573#endif
1574
1575#ifdef USE_BLUETOOTH
1576    case AF_BLUETOOTH:
1577    {
1578        switch(s->sock_proto)
1579        {
1580
1581        case BTPROTO_L2CAP:
1582            *len_ret = sizeof (struct sockaddr_l2);
1583            return 1;
1584        case BTPROTO_RFCOMM:
1585            *len_ret = sizeof (struct sockaddr_rc);
1586            return 1;
1587        case BTPROTO_HCI:
1588            *len_ret = sizeof (struct sockaddr_hci);
1589            return 1;
1590#if !defined(__FreeBSD__)
1591        case BTPROTO_SCO:
1592            *len_ret = sizeof (struct sockaddr_sco);
1593            return 1;
1594#endif
1595        default:
1596            PyErr_SetString(socket_error, "getsockaddrlen: "
1597                            "unknown BT protocol");
1598            return 0;
1599
1600        }
1601    }
1602#endif
1603
1604#ifdef HAVE_NETPACKET_PACKET_H
1605    case AF_PACKET:
1606    {
1607        *len_ret = sizeof (struct sockaddr_ll);
1608        return 1;
1609    }
1610#endif
1611
1612#ifdef HAVE_LINUX_TIPC_H
1613    case AF_TIPC:
1614    {
1615        *len_ret = sizeof (struct sockaddr_tipc);
1616        return 1;
1617    }
1618#endif
1619
1620    /* More cases here... */
1621
1622    default:
1623        PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1624        return 0;
1625
1626    }
1627}
1628
1629
1630/* s.accept() method */
1631
1632static PyObject *
1633sock_accept(PySocketSockObject *s)
1634{
1635    sock_addr_t addrbuf;
1636    SOCKET_T newfd;
1637    socklen_t addrlen;
1638    PyObject *sock = NULL;
1639    PyObject *addr = NULL;
1640    PyObject *res = NULL;
1641    int timeout;
1642
1643    if (!getsockaddrlen(s, &addrlen))
1644        return NULL;
1645    memset(&addrbuf, 0, addrlen);
1646
1647#ifdef MS_WINDOWS
1648    newfd = INVALID_SOCKET;
1649#else
1650    newfd = -1;
1651#endif
1652
1653    if (!IS_SELECTABLE(s))
1654        return select_error();
1655
1656    Py_BEGIN_ALLOW_THREADS
1657    timeout = internal_select(s, 0);
1658    if (!timeout)
1659        newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
1660    Py_END_ALLOW_THREADS
1661
1662    if (timeout == 1) {
1663        PyErr_SetString(socket_timeout, "timed out");
1664        return NULL;
1665    }
1666
1667#ifdef MS_WINDOWS
1668    if (newfd == INVALID_SOCKET)
1669#else
1670    if (newfd < 0)
1671#endif
1672        return s->errorhandler();
1673
1674    /* Create the new object with unspecified family,
1675       to avoid calls to bind() etc. on it. */
1676    sock = (PyObject *) new_sockobject(newfd,
1677                                       s->sock_family,
1678                                       s->sock_type,
1679                                       s->sock_proto);
1680
1681    if (sock == NULL) {
1682        SOCKETCLOSE(newfd);
1683        goto finally;
1684    }
1685    addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
1686                        addrlen, s->sock_proto);
1687    if (addr == NULL)
1688        goto finally;
1689
1690    res = PyTuple_Pack(2, sock, addr);
1691
1692finally:
1693    Py_XDECREF(sock);
1694    Py_XDECREF(addr);
1695    return res;
1696}
1697
1698PyDoc_STRVAR(accept_doc,
1699"accept() -> (socket object, address info)\n\
1700\n\
1701Wait for an incoming connection.  Return a new socket representing the\n\
1702connection, and the address of the client.  For IP sockets, the address\n\
1703info is a pair (hostaddr, port).");
1704
1705/* s.setblocking(flag) method.  Argument:
1706   False -- non-blocking mode; same as settimeout(0)
1707   True -- blocking mode; same as settimeout(None)
1708*/
1709
1710static PyObject *
1711sock_setblocking(PySocketSockObject *s, PyObject *arg)
1712{
1713    int block;
1714
1715    block = PyInt_AsLong(arg);
1716    if (block == -1 && PyErr_Occurred())
1717        return NULL;
1718
1719    s->sock_timeout = block ? -1.0 : 0.0;
1720    internal_setblocking(s, block);
1721
1722    Py_INCREF(Py_None);
1723    return Py_None;
1724}
1725
1726PyDoc_STRVAR(setblocking_doc,
1727"setblocking(flag)\n\
1728\n\
1729Set the socket to blocking (flag is true) or non-blocking (false).\n\
1730setblocking(True) is equivalent to settimeout(None);\n\
1731setblocking(False) is equivalent to settimeout(0.0).");
1732
1733/* s.settimeout(timeout) method.  Argument:
1734   None -- no timeout, blocking mode; same as setblocking(True)
1735   0.0  -- non-blocking mode; same as setblocking(False)
1736   > 0  -- timeout mode; operations time out after timeout seconds
1737   < 0  -- illegal; raises an exception
1738*/
1739static PyObject *
1740sock_settimeout(PySocketSockObject *s, PyObject *arg)
1741{
1742    double timeout;
1743
1744    if (arg == Py_None)
1745        timeout = -1.0;
1746    else {
1747        timeout = PyFloat_AsDouble(arg);
1748        if (timeout < 0.0) {
1749            if (!PyErr_Occurred())
1750                PyErr_SetString(PyExc_ValueError,
1751                                "Timeout value out of range");
1752            return NULL;
1753        }
1754    }
1755
1756    s->sock_timeout = timeout;
1757    internal_setblocking(s, timeout < 0.0);
1758
1759    Py_INCREF(Py_None);
1760    return Py_None;
1761}
1762
1763PyDoc_STRVAR(settimeout_doc,
1764"settimeout(timeout)\n\
1765\n\
1766Set a timeout on socket operations.  'timeout' can be a float,\n\
1767giving in seconds, or None.  Setting a timeout of None disables\n\
1768the timeout feature and is equivalent to setblocking(1).\n\
1769Setting a timeout of zero is the same as setblocking(0).");
1770
1771/* s.gettimeout() method.
1772   Returns the timeout associated with a socket. */
1773static PyObject *
1774sock_gettimeout(PySocketSockObject *s)
1775{
1776    if (s->sock_timeout < 0.0) {
1777        Py_INCREF(Py_None);
1778        return Py_None;
1779    }
1780    else
1781        return PyFloat_FromDouble(s->sock_timeout);
1782}
1783
1784PyDoc_STRVAR(gettimeout_doc,
1785"gettimeout() -> timeout\n\
1786\n\
1787Returns the timeout in floating seconds associated with socket \n\
1788operations. A timeout of None indicates that timeouts on socket \n\
1789operations are disabled.");
1790
1791#ifdef RISCOS
1792/* s.sleeptaskw(1 | 0) method */
1793
1794static PyObject *
1795sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1796{
1797    int block;
1798    block = PyInt_AsLong(arg);
1799    if (block == -1 && PyErr_Occurred())
1800        return NULL;
1801    Py_BEGIN_ALLOW_THREADS
1802    socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1803    Py_END_ALLOW_THREADS
1804
1805    Py_INCREF(Py_None);
1806    return Py_None;
1807}
1808PyDoc_STRVAR(sleeptaskw_doc,
1809"sleeptaskw(flag)\n\
1810\n\
1811Allow sleeps in taskwindows.");
1812#endif
1813
1814
1815/* s.setsockopt() method.
1816   With an integer third argument, sets an integer option.
1817   With a string third argument, sets an option from a buffer;
1818   use optional built-in module 'struct' to encode the string. */
1819
1820static PyObject *
1821sock_setsockopt(PySocketSockObject *s, PyObject *args)
1822{
1823    int level;
1824    int optname;
1825    int res;
1826    char *buf;
1827    int buflen;
1828    int flag;
1829
1830    if (PyArg_ParseTuple(args, "iii:setsockopt",
1831                         &level, &optname, &flag)) {
1832        buf = (char *) &flag;
1833        buflen = sizeof flag;
1834    }
1835    else {
1836        PyErr_Clear();
1837        if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1838                              &level, &optname, &buf, &buflen))
1839            return NULL;
1840    }
1841    res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1842    if (res < 0)
1843        return s->errorhandler();
1844    Py_INCREF(Py_None);
1845    return Py_None;
1846}
1847
1848PyDoc_STRVAR(setsockopt_doc,
1849"setsockopt(level, option, value)\n\
1850\n\
1851Set a socket option.  See the Unix manual for level and option.\n\
1852The value argument can either be an integer or a string.");
1853
1854
1855/* s.getsockopt() method.
1856   With two arguments, retrieves an integer option.
1857   With a third integer argument, retrieves a string buffer of that size;
1858   use optional built-in module 'struct' to decode the string. */
1859
1860static PyObject *
1861sock_getsockopt(PySocketSockObject *s, PyObject *args)
1862{
1863    int level;
1864    int optname;
1865    int res;
1866    PyObject *buf;
1867    socklen_t buflen = 0;
1868
1869#ifdef __BEOS__
1870    /* We have incomplete socket support. */
1871    PyErr_SetString(socket_error, "getsockopt not supported");
1872    return NULL;
1873#else
1874
1875    if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1876                          &level, &optname, &buflen))
1877        return NULL;
1878
1879    if (buflen == 0) {
1880        int flag = 0;
1881        socklen_t flagsize = sizeof flag;
1882        res = getsockopt(s->sock_fd, level, optname,
1883                         (void *)&flag, &flagsize);
1884        if (res < 0)
1885            return s->errorhandler();
1886        return PyInt_FromLong(flag);
1887    }
1888#ifdef __VMS
1889    /* socklen_t is unsigned so no negative test is needed,
1890       test buflen == 0 is previously done */
1891    if (buflen > 1024) {
1892#else
1893    if (buflen <= 0 || buflen > 1024) {
1894#endif
1895        PyErr_SetString(socket_error,
1896                        "getsockopt buflen out of range");
1897        return NULL;
1898    }
1899    buf = PyString_FromStringAndSize((char *)NULL, buflen);
1900    if (buf == NULL)
1901        return NULL;
1902    res = getsockopt(s->sock_fd, level, optname,
1903                     (void *)PyString_AS_STRING(buf), &buflen);
1904    if (res < 0) {
1905        Py_DECREF(buf);
1906        return s->errorhandler();
1907    }
1908    _PyString_Resize(&buf, buflen);
1909    return buf;
1910#endif /* __BEOS__ */
1911}
1912
1913PyDoc_STRVAR(getsockopt_doc,
1914"getsockopt(level, option[, buffersize]) -> value\n\
1915\n\
1916Get a socket option.  See the Unix manual for level and option.\n\
1917If a nonzero buffersize argument is given, the return value is a\n\
1918string of that length; otherwise it is an integer.");
1919
1920
1921/* s.bind(sockaddr) method */
1922
1923static PyObject *
1924sock_bind(PySocketSockObject *s, PyObject *addro)
1925{
1926    sock_addr_t addrbuf;
1927    int addrlen;
1928    int res;
1929
1930    if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1931        return NULL;
1932    Py_BEGIN_ALLOW_THREADS
1933    res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
1934    Py_END_ALLOW_THREADS
1935    if (res < 0)
1936        return s->errorhandler();
1937    Py_INCREF(Py_None);
1938    return Py_None;
1939}
1940
1941PyDoc_STRVAR(bind_doc,
1942"bind(address)\n\
1943\n\
1944Bind the socket to a local address.  For IP sockets, the address is a\n\
1945pair (host, port); the host must refer to the local host. For raw packet\n\
1946sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1947
1948
1949/* s.close() method.
1950   Set the file descriptor to -1 so operations tried subsequently
1951   will surely fail. */
1952
1953static PyObject *
1954sock_close(PySocketSockObject *s)
1955{
1956    SOCKET_T fd;
1957
1958    if ((fd = s->sock_fd) != -1) {
1959        s->sock_fd = -1;
1960        Py_BEGIN_ALLOW_THREADS
1961        (void) SOCKETCLOSE(fd);
1962        Py_END_ALLOW_THREADS
1963    }
1964    Py_INCREF(Py_None);
1965    return Py_None;
1966}
1967
1968PyDoc_STRVAR(close_doc,
1969"close()\n\
1970\n\
1971Close the socket.  It cannot be used after this call.");
1972
1973static int
1974internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
1975                 int *timeoutp)
1976{
1977    int res, timeout;
1978
1979    timeout = 0;
1980    res = connect(s->sock_fd, addr, addrlen);
1981
1982#ifdef MS_WINDOWS
1983
1984    if (s->sock_timeout > 0.0) {
1985        if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
1986            IS_SELECTABLE(s)) {
1987            /* This is a mess.  Best solution: trust select */
1988            fd_set fds;
1989            fd_set fds_exc;
1990            struct timeval tv;
1991            tv.tv_sec = (int)s->sock_timeout;
1992            tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1993            FD_ZERO(&fds);
1994            FD_SET(s->sock_fd, &fds);
1995            FD_ZERO(&fds_exc);
1996            FD_SET(s->sock_fd, &fds_exc);
1997            res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
1998            if (res == 0) {
1999                res = WSAEWOULDBLOCK;
2000                timeout = 1;
2001            } else if (res > 0) {
2002                if (FD_ISSET(s->sock_fd, &fds))
2003                    /* The socket is in the writeable set - this
2004                       means connected */
2005                    res = 0;
2006                else {
2007                    /* As per MS docs, we need to call getsockopt()
2008                       to get the underlying error */
2009                    int res_size = sizeof res;
2010                    /* It must be in the exception set */
2011                    assert(FD_ISSET(s->sock_fd, &fds_exc));
2012                    if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
2013                                        (char *)&res, &res_size))
2014                        /* getsockopt also clears WSAGetLastError,
2015                           so reset it back. */
2016                        WSASetLastError(res);
2017                    else
2018                        res = WSAGetLastError();
2019                }
2020            }
2021            /* else if (res < 0) an error occurred */
2022        }
2023    }
2024
2025    if (res < 0)
2026        res = WSAGetLastError();
2027
2028#else
2029
2030    if (s->sock_timeout > 0.0) {
2031        if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
2032            timeout = internal_select(s, 1);
2033            if (timeout == 0) {
2034                /* Bug #1019808: in case of an EINPROGRESS,
2035                   use getsockopt(SO_ERROR) to get the real
2036                   error. */
2037                socklen_t res_size = sizeof res;
2038                (void)getsockopt(s->sock_fd, SOL_SOCKET,
2039                                 SO_ERROR, &res, &res_size);
2040                if (res == EISCONN)
2041                    res = 0;
2042                errno = res;
2043            }
2044            else if (timeout == -1) {
2045                res = errno;            /* had error */
2046            }
2047            else
2048                res = EWOULDBLOCK;                      /* timed out */
2049        }
2050    }
2051
2052    if (res < 0)
2053        res = errno;
2054
2055#endif
2056    *timeoutp = timeout;
2057
2058    return res;
2059}
2060
2061/* s.connect(sockaddr) method */
2062
2063static PyObject *
2064sock_connect(PySocketSockObject *s, PyObject *addro)
2065{
2066    sock_addr_t addrbuf;
2067    int addrlen;
2068    int res;
2069    int timeout;
2070
2071    if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2072        return NULL;
2073
2074    Py_BEGIN_ALLOW_THREADS
2075    res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2076    Py_END_ALLOW_THREADS
2077
2078    if (timeout == 1) {
2079        PyErr_SetString(socket_timeout, "timed out");
2080        return NULL;
2081    }
2082    if (res != 0)
2083        return s->errorhandler();
2084    Py_INCREF(Py_None);
2085    return Py_None;
2086}
2087
2088PyDoc_STRVAR(connect_doc,
2089"connect(address)\n\
2090\n\
2091Connect the socket to a remote address.  For IP sockets, the address\n\
2092is a pair (host, port).");
2093
2094
2095/* s.connect_ex(sockaddr) method */
2096
2097static PyObject *
2098sock_connect_ex(PySocketSockObject *s, PyObject *addro)
2099{
2100    sock_addr_t addrbuf;
2101    int addrlen;
2102    int res;
2103    int timeout;
2104
2105    if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2106        return NULL;
2107
2108    Py_BEGIN_ALLOW_THREADS
2109    res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2110    Py_END_ALLOW_THREADS
2111
2112    /* Signals are not errors (though they may raise exceptions).  Adapted
2113       from PyErr_SetFromErrnoWithFilenameObject(). */
2114#ifdef EINTR
2115    if (res == EINTR && PyErr_CheckSignals())
2116        return NULL;
2117#endif
2118
2119    return PyInt_FromLong((long) res);
2120}
2121
2122PyDoc_STRVAR(connect_ex_doc,
2123"connect_ex(address) -> errno\n\
2124\n\
2125This is like connect(address), but returns an error code (the errno value)\n\
2126instead of raising an exception when an error occurs.");
2127
2128
2129/* s.fileno() method */
2130
2131static PyObject *
2132sock_fileno(PySocketSockObject *s)
2133{
2134#if SIZEOF_SOCKET_T <= SIZEOF_LONG
2135    return PyInt_FromLong((long) s->sock_fd);
2136#else
2137    return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
2138#endif
2139}
2140
2141PyDoc_STRVAR(fileno_doc,
2142"fileno() -> integer\n\
2143\n\
2144Return the integer file descriptor of the socket.");
2145
2146
2147#ifndef NO_DUP
2148/* s.dup() method */
2149
2150static PyObject *
2151sock_dup(PySocketSockObject *s)
2152{
2153    SOCKET_T newfd;
2154    PyObject *sock;
2155
2156    newfd = dup(s->sock_fd);
2157    if (newfd < 0)
2158        return s->errorhandler();
2159    sock = (PyObject *) new_sockobject(newfd,
2160                                       s->sock_family,
2161                                       s->sock_type,
2162                                       s->sock_proto);
2163    if (sock == NULL)
2164        SOCKETCLOSE(newfd);
2165    return sock;
2166}
2167
2168PyDoc_STRVAR(dup_doc,
2169"dup() -> socket object\n\
2170\n\
2171Return a new socket object connected to the same system resource.");
2172
2173#endif
2174
2175
2176/* s.getsockname() method */
2177
2178static PyObject *
2179sock_getsockname(PySocketSockObject *s)
2180{
2181    sock_addr_t addrbuf;
2182    int res;
2183    socklen_t addrlen;
2184
2185    if (!getsockaddrlen(s, &addrlen))
2186        return NULL;
2187    memset(&addrbuf, 0, addrlen);
2188    Py_BEGIN_ALLOW_THREADS
2189    res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2190    Py_END_ALLOW_THREADS
2191    if (res < 0)
2192        return s->errorhandler();
2193    return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2194                        s->sock_proto);
2195}
2196
2197PyDoc_STRVAR(getsockname_doc,
2198"getsockname() -> address info\n\
2199\n\
2200Return the address of the local endpoint.  For IP sockets, the address\n\
2201info is a pair (hostaddr, port).");
2202
2203
2204#ifdef HAVE_GETPEERNAME         /* Cray APP doesn't have this :-( */
2205/* s.getpeername() method */
2206
2207static PyObject *
2208sock_getpeername(PySocketSockObject *s)
2209{
2210    sock_addr_t addrbuf;
2211    int res;
2212    socklen_t addrlen;
2213
2214    if (!getsockaddrlen(s, &addrlen))
2215        return NULL;
2216    memset(&addrbuf, 0, addrlen);
2217    Py_BEGIN_ALLOW_THREADS
2218    res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2219    Py_END_ALLOW_THREADS
2220    if (res < 0)
2221        return s->errorhandler();
2222    return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2223                        s->sock_proto);
2224}
2225
2226PyDoc_STRVAR(getpeername_doc,
2227"getpeername() -> address info\n\
2228\n\
2229Return the address of the remote endpoint.  For IP sockets, the address\n\
2230info is a pair (hostaddr, port).");
2231
2232#endif /* HAVE_GETPEERNAME */
2233
2234
2235/* s.listen(n) method */
2236
2237static PyObject *
2238sock_listen(PySocketSockObject *s, PyObject *arg)
2239{
2240    int backlog;
2241    int res;
2242
2243    backlog = PyInt_AsLong(arg);
2244    if (backlog == -1 && PyErr_Occurred())
2245        return NULL;
2246    Py_BEGIN_ALLOW_THREADS
2247    /* To avoid problems on systems that don't allow a negative backlog
2248     * (which doesn't make sense anyway) we force a minimum value of 0. */
2249    if (backlog < 0)
2250        backlog = 0;
2251    res = listen(s->sock_fd, backlog);
2252    Py_END_ALLOW_THREADS
2253    if (res < 0)
2254        return s->errorhandler();
2255    Py_INCREF(Py_None);
2256    return Py_None;
2257}
2258
2259PyDoc_STRVAR(listen_doc,
2260"listen(backlog)\n\
2261\n\
2262Enable a server to accept connections.  The backlog argument must be at\n\
2263least 0 (if it is lower, it is set to 0); it specifies the number of\n\
2264unaccepted connections that the system will allow before refusing new\n\
2265connections.");
2266
2267
2268#ifndef NO_DUP
2269/* s.makefile(mode) method.
2270   Create a new open file object referring to a dupped version of
2271   the socket's file descriptor.  (The dup() call is necessary so
2272   that the open file and socket objects may be closed independent
2273   of each other.)
2274   The mode argument specifies 'r' or 'w' passed to fdopen(). */
2275
2276static PyObject *
2277sock_makefile(PySocketSockObject *s, PyObject *args)
2278{
2279    extern int fclose(FILE *);
2280    char *mode = "r";
2281    int bufsize = -1;
2282#ifdef MS_WIN32
2283    Py_intptr_t fd;
2284#else
2285    int fd;
2286#endif
2287    FILE *fp;
2288    PyObject *f;
2289#ifdef __VMS
2290    char *mode_r = "r";
2291    char *mode_w = "w";
2292#endif
2293
2294    if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
2295        return NULL;
2296#ifdef __VMS
2297    if (strcmp(mode,"rb") == 0) {
2298        mode = mode_r;
2299    }
2300    else {
2301        if (strcmp(mode,"wb") == 0) {
2302            mode = mode_w;
2303        }
2304    }
2305#endif
2306#ifdef MS_WIN32
2307    if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
2308        ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
2309#else
2310    if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
2311#endif
2312    {
2313        if (fd >= 0)
2314            SOCKETCLOSE(fd);
2315        return s->errorhandler();
2316    }
2317    f = PyFile_FromFile(fp, "<socket>", mode, fclose);
2318    if (f != NULL)
2319        PyFile_SetBufSize(f, bufsize);
2320    return f;
2321}
2322
2323PyDoc_STRVAR(makefile_doc,
2324"makefile([mode[, buffersize]]) -> file object\n\
2325\n\
2326Return a regular file object corresponding to the socket.\n\
2327The mode and buffersize arguments are as for the built-in open() function.");
2328
2329#endif /* NO_DUP */
2330
2331/*
2332 * This is the guts of the recv() and recv_into() methods, which reads into a
2333 * char buffer.  If you have any inc/dec ref to do to the objects that contain
2334 * the buffer, do it in the caller.  This function returns the number of bytes
2335 * successfully read.  If there was an error, it returns -1.  Note that it is
2336 * also possible that we return a number of bytes smaller than the request
2337 * bytes.
2338 */
2339static ssize_t
2340sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
2341{
2342    ssize_t outlen = -1;
2343    int timeout;
2344#ifdef __VMS
2345    int remaining;
2346    char *read_buf;
2347#endif
2348
2349    if (!IS_SELECTABLE(s)) {
2350        select_error();
2351        return -1;
2352    }
2353
2354#ifndef __VMS
2355    Py_BEGIN_ALLOW_THREADS
2356    timeout = internal_select(s, 0);
2357    if (!timeout)
2358        outlen = recv(s->sock_fd, cbuf, len, flags);
2359    Py_END_ALLOW_THREADS
2360
2361    if (timeout == 1) {
2362        PyErr_SetString(socket_timeout, "timed out");
2363        return -1;
2364    }
2365    if (outlen < 0) {
2366        /* Note: the call to errorhandler() ALWAYS indirectly returned
2367           NULL, so ignore its return value */
2368        s->errorhandler();
2369        return -1;
2370    }
2371#else
2372    read_buf = cbuf;
2373    remaining = len;
2374    while (remaining != 0) {
2375        unsigned int segment;
2376        int nread = -1;
2377
2378        segment = remaining /SEGMENT_SIZE;
2379        if (segment != 0) {
2380            segment = SEGMENT_SIZE;
2381        }
2382        else {
2383            segment = remaining;
2384        }
2385
2386        Py_BEGIN_ALLOW_THREADS
2387        timeout = internal_select(s, 0);
2388        if (!timeout)
2389            nread = recv(s->sock_fd, read_buf, segment, flags);
2390        Py_END_ALLOW_THREADS
2391
2392        if (timeout == 1) {
2393            PyErr_SetString(socket_timeout, "timed out");
2394            return -1;
2395        }
2396        if (nread < 0) {
2397            s->errorhandler();
2398            return -1;
2399        }
2400        if (nread != remaining) {
2401            read_buf += nread;
2402            break;
2403        }
2404
2405        remaining -= segment;
2406        read_buf += segment;
2407    }
2408    outlen = read_buf - cbuf;
2409#endif /* !__VMS */
2410
2411    return outlen;
2412}
2413
2414
2415/* s.recv(nbytes [,flags]) method */
2416
2417static PyObject *
2418sock_recv(PySocketSockObject *s, PyObject *args)
2419{
2420    int recvlen, flags = 0;
2421    ssize_t outlen;
2422    PyObject *buf;
2423
2424    if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
2425        return NULL;
2426
2427    if (recvlen < 0) {
2428        PyErr_SetString(PyExc_ValueError,
2429                        "negative buffersize in recv");
2430        return NULL;
2431    }
2432
2433    /* Allocate a new string. */
2434    buf = PyString_FromStringAndSize((char *) 0, recvlen);
2435    if (buf == NULL)
2436        return NULL;
2437
2438    /* Call the guts */
2439    outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
2440    if (outlen < 0) {
2441        /* An error occurred, release the string and return an
2442           error. */
2443        Py_DECREF(buf);
2444        return NULL;
2445    }
2446    if (outlen != recvlen) {
2447        /* We did not read as many bytes as we anticipated, resize the
2448           string if possible and be successful. */
2449        if (_PyString_Resize(&buf, outlen) < 0)
2450            /* Oopsy, not so successful after all. */
2451            return NULL;
2452    }
2453
2454    return buf;
2455}
2456
2457PyDoc_STRVAR(recv_doc,
2458"recv(buffersize[, flags]) -> data\n\
2459\n\
2460Receive up to buffersize bytes from the socket.  For the optional flags\n\
2461argument, see the Unix manual.  When no data is available, block until\n\
2462at least one byte is available or until the remote end is closed.  When\n\
2463the remote end is closed and all data is read, return the empty string.");
2464
2465
2466/* s.recv_into(buffer, [nbytes [,flags]]) method */
2467
2468static PyObject*
2469sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
2470{
2471    static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2472
2473    int recvlen = 0, flags = 0;
2474    ssize_t readlen;
2475    Py_buffer buf;
2476    Py_ssize_t buflen;
2477
2478    /* Get the buffer's memory */
2479    if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist,
2480                                     &buf, &recvlen, &flags))
2481        return NULL;
2482    buflen = buf.len;
2483    assert(buf.buf != 0 && buflen > 0);
2484
2485    if (recvlen < 0) {
2486        PyErr_SetString(PyExc_ValueError,
2487                        "negative buffersize in recv_into");
2488        goto error;
2489    }
2490    if (recvlen == 0) {
2491        /* If nbytes was not specified, use the buffer's length */
2492        recvlen = buflen;
2493    }
2494
2495    /* Check if the buffer is large enough */
2496    if (buflen < recvlen) {
2497        PyErr_SetString(PyExc_ValueError,
2498                        "buffer too small for requested bytes");
2499        goto error;
2500    }
2501
2502    /* Call the guts */
2503    readlen = sock_recv_guts(s, buf.buf, recvlen, flags);
2504    if (readlen < 0) {
2505        /* Return an error. */
2506        goto error;
2507    }
2508
2509    PyBuffer_Release(&buf);
2510    /* Return the number of bytes read.  Note that we do not do anything
2511       special here in the case that readlen < recvlen. */
2512    return PyInt_FromSsize_t(readlen);
2513
2514error:
2515    PyBuffer_Release(&buf);
2516    return NULL;
2517}
2518
2519PyDoc_STRVAR(recv_into_doc,
2520"recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2521\n\
2522A version of recv() that stores its data into a buffer rather than creating \n\
2523a new string.  Receive up to buffersize bytes from the socket.  If buffersize \n\
2524is not specified (or 0), receive up to the size available in the given buffer.\n\
2525\n\
2526See recv() for documentation about the flags.");
2527
2528
2529/*
2530 * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
2531 * into a char buffer.  If you have any inc/def ref to do to the objects that
2532 * contain the buffer, do it in the caller.  This function returns the number
2533 * of bytes successfully read.  If there was an error, it returns -1.  Note
2534 * that it is also possible that we return a number of bytes smaller than the
2535 * request bytes.
2536 *
2537 * 'addr' is a return value for the address object.  Note that you must decref
2538 * it yourself.
2539 */
2540static ssize_t
2541sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
2542                   PyObject** addr)
2543{
2544    sock_addr_t addrbuf;
2545    int timeout;
2546    ssize_t n = -1;
2547    socklen_t addrlen;
2548
2549    *addr = NULL;
2550
2551    if (!getsockaddrlen(s, &addrlen))
2552        return -1;
2553
2554    if (!IS_SELECTABLE(s)) {
2555        select_error();
2556        return -1;
2557    }
2558
2559    Py_BEGIN_ALLOW_THREADS
2560    memset(&addrbuf, 0, addrlen);
2561    timeout = internal_select(s, 0);
2562    if (!timeout) {
2563#ifndef MS_WINDOWS
2564#if defined(PYOS_OS2) && !defined(PYCC_GCC)
2565        n = recvfrom(s->sock_fd, cbuf, len, flags,
2566                     SAS2SA(&addrbuf), &addrlen);
2567#else
2568        n = recvfrom(s->sock_fd, cbuf, len, flags,
2569                     (void *) &addrbuf, &addrlen);
2570#endif
2571#else
2572        n = recvfrom(s->sock_fd, cbuf, len, flags,
2573                     SAS2SA(&addrbuf), &addrlen);
2574#endif
2575    }
2576    Py_END_ALLOW_THREADS
2577
2578    if (timeout == 1) {
2579        PyErr_SetString(socket_timeout, "timed out");
2580        return -1;
2581    }
2582    if (n < 0) {
2583        s->errorhandler();
2584        return -1;
2585    }
2586
2587    if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
2588                               addrlen, s->sock_proto)))
2589        return -1;
2590
2591    return n;
2592}
2593
2594/* s.recvfrom(nbytes [,flags]) method */
2595
2596static PyObject *
2597sock_recvfrom(PySocketSockObject *s, PyObject *args)
2598{
2599    PyObject *buf = NULL;
2600    PyObject *addr = NULL;
2601    PyObject *ret = NULL;
2602    int recvlen, flags = 0;
2603    ssize_t outlen;
2604
2605    if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
2606        return NULL;
2607
2608    if (recvlen < 0) {
2609        PyErr_SetString(PyExc_ValueError,
2610                        "negative buffersize in recvfrom");
2611        return NULL;
2612    }
2613
2614    buf = PyString_FromStringAndSize((char *) 0, recvlen);
2615    if (buf == NULL)
2616        return NULL;
2617
2618    outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
2619                                recvlen, flags, &addr);
2620    if (outlen < 0) {
2621        goto finally;
2622    }
2623
2624    if (outlen != recvlen) {
2625        /* We did not read as many bytes as we anticipated, resize the
2626           string if possible and be successful. */
2627        if (_PyString_Resize(&buf, outlen) < 0)
2628            /* Oopsy, not so successful after all. */
2629            goto finally;
2630    }
2631
2632    ret = PyTuple_Pack(2, buf, addr);
2633
2634finally:
2635    Py_XDECREF(buf);
2636    Py_XDECREF(addr);
2637    return ret;
2638}
2639
2640PyDoc_STRVAR(recvfrom_doc,
2641"recvfrom(buffersize[, flags]) -> (data, address info)\n\
2642\n\
2643Like recv(buffersize, flags) but also return the sender's address info.");
2644
2645
2646/* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2647
2648static PyObject *
2649sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
2650{
2651    static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2652
2653    int recvlen = 0, flags = 0;
2654    ssize_t readlen;
2655    Py_buffer buf;
2656    int buflen;
2657
2658    PyObject *addr = NULL;
2659
2660    if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into",
2661                                     kwlist, &buf,
2662                                     &recvlen, &flags))
2663        return NULL;
2664    buflen = buf.len;
2665    assert(buf.buf != 0 && buflen > 0);
2666
2667    if (recvlen < 0) {
2668        PyErr_SetString(PyExc_ValueError,
2669                        "negative buffersize in recvfrom_into");
2670        goto error;
2671    }
2672    if (recvlen == 0) {
2673        /* If nbytes was not specified, use the buffer's length */
2674        recvlen = buflen;
2675    }
2676
2677    readlen = sock_recvfrom_guts(s, buf.buf, recvlen, flags, &addr);
2678    if (readlen < 0) {
2679        /* Return an error */
2680        goto error;
2681    }
2682
2683    PyBuffer_Release(&buf);
2684    /* Return the number of bytes read and the address.  Note that we do
2685       not do anything special here in the case that readlen < recvlen. */
2686    return Py_BuildValue("lN", readlen, addr);
2687
2688error:
2689    Py_XDECREF(addr);
2690    PyBuffer_Release(&buf);
2691    return NULL;
2692}
2693
2694PyDoc_STRVAR(recvfrom_into_doc,
2695"recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2696\n\
2697Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2698
2699
2700/* s.send(data [,flags]) method */
2701
2702static PyObject *
2703sock_send(PySocketSockObject *s, PyObject *args)
2704{
2705    char *buf;
2706    int len, n = -1, flags = 0, timeout;
2707    Py_buffer pbuf;
2708
2709    if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
2710        return NULL;
2711
2712    if (!IS_SELECTABLE(s)) {
2713        PyBuffer_Release(&pbuf);
2714        return select_error();
2715    }
2716    buf = pbuf.buf;
2717    len = pbuf.len;
2718
2719    Py_BEGIN_ALLOW_THREADS
2720    timeout = internal_select(s, 1);
2721    if (!timeout)
2722#ifdef __VMS
2723        n = sendsegmented(s->sock_fd, buf, len, flags);
2724#else
2725        n = send(s->sock_fd, buf, len, flags);
2726#endif
2727    Py_END_ALLOW_THREADS
2728
2729    PyBuffer_Release(&pbuf);
2730
2731    if (timeout == 1) {
2732        PyErr_SetString(socket_timeout, "timed out");
2733        return NULL;
2734    }
2735    if (n < 0)
2736        return s->errorhandler();
2737    return PyInt_FromLong((long)n);
2738}
2739
2740PyDoc_STRVAR(send_doc,
2741"send(data[, flags]) -> count\n\
2742\n\
2743Send a data string to the socket.  For the optional flags\n\
2744argument, see the Unix manual.  Return the number of bytes\n\
2745sent; this may be less than len(data) if the network is busy.");
2746
2747
2748/* s.sendall(data [,flags]) method */
2749
2750static PyObject *
2751sock_sendall(PySocketSockObject *s, PyObject *args)
2752{
2753    char *buf;
2754    int len, n = -1, flags = 0, timeout, saved_errno;
2755    Py_buffer pbuf;
2756
2757    if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
2758        return NULL;
2759    buf = pbuf.buf;
2760    len = pbuf.len;
2761
2762    if (!IS_SELECTABLE(s)) {
2763        PyBuffer_Release(&pbuf);
2764        return select_error();
2765    }
2766
2767    do {
2768        Py_BEGIN_ALLOW_THREADS
2769        timeout = internal_select(s, 1);
2770        n = -1;
2771        if (!timeout) {
2772#ifdef __VMS
2773            n = sendsegmented(s->sock_fd, buf, len, flags);
2774#else
2775            n = send(s->sock_fd, buf, len, flags);
2776#endif
2777        }
2778        Py_END_ALLOW_THREADS
2779        if (timeout == 1) {
2780            PyBuffer_Release(&pbuf);
2781            PyErr_SetString(socket_timeout, "timed out");
2782            return NULL;
2783        }
2784        /* PyErr_CheckSignals() might change errno */
2785        saved_errno = errno;
2786        /* We must run our signal handlers before looping again.
2787           send() can return a successful partial write when it is
2788           interrupted, so we can't restrict ourselves to EINTR. */
2789        if (PyErr_CheckSignals()) {
2790            PyBuffer_Release(&pbuf);
2791            return NULL;
2792        }
2793        if (n < 0) {
2794            /* If interrupted, try again */
2795            if (saved_errno == EINTR)
2796                continue;
2797            else
2798                break;
2799        }
2800        buf += n;
2801        len -= n;
2802    } while (len > 0);
2803    PyBuffer_Release(&pbuf);
2804
2805    if (n < 0)
2806        return s->errorhandler();
2807
2808    Py_INCREF(Py_None);
2809    return Py_None;
2810}
2811
2812PyDoc_STRVAR(sendall_doc,
2813"sendall(data[, flags])\n\
2814\n\
2815Send a data string to the socket.  For the optional flags\n\
2816argument, see the Unix manual.  This calls send() repeatedly\n\
2817until all data is sent.  If an error occurs, it's impossible\n\
2818to tell how much data has been sent.");
2819
2820
2821/* s.sendto(data, [flags,] sockaddr) method */
2822
2823static PyObject *
2824sock_sendto(PySocketSockObject *s, PyObject *args)
2825{
2826    Py_buffer pbuf;
2827    PyObject *addro;
2828    char *buf;
2829    Py_ssize_t len;
2830    sock_addr_t addrbuf;
2831    int addrlen, n = -1, flags, timeout;
2832    int arglen;
2833
2834    flags = 0;
2835    arglen = PyTuple_Size(args);
2836    switch(arglen) {
2837        case 2:
2838            PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro);
2839            break;
2840        case 3:
2841            PyArg_ParseTuple(args, "s*iO:sendto", &pbuf, &flags, &addro);
2842            break;
2843        default:
2844            PyErr_Format(PyExc_TypeError, "sendto() takes 2 or 3"
2845                         " arguments (%d given)", arglen);
2846    }
2847    if (PyErr_Occurred())
2848        return NULL;
2849
2850    buf = pbuf.buf;
2851    len = pbuf.len;
2852
2853    if (!IS_SELECTABLE(s)) {
2854        PyBuffer_Release(&pbuf);
2855        return select_error();
2856    }
2857
2858    if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
2859        PyBuffer_Release(&pbuf);
2860        return NULL;
2861    }
2862
2863    Py_BEGIN_ALLOW_THREADS
2864    timeout = internal_select(s, 1);
2865    if (!timeout)
2866        n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
2867    Py_END_ALLOW_THREADS
2868
2869    PyBuffer_Release(&pbuf);
2870    if (timeout == 1) {
2871        PyErr_SetString(socket_timeout, "timed out");
2872        return NULL;
2873    }
2874    if (n < 0)
2875        return s->errorhandler();
2876    return PyInt_FromLong((long)n);
2877}
2878
2879PyDoc_STRVAR(sendto_doc,
2880"sendto(data[, flags], address) -> count\n\
2881\n\
2882Like send(data, flags) but allows specifying the destination address.\n\
2883For IP sockets, the address is a pair (hostaddr, port).");
2884
2885
2886/* s.shutdown(how) method */
2887
2888static PyObject *
2889sock_shutdown(PySocketSockObject *s, PyObject *arg)
2890{
2891    int how;
2892    int res;
2893
2894    how = PyInt_AsLong(arg);
2895    if (how == -1 && PyErr_Occurred())
2896        return NULL;
2897    Py_BEGIN_ALLOW_THREADS
2898    res = shutdown(s->sock_fd, how);
2899    Py_END_ALLOW_THREADS
2900    if (res < 0)
2901        return s->errorhandler();
2902    Py_INCREF(Py_None);
2903    return Py_None;
2904}
2905
2906PyDoc_STRVAR(shutdown_doc,
2907"shutdown(flag)\n\
2908\n\
2909Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2910of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2911
2912#if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2913static PyObject*
2914sock_ioctl(PySocketSockObject *s, PyObject *arg)
2915{
2916    unsigned long cmd = SIO_RCVALL;
2917    PyObject *argO;
2918    DWORD recv;
2919
2920    if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
2921        return NULL;
2922
2923    switch (cmd) {
2924    case SIO_RCVALL: {
2925        unsigned int option = RCVALL_ON;
2926        if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
2927            return NULL;
2928        if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
2929                         NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
2930            return set_error();
2931        }
2932        return PyLong_FromUnsignedLong(recv); }
2933    case SIO_KEEPALIVE_VALS: {
2934        struct tcp_keepalive ka;
2935        if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
2936                        &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
2937            return NULL;
2938        if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
2939                         NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
2940            return set_error();
2941        }
2942        return PyLong_FromUnsignedLong(recv); }
2943    default:
2944        PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd);
2945        return NULL;
2946    }
2947}
2948PyDoc_STRVAR(sock_ioctl_doc,
2949"ioctl(cmd, option) -> long\n\
2950\n\
2951Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
2952SIO_RCVALL:  'option' must be one of the socket.RCVALL_* constants.\n\
2953SIO_KEEPALIVE_VALS:  'option' is a tuple of (onoff, timeout, interval).");
2954
2955#endif
2956
2957/* List of methods for socket objects */
2958
2959static PyMethodDef sock_methods[] = {
2960    {"accept",            (PyCFunction)sock_accept, METH_NOARGS,
2961                      accept_doc},
2962    {"bind",              (PyCFunction)sock_bind, METH_O,
2963                      bind_doc},
2964    {"close",             (PyCFunction)sock_close, METH_NOARGS,
2965                      close_doc},
2966    {"connect",           (PyCFunction)sock_connect, METH_O,
2967                      connect_doc},
2968    {"connect_ex",        (PyCFunction)sock_connect_ex, METH_O,
2969                      connect_ex_doc},
2970#ifndef NO_DUP
2971    {"dup",               (PyCFunction)sock_dup, METH_NOARGS,
2972                      dup_doc},
2973#endif
2974    {"fileno",            (PyCFunction)sock_fileno, METH_NOARGS,
2975                      fileno_doc},
2976#ifdef HAVE_GETPEERNAME
2977    {"getpeername",       (PyCFunction)sock_getpeername,
2978                      METH_NOARGS, getpeername_doc},
2979#endif
2980    {"getsockname",       (PyCFunction)sock_getsockname,
2981                      METH_NOARGS, getsockname_doc},
2982    {"getsockopt",        (PyCFunction)sock_getsockopt, METH_VARARGS,
2983                      getsockopt_doc},
2984#if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2985    {"ioctl",             (PyCFunction)sock_ioctl, METH_VARARGS,
2986                      sock_ioctl_doc},
2987#endif
2988    {"listen",            (PyCFunction)sock_listen, METH_O,
2989                      listen_doc},
2990#ifndef NO_DUP
2991    {"makefile",          (PyCFunction)sock_makefile, METH_VARARGS,
2992                      makefile_doc},
2993#endif
2994    {"recv",              (PyCFunction)sock_recv, METH_VARARGS,
2995                      recv_doc},
2996    {"recv_into",         (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
2997                      recv_into_doc},
2998    {"recvfrom",          (PyCFunction)sock_recvfrom, METH_VARARGS,
2999                      recvfrom_doc},
3000    {"recvfrom_into",  (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
3001                      recvfrom_into_doc},
3002    {"send",              (PyCFunction)sock_send, METH_VARARGS,
3003                      send_doc},
3004    {"sendall",           (PyCFunction)sock_sendall, METH_VARARGS,
3005                      sendall_doc},
3006    {"sendto",            (PyCFunction)sock_sendto, METH_VARARGS,
3007                      sendto_doc},
3008    {"setblocking",       (PyCFunction)sock_setblocking, METH_O,
3009                      setblocking_doc},
3010    {"settimeout",    (PyCFunction)sock_settimeout, METH_O,
3011                      settimeout_doc},
3012    {"gettimeout",    (PyCFunction)sock_gettimeout, METH_NOARGS,
3013                      gettimeout_doc},
3014    {"setsockopt",        (PyCFunction)sock_setsockopt, METH_VARARGS,
3015                      setsockopt_doc},
3016    {"shutdown",          (PyCFunction)sock_shutdown, METH_O,
3017                      shutdown_doc},
3018#ifdef RISCOS
3019    {"sleeptaskw",        (PyCFunction)sock_sleeptaskw, METH_O,
3020                      sleeptaskw_doc},
3021#endif
3022    {NULL,                      NULL}           /* sentinel */
3023};
3024
3025/* SockObject members */
3026static PyMemberDef sock_memberlist[] = {
3027       {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
3028       {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
3029       {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
3030       {"timeout", T_DOUBLE, offsetof(PySocketSockObject, sock_timeout), READONLY, "the socket timeout"},
3031       {0},
3032};
3033
3034/* Deallocate a socket object in response to the last Py_DECREF().
3035   First close the file description. */
3036
3037static void
3038sock_dealloc(PySocketSockObject *s)
3039{
3040    if (s->sock_fd != -1)
3041        (void) SOCKETCLOSE(s->sock_fd);
3042    Py_TYPE(s)->tp_free((PyObject *)s);
3043}
3044
3045
3046static PyObject *
3047sock_repr(PySocketSockObject *s)
3048{
3049    char buf[512];
3050#if SIZEOF_SOCKET_T > SIZEOF_LONG
3051    if (s->sock_fd > LONG_MAX) {
3052        /* this can occur on Win64, and actually there is a special
3053           ugly printf formatter for decimal pointer length integer
3054           printing, only bother if necessary*/
3055        PyErr_SetString(PyExc_OverflowError,
3056                        "no printf formatter to display "
3057                        "the socket descriptor in decimal");
3058        return NULL;
3059    }
3060#endif
3061    PyOS_snprintf(
3062        buf, sizeof(buf),
3063        "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
3064        (long)s->sock_fd, s->sock_family,
3065        s->sock_type,
3066        s->sock_proto);
3067    return PyString_FromString(buf);
3068}
3069
3070
3071/* Create a new, uninitialized socket object. */
3072
3073static PyObject *
3074sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3075{
3076    PyObject *new;
3077
3078    new = type->tp_alloc(type, 0);
3079    if (new != NULL) {
3080        ((PySocketSockObject *)new)->sock_fd = -1;
3081        ((PySocketSockObject *)new)->sock_timeout = -1.0;
3082        ((PySocketSockObject *)new)->errorhandler = &set_error;
3083    }
3084    return new;
3085}
3086
3087
3088/* Initialize a new socket object. */
3089
3090/*ARGSUSED*/
3091static int
3092sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
3093{
3094    PySocketSockObject *s = (PySocketSockObject *)self;
3095    SOCKET_T fd;
3096    int family = AF_INET, type = SOCK_STREAM, proto = 0;
3097    static char *keywords[] = {"family", "type", "proto", 0};
3098
3099    if (!PyArg_ParseTupleAndKeywords(args, kwds,
3100                                     "|iii:socket", keywords,
3101                                     &family, &type, &proto))
3102        return -1;
3103
3104    Py_BEGIN_ALLOW_THREADS
3105    fd = socket(family, type, proto);
3106    Py_END_ALLOW_THREADS
3107
3108#ifdef MS_WINDOWS
3109    if (fd == INVALID_SOCKET)
3110#else
3111    if (fd < 0)
3112#endif
3113    {
3114        set_error();
3115        return -1;
3116    }
3117    init_sockobject(s, fd, family, type, proto);
3118
3119    return 0;
3120
3121}
3122
3123
3124/* Type object for socket objects. */
3125
3126static PyTypeObject sock_type = {
3127    PyVarObject_HEAD_INIT(0, 0)         /* Must fill in type value later */
3128    "_socket.socket",                           /* tp_name */
3129    sizeof(PySocketSockObject),                 /* tp_basicsize */
3130    0,                                          /* tp_itemsize */
3131    (destructor)sock_dealloc,                   /* tp_dealloc */
3132    0,                                          /* tp_print */
3133    0,                                          /* tp_getattr */
3134    0,                                          /* tp_setattr */
3135    0,                                          /* tp_compare */
3136    (reprfunc)sock_repr,                        /* tp_repr */
3137    0,                                          /* tp_as_number */
3138    0,                                          /* tp_as_sequence */
3139    0,                                          /* tp_as_mapping */
3140    0,                                          /* tp_hash */
3141    0,                                          /* tp_call */
3142    0,                                          /* tp_str */
3143    PyObject_GenericGetAttr,                    /* tp_getattro */
3144    0,                                          /* tp_setattro */
3145    0,                                          /* tp_as_buffer */
3146    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3147    sock_doc,                                   /* tp_doc */
3148    0,                                          /* tp_traverse */
3149    0,                                          /* tp_clear */
3150    0,                                          /* tp_richcompare */
3151    0,                                          /* tp_weaklistoffset */
3152    0,                                          /* tp_iter */
3153    0,                                          /* tp_iternext */
3154    sock_methods,                               /* tp_methods */
3155    sock_memberlist,                            /* tp_members */
3156    0,                                          /* tp_getset */
3157    0,                                          /* tp_base */
3158    0,                                          /* tp_dict */
3159    0,                                          /* tp_descr_get */
3160    0,                                          /* tp_descr_set */
3161    0,                                          /* tp_dictoffset */
3162    sock_initobj,                               /* tp_init */
3163    PyType_GenericAlloc,                        /* tp_alloc */
3164    sock_new,                                   /* tp_new */
3165    PyObject_Del,                               /* tp_free */
3166};
3167
3168
3169/* Python interface to gethostname(). */
3170
3171/*ARGSUSED*/
3172static PyObject *
3173socket_gethostname(PyObject *self, PyObject *unused)
3174{
3175    char buf[1024];
3176    int res;
3177    Py_BEGIN_ALLOW_THREADS
3178    res = gethostname(buf, (int) sizeof buf - 1);
3179    Py_END_ALLOW_THREADS
3180    if (res < 0)
3181        return set_error();
3182    buf[sizeof buf - 1] = '\0';
3183    return PyString_FromString(buf);
3184}
3185
3186PyDoc_STRVAR(gethostname_doc,
3187"gethostname() -> string\n\
3188\n\
3189Return the current host name.");
3190
3191
3192/* Python interface to gethostbyname(name). */
3193
3194/*ARGSUSED*/
3195static PyObject *
3196socket_gethostbyname(PyObject *self, PyObject *args)
3197{
3198    char *name;
3199    sock_addr_t addrbuf;
3200
3201    if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
3202        return NULL;
3203    if (setipaddr(name, SAS2SA(&addrbuf),  sizeof(addrbuf), AF_INET) < 0)
3204        return NULL;
3205    return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
3206}
3207
3208PyDoc_STRVAR(gethostbyname_doc,
3209"gethostbyname(host) -> address\n\
3210\n\
3211Return the IP address (a string of the form '255.255.255.255') for a host.");
3212
3213
3214/* Convenience function common to gethostbyname_ex and gethostbyaddr */
3215
3216static PyObject *
3217gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
3218{
3219    char **pch;
3220    PyObject *rtn_tuple = (PyObject *)NULL;
3221    PyObject *name_list = (PyObject *)NULL;
3222    PyObject *addr_list = (PyObject *)NULL;
3223    PyObject *tmp;
3224
3225    if (h == NULL) {
3226        /* Let's get real error message to return */
3227#ifndef RISCOS
3228        set_herror(h_errno);
3229#else
3230        PyErr_SetString(socket_error, "host not found");
3231#endif
3232        return NULL;
3233    }
3234
3235    if (h->h_addrtype != af) {
3236        /* Let's get real error message to return */
3237        PyErr_SetString(socket_error,
3238                        (char *)strerror(EAFNOSUPPORT));
3239
3240        return NULL;
3241    }
3242
3243    switch (af) {
3244
3245    case AF_INET:
3246        if (alen < sizeof(struct sockaddr_in))
3247            return NULL;
3248        break;
3249
3250#ifdef ENABLE_IPV6
3251    case AF_INET6:
3252        if (alen < sizeof(struct sockaddr_in6))
3253            return NULL;
3254        break;
3255#endif
3256
3257    }
3258
3259    if ((name_list = PyList_New(0)) == NULL)
3260        goto err;
3261
3262    if ((addr_list = PyList_New(0)) == NULL)
3263        goto err;
3264
3265    /* SF #1511317: h_aliases can be NULL */
3266    if (h->h_aliases) {
3267        for (pch = h->h_aliases; *pch != NULL; pch++) {
3268            int status;
3269            tmp = PyString_FromString(*pch);
3270            if (tmp == NULL)
3271                goto err;
3272
3273            status = PyList_Append(name_list, tmp);
3274            Py_DECREF(tmp);
3275
3276            if (status)
3277                goto err;
3278        }
3279    }
3280
3281    for (pch = h->h_addr_list; *pch != NULL; pch++) {
3282        int status;
3283
3284        switch (af) {
3285
3286        case AF_INET:
3287            {
3288            struct sockaddr_in sin;
3289            memset(&sin, 0, sizeof(sin));
3290            sin.sin_family = af;
3291#ifdef HAVE_SOCKADDR_SA_LEN
3292            sin.sin_len = sizeof(sin);
3293#endif
3294            memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
3295            tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
3296
3297            if (pch == h->h_addr_list && alen >= sizeof(sin))
3298                memcpy((char *) addr, &sin, sizeof(sin));
3299            break;
3300            }
3301
3302#ifdef ENABLE_IPV6
3303        case AF_INET6:
3304            {
3305            struct sockaddr_in6 sin6;
3306            memset(&sin6, 0, sizeof(sin6));
3307            sin6.sin6_family = af;
3308#ifdef HAVE_SOCKADDR_SA_LEN
3309            sin6.sin6_len = sizeof(sin6);
3310#endif
3311            memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
3312            tmp = makeipaddr((struct sockaddr *)&sin6,
3313                sizeof(sin6));
3314
3315            if (pch == h->h_addr_list && alen >= sizeof(sin6))
3316                memcpy((char *) addr, &sin6, sizeof(sin6));
3317            break;
3318            }
3319#endif
3320
3321        default:                /* can't happen */
3322            PyErr_SetString(socket_error,
3323                            "unsupported address family");
3324            return NULL;
3325        }
3326
3327        if (tmp == NULL)
3328            goto err;
3329
3330        status = PyList_Append(addr_list, tmp);
3331        Py_DECREF(tmp);
3332
3333        if (status)
3334            goto err;
3335    }
3336
3337    rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
3338
3339 err:
3340    Py_XDECREF(name_list);
3341    Py_XDECREF(addr_list);
3342    return rtn_tuple;
3343}
3344
3345
3346/* Python interface to gethostbyname_ex(name). */
3347
3348/*ARGSUSED*/
3349static PyObject *
3350socket_gethostbyname_ex(PyObject *self, PyObject *args)
3351{
3352    char *name;
3353    struct hostent *h;
3354#ifdef ENABLE_IPV6
3355    struct sockaddr_storage addr;
3356#else
3357    struct sockaddr_in addr;
3358#endif
3359    struct sockaddr *sa;
3360    PyObject *ret;
3361#ifdef HAVE_GETHOSTBYNAME_R
3362    struct hostent hp_allocated;
3363#ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3364    struct hostent_data data;
3365#else
3366    char buf[16384];
3367    int buf_len = (sizeof buf) - 1;
3368    int errnop;
3369#endif
3370#if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3371    int result;
3372#endif
3373#endif /* HAVE_GETHOSTBYNAME_R */
3374
3375    if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
3376        return NULL;
3377    if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
3378        return NULL;
3379    Py_BEGIN_ALLOW_THREADS
3380#ifdef HAVE_GETHOSTBYNAME_R
3381#if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3382    result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
3383                             &h, &errnop);
3384#elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3385    h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
3386#else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3387    memset((void *) &data, '\0', sizeof(data));
3388    result = gethostbyname_r(name, &hp_allocated, &data);
3389    h = (result != 0) ? NULL : &hp_allocated;
3390#endif
3391#else /* not HAVE_GETHOSTBYNAME_R */
3392#ifdef USE_GETHOSTBYNAME_LOCK
3393    PyThread_acquire_lock(netdb_lock, 1);
3394#endif
3395    h = gethostbyname(name);
3396#endif /* HAVE_GETHOSTBYNAME_R */
3397    Py_END_ALLOW_THREADS
3398    /* Some C libraries would require addr.__ss_family instead of
3399       addr.ss_family.
3400       Therefore, we cast the sockaddr_storage into sockaddr to
3401       access sa_family. */
3402    sa = (struct sockaddr*)&addr;
3403    ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
3404                         sa->sa_family);
3405#ifdef USE_GETHOSTBYNAME_LOCK
3406    PyThread_release_lock(netdb_lock);
3407#endif
3408    return ret;
3409}
3410
3411PyDoc_STRVAR(ghbn_ex_doc,
3412"gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3413\n\
3414Return the true host name, a list of aliases, and a list of IP addresses,\n\
3415for a host.  The host argument is a string giving a host name or IP number.");
3416
3417
3418/* Python interface to gethostbyaddr(IP). */
3419
3420/*ARGSUSED*/
3421static PyObject *
3422socket_gethostbyaddr(PyObject *self, PyObject *args)
3423{
3424#ifdef ENABLE_IPV6
3425    struct sockaddr_storage addr;
3426#else
3427    struct sockaddr_in addr;
3428#endif
3429    struct sockaddr *sa = (struct sockaddr *)&addr;
3430    char *ip_num;
3431    struct hostent *h;
3432    PyObject *ret;
3433#ifdef HAVE_GETHOSTBYNAME_R
3434    struct hostent hp_allocated;
3435#ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3436    struct hostent_data data;
3437#else
3438    /* glibcs up to 2.10 assume that the buf argument to
3439       gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
3440       does not ensure. The attribute below instructs the compiler
3441       to maintain this alignment. */
3442    char buf[16384] Py_ALIGNED(8);
3443    int buf_len = (sizeof buf) - 1;
3444    int errnop;
3445#endif
3446#if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3447    int result;
3448#endif
3449#endif /* HAVE_GETHOSTBYNAME_R */
3450    char *ap;
3451    int al;
3452    int af;
3453
3454    if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
3455        return NULL;
3456    af = AF_UNSPEC;
3457    if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
3458        return NULL;
3459    af = sa->sa_family;
3460    ap = NULL;
3461    switch (af) {
3462    case AF_INET:
3463        ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
3464        al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
3465        break;
3466#ifdef ENABLE_IPV6
3467    case AF_INET6:
3468        ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
3469        al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
3470        break;
3471#endif
3472    default:
3473        PyErr_SetString(socket_error, "unsupported address family");
3474        return NULL;
3475    }
3476    Py_BEGIN_ALLOW_THREADS
3477#ifdef HAVE_GETHOSTBYNAME_R
3478#if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3479    result = gethostbyaddr_r(ap, al, af,
3480        &hp_allocated, buf, buf_len,
3481        &h, &errnop);
3482#elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3483    h = gethostbyaddr_r(ap, al, af,
3484                        &hp_allocated, buf, buf_len, &errnop);
3485#else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3486    memset((void *) &data, '\0', sizeof(data));
3487    result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
3488    h = (result != 0) ? NULL : &hp_allocated;
3489#endif
3490#else /* not HAVE_GETHOSTBYNAME_R */
3491#ifdef USE_GETHOSTBYNAME_LOCK
3492    PyThread_acquire_lock(netdb_lock, 1);
3493#endif
3494    h = gethostbyaddr(ap, al, af);
3495#endif /* HAVE_GETHOSTBYNAME_R */
3496    Py_END_ALLOW_THREADS
3497    ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
3498#ifdef USE_GETHOSTBYNAME_LOCK
3499    PyThread_release_lock(netdb_lock);
3500#endif
3501    return ret;
3502}
3503
3504PyDoc_STRVAR(gethostbyaddr_doc,
3505"gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3506\n\
3507Return the true host name, a list of aliases, and a list of IP addresses,\n\
3508for a host.  The host argument is a string giving a host name or IP number.");
3509
3510
3511/* Python interface to getservbyname(name).
3512   This only returns the port number, since the other info is already
3513   known or not useful (like the list of aliases). */
3514
3515/*ARGSUSED*/
3516static PyObject *
3517socket_getservbyname(PyObject *self, PyObject *args)
3518{
3519    char *name, *proto=NULL;
3520    struct servent *sp;
3521    if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
3522        return NULL;
3523    Py_BEGIN_ALLOW_THREADS
3524    sp = getservbyname(name, proto);
3525    Py_END_ALLOW_THREADS
3526    if (sp == NULL) {
3527        PyErr_SetString(socket_error, "service/proto not found");
3528        return NULL;
3529    }
3530    return PyInt_FromLong((long) ntohs(sp->s_port));
3531}
3532
3533PyDoc_STRVAR(getservbyname_doc,
3534"getservbyname(servicename[, protocolname]) -> integer\n\
3535\n\
3536Return a port number from a service name and protocol name.\n\
3537The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3538otherwise any protocol will match.");
3539
3540
3541/* Python interface to getservbyport(port).
3542   This only returns the service name, since the other info is already
3543   known or not useful (like the list of aliases). */
3544
3545/*ARGSUSED*/
3546static PyObject *
3547socket_getservbyport(PyObject *self, PyObject *args)
3548{
3549    int port;
3550    char *proto=NULL;
3551    struct servent *sp;
3552    if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
3553        return NULL;
3554    if (port < 0 || port > 0xffff) {
3555        PyErr_SetString(
3556            PyExc_OverflowError,
3557            "getservbyport: port must be 0-65535.");
3558        return NULL;
3559    }
3560    Py_BEGIN_ALLOW_THREADS
3561    sp = getservbyport(htons((short)port), proto);
3562    Py_END_ALLOW_THREADS
3563    if (sp == NULL) {
3564        PyErr_SetString(socket_error, "port/proto not found");
3565        return NULL;
3566    }
3567    return PyString_FromString(sp->s_name);
3568}
3569
3570PyDoc_STRVAR(getservbyport_doc,
3571"getservbyport(port[, protocolname]) -> string\n\
3572\n\
3573Return the service name from a port number and protocol name.\n\
3574The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3575otherwise any protocol will match.");
3576
3577/* Python interface to getprotobyname(name).
3578   This only returns the protocol number, since the other info is
3579   already known or not useful (like the list of aliases). */
3580
3581/*ARGSUSED*/
3582static PyObject *
3583socket_getprotobyname(PyObject *self, PyObject *args)
3584{
3585    char *name;
3586    struct protoent *sp;
3587#ifdef __BEOS__
3588/* Not available in BeOS yet. - [cjh] */
3589    PyErr_SetString(socket_error, "getprotobyname not supported");
3590    return NULL;
3591#else
3592    if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
3593        return NULL;
3594    Py_BEGIN_ALLOW_THREADS
3595    sp = getprotobyname(name);
3596    Py_END_ALLOW_THREADS
3597    if (sp == NULL) {
3598        PyErr_SetString(socket_error, "protocol not found");
3599        return NULL;
3600    }
3601    return PyInt_FromLong((long) sp->p_proto);
3602#endif
3603}
3604
3605PyDoc_STRVAR(getprotobyname_doc,
3606"getprotobyname(name) -> integer\n\
3607\n\
3608Return the protocol number for the named protocol.  (Rarely used.)");
3609
3610
3611#ifdef HAVE_SOCKETPAIR
3612/* Create a pair of sockets using the socketpair() function.
3613   Arguments as for socket() except the default family is AF_UNIX if
3614   defined on the platform; otherwise, the default is AF_INET. */
3615
3616/*ARGSUSED*/
3617static PyObject *
3618socket_socketpair(PyObject *self, PyObject *args)
3619{
3620    PySocketSockObject *s0 = NULL, *s1 = NULL;
3621    SOCKET_T sv[2];
3622    int family, type = SOCK_STREAM, proto = 0;
3623    PyObject *res = NULL;
3624
3625#if defined(AF_UNIX)
3626    family = AF_UNIX;
3627#else
3628    family = AF_INET;
3629#endif
3630    if (!PyArg_ParseTuple(args, "|iii:socketpair",
3631                          &family, &type, &proto))
3632        return NULL;
3633    /* Create a pair of socket fds */
3634    if (socketpair(family, type, proto, sv) < 0)
3635        return set_error();
3636    s0 = new_sockobject(sv[0], family, type, proto);
3637    if (s0 == NULL)
3638        goto finally;
3639    s1 = new_sockobject(sv[1], family, type, proto);
3640    if (s1 == NULL)
3641        goto finally;
3642    res = PyTuple_Pack(2, s0, s1);
3643
3644finally:
3645    if (res == NULL) {
3646        if (s0 == NULL)
3647            SOCKETCLOSE(sv[0]);
3648        if (s1 == NULL)
3649            SOCKETCLOSE(sv[1]);
3650    }
3651    Py_XDECREF(s0);
3652    Py_XDECREF(s1);
3653    return res;
3654}
3655
3656PyDoc_STRVAR(socketpair_doc,
3657"socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3658\n\
3659Create a pair of socket objects from the sockets returned by the platform\n\
3660socketpair() function.\n\
3661The arguments are the same as for socket() except the default family is\n\
3662AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3663
3664#endif /* HAVE_SOCKETPAIR */
3665
3666
3667#ifndef NO_DUP
3668/* Create a socket object from a numeric file description.
3669   Useful e.g. if stdin is a socket.
3670   Additional arguments as for socket(). */
3671
3672/*ARGSUSED*/
3673static PyObject *
3674socket_fromfd(PyObject *self, PyObject *args)
3675{
3676    PySocketSockObject *s;
3677    SOCKET_T fd;
3678    int family, type, proto = 0;
3679    if (!PyArg_ParseTuple(args, "iii|i:fromfd",
3680                          &fd, &family, &type, &proto))
3681        return NULL;
3682    /* Dup the fd so it and the socket can be closed independently */
3683    fd = dup(fd);
3684    if (fd < 0)
3685        return set_error();
3686    s = new_sockobject(fd, family, type, proto);
3687    return (PyObject *) s;
3688}
3689
3690PyDoc_STRVAR(fromfd_doc,
3691"fromfd(fd, family, type[, proto]) -> socket object\n\
3692\n\
3693Create a socket object from a duplicate of the given\n\
3694file descriptor.\n\
3695The remaining arguments are the same as for socket().");
3696
3697#endif /* NO_DUP */
3698
3699
3700static PyObject *
3701socket_ntohs(PyObject *self, PyObject *args)
3702{
3703    int x1, x2;
3704
3705    if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
3706        return NULL;
3707    }
3708    if (x1 < 0) {
3709        PyErr_SetString(PyExc_OverflowError,
3710            "can't convert negative number to unsigned long");
3711        return NULL;
3712    }
3713    x2 = (unsigned int)ntohs((unsigned short)x1);
3714    return PyInt_FromLong(x2);
3715}
3716
3717PyDoc_STRVAR(ntohs_doc,
3718"ntohs(integer) -> integer\n\
3719\n\
3720Convert a 16-bit integer from network to host byte order.");
3721
3722
3723static PyObject *
3724socket_ntohl(PyObject *self, PyObject *arg)
3725{
3726    unsigned long x;
3727
3728    if (PyInt_Check(arg)) {
3729        x = PyInt_AS_LONG(arg);
3730        if (x == (unsigned long) -1 && PyErr_Occurred())
3731            return NULL;
3732        if ((long)x < 0) {
3733            PyErr_SetString(PyExc_OverflowError,
3734              "can't convert negative number to unsigned long");
3735            return NULL;
3736        }
3737    }
3738    else if (PyLong_Check(arg)) {
3739        x = PyLong_AsUnsignedLong(arg);
3740        if (x == (unsigned long) -1 && PyErr_Occurred())
3741            return NULL;
3742#if SIZEOF_LONG > 4
3743        {
3744            unsigned long y;
3745            /* only want the trailing 32 bits */
3746            y = x & 0xFFFFFFFFUL;
3747            if (y ^ x)
3748                return PyErr_Format(PyExc_OverflowError,
3749                            "long int larger than 32 bits");
3750            x = y;
3751        }
3752#endif
3753    }
3754    else
3755        return PyErr_Format(PyExc_TypeError,
3756                            "expected int/long, %s found",
3757                            Py_TYPE(arg)->tp_name);
3758    if (x == (unsigned long) -1 && PyErr_Occurred())
3759        return NULL;
3760    return PyLong_FromUnsignedLong(ntohl(x));
3761}
3762
3763PyDoc_STRVAR(ntohl_doc,
3764"ntohl(integer) -> integer\n\
3765\n\
3766Convert a 32-bit integer from network to host byte order.");
3767
3768
3769static PyObject *
3770socket_htons(PyObject *self, PyObject *args)
3771{
3772    int x1, x2;
3773
3774    if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
3775        return NULL;
3776    }
3777    if (x1 < 0) {
3778        PyErr_SetString(PyExc_OverflowError,
3779            "can't convert negative number to unsigned long");
3780        return NULL;
3781    }
3782    x2 = (unsigned int)htons((unsigned short)x1);
3783    return PyInt_FromLong(x2);
3784}
3785
3786PyDoc_STRVAR(htons_doc,
3787"htons(integer) -> integer\n\
3788\n\
3789Convert a 16-bit integer from host to network byte order.");
3790
3791
3792static PyObject *
3793socket_htonl(PyObject *self, PyObject *arg)
3794{
3795    unsigned long x;
3796
3797    if (PyInt_Check(arg)) {
3798        x = PyInt_AS_LONG(arg);
3799        if (x == (unsigned long) -1 && PyErr_Occurred())
3800            return NULL;
3801        if ((long)x < 0) {
3802            PyErr_SetString(PyExc_OverflowError,
3803              "can't convert negative number to unsigned long");
3804            return NULL;
3805        }
3806    }
3807    else if (PyLong_Check(arg)) {
3808        x = PyLong_AsUnsignedLong(arg);
3809        if (x == (unsigned long) -1 && PyErr_Occurred())
3810            return NULL;
3811#if SIZEOF_LONG > 4
3812        {
3813            unsigned long y;
3814            /* only want the trailing 32 bits */
3815            y = x & 0xFFFFFFFFUL;
3816            if (y ^ x)
3817                return PyErr_Format(PyExc_OverflowError,
3818                            "long int larger than 32 bits");
3819            x = y;
3820        }
3821#endif
3822    }
3823    else
3824        return PyErr_Format(PyExc_TypeError,
3825                            "expected int/long, %s found",
3826                            Py_TYPE(arg)->tp_name);
3827    return PyLong_FromUnsignedLong(htonl((unsigned long)x));
3828}
3829
3830PyDoc_STRVAR(htonl_doc,
3831"htonl(integer) -> integer\n\
3832\n\
3833Convert a 32-bit integer from host to network byte order.");
3834
3835/* socket.inet_aton() and socket.inet_ntoa() functions. */
3836
3837PyDoc_STRVAR(inet_aton_doc,
3838"inet_aton(string) -> packed 32-bit IP representation\n\
3839\n\
3840Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3841binary format used in low-level network functions.");
3842
3843static PyObject*
3844socket_inet_aton(PyObject *self, PyObject *args)
3845{
3846#ifndef INADDR_NONE
3847#define INADDR_NONE (-1)
3848#endif
3849#ifdef HAVE_INET_ATON
3850    struct in_addr buf;
3851#endif
3852
3853#if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3854#if (SIZEOF_INT != 4)
3855#error "Not sure if in_addr_t exists and int is not 32-bits."
3856#endif
3857    /* Have to use inet_addr() instead */
3858    unsigned int packed_addr;
3859#endif
3860    char *ip_addr;
3861
3862    if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
3863        return NULL;
3864
3865
3866#ifdef HAVE_INET_ATON
3867
3868#ifdef USE_INET_ATON_WEAKLINK
3869    if (inet_aton != NULL) {
3870#endif
3871    if (inet_aton(ip_addr, &buf))
3872        return PyString_FromStringAndSize((char *)(&buf),
3873                                          sizeof(buf));
3874
3875    PyErr_SetString(socket_error,
3876                    "illegal IP address string passed to inet_aton");
3877    return NULL;
3878
3879#ifdef USE_INET_ATON_WEAKLINK
3880   } else {
3881#endif
3882
3883#endif
3884
3885#if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3886
3887    /* special-case this address as inet_addr might return INADDR_NONE
3888     * for this */
3889    if (strcmp(ip_addr, "255.255.255.255") == 0) {
3890        packed_addr = 0xFFFFFFFF;
3891    } else {
3892
3893        packed_addr = inet_addr(ip_addr);
3894
3895        if (packed_addr == INADDR_NONE) {               /* invalid address */
3896            PyErr_SetString(socket_error,
3897                "illegal IP address string passed to inet_aton");
3898            return NULL;
3899        }
3900    }
3901    return PyString_FromStringAndSize((char *) &packed_addr,
3902                                      sizeof(packed_addr));
3903
3904#ifdef USE_INET_ATON_WEAKLINK
3905   }
3906#endif
3907
3908#endif
3909}
3910
3911PyDoc_STRVAR(inet_ntoa_doc,
3912"inet_ntoa(packed_ip) -> ip_address_string\n\
3913\n\
3914Convert an IP address from 32-bit packed binary format to string format");
3915
3916static PyObject*
3917socket_inet_ntoa(PyObject *self, PyObject *args)
3918{
3919    char *packed_str;
3920    int addr_len;
3921    struct in_addr packed_addr;
3922
3923    if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
3924        return NULL;
3925    }
3926
3927    if (addr_len != sizeof(packed_addr)) {
3928        PyErr_SetString(socket_error,
3929            "packed IP wrong length for inet_ntoa");
3930        return NULL;
3931    }
3932
3933    memcpy(&packed_addr, packed_str, addr_len);
3934
3935    return PyString_FromString(inet_ntoa(packed_addr));
3936}
3937
3938#ifdef HAVE_INET_PTON
3939
3940PyDoc_STRVAR(inet_pton_doc,
3941"inet_pton(af, ip) -> packed IP address string\n\
3942\n\
3943Convert an IP address from string format to a packed string suitable\n\
3944for use with low-level network functions.");
3945
3946static PyObject *
3947socket_inet_pton(PyObject *self, PyObject *args)
3948{
3949    int af;
3950    char* ip;
3951    int retval;
3952#ifdef ENABLE_IPV6
3953    char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
3954#else
3955    char packed[sizeof(struct in_addr)];
3956#endif
3957    if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
3958        return NULL;
3959    }
3960
3961#if !defined(ENABLE_IPV6) && defined(AF_INET6)
3962    if(af == AF_INET6) {
3963        PyErr_SetString(socket_error,
3964                        "can't use AF_INET6, IPv6 is disabled");
3965        return NULL;
3966    }
3967#endif
3968
3969    retval = inet_pton(af, ip, packed);
3970    if (retval < 0) {
3971        PyErr_SetFromErrno(socket_error);
3972        return NULL;
3973    } else if (retval == 0) {
3974        PyErr_SetString(socket_error,
3975            "illegal IP address string passed to inet_pton");
3976        return NULL;
3977    } else if (af == AF_INET) {
3978        return PyString_FromStringAndSize(packed,
3979            sizeof(struct in_addr));
3980#ifdef ENABLE_IPV6
3981    } else if (af == AF_INET6) {
3982        return PyString_FromStringAndSize(packed,
3983            sizeof(struct in6_addr));
3984#endif
3985    } else {
3986        PyErr_SetString(socket_error, "unknown address family");
3987        return NULL;
3988    }
3989}
3990
3991PyDoc_STRVAR(inet_ntop_doc,
3992"inet_ntop(af, packed_ip) -> string formatted IP address\n\
3993\n\
3994Convert a packed IP address of the given family to string format.");
3995
3996static PyObject *
3997socket_inet_ntop(PyObject *self, PyObject *args)
3998{
3999    int af;
4000    char* packed;
4001    int len;
4002    const char* retval;
4003#ifdef ENABLE_IPV6
4004    char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
4005#else
4006    char ip[INET_ADDRSTRLEN + 1];
4007#endif
4008
4009    /* Guarantee NUL-termination for PyString_FromString() below */
4010    memset((void *) &ip[0], '\0', sizeof(ip));
4011
4012    if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
4013        return NULL;
4014    }
4015
4016    if (af == AF_INET) {
4017        if (len != sizeof(struct in_addr)) {
4018            PyErr_SetString(PyExc_ValueError,
4019                "invalid length of packed IP address string");
4020            return NULL;
4021        }
4022#ifdef ENABLE_IPV6
4023    } else if (af == AF_INET6) {
4024        if (len != sizeof(struct in6_addr)) {
4025            PyErr_SetString(PyExc_ValueError,
4026                "invalid length of packed IP address string");
4027            return NULL;
4028        }
4029#endif
4030    } else {
4031        PyErr_Format(PyExc_ValueError,
4032            "unknown address family %d", af);
4033        return NULL;
4034    }
4035
4036    retval = inet_ntop(af, packed, ip, sizeof(ip));
4037    if (!retval) {
4038        PyErr_SetFromErrno(socket_error);
4039        return NULL;
4040    } else {
4041        return PyString_FromString(retval);
4042    }
4043
4044    /* NOTREACHED */
4045    PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
4046    return NULL;
4047}
4048
4049#endif /* HAVE_INET_PTON */
4050
4051/* Python interface to getaddrinfo(host, port). */
4052
4053/*ARGSUSED*/
4054static PyObject *
4055socket_getaddrinfo(PyObject *self, PyObject *args)
4056{
4057    struct addrinfo hints, *res;
4058    struct addrinfo *res0 = NULL;
4059    PyObject *hobj = NULL;
4060    PyObject *pobj = (PyObject *)NULL;
4061    char pbuf[30];
4062    char *hptr, *pptr;
4063    int family, socktype, protocol, flags;
4064    int error;
4065    PyObject *all = (PyObject *)NULL;
4066    PyObject *single = (PyObject *)NULL;
4067    PyObject *idna = NULL;
4068
4069    family = socktype = protocol = flags = 0;
4070    family = AF_UNSPEC;
4071    if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
4072                          &hobj, &pobj, &family, &socktype,
4073                          &protocol, &flags)) {
4074        return NULL;
4075    }
4076    if (hobj == Py_None) {
4077        hptr = NULL;
4078    } else if (PyUnicode_Check(hobj)) {
4079        idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
4080        if (!idna)
4081            return NULL;
4082        hptr = PyString_AsString(idna);
4083    } else if (PyString_Check(hobj)) {
4084        hptr = PyString_AsString(hobj);
4085    } else {
4086        PyErr_SetString(PyExc_TypeError,
4087                        "getaddrinfo() argument 1 must be string or None");
4088        return NULL;
4089    }
4090    if (PyInt_Check(pobj)) {
4091        PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
4092        pptr = pbuf;
4093    } else if (PyString_Check(pobj)) {
4094        pptr = PyString_AsString(pobj);
4095    } else if (pobj == Py_None) {
4096        pptr = (char *)NULL;
4097    } else {
4098        PyErr_SetString(socket_error, "Int or String expected");
4099        goto err;
4100    }
4101    memset(&hints, 0, sizeof(hints));
4102    hints.ai_family = family;
4103    hints.ai_socktype = socktype;
4104    hints.ai_protocol = protocol;
4105    hints.ai_flags = flags;
4106    Py_BEGIN_ALLOW_THREADS
4107    ACQUIRE_GETADDRINFO_LOCK
4108    error = getaddrinfo(hptr, pptr, &hints, &res0);
4109    Py_END_ALLOW_THREADS
4110    RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
4111    if (error) {
4112        set_gaierror(error);
4113        goto err;
4114    }
4115
4116    if ((all = PyList_New(0)) == NULL)
4117        goto err;
4118    for (res = res0; res; res = res->ai_next) {
4119        PyObject *addr =
4120            makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
4121        if (addr == NULL)
4122            goto err;
4123        single = Py_BuildValue("iiisO", res->ai_family,
4124            res->ai_socktype, res->ai_protocol,
4125            res->ai_canonname ? res->ai_canonname : "",
4126            addr);
4127        Py_DECREF(addr);
4128        if (single == NULL)
4129            goto err;
4130
4131        if (PyList_Append(all, single))
4132            goto err;
4133        Py_XDECREF(single);
4134    }
4135    Py_XDECREF(idna);
4136    if (res0)
4137        freeaddrinfo(res0);
4138    return all;
4139 err:
4140    Py_XDECREF(single);
4141    Py_XDECREF(all);
4142    Py_XDECREF(idna);
4143    if (res0)
4144        freeaddrinfo(res0);
4145    return (PyObject *)NULL;
4146}
4147
4148PyDoc_STRVAR(getaddrinfo_doc,
4149"getaddrinfo(host, port [, family, socktype, proto, flags])\n\
4150    -> list of (family, socktype, proto, canonname, sockaddr)\n\
4151\n\
4152Resolve host and port into addrinfo struct.");
4153
4154/* Python interface to getnameinfo(sa, flags). */
4155
4156/*ARGSUSED*/
4157static PyObject *
4158socket_getnameinfo(PyObject *self, PyObject *args)
4159{
4160    PyObject *sa = (PyObject *)NULL;
4161    int flags;
4162    char *hostp;
4163    int port, flowinfo, scope_id;
4164    char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
4165    struct addrinfo hints, *res = NULL;
4166    int error;
4167    PyObject *ret = (PyObject *)NULL;
4168
4169    flags = flowinfo = scope_id = 0;
4170    if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
4171        return NULL;
4172    if (!PyTuple_Check(sa)) {
4173        PyErr_SetString(PyExc_TypeError,
4174                        "getnameinfo() argument 1 must be a tuple");
4175        return NULL;
4176    }
4177    if (!PyArg_ParseTuple(sa, "si|ii",
4178                          &hostp, &port, &flowinfo, &scope_id))
4179        return NULL;
4180    PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
4181    memset(&hints, 0, sizeof(hints));
4182    hints.ai_family = AF_UNSPEC;
4183    hints.ai_socktype = SOCK_DGRAM;     /* make numeric port happy */
4184    Py_BEGIN_ALLOW_THREADS
4185    ACQUIRE_GETADDRINFO_LOCK
4186    error = getaddrinfo(hostp, pbuf, &hints, &res);
4187    Py_END_ALLOW_THREADS
4188    RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
4189    if (error) {
4190        set_gaierror(error);
4191        goto fail;
4192    }
4193    if (res->ai_next) {
4194        PyErr_SetString(socket_error,
4195            "sockaddr resolved to multiple addresses");
4196        goto fail;
4197    }
4198    switch (res->ai_family) {
4199    case AF_INET:
4200        {
4201        if (PyTuple_GET_SIZE(sa) != 2) {
4202            PyErr_SetString(socket_error,
4203                "IPv4 sockaddr must be 2 tuple");
4204            goto fail;
4205        }
4206        break;
4207        }
4208#ifdef ENABLE_IPV6
4209    case AF_INET6:
4210        {
4211        struct sockaddr_in6 *sin6;
4212        sin6 = (struct sockaddr_in6 *)res->ai_addr;
4213        sin6->sin6_flowinfo = flowinfo;
4214        sin6->sin6_scope_id = scope_id;
4215        break;
4216        }
4217#endif
4218    }
4219    error = getnameinfo(res->ai_addr, res->ai_addrlen,
4220                    hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
4221    if (error) {
4222        set_gaierror(error);
4223        goto fail;
4224    }
4225    ret = Py_BuildValue("ss", hbuf, pbuf);
4226
4227fail:
4228    if (res)
4229        freeaddrinfo(res);
4230    return ret;
4231}
4232
4233PyDoc_STRVAR(getnameinfo_doc,
4234"getnameinfo(sockaddr, flags) --> (host, port)\n\
4235\n\
4236Get host and port for a sockaddr.");
4237
4238
4239/* Python API to getting and setting the default timeout value. */
4240
4241static PyObject *
4242socket_getdefaulttimeout(PyObject *self)
4243{
4244    if (defaulttimeout < 0.0) {
4245        Py_INCREF(Py_None);
4246        return Py_None;
4247    }
4248    else
4249        return PyFloat_FromDouble(defaulttimeout);
4250}
4251
4252PyDoc_STRVAR(getdefaulttimeout_doc,
4253"getdefaulttimeout() -> timeout\n\
4254\n\
4255Returns the default timeout in floating seconds for new socket objects.\n\
4256A value of None indicates that new socket objects have no timeout.\n\
4257When the socket module is first imported, the default is None.");
4258
4259static PyObject *
4260socket_setdefaulttimeout(PyObject *self, PyObject *arg)
4261{
4262    double timeout;
4263
4264    if (arg == Py_None)
4265        timeout = -1.0;
4266    else {
4267        timeout = PyFloat_AsDouble(arg);
4268        if (timeout < 0.0) {
4269            if (!PyErr_Occurred())
4270                PyErr_SetString(PyExc_ValueError,
4271                                "Timeout value out of range");
4272            return NULL;
4273        }
4274    }
4275
4276    defaulttimeout = timeout;
4277
4278    Py_INCREF(Py_None);
4279    return Py_None;
4280}
4281
4282PyDoc_STRVAR(setdefaulttimeout_doc,
4283"setdefaulttimeout(timeout)\n\
4284\n\
4285Set the default timeout in floating seconds for new socket objects.\n\
4286A value of None indicates that new socket objects have no timeout.\n\
4287When the socket module is first imported, the default is None.");
4288
4289
4290/* List of functions exported by this module. */
4291
4292static PyMethodDef socket_methods[] = {
4293    {"gethostbyname",           socket_gethostbyname,
4294     METH_VARARGS, gethostbyname_doc},
4295    {"gethostbyname_ex",        socket_gethostbyname_ex,
4296     METH_VARARGS, ghbn_ex_doc},
4297    {"gethostbyaddr",           socket_gethostbyaddr,
4298     METH_VARARGS, gethostbyaddr_doc},
4299    {"gethostname",             socket_gethostname,
4300     METH_NOARGS,  gethostname_doc},
4301    {"getservbyname",           socket_getservbyname,
4302     METH_VARARGS, getservbyname_doc},
4303    {"getservbyport",           socket_getservbyport,
4304     METH_VARARGS, getservbyport_doc},
4305    {"getprotobyname",          socket_getprotobyname,
4306     METH_VARARGS, getprotobyname_doc},
4307#ifndef NO_DUP
4308    {"fromfd",                  socket_fromfd,
4309     METH_VARARGS, fromfd_doc},
4310#endif
4311#ifdef HAVE_SOCKETPAIR
4312    {"socketpair",              socket_socketpair,
4313     METH_VARARGS, socketpair_doc},
4314#endif
4315    {"ntohs",                   socket_ntohs,
4316     METH_VARARGS, ntohs_doc},
4317    {"ntohl",                   socket_ntohl,
4318     METH_O, ntohl_doc},
4319    {"htons",                   socket_htons,
4320     METH_VARARGS, htons_doc},
4321    {"htonl",                   socket_htonl,
4322     METH_O, htonl_doc},
4323    {"inet_aton",               socket_inet_aton,
4324     METH_VARARGS, inet_aton_doc},
4325    {"inet_ntoa",               socket_inet_ntoa,
4326     METH_VARARGS, inet_ntoa_doc},
4327#ifdef HAVE_INET_PTON
4328    {"inet_pton",               socket_inet_pton,
4329     METH_VARARGS, inet_pton_doc},
4330    {"inet_ntop",               socket_inet_ntop,
4331     METH_VARARGS, inet_ntop_doc},
4332#endif
4333    {"getaddrinfo",             socket_getaddrinfo,
4334     METH_VARARGS, getaddrinfo_doc},
4335    {"getnameinfo",             socket_getnameinfo,
4336     METH_VARARGS, getnameinfo_doc},
4337    {"getdefaulttimeout",       (PyCFunction)socket_getdefaulttimeout,
4338     METH_NOARGS, getdefaulttimeout_doc},
4339    {"setdefaulttimeout",       socket_setdefaulttimeout,
4340     METH_O, setdefaulttimeout_doc},
4341    {NULL,                      NULL}            /* Sentinel */
4342};
4343
4344
4345#ifdef RISCOS
4346#define OS_INIT_DEFINED
4347
4348static int
4349os_init(void)
4350{
4351    _kernel_swi_regs r;
4352
4353    r.r[0] = 0;
4354    _kernel_swi(0x43380, &r, &r);
4355    taskwindow = r.r[0];
4356
4357    return 1;
4358}
4359
4360#endif /* RISCOS */
4361
4362
4363#ifdef MS_WINDOWS
4364#define OS_INIT_DEFINED
4365
4366/* Additional initialization and cleanup for Windows */
4367
4368static void
4369os_cleanup(void)
4370{
4371    WSACleanup();
4372}
4373
4374static int
4375os_init(void)
4376{
4377    WSADATA WSAData;
4378    int ret;
4379    char buf[100];
4380    ret = WSAStartup(0x0101, &WSAData);
4381    switch (ret) {
4382    case 0:     /* No error */
4383        Py_AtExit(os_cleanup);
4384        return 1; /* Success */
4385    case WSASYSNOTREADY:
4386        PyErr_SetString(PyExc_ImportError,
4387                        "WSAStartup failed: network not ready");
4388        break;
4389    case WSAVERNOTSUPPORTED:
4390    case WSAEINVAL:
4391        PyErr_SetString(
4392            PyExc_ImportError,
4393            "WSAStartup failed: requested version not supported");
4394        break;
4395    default:
4396        PyOS_snprintf(buf, sizeof(buf),
4397                      "WSAStartup failed: error code %d", ret);
4398        PyErr_SetString(PyExc_ImportError, buf);
4399        break;
4400    }
4401    return 0; /* Failure */
4402}
4403
4404#endif /* MS_WINDOWS */
4405
4406
4407#ifdef PYOS_OS2
4408#define OS_INIT_DEFINED
4409
4410/* Additional initialization for OS/2 */
4411
4412static int
4413os_init(void)
4414{
4415#ifndef PYCC_GCC
4416    char reason[64];
4417    int rc = sock_init();
4418
4419    if (rc == 0) {
4420        return 1; /* Success */
4421    }
4422
4423    PyOS_snprintf(reason, sizeof(reason),
4424                  "OS/2 TCP/IP Error# %d", sock_errno());
4425    PyErr_SetString(PyExc_ImportError, reason);
4426
4427    return 0;  /* Failure */
4428#else
4429    /* No need to initialize sockets with GCC/EMX */
4430    return 1; /* Success */
4431#endif
4432}
4433
4434#endif /* PYOS_OS2 */
4435
4436
4437#ifndef OS_INIT_DEFINED
4438static int
4439os_init(void)
4440{
4441    return 1; /* Success */
4442}
4443#endif
4444
4445
4446/* C API table - always add new things to the end for binary
4447   compatibility. */
4448static
4449PySocketModule_APIObject PySocketModuleAPI =
4450{
4451    &sock_type,
4452    NULL
4453};
4454
4455
4456/* Initialize the _socket module.
4457
4458   This module is actually called "_socket", and there's a wrapper
4459   "socket.py" which implements some additional functionality.  On some
4460   platforms (e.g. Windows and OS/2), socket.py also implements a
4461   wrapper for the socket type that provides missing functionality such
4462   as makefile(), dup() and fromfd().  The import of "_socket" may fail
4463   with an ImportError exception if os-specific initialization fails.
4464   On Windows, this does WINSOCK initialization.  When WINSOCK is
4465   initialized successfully, a call to WSACleanup() is scheduled to be
4466   made at exit time.
4467*/
4468
4469PyDoc_STRVAR(socket_doc,
4470"Implementation module for socket operations.\n\
4471\n\
4472See the socket module for documentation.");
4473
4474PyMODINIT_FUNC
4475init_socket(void)
4476{
4477    PyObject *m, *has_ipv6;
4478
4479    if (!os_init())
4480        return;
4481
4482    Py_TYPE(&sock_type) = &PyType_Type;
4483    m = Py_InitModule3(PySocket_MODULE_NAME,
4484                       socket_methods,
4485                       socket_doc);
4486    if (m == NULL)
4487        return;
4488
4489    socket_error = PyErr_NewException("socket.error",
4490                                      PyExc_IOError, NULL);
4491    if (socket_error == NULL)
4492        return;
4493    PySocketModuleAPI.error = socket_error;
4494    Py_INCREF(socket_error);
4495    PyModule_AddObject(m, "error", socket_error);
4496    socket_herror = PyErr_NewException("socket.herror",
4497                                       socket_error, NULL);
4498    if (socket_herror == NULL)
4499        return;
4500    Py_INCREF(socket_herror);
4501    PyModule_AddObject(m, "herror", socket_herror);
4502    socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
4503        NULL);
4504    if (socket_gaierror == NULL)
4505        return;
4506    Py_INCREF(socket_gaierror);
4507    PyModule_AddObject(m, "gaierror", socket_gaierror);
4508    socket_timeout = PyErr_NewException("socket.timeout",
4509                                        socket_error, NULL);
4510    if (socket_timeout == NULL)
4511        return;
4512    Py_INCREF(socket_timeout);
4513    PyModule_AddObject(m, "timeout", socket_timeout);
4514    Py_INCREF((PyObject *)&sock_type);
4515    if (PyModule_AddObject(m, "SocketType",
4516                           (PyObject *)&sock_type) != 0)
4517        return;
4518    Py_INCREF((PyObject *)&sock_type);
4519    if (PyModule_AddObject(m, "socket",
4520                           (PyObject *)&sock_type) != 0)
4521        return;
4522
4523#ifdef ENABLE_IPV6
4524    has_ipv6 = Py_True;
4525#else
4526    has_ipv6 = Py_False;
4527#endif
4528    Py_INCREF(has_ipv6);
4529    PyModule_AddObject(m, "has_ipv6", has_ipv6);
4530
4531    /* Export C API */
4532    if (PyModule_AddObject(m, PySocket_CAPI_NAME,
4533           PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL)
4534                             ) != 0)
4535        return;
4536
4537    /* Address families (we only support AF_INET and AF_UNIX) */
4538#ifdef AF_UNSPEC
4539    PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
4540#endif
4541    PyModule_AddIntConstant(m, "AF_INET", AF_INET);
4542#ifdef AF_INET6
4543    PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
4544#endif /* AF_INET6 */
4545#if defined(AF_UNIX)
4546    PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
4547#endif /* AF_UNIX */
4548#ifdef AF_AX25
4549    /* Amateur Radio AX.25 */
4550    PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
4551#endif
4552#ifdef AF_IPX
4553    PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
4554#endif
4555#ifdef AF_APPLETALK
4556    /* Appletalk DDP */
4557    PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
4558#endif
4559#ifdef AF_NETROM
4560    /* Amateur radio NetROM */
4561    PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
4562#endif
4563#ifdef AF_BRIDGE
4564    /* Multiprotocol bridge */
4565    PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
4566#endif
4567#ifdef AF_ATMPVC
4568    /* ATM PVCs */
4569    PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
4570#endif
4571#ifdef AF_AAL5
4572    /* Reserved for Werner's ATM */
4573    PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
4574#endif
4575#ifdef AF_X25
4576    /* Reserved for X.25 project */
4577    PyModule_AddIntConstant(m, "AF_X25", AF_X25);
4578#endif
4579#ifdef AF_INET6
4580    PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
4581#endif
4582#ifdef AF_ROSE
4583    /* Amateur Radio X.25 PLP */
4584    PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
4585#endif
4586#ifdef AF_DECnet
4587    /* Reserved for DECnet project */
4588    PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
4589#endif
4590#ifdef AF_NETBEUI
4591    /* Reserved for 802.2LLC project */
4592    PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
4593#endif
4594#ifdef AF_SECURITY
4595    /* Security callback pseudo AF */
4596    PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
4597#endif
4598#ifdef AF_KEY
4599    /* PF_KEY key management API */
4600    PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
4601#endif
4602#ifdef AF_NETLINK
4603    /*  */
4604    PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
4605    PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
4606#ifdef NETLINK_SKIP
4607    PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
4608#endif
4609#ifdef NETLINK_W1
4610    PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
4611#endif
4612    PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
4613    PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
4614#ifdef NETLINK_TCPDIAG
4615    PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
4616#endif
4617#ifdef NETLINK_NFLOG
4618    PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
4619#endif
4620#ifdef NETLINK_XFRM
4621    PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
4622#endif
4623#ifdef NETLINK_ARPD
4624    PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
4625#endif
4626#ifdef NETLINK_ROUTE6
4627    PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
4628#endif
4629    PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
4630#ifdef NETLINK_DNRTMSG
4631    PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
4632#endif
4633#ifdef NETLINK_TAPBASE
4634    PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
4635#endif
4636#endif /* AF_NETLINK */
4637#ifdef AF_ROUTE
4638    /* Alias to emulate 4.4BSD */
4639    PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
4640#endif
4641#ifdef AF_ASH
4642    /* Ash */
4643    PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
4644#endif
4645#ifdef AF_ECONET
4646    /* Acorn Econet */
4647    PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
4648#endif
4649#ifdef AF_ATMSVC
4650    /* ATM SVCs */
4651    PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
4652#endif
4653#ifdef AF_SNA
4654    /* Linux SNA Project (nutters!) */
4655    PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
4656#endif
4657#ifdef AF_IRDA
4658    /* IRDA sockets */
4659    PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
4660#endif
4661#ifdef AF_PPPOX
4662    /* PPPoX sockets */
4663    PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
4664#endif
4665#ifdef AF_WANPIPE
4666    /* Wanpipe API Sockets */
4667    PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
4668#endif
4669#ifdef AF_LLC
4670    /* Linux LLC */
4671    PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
4672#endif
4673
4674#ifdef USE_BLUETOOTH
4675    PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
4676    PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
4677    PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
4678    PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
4679#if !defined(__NetBSD__) && !defined(__DragonFly__)
4680    PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
4681#endif
4682#if !defined(__FreeBSD__)
4683#if !defined(__NetBSD__) && !defined(__DragonFly__)
4684    PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
4685#endif
4686    PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
4687    PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
4688#endif
4689    PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
4690    PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
4691    PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4692#endif
4693
4694#ifdef AF_PACKET
4695    PyModule_AddIntMacro(m, AF_PACKET);
4696#endif
4697#ifdef PF_PACKET
4698    PyModule_AddIntMacro(m, PF_PACKET);
4699#endif
4700#ifdef PACKET_HOST
4701    PyModule_AddIntMacro(m, PACKET_HOST);
4702#endif
4703#ifdef PACKET_BROADCAST
4704    PyModule_AddIntMacro(m, PACKET_BROADCAST);
4705#endif
4706#ifdef PACKET_MULTICAST
4707    PyModule_AddIntMacro(m, PACKET_MULTICAST);
4708#endif
4709#ifdef PACKET_OTHERHOST
4710    PyModule_AddIntMacro(m, PACKET_OTHERHOST);
4711#endif
4712#ifdef PACKET_OUTGOING
4713    PyModule_AddIntMacro(m, PACKET_OUTGOING);
4714#endif
4715#ifdef PACKET_LOOPBACK
4716    PyModule_AddIntMacro(m, PACKET_LOOPBACK);
4717#endif
4718#ifdef PACKET_FASTROUTE
4719    PyModule_AddIntMacro(m, PACKET_FASTROUTE);
4720#endif
4721
4722#ifdef HAVE_LINUX_TIPC_H
4723    PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
4724
4725    /* for addresses */
4726    PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
4727    PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
4728    PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
4729
4730    PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
4731    PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
4732    PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
4733
4734    /* for setsockopt() */
4735    PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
4736    PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
4737    PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
4738    PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
4739                    TIPC_DEST_DROPPABLE);
4740    PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
4741
4742    PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
4743                    TIPC_LOW_IMPORTANCE);
4744    PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
4745                    TIPC_MEDIUM_IMPORTANCE);
4746    PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
4747                    TIPC_HIGH_IMPORTANCE);
4748    PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
4749                    TIPC_CRITICAL_IMPORTANCE);
4750
4751    /* for subscriptions */
4752    PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
4753    PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
4754#ifdef TIPC_SUB_CANCEL
4755    /* doesn't seem to be available everywhere */
4756    PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
4757#endif
4758    PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
4759    PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
4760    PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
4761    PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
4762    PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
4763    PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
4764#endif
4765
4766    /* Socket types */
4767    PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
4768    PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
4769#ifndef __BEOS__
4770/* We have incomplete socket support. */
4771    PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
4772    PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
4773#if defined(SOCK_RDM)
4774    PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
4775#endif
4776#endif
4777
4778#ifdef  SO_DEBUG
4779    PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
4780#endif
4781#ifdef  SO_ACCEPTCONN
4782    PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
4783#endif
4784#ifdef  SO_REUSEADDR
4785    PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
4786#endif
4787#ifdef SO_EXCLUSIVEADDRUSE
4788    PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
4789#endif
4790
4791#ifdef  SO_KEEPALIVE
4792    PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
4793#endif
4794#ifdef  SO_DONTROUTE
4795    PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
4796#endif
4797#ifdef  SO_BROADCAST
4798    PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
4799#endif
4800#ifdef  SO_USELOOPBACK
4801    PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
4802#endif
4803#ifdef  SO_LINGER
4804    PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
4805#endif
4806#ifdef  SO_OOBINLINE
4807    PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
4808#endif
4809#ifdef  SO_REUSEPORT
4810    PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
4811#endif
4812#ifdef  SO_SNDBUF
4813    PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
4814#endif
4815#ifdef  SO_RCVBUF
4816    PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
4817#endif
4818#ifdef  SO_SNDLOWAT
4819    PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
4820#endif
4821#ifdef  SO_RCVLOWAT
4822    PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
4823#endif
4824#ifdef  SO_SNDTIMEO
4825    PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
4826#endif
4827#ifdef  SO_RCVTIMEO
4828    PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
4829#endif
4830#ifdef  SO_ERROR
4831    PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
4832#endif
4833#ifdef  SO_TYPE
4834    PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
4835#endif
4836#ifdef SO_SETFIB
4837    PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB);
4838#endif
4839
4840    /* Maximum number of connections for "listen" */
4841#ifdef  SOMAXCONN
4842    PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
4843#else
4844    PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
4845#endif
4846
4847    /* Flags for send, recv */
4848#ifdef  MSG_OOB
4849    PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
4850#endif
4851#ifdef  MSG_PEEK
4852    PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
4853#endif
4854#ifdef  MSG_DONTROUTE
4855    PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
4856#endif
4857#ifdef  MSG_DONTWAIT
4858    PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
4859#endif
4860#ifdef  MSG_EOR
4861    PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
4862#endif
4863#ifdef  MSG_TRUNC
4864    PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
4865#endif
4866#ifdef  MSG_CTRUNC
4867    PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
4868#endif
4869#ifdef  MSG_WAITALL
4870    PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
4871#endif
4872#ifdef  MSG_BTAG
4873    PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
4874#endif
4875#ifdef  MSG_ETAG
4876    PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
4877#endif
4878
4879    /* Protocol level and numbers, usable for [gs]etsockopt */
4880#ifdef  SOL_SOCKET
4881    PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
4882#endif
4883#ifdef  SOL_IP
4884    PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
4885#else
4886    PyModule_AddIntConstant(m, "SOL_IP", 0);
4887#endif
4888#ifdef  SOL_IPX
4889    PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
4890#endif
4891#ifdef  SOL_AX25
4892    PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
4893#endif
4894#ifdef  SOL_ATALK
4895    PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
4896#endif
4897#ifdef  SOL_NETROM
4898    PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
4899#endif
4900#ifdef  SOL_ROSE
4901    PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
4902#endif
4903#ifdef  SOL_TCP
4904    PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
4905#else
4906    PyModule_AddIntConstant(m, "SOL_TCP", 6);
4907#endif
4908#ifdef  SOL_UDP
4909    PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
4910#else
4911    PyModule_AddIntConstant(m, "SOL_UDP", 17);
4912#endif
4913#ifdef  IPPROTO_IP
4914    PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
4915#else
4916    PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
4917#endif
4918#ifdef  IPPROTO_HOPOPTS
4919    PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
4920#endif
4921#ifdef  IPPROTO_ICMP
4922    PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
4923#else
4924    PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
4925#endif
4926#ifdef  IPPROTO_IGMP
4927    PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
4928#endif
4929#ifdef  IPPROTO_GGP
4930    PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
4931#endif
4932#ifdef  IPPROTO_IPV4
4933    PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
4934#endif
4935#ifdef  IPPROTO_IPV6
4936    PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4937#endif
4938#ifdef  IPPROTO_IPIP
4939    PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
4940#endif
4941#ifdef  IPPROTO_TCP
4942    PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
4943#else
4944    PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
4945#endif
4946#ifdef  IPPROTO_EGP
4947    PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
4948#endif
4949#ifdef  IPPROTO_PUP
4950    PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
4951#endif
4952#ifdef  IPPROTO_UDP
4953    PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
4954#else
4955    PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
4956#endif
4957#ifdef  IPPROTO_IDP
4958    PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
4959#endif
4960#ifdef  IPPROTO_HELLO
4961    PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
4962#endif
4963#ifdef  IPPROTO_ND
4964    PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
4965#endif
4966#ifdef  IPPROTO_TP
4967    PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
4968#endif
4969#ifdef  IPPROTO_IPV6
4970    PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4971#endif
4972#ifdef  IPPROTO_ROUTING
4973    PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
4974#endif
4975#ifdef  IPPROTO_FRAGMENT
4976    PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
4977#endif
4978#ifdef  IPPROTO_RSVP
4979    PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
4980#endif
4981#ifdef  IPPROTO_GRE
4982    PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
4983#endif
4984#ifdef  IPPROTO_ESP
4985    PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
4986#endif
4987#ifdef  IPPROTO_AH
4988    PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
4989#endif
4990#ifdef  IPPROTO_MOBILE
4991    PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
4992#endif
4993#ifdef  IPPROTO_ICMPV6
4994    PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
4995#endif
4996#ifdef  IPPROTO_NONE
4997    PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
4998#endif
4999#ifdef  IPPROTO_DSTOPTS
5000    PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
5001#endif
5002#ifdef  IPPROTO_XTP
5003    PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
5004#endif
5005#ifdef  IPPROTO_EON
5006    PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
5007#endif
5008#ifdef  IPPROTO_PIM
5009    PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
5010#endif
5011#ifdef  IPPROTO_IPCOMP
5012    PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
5013#endif
5014#ifdef  IPPROTO_VRRP
5015    PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
5016#endif
5017#ifdef  IPPROTO_BIP
5018    PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
5019#endif
5020/**/
5021#ifdef  IPPROTO_RAW
5022    PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
5023#else
5024    PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
5025#endif
5026#ifdef  IPPROTO_MAX
5027    PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
5028#endif
5029
5030    /* Some port configuration */
5031#ifdef  IPPORT_RESERVED
5032    PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
5033#else
5034    PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
5035#endif
5036#ifdef  IPPORT_USERRESERVED
5037    PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
5038#else
5039    PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
5040#endif
5041
5042    /* Some reserved IP v.4 addresses */
5043#ifdef  INADDR_ANY
5044    PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
5045#else
5046    PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
5047#endif
5048#ifdef  INADDR_BROADCAST
5049    PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
5050#else
5051    PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
5052#endif
5053#ifdef  INADDR_LOOPBACK
5054    PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
5055#else
5056    PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
5057#endif
5058#ifdef  INADDR_UNSPEC_GROUP
5059    PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
5060#else
5061    PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
5062#endif
5063#ifdef  INADDR_ALLHOSTS_GROUP
5064    PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
5065                            INADDR_ALLHOSTS_GROUP);
5066#else
5067    PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
5068#endif
5069#ifdef  INADDR_MAX_LOCAL_GROUP
5070    PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
5071                            INADDR_MAX_LOCAL_GROUP);
5072#else
5073    PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
5074#endif
5075#ifdef  INADDR_NONE
5076    PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
5077#else
5078    PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
5079#endif
5080
5081    /* IPv4 [gs]etsockopt options */
5082#ifdef  IP_OPTIONS
5083    PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
5084#endif
5085#ifdef  IP_HDRINCL
5086    PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
5087#endif
5088#ifdef  IP_TOS
5089    PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
5090#endif
5091#ifdef  IP_TTL
5092    PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
5093#endif
5094#ifdef  IP_RECVOPTS
5095    PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
5096#endif
5097#ifdef  IP_RECVRETOPTS
5098    PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
5099#endif
5100#ifdef  IP_RECVDSTADDR
5101    PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
5102#endif
5103#ifdef  IP_RETOPTS
5104    PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
5105#endif
5106#ifdef  IP_MULTICAST_IF
5107    PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
5108#endif
5109#ifdef  IP_MULTICAST_TTL
5110    PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
5111#endif
5112#ifdef  IP_MULTICAST_LOOP
5113    PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
5114#endif
5115#ifdef  IP_ADD_MEMBERSHIP
5116    PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
5117#endif
5118#ifdef  IP_DROP_MEMBERSHIP
5119    PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
5120#endif
5121#ifdef  IP_DEFAULT_MULTICAST_TTL
5122    PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
5123                            IP_DEFAULT_MULTICAST_TTL);
5124#endif
5125#ifdef  IP_DEFAULT_MULTICAST_LOOP
5126    PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
5127                            IP_DEFAULT_MULTICAST_LOOP);
5128#endif
5129#ifdef  IP_MAX_MEMBERSHIPS
5130    PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
5131#endif
5132
5133    /* IPv6 [gs]etsockopt options, defined in RFC2553 */
5134#ifdef  IPV6_JOIN_GROUP
5135    PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
5136#endif
5137#ifdef  IPV6_LEAVE_GROUP
5138    PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
5139#endif
5140#ifdef  IPV6_MULTICAST_HOPS
5141    PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
5142#endif
5143#ifdef  IPV6_MULTICAST_IF
5144    PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
5145#endif
5146#ifdef  IPV6_MULTICAST_LOOP
5147    PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
5148#endif
5149#ifdef  IPV6_UNICAST_HOPS
5150    PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
5151#endif
5152    /* Additional IPV6 socket options, defined in RFC 3493 */
5153#ifdef IPV6_V6ONLY
5154    PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
5155#endif
5156    /* Advanced IPV6 socket options, from RFC 3542 */
5157#ifdef IPV6_CHECKSUM
5158    PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
5159#endif
5160#ifdef IPV6_DONTFRAG
5161    PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
5162#endif
5163#ifdef IPV6_DSTOPTS
5164    PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
5165#endif
5166#ifdef IPV6_HOPLIMIT
5167    PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
5168#endif
5169#ifdef IPV6_HOPOPTS
5170    PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
5171#endif
5172#ifdef IPV6_NEXTHOP
5173    PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
5174#endif
5175#ifdef IPV6_PATHMTU
5176    PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
5177#endif
5178#ifdef IPV6_PKTINFO
5179    PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
5180#endif
5181#ifdef IPV6_RECVDSTOPTS
5182    PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
5183#endif
5184#ifdef IPV6_RECVHOPLIMIT
5185    PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
5186#endif
5187#ifdef IPV6_RECVHOPOPTS
5188    PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
5189#endif
5190#ifdef IPV6_RECVPKTINFO
5191    PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
5192#endif
5193#ifdef IPV6_RECVRTHDR
5194    PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
5195#endif
5196#ifdef IPV6_RECVTCLASS
5197    PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
5198#endif
5199#ifdef IPV6_RTHDR
5200    PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
5201#endif
5202#ifdef IPV6_RTHDRDSTOPTS
5203    PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
5204#endif
5205#ifdef IPV6_RTHDR_TYPE_0
5206    PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
5207#endif
5208#ifdef IPV6_RECVPATHMTU
5209    PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
5210#endif
5211#ifdef IPV6_TCLASS
5212    PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
5213#endif
5214#ifdef IPV6_USE_MIN_MTU
5215    PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
5216#endif
5217
5218    /* TCP options */
5219#ifdef  TCP_NODELAY
5220    PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
5221#endif
5222#ifdef  TCP_MAXSEG
5223    PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
5224#endif
5225#ifdef  TCP_CORK
5226    PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
5227#endif
5228#ifdef  TCP_KEEPIDLE
5229    PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
5230#endif
5231#ifdef  TCP_KEEPINTVL
5232    PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
5233#endif
5234#ifdef  TCP_KEEPCNT
5235    PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
5236#endif
5237#ifdef  TCP_SYNCNT
5238    PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
5239#endif
5240#ifdef  TCP_LINGER2
5241    PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
5242#endif
5243#ifdef  TCP_DEFER_ACCEPT
5244    PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
5245#endif
5246#ifdef  TCP_WINDOW_CLAMP
5247    PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
5248#endif
5249#ifdef  TCP_INFO
5250    PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
5251#endif
5252#ifdef  TCP_QUICKACK
5253    PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
5254#endif
5255
5256
5257    /* IPX options */
5258#ifdef  IPX_TYPE
5259    PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
5260#endif
5261
5262    /* get{addr,name}info parameters */
5263#ifdef EAI_ADDRFAMILY
5264    PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
5265#endif
5266#ifdef EAI_AGAIN
5267    PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
5268#endif
5269#ifdef EAI_BADFLAGS
5270    PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
5271#endif
5272#ifdef EAI_FAIL
5273    PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
5274#endif
5275#ifdef EAI_FAMILY
5276    PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
5277#endif
5278#ifdef EAI_MEMORY
5279    PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
5280#endif
5281#ifdef EAI_NODATA
5282    PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
5283#endif
5284#ifdef EAI_NONAME
5285    PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
5286#endif
5287#ifdef EAI_OVERFLOW
5288    PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
5289#endif
5290#ifdef EAI_SERVICE
5291    PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
5292#endif
5293#ifdef EAI_SOCKTYPE
5294    PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
5295#endif
5296#ifdef EAI_SYSTEM
5297    PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
5298#endif
5299#ifdef EAI_BADHINTS
5300    PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
5301#endif
5302#ifdef EAI_PROTOCOL
5303    PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
5304#endif
5305#ifdef EAI_MAX
5306    PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
5307#endif
5308#ifdef AI_PASSIVE
5309    PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
5310#endif
5311#ifdef AI_CANONNAME
5312    PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
5313#endif
5314#ifdef AI_NUMERICHOST
5315    PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
5316#endif
5317#ifdef AI_NUMERICSERV
5318    PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
5319#endif
5320#ifdef AI_MASK
5321    PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
5322#endif
5323#ifdef AI_ALL
5324    PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
5325#endif
5326#ifdef AI_V4MAPPED_CFG
5327    PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
5328#endif
5329#ifdef AI_ADDRCONFIG
5330    PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
5331#endif
5332#ifdef AI_V4MAPPED
5333    PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
5334#endif
5335#ifdef AI_DEFAULT
5336    PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
5337#endif
5338#ifdef NI_MAXHOST
5339    PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
5340#endif
5341#ifdef NI_MAXSERV
5342    PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
5343#endif
5344#ifdef NI_NOFQDN
5345    PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
5346#endif
5347#ifdef NI_NUMERICHOST
5348    PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
5349#endif
5350#ifdef NI_NAMEREQD
5351    PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
5352#endif
5353#ifdef NI_NUMERICSERV
5354    PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
5355#endif
5356#ifdef NI_DGRAM
5357    PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
5358#endif
5359
5360    /* shutdown() parameters */
5361#ifdef SHUT_RD
5362    PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
5363#elif defined(SD_RECEIVE)
5364    PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
5365#else
5366    PyModule_AddIntConstant(m, "SHUT_RD", 0);
5367#endif
5368#ifdef SHUT_WR
5369    PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
5370#elif defined(SD_SEND)
5371    PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
5372#else
5373    PyModule_AddIntConstant(m, "SHUT_WR", 1);
5374#endif
5375#ifdef SHUT_RDWR
5376    PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
5377#elif defined(SD_BOTH)
5378    PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
5379#else
5380    PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
5381#endif
5382
5383#ifdef SIO_RCVALL
5384    {
5385        DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS};
5386        const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
5387        int i;
5388        for(i = 0; i<sizeof(codes)/sizeof(*codes); ++i) {
5389            PyObject *tmp;
5390            tmp = PyLong_FromUnsignedLong(codes[i]);
5391            if (tmp == NULL)
5392                return;
5393            PyModule_AddObject(m, names[i], tmp);
5394        }
5395    }
5396    PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
5397    PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
5398    PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
5399#ifdef RCVALL_IPLEVEL
5400    PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
5401#endif
5402#ifdef RCVALL_MAX
5403    PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
5404#endif
5405#endif /* _MSTCPIP_ */
5406
5407    /* Initialize gethostbyname lock */
5408#if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5409    netdb_lock = PyThread_allocate_lock();
5410#endif
5411}
5412
5413
5414#ifndef HAVE_INET_PTON
5415#if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
5416
5417/* Simplistic emulation code for inet_pton that only works for IPv4 */
5418/* These are not exposed because they do not set errno properly */
5419
5420int
5421inet_pton(int af, const char *src, void *dst)
5422{
5423    if (af == AF_INET) {
5424#if (SIZEOF_INT != 4)
5425#error "Not sure if in_addr_t exists and int is not 32-bits."
5426#endif
5427        unsigned int packed_addr;
5428        packed_addr = inet_addr(src);
5429        if (packed_addr == INADDR_NONE)
5430            return 0;
5431        memcpy(dst, &packed_addr, 4);
5432        return 1;
5433    }
5434    /* Should set errno to EAFNOSUPPORT */
5435    return -1;
5436}
5437
5438const char *
5439inet_ntop(int af, const void *src, char *dst, socklen_t size)
5440{
5441    if (af == AF_INET) {
5442        struct in_addr packed_addr;
5443        if (size < 16)
5444            /* Should set errno to ENOSPC. */
5445            return NULL;
5446        memcpy(&packed_addr, src, sizeof(packed_addr));
5447        return strncpy(dst, inet_ntoa(packed_addr), size);
5448    }
5449    /* Should set errno to EAFNOSUPPORT */
5450    return NULL;
5451}
5452
5453#endif
5454#endif
5455