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