source: python/vendor/Python-2.6.5/Modules/socketmodule.c

Last change on this file was 2, checked in by Yuri Dario, 15 years ago

Initial import for vendor code.

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