3 /* SSL support based on patches by Brian E Gallew and Laszlo Kovacs */
6 This module provides an interface to Berkeley socket IPC.
10 - only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
11 portable manner, though AF_PACKET is supported under Linux.
12 - no read/write operations (use sendall/recv or makefile instead)
13 - additional restrictions apply on Windows (compensated for by socket.py)
17 - socket.error: exception raised for socket specific errors
18 - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
19 a subclass of socket.error
20 - socket.herror: exception raised for gethostby* errors,
21 a subclass of socket.error
22 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
23 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
24 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
25 - socket.getprotobyname(protocolname) --> protocol number
26 - socket.getservbyname(servicename, protocolname) --> port number
27 - socket.socket(family, type [, proto]) --> new socket object
28 - socket.ntohs(16 bit value) --> new int object
29 - socket.ntohl(32 bit value) --> new int object
30 - socket.htons(16 bit value) --> new int object
31 - socket.htonl(32 bit value) --> new int object
32 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
33 --> List of (family, socktype, proto, canonname, sockaddr)
34 - socket.getnameinfo(sockaddr, flags) --> (host, port)
35 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
36 - socket.inet_aton(IP address) -> 32-bit packed IP representation
37 - socket.inet_ntoa(packed IP) -> IP address string
38 - socket.ssl(socket, keyfile, certfile) -> new ssl object
39 - an Internet socket address is a pair (hostname, port)
40 where hostname can be anything recognized by gethostbyname()
41 (including the dd.dd.dd.dd notation) and port is in host byte order
42 - where a hostname is returned, the dd.dd.dd.dd notation is used
43 - a UNIX domain socket address is a string specifying the pathname
44 - an AF_PACKET socket address is a tuple containing a string
45 specifying the ethernet interface and an integer specifying
46 the Ethernet protocol number to be received. For example:
47 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
48 specify packet-type and ha-type/addr -- these are ignored by
49 networking code, but accepted since they are returned by the
54 - s.accept() --> new socket object, sockaddr
55 - s.bind(sockaddr) --> None
57 - s.connect(sockaddr) --> None
58 - s.connect_ex(sockaddr) --> 0 or errno (handy for e.g. async connect)
59 - s.fileno() --> file descriptor
60 - s.dup() --> same as socket.fromfd(os.dup(s.fileno(), ...)
61 - s.getpeername() --> sockaddr
62 - s.getsockname() --> sockaddr
63 - s.getsockopt(level, optname[, buflen]) --> int or string
64 - s.listen(backlog) --> None
65 - s.makefile([mode[, bufsize]]) --> file object
66 - s.recv(buflen [,flags]) --> string
67 - s.recvfrom(buflen [,flags]) --> string, sockaddr
68 - s.send(string [,flags]) --> nbytes
69 - s.sendall(string [,flags]) # tries to send everything in a loop
70 - s.sendto(string, [flags,] sockaddr) --> nbytes
71 - s.setblocking(0 | 1) --> None
72 - s.setsockopt(level, optname, value) --> None
73 - s.shutdown(how) --> None
74 - repr(s) --> "<socket object, fd=%d, family=%d, type=%d, protocol=%d>"
80 /* XXX This is a terrible mess of of platform-dependent preprocessor hacks.
81 I hope some day someone can clean this up please... */
83 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
84 script doesn't get this right, so we hardcode some platform checks below.
85 On the other hand, not all Linux versions agree, so there the settings
86 computed by the configure script are needed! */
89 #undef HAVE_GETHOSTBYNAME_R_3_ARG
90 #undef HAVE_GETHOSTBYNAME_R_5_ARG
91 #undef HAVE_GETHOSTBYNAME_R_6_ARG
95 #undef HAVE_GETHOSTBYNAME_R
98 #ifdef HAVE_GETHOSTBYNAME_R
99 #if defined(_AIX) || defined(__osf__)
100 #define HAVE_GETHOSTBYNAME_R_3_ARG
101 #elif defined(__sun) || defined(__sgi)
102 #define HAVE_GETHOSTBYNAME_R_5_ARG
104 /* Rely on the configure script */
106 #undef HAVE_GETHOSTBYNAME_R
110 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && !defined(MS_WINDOWS)
111 #define USE_GETHOSTBYNAME_LOCK
114 #ifdef USE_GETHOSTBYNAME_LOCK
115 #include "pythread.h"
118 #if defined(PYCC_VACPP)
121 #include <sys/ioctl.h>
126 #if defined(PYOS_OS2)
128 #define INCL_DOSERRORS
134 #include <sys/types.h>
139 #include <sys/socket.h>
140 #include <netinet/in.h>
141 #if !(defined(__BEOS__) || defined(__CYGWIN__) || (defined(PYOS_OS2) && defined(PYCC_VACPP)))
142 #include <netinet/tcp.h>
145 /* Headers needed for inet_ntoa() and inet_addr() */
147 #include <net/netdb.h>
148 #elif defined(PYOS_OS2) && defined(PYCC_VACPP)
150 typedef size_t socklen_t
;
153 #include <arpa/inet.h>
160 #include <sys/fcntl.h>
162 int h_errno
; /* not used */
176 #ifdef HAVE_NETPACKET_PACKET_H
177 #include <sys/ioctl.h>
179 #include <netpacket/packet.h>
187 #define offsetof(type, member) ((size_t)(&((type *)0)->member))
191 #define O_NDELAY O_NONBLOCK /* For QNX only? */
195 /* fdopen() isn't declared in stdio.h (sigh) */
199 #include "addrinfo.h"
202 #include "openssl/rsa.h"
203 #include "openssl/crypto.h"
204 #include "openssl/x509.h"
205 #include "openssl/pem.h"
206 #include "openssl/ssl.h"
207 #include "openssl/err.h"
208 #include "openssl/rand.h"
211 #ifndef HAVE_INET_PTON
212 int inet_pton (int af
, const char *src
, void *dst
);
213 const char *inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
);
217 /* On OS X, getaddrinfo returns no error indication of lookup
218 failure, so we must use the emulation instead of the libinfo
219 implementation. Unfortunately, performing an autoconf test
220 for this bug would require DNS access for the machine performing
221 the configuration, which is not acceptable. Therefore, we
222 determine the bug just by checking for __APPLE__. If this bug
223 gets ever fixed, perhaps checking for sys/version.h would be
224 appropriate, which is 10/0 on the system with the bug. */
225 #undef HAVE_GETADDRINFO
226 /* avoid clashes with the C library definition of the symbol. */
227 #define getaddrinfo fake_getaddrinfo
230 /* I know this is a bad practice, but it is the easiest... */
231 #if !defined(HAVE_GETADDRINFO)
232 #include "getaddrinfo.c"
234 #if !defined(HAVE_GETNAMEINFO)
235 #include "getnameinfo.c"
238 #if defined(MS_WINDOWS) || defined(__BEOS__)
239 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
240 /* seem to be a few differences in the API */
241 #define SOCKETCLOSE closesocket
242 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
245 /* abstract the socket file descriptor type */
247 typedef SOCKET SOCKET_T
;
249 # define SIZEOF_SOCKET_T 8
251 # define SIZEOF_SOCKET_T 4
254 typedef int SOCKET_T
;
255 # define SIZEOF_SOCKET_T SIZEOF_INT
259 # define EAFNOSUPPORT WSAEAFNOSUPPORT
260 # define snprintf _snprintf
263 #if defined(PYOS_OS2)
264 #define SOCKETCLOSE soclose
265 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
269 #define SOCKETCLOSE close
273 /* XXX There's a problem here: *static* functions are not supposed to have
274 a Py prefix (or use CapitalizedWords). Later... */
276 /* Global variable holding the exception type for errors detected
277 by this module (but not argument type or memory errors, etc.). */
279 static PyObject
*PySocket_Error
;
280 static PyObject
*PyH_Error
;
281 static PyObject
*PyGAI_Error
;
284 static PyObject
*PySSLErrorObject
;
289 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
290 static int taskwindow
;
294 /* Convenience function to raise an error according to errno
295 and return a NULL pointer from a function. */
301 int err_no
= WSAGetLastError();
303 static struct { int no
; const char *msg
; } *msgp
, msgs
[] = {
304 { WSAEINTR
, "Interrupted system call" },
305 { WSAEBADF
, "Bad file descriptor" },
306 { WSAEACCES
, "Permission denied" },
307 { WSAEFAULT
, "Bad address" },
308 { WSAEINVAL
, "Invalid argument" },
309 { WSAEMFILE
, "Too many open files" },
311 "The socket operation could not complete "
312 "without blocking" },
313 { WSAEINPROGRESS
, "Operation now in progress" },
314 { WSAEALREADY
, "Operation already in progress" },
315 { WSAENOTSOCK
, "Socket operation on non-socket" },
316 { WSAEDESTADDRREQ
, "Destination address required" },
317 { WSAEMSGSIZE
, "Message too long" },
318 { WSAEPROTOTYPE
, "Protocol wrong type for socket" },
319 { WSAENOPROTOOPT
, "Protocol not available" },
320 { WSAEPROTONOSUPPORT
, "Protocol not supported" },
321 { WSAESOCKTNOSUPPORT
, "Socket type not supported" },
322 { WSAEOPNOTSUPP
, "Operation not supported" },
323 { WSAEPFNOSUPPORT
, "Protocol family not supported" },
324 { WSAEAFNOSUPPORT
, "Address family not supported" },
325 { WSAEADDRINUSE
, "Address already in use" },
327 "Can't assign requested address" },
328 { WSAENETDOWN
, "Network is down" },
329 { WSAENETUNREACH
, "Network is unreachable" },
331 "Network dropped connection on reset" },
333 "Software caused connection abort" },
334 { WSAECONNRESET
, "Connection reset by peer" },
335 { WSAENOBUFS
, "No buffer space available" },
336 { WSAEISCONN
, "Socket is already connected" },
337 { WSAENOTCONN
, "Socket is not connected" },
338 { WSAESHUTDOWN
, "Can't send after socket shutdown" },
340 "Too many references: can't splice" },
341 { WSAETIMEDOUT
, "Operation timed out" },
342 { WSAECONNREFUSED
, "Connection refused" },
343 { WSAELOOP
, "Too many levels of symbolic links" },
344 { WSAENAMETOOLONG
, "File name too long" },
345 { WSAEHOSTDOWN
, "Host is down" },
346 { WSAEHOSTUNREACH
, "No route to host" },
347 { WSAENOTEMPTY
, "Directory not empty" },
348 { WSAEPROCLIM
, "Too many processes" },
349 { WSAEUSERS
, "Too many users" },
350 { WSAEDQUOT
, "Disc quota exceeded" },
351 { WSAESTALE
, "Stale NFS file handle" },
352 { WSAEREMOTE
, "Too many levels of remote in path" },
354 "Network subsystem is unvailable" },
355 { WSAVERNOTSUPPORTED
,
356 "WinSock version is not supported" },
358 "Successful WSAStartup() not yet performed" },
359 { WSAEDISCON
, "Graceful shutdown in progress" },
360 /* Resolver errors */
361 { WSAHOST_NOT_FOUND
, "No such host is known" },
362 { WSATRY_AGAIN
, "Host not found, or server failed" },
364 "Unexpected server error encountered" },
365 { WSANO_DATA
, "Valid name without requested data" },
366 { WSANO_ADDRESS
, "No address, look for MX record" },
370 const char *msg
= "winsock error";
372 for (msgp
= msgs
; msgp
->msg
; msgp
++) {
373 if (err_no
== msgp
->no
) {
379 v
= Py_BuildValue("(is)", err_no
, msg
);
381 PyErr_SetObject(PySocket_Error
, v
);
389 #if defined(PYOS_OS2)
390 if (sock_errno() != NO_ERROR
) {
394 int myerrorcode
= sock_errno();
396 /* Retrieve Socket-Related Error Message from MPTN.MSG File */
397 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
398 myerrorcode
- SOCBASEERR
+ 26, "mptn.msg", &msglen
);
399 if (rc
== NO_ERROR
) {
402 outbuf
[msglen
] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
403 if (strlen(outbuf
) > 0) { /* If Non-Empty Msg, Trim CRLF */
404 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
405 while (lastc
> outbuf
&& isspace(*lastc
))
406 *lastc
-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
408 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
410 PyErr_SetObject(PySocket_Error
, v
);
418 return PyErr_SetFromErrno(PySocket_Error
);
427 #ifdef HAVE_HSTRERROR
428 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
430 v
= Py_BuildValue("(is)", h_error
, "host not found");
433 PyErr_SetObject(PyH_Error
, v
);
446 if (error
== EAI_SYSTEM
)
447 return PySocket_Err();
449 #ifdef HAVE_GAI_STRERROR
450 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
452 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
455 PyErr_SetObject(PyGAI_Error
, v
);
463 /* The object holding a socket. It holds some extra information,
464 like the address family, which is used to decode socket address
465 arguments properly. */
469 SOCKET_T sock_fd
; /* Socket file descriptor */
470 int sock_family
; /* Address family, e.g., AF_INET */
471 int sock_type
; /* Socket type, e.g., SOCK_STREAM */
472 int sock_proto
; /* Protocol type, usually 0 */
474 struct sockaddr_in in
;
476 struct sockaddr_un un
;
479 struct sockaddr_in6 in6
;
480 struct sockaddr_storage storage
;
482 #ifdef HAVE_NETPACKET_PACKET_H
483 struct sockaddr_ll ll
;
486 } PySocketSockObject
;
490 #define X509_NAME_MAXLEN 256
494 PySocketSockObject
*Socket
; /* Socket on which we're layered */
499 char server
[X509_NAME_MAXLEN
];
500 char issuer
[X509_NAME_MAXLEN
];
504 staticforward PyTypeObject PySSL_Type
;
505 staticforward PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
);
506 staticforward PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
);
508 #define PySSLObject_Check(v) ((v)->ob_type == &PySSL_Type)
512 /* A forward reference to the Socktype type object.
513 The Socktype variable contains pointers to various functions,
514 some of which call newsockobject(), which uses Socktype, so
515 there has to be a circular reference. */
517 staticforward PyTypeObject PySocketSock_Type
;
520 /* Initialize a new socket object. */
523 init_sockobject(PySocketSockObject
*s
,
524 SOCKET_T fd
, int family
, int type
, int proto
)
530 s
->sock_family
= family
;
532 s
->sock_proto
= proto
;
535 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
541 /* Create a new socket object.
542 This just creates the object and initializes it.
543 If the creation fails, return NULL and set an exception (implicit
546 static PySocketSockObject
*
547 PySocketSock_New(SOCKET_T fd
, int family
, int type
, int proto
)
549 PySocketSockObject
*s
;
550 s
= (PySocketSockObject
*)
551 PyType_GenericNew(&PySocketSock_Type
, NULL
, NULL
);
553 init_sockobject(s
, fd
, family
, type
, proto
);
558 /* Lock to allow python interpreter to continue, but only allow one
559 thread to be in gethostbyname */
560 #ifdef USE_GETHOSTBYNAME_LOCK
561 PyThread_type_lock gethostbyname_lock
;
565 /* Convert a string specifying a host name or one of a few symbolic
566 names to a numeric IP address. This usually calls gethostbyname()
567 to do the work; the names "" and "<broadcast>" are special.
568 Return the length (IPv4 should be 4 bytes), or negative if
569 an error occurred; then an exception is raised. */
572 setipaddr(char* name
, struct sockaddr
* addr_ret
, int af
)
574 struct addrinfo hints
, *res
;
577 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
578 if (name
[0] == '\0') {
580 memset(&hints
, 0, sizeof(hints
));
581 hints
.ai_family
= af
;
582 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
583 hints
.ai_flags
= AI_PASSIVE
;
584 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
589 switch (res
->ai_family
) {
600 PyErr_SetString(PySocket_Error
,
601 "unsupported address family");
606 PyErr_SetString(PySocket_Error
,
607 "wildcard resolved to multiple address");
610 memcpy(addr_ret
, res
->ai_addr
, res
->ai_addrlen
);
614 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
615 struct sockaddr_in
*sin
;
616 if (af
!= PF_INET
&& af
!= PF_UNSPEC
) {
617 PyErr_SetString(PySocket_Error
,
618 "address family mismatched");
621 sin
= (struct sockaddr_in
*)addr_ret
;
622 memset((void *) sin
, '\0', sizeof(*sin
));
623 sin
->sin_family
= AF_INET
;
624 #ifdef HAVE_SOCKADDR_SA_LEN
625 sin
->sin_len
= sizeof(*sin
);
627 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
628 return sizeof(sin
->sin_addr
);
630 memset(&hints
, 0, sizeof(hints
));
631 hints
.ai_family
= af
;
632 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
633 #if defined(__digital__) && defined(__unix__)
634 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
635 /* On Tru64 V5.1, numeric-to-addr conversion
636 fails if no address family is given. Assume IPv4 for now.*/
637 hints
.ai_family
= AF_INET
;
638 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
645 memcpy((char *) addr_ret
, res
->ai_addr
, res
->ai_addrlen
);
647 switch (addr_ret
->sa_family
) {
655 PyErr_SetString(PySocket_Error
, "unknown address family");
661 /* Create a string object representing an IP address.
662 This is always a string of the form 'dd.dd.dd.dd' (with variable
666 makeipaddr(struct sockaddr
*addr
, int addrlen
)
668 char buf
[NI_MAXHOST
];
671 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
677 return PyString_FromString(buf
);
681 /* Create an object representing the given socket address,
682 suitable for passing it back to bind(), connect() etc.
683 The family field of the sockaddr structure is inspected
684 to determine what kind of address it really is. */
688 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
)
691 /* No address -- may be recvfrom() from known socket */
697 /* XXX: BeOS version of accept() doesn't set family correctly */
698 addr
->sa_family
= AF_INET
;
701 switch (addr
->sa_family
) {
705 struct sockaddr_in
*a
;
706 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
707 PyObject
*ret
= NULL
;
709 a
= (struct sockaddr_in
*)addr
;
710 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
719 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
720 return PyString_FromString(a
->sun_path
);
727 struct sockaddr_in6
*a
;
728 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
729 PyObject
*ret
= NULL
;
731 a
= (struct sockaddr_in6
*)addr
;
732 ret
= Py_BuildValue("Oiii", addrobj
, ntohs(a
->sin6_port
),
733 a
->sin6_flowinfo
, a
->sin6_scope_id
);
740 #ifdef HAVE_NETPACKET_PACKET_H
743 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
746 /* need to look up interface name give index */
747 if (a
->sll_ifindex
) {
748 ifr
.ifr_ifindex
= a
->sll_ifindex
;
749 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
750 ifname
= ifr
.ifr_name
;
752 return Py_BuildValue("shbhs#", ifname
, ntohs(a
->sll_protocol
),
753 a
->sll_pkttype
, a
->sll_hatype
,
754 a
->sll_addr
, a
->sll_halen
);
758 /* More cases here... */
761 /* If we don't know the address family, don't raise an
762 exception -- return it as a tuple. */
763 return Py_BuildValue("is#",
766 sizeof(addr
->sa_data
));
772 /* Parse a socket address argument according to the socket object's
773 address family. Return 1 if the address was in the proper format,
774 0 of not. The address is returned through addr_ret, its length
778 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
779 struct sockaddr
**addr_ret
, int *len_ret
)
781 switch (s
->sock_family
) {
786 struct sockaddr_un
* addr
;
789 addr
= (struct sockaddr_un
* )&(s
->sock_addr
).un
;
790 if (!PyArg_Parse(args
, "t#", &path
, &len
))
792 if (len
> sizeof addr
->sun_path
) {
793 PyErr_SetString(PySocket_Error
,
794 "AF_UNIX path too long");
797 addr
->sun_family
= s
->sock_family
;
798 memcpy(addr
->sun_path
, path
, len
);
799 addr
->sun_path
[len
] = 0;
800 *addr_ret
= (struct sockaddr
*) addr
;
801 *len_ret
= len
+ sizeof(*addr
) - sizeof(addr
->sun_path
);
808 struct sockaddr_in
* addr
;
811 addr
=(struct sockaddr_in
*)&(s
->sock_addr
).in
;
812 if (!PyTuple_Check(args
)) {
813 PyErr_Format(PyExc_TypeError
,
814 "getsockaddrarg: AF_INET address must be tuple, not %.500s",
815 args
->ob_type
->tp_name
);
818 if (!PyArg_ParseTuple(args
, "si:getsockaddrarg", &host
, &port
))
820 if (setipaddr(host
, (struct sockaddr
*)addr
, AF_INET
) < 0)
822 addr
->sin_family
= AF_INET
;
823 addr
->sin_port
= htons((short)port
);
824 *addr_ret
= (struct sockaddr
*) addr
;
825 *len_ret
= sizeof *addr
;
832 struct sockaddr_in6
* addr
;
834 int port
, flowinfo
, scope_id
;
835 addr
= (struct sockaddr_in6
*)&(s
->sock_addr
).in6
;
836 flowinfo
= scope_id
= 0;
837 if (!PyArg_ParseTuple(args
, "si|ii", &host
, &port
, &flowinfo
,
841 if (setipaddr(host
, (struct sockaddr
*)addr
, AF_INET6
) < 0)
843 addr
->sin6_family
= s
->sock_family
;
844 addr
->sin6_port
= htons((short)port
);
845 addr
->sin6_flowinfo
= flowinfo
;
846 addr
->sin6_scope_id
= scope_id
;
847 *addr_ret
= (struct sockaddr
*) addr
;
848 *len_ret
= sizeof *addr
;
853 #ifdef HAVE_NETPACKET_PACKET_H
856 struct sockaddr_ll
* addr
;
864 if (!PyArg_ParseTuple(args
, "si|iis", &interfaceName
,
865 &protoNumber
, &pkttype
, &hatype
, &haddr
))
867 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
868 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
869 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
873 addr
= &(s
->sock_addr
.ll
);
874 addr
->sll_family
= AF_PACKET
;
875 addr
->sll_protocol
= htons((short)protoNumber
);
876 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
877 addr
->sll_pkttype
= pkttype
;
878 addr
->sll_hatype
= hatype
;
879 *addr_ret
= (struct sockaddr
*) addr
;
880 *len_ret
= sizeof *addr
;
885 /* More cases here... */
888 PyErr_SetString(PySocket_Error
, "getsockaddrarg: bad family");
895 /* Get the address length according to the socket object's address family.
896 Return 1 if the family is known, 0 otherwise. The length is returned
900 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
902 switch (s
->sock_family
) {
907 *len_ret
= sizeof (struct sockaddr_un
);
914 *len_ret
= sizeof (struct sockaddr_in
);
921 *len_ret
= sizeof (struct sockaddr_in6
);
926 #ifdef HAVE_NETPACKET_PACKET_H
929 *len_ret
= sizeof (struct sockaddr_ll
);
934 /* More cases here... */
937 PyErr_SetString(PySocket_Error
, "getsockaddrlen: bad family");
944 /* s.accept() method */
947 PySocketSock_accept(PySocketSockObject
*s
)
952 PyObject
*sock
= NULL
;
953 PyObject
*addr
= NULL
;
954 PyObject
*res
= NULL
;
956 if (!getsockaddrlen(s
, &addrlen
))
958 memset(addrbuf
, 0, addrlen
);
959 Py_BEGIN_ALLOW_THREADS
960 newfd
= accept(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
963 if (newfd
== INVALID_SOCKET
)
967 return PySocket_Err();
969 /* Create the new object with unspecified family,
970 to avoid calls to bind() etc. on it. */
971 sock
= (PyObject
*) PySocketSock_New(newfd
,
979 addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*)addrbuf
,
984 res
= Py_BuildValue("OO", sock
, addr
);
992 static char accept_doc
[] =
993 "accept() -> (socket object, address info)\n\
995 Wait for an incoming connection. Return a new socket representing the\n\
996 connection, and the address of the client. For IP sockets, the address\n\
997 info is a pair (hostaddr, port).";
1000 /* s.setblocking(1 | 0) method */
1003 PySocketSock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1011 block
= PyInt_AsLong(arg
);
1012 if (block
== -1 && PyErr_Occurred())
1014 Py_BEGIN_ALLOW_THREADS
1017 setsockopt( s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
1018 (void *)(&block
), sizeof( int ) );
1024 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
1025 #else /* !PYOS_OS2 */
1026 delay_flag
= fcntl (s
->sock_fd
, F_GETFL
, 0);
1028 delay_flag
&= (~O_NDELAY
);
1030 delay_flag
|= O_NDELAY
;
1031 fcntl (s
->sock_fd
, F_SETFL
, delay_flag
);
1032 #endif /* !PYOS_OS2 */
1033 #else /* MS_WINDOWS */
1035 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
1036 #endif /* MS_WINDOWS */
1037 #endif /* __BEOS__ */
1039 Py_END_ALLOW_THREADS
1045 static char setblocking_doc
[] =
1046 "setblocking(flag)\n\
1048 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1049 This uses the FIONBIO ioctl with the O_NDELAY flag.";
1053 /* s.sleeptaskw(1 | 0) method */
1056 PySocketSock_sleeptaskw(PySocketSockObject
*s
,PyObject
*args
)
1060 if (!PyArg_GetInt(args
, &block
))
1062 Py_BEGIN_ALLOW_THREADS
1063 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1064 Py_END_ALLOW_THREADS
1069 static char sleeptaskw_doc
[] =
1070 "sleeptaskw(flag)\n\
1072 Allow sleeps in taskwindows.";
1076 /* s.setsockopt() method.
1077 With an integer third argument, sets an integer option.
1078 With a string third argument, sets an option from a buffer;
1079 use optional built-in module 'struct' to encode the string. */
1082 PySocketSock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1091 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1092 &level
, &optname
, &flag
)) {
1093 buf
= (char *) &flag
;
1094 buflen
= sizeof flag
;
1098 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1099 &level
, &optname
, &buf
, &buflen
))
1102 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1104 return PySocket_Err();
1109 static char setsockopt_doc
[] =
1110 "setsockopt(level, option, value)\n\
1112 Set a socket option. See the Unix manual for level and option.\n\
1113 The value argument can either be an integer or a string.";
1116 /* s.getsockopt() method.
1117 With two arguments, retrieves an integer option.
1118 With a third integer argument, retrieves a string buffer of that size;
1119 use optional built-in module 'struct' to decode the string. */
1122 PySocketSock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1128 socklen_t buflen
= 0;
1131 /* We have incomplete socket support. */
1132 PyErr_SetString(PySocket_Error
, "getsockopt not supported");
1136 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1137 &level
, &optname
, &buflen
))
1142 socklen_t flagsize
= sizeof flag
;
1143 res
= getsockopt(s
->sock_fd
, level
, optname
,
1144 (void *)&flag
, &flagsize
);
1146 return PySocket_Err();
1147 return PyInt_FromLong(flag
);
1149 if (buflen
<= 0 || buflen
> 1024) {
1150 PyErr_SetString(PySocket_Error
,
1151 "getsockopt buflen out of range");
1154 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1157 res
= getsockopt(s
->sock_fd
, level
, optname
,
1158 (void *)PyString_AS_STRING(buf
), &buflen
);
1161 return PySocket_Err();
1163 _PyString_Resize(&buf
, buflen
);
1165 #endif /* __BEOS__ */
1168 static char getsockopt_doc
[] =
1169 "getsockopt(level, option[, buffersize]) -> value\n\
1171 Get a socket option. See the Unix manual for level and option.\n\
1172 If a nonzero buffersize argument is given, the return value is a\n\
1173 string of that length; otherwise it is an integer.";
1176 /* s.bind(sockaddr) method */
1179 PySocketSock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1181 struct sockaddr
*addr
;
1185 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1187 Py_BEGIN_ALLOW_THREADS
1188 res
= bind(s
->sock_fd
, addr
, addrlen
);
1189 Py_END_ALLOW_THREADS
1191 return PySocket_Err();
1196 static char bind_doc
[] =
1199 Bind the socket to a local address. For IP sockets, the address is a\n\
1200 pair (host, port); the host must refer to the local host. For raw packet\n\
1201 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])";
1204 /* s.close() method.
1205 Set the file descriptor to -1 so operations tried subsequently
1206 will surely fail. */
1209 PySocketSock_close(PySocketSockObject
*s
)
1213 if ((fd
= s
->sock_fd
) != -1) {
1215 Py_BEGIN_ALLOW_THREADS
1216 (void) SOCKETCLOSE(fd
);
1217 Py_END_ALLOW_THREADS
1223 static char close_doc
[] =
1226 Close the socket. It cannot be used after this call.";
1229 /* s.connect(sockaddr) method */
1232 PySocketSock_connect(PySocketSockObject
*s
, PyObject
*addro
)
1234 struct sockaddr
*addr
;
1238 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1240 Py_BEGIN_ALLOW_THREADS
1241 res
= connect(s
->sock_fd
, addr
, addrlen
);
1242 Py_END_ALLOW_THREADS
1244 return PySocket_Err();
1249 static char connect_doc
[] =
1250 "connect(address)\n\
1252 Connect the socket to a remote address. For IP sockets, the address\n\
1253 is a pair (host, port).";
1256 /* s.connect_ex(sockaddr) method */
1259 PySocketSock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
1261 struct sockaddr
*addr
;
1265 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1267 Py_BEGIN_ALLOW_THREADS
1268 res
= connect(s
->sock_fd
, addr
, addrlen
);
1269 Py_END_ALLOW_THREADS
1272 res
= WSAGetLastError();
1277 return PyInt_FromLong((long) res
);
1280 static char connect_ex_doc
[] =
1281 "connect_ex(address)\n\
1283 This is like connect(address), but returns an error code (the errno value)\n\
1284 instead of raising an exception when an error occurs.";
1287 /* s.fileno() method */
1290 PySocketSock_fileno(PySocketSockObject
*s
)
1292 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1293 return PyInt_FromLong((long) s
->sock_fd
);
1295 return PyLong_FromLongLong((LONG_LONG
)s
->sock_fd
);
1299 static char fileno_doc
[] =
1300 "fileno() -> integer\n\
1302 Return the integer file descriptor of the socket.";
1306 /* s.dup() method */
1309 PySocketSock_dup(PySocketSockObject
*s
)
1314 newfd
= dup(s
->sock_fd
);
1316 return PySocket_Err();
1317 sock
= (PyObject
*) PySocketSock_New(newfd
,
1326 static char dup_doc
[] =
1327 "dup() -> socket object\n\
1329 Return a new socket object connected to the same system resource.";
1334 /* s.getsockname() method */
1337 PySocketSock_getsockname(PySocketSockObject
*s
)
1343 if (!getsockaddrlen(s
, &addrlen
))
1345 memset(addrbuf
, 0, addrlen
);
1346 Py_BEGIN_ALLOW_THREADS
1347 res
= getsockname(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
1348 Py_END_ALLOW_THREADS
1350 return PySocket_Err();
1351 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) addrbuf
, addrlen
);
1354 static char getsockname_doc
[] =
1355 "getsockname() -> address info\n\
1357 Return the address of the local endpoint. For IP sockets, the address\n\
1358 info is a pair (hostaddr, port).";
1361 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
1362 /* s.getpeername() method */
1365 PySocketSock_getpeername(PySocketSockObject
*s
)
1371 if (!getsockaddrlen(s
, &addrlen
))
1373 memset(addrbuf
, 0, addrlen
);
1374 Py_BEGIN_ALLOW_THREADS
1375 res
= getpeername(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
1376 Py_END_ALLOW_THREADS
1378 return PySocket_Err();
1379 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) addrbuf
, addrlen
);
1382 static char getpeername_doc
[] =
1383 "getpeername() -> address info\n\
1385 Return the address of the remote endpoint. For IP sockets, the address\n\
1386 info is a pair (hostaddr, port).";
1388 #endif /* HAVE_GETPEERNAME */
1391 /* s.listen(n) method */
1394 PySocketSock_listen(PySocketSockObject
*s
, PyObject
*arg
)
1399 backlog
= PyInt_AsLong(arg
);
1400 if (backlog
== -1 && PyErr_Occurred())
1402 Py_BEGIN_ALLOW_THREADS
1405 res
= listen(s
->sock_fd
, backlog
);
1406 Py_END_ALLOW_THREADS
1408 return PySocket_Err();
1413 static char listen_doc
[] =
1416 Enable a server to accept connections. The backlog argument must be at\n\
1417 least 1; it specifies the number of unaccepted connection that the system\n\
1418 will allow before refusing new connections.";
1422 /* s.makefile(mode) method.
1423 Create a new open file object referring to a dupped version of
1424 the socket's file descriptor. (The dup() call is necessary so
1425 that the open file and socket objects may be closed independent
1427 The mode argument specifies 'r' or 'w' passed to fdopen(). */
1430 PySocketSock_makefile(PySocketSockObject
*s
, PyObject
*args
)
1432 extern int fclose(FILE *);
1443 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
1446 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
1447 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
1449 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
1454 return PySocket_Err();
1457 /* Workaround for bug in Metrowerks MSL vs. GUSI I/O library */
1458 if (strchr(mode
, 'b') != NULL
)
1461 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
1463 PyFile_SetBufSize(f
, bufsize
);
1467 static char makefile_doc
[] =
1468 "makefile([mode[, buffersize]]) -> file object\n\
1470 Return a regular file object corresponding to the socket.\n\
1471 The mode and buffersize arguments are as for the built-in open() function.";
1476 /* s.recv(nbytes [,flags]) method */
1479 PySocketSock_recv(PySocketSockObject
*s
, PyObject
*args
)
1481 int len
, n
, flags
= 0;
1483 if (!PyArg_ParseTuple(args
, "i|i:recv", &len
, &flags
))
1486 PyErr_SetString(PyExc_ValueError
,
1487 "negative buffersize in connect");
1490 buf
= PyString_FromStringAndSize((char *) 0, len
);
1493 Py_BEGIN_ALLOW_THREADS
1494 n
= recv(s
->sock_fd
, PyString_AS_STRING(buf
), len
, flags
);
1495 Py_END_ALLOW_THREADS
1498 return PySocket_Err();
1500 if (n
!= len
&& _PyString_Resize(&buf
, n
) < 0)
1505 static char recv_doc
[] =
1506 "recv(buffersize[, flags]) -> data\n\
1508 Receive up to buffersize bytes from the socket. For the optional flags\n\
1509 argument, see the Unix manual. When no data is available, block until\n\
1510 at least one byte is available or until the remote end is closed. When\n\
1511 the remote end is closed and all data is read, return the empty string.";
1514 /* s.recvfrom(nbytes [,flags]) method */
1517 PySocketSock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
1520 PyObject
*buf
= NULL
;
1521 PyObject
*addr
= NULL
;
1522 PyObject
*ret
= NULL
;
1524 int len
, n
, flags
= 0;
1526 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &len
, &flags
))
1528 if (!getsockaddrlen(s
, &addrlen
))
1530 buf
= PyString_FromStringAndSize((char *) 0, len
);
1533 Py_BEGIN_ALLOW_THREADS
1534 memset(addrbuf
, 0, addrlen
);
1535 n
= recvfrom(s
->sock_fd
, PyString_AS_STRING(buf
), len
, flags
,
1537 #if defined(PYOS_OS2)
1538 (struct sockaddr
*)addrbuf
, &addrlen
1540 (void *)addrbuf
, &addrlen
1543 (struct sockaddr
*)addrbuf
, &addrlen
1546 Py_END_ALLOW_THREADS
1549 return PySocket_Err();
1551 if (n
!= len
&& _PyString_Resize(&buf
, n
) < 0)
1554 if (!(addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*)addrbuf
, addrlen
)))
1557 ret
= Py_BuildValue("OO", buf
, addr
);
1564 static char recvfrom_doc
[] =
1565 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
1567 Like recv(buffersize, flags) but also return the sender's address info.";
1570 /* s.send(data [,flags]) method */
1573 PySocketSock_send(PySocketSockObject
*s
, PyObject
*args
)
1576 int len
, n
, flags
= 0;
1577 if (!PyArg_ParseTuple(args
, "s#|i:send", &buf
, &len
, &flags
))
1579 Py_BEGIN_ALLOW_THREADS
1580 n
= send(s
->sock_fd
, buf
, len
, flags
);
1581 Py_END_ALLOW_THREADS
1583 return PySocket_Err();
1584 return PyInt_FromLong((long)n
);
1587 static char send_doc
[] =
1588 "send(data[, flags]) -> count\n\
1590 Send a data string to the socket. For the optional flags\n\
1591 argument, see the Unix manual. Return the number of bytes\n\
1592 sent; this may be less than len(data) if the network is busy.";
1595 /* s.sendall(data [,flags]) method */
1598 PySocketSock_sendall(PySocketSockObject
*s
, PyObject
*args
)
1601 int len
, n
, flags
= 0, total
= 0;
1602 if (!PyArg_ParseTuple(args
, "s#|i:sendall", &buf
, &len
, &flags
))
1604 Py_BEGIN_ALLOW_THREADS
1606 n
= send(s
->sock_fd
, buf
, len
, flags
);
1613 Py_END_ALLOW_THREADS
1615 return PySocket_Err();
1620 static char sendall_doc
[] =
1621 "sendall(data[, flags])\n\
1623 Send a data string to the socket. For the optional flags\n\
1624 argument, see the Unix manual. This calls send() repeatedly\n\
1625 until all data is sent. If an error occurs, it's impossible\n\
1626 to tell how much data has been sent.";
1629 /* s.sendto(data, [flags,] sockaddr) method */
1632 PySocketSock_sendto(PySocketSockObject
*s
, PyObject
*args
)
1636 struct sockaddr
*addr
;
1637 int addrlen
, len
, n
, flags
;
1639 if (!PyArg_ParseTuple(args
, "s#O:sendto", &buf
, &len
, &addro
)) {
1641 if (!PyArg_ParseTuple(args
, "s#iO:sendto",
1642 &buf
, &len
, &flags
, &addro
))
1645 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1647 Py_BEGIN_ALLOW_THREADS
1648 n
= sendto(s
->sock_fd
, buf
, len
, flags
, addr
, addrlen
);
1649 Py_END_ALLOW_THREADS
1651 return PySocket_Err();
1652 return PyInt_FromLong((long)n
);
1655 static char sendto_doc
[] =
1656 "sendto(data[, flags], address)\n\
1658 Like send(data, flags) but allows specifying the destination address.\n\
1659 For IP sockets, the address is a pair (hostaddr, port).";
1662 /* s.shutdown(how) method */
1665 PySocketSock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
1670 how
= PyInt_AsLong(arg
);
1671 if (how
== -1 && PyErr_Occurred())
1673 Py_BEGIN_ALLOW_THREADS
1674 res
= shutdown(s
->sock_fd
, how
);
1675 Py_END_ALLOW_THREADS
1677 return PySocket_Err();
1682 static char shutdown_doc
[] =
1685 Shut down the reading side of the socket (flag == 0), the writing side\n\
1686 of the socket (flag == 1), or both ends (flag == 2).";
1689 /* List of methods for socket objects */
1691 static PyMethodDef PySocketSock_methods
[] = {
1692 {"accept", (PyCFunction
)PySocketSock_accept
, METH_NOARGS
,
1694 {"bind", (PyCFunction
)PySocketSock_bind
, METH_O
,
1696 {"close", (PyCFunction
)PySocketSock_close
, METH_NOARGS
,
1698 {"connect", (PyCFunction
)PySocketSock_connect
, METH_O
,
1700 {"connect_ex", (PyCFunction
)PySocketSock_connect_ex
, METH_O
,
1703 {"dup", (PyCFunction
)PySocketSock_dup
, METH_NOARGS
,
1706 {"fileno", (PyCFunction
)PySocketSock_fileno
, METH_NOARGS
,
1708 #ifdef HAVE_GETPEERNAME
1709 {"getpeername", (PyCFunction
)PySocketSock_getpeername
,
1710 METH_NOARGS
, getpeername_doc
},
1712 {"getsockname", (PyCFunction
)PySocketSock_getsockname
,
1713 METH_NOARGS
, getsockname_doc
},
1714 {"getsockopt", (PyCFunction
)PySocketSock_getsockopt
, METH_VARARGS
,
1716 {"listen", (PyCFunction
)PySocketSock_listen
, METH_O
,
1719 {"makefile", (PyCFunction
)PySocketSock_makefile
, METH_VARARGS
,
1722 {"recv", (PyCFunction
)PySocketSock_recv
, METH_VARARGS
,
1724 {"recvfrom", (PyCFunction
)PySocketSock_recvfrom
, METH_VARARGS
,
1726 {"send", (PyCFunction
)PySocketSock_send
, METH_VARARGS
,
1728 {"sendall", (PyCFunction
)PySocketSock_sendall
, METH_VARARGS
,
1730 {"sendto", (PyCFunction
)PySocketSock_sendto
, METH_VARARGS
,
1732 {"setblocking", (PyCFunction
)PySocketSock_setblocking
, METH_O
,
1734 {"setsockopt", (PyCFunction
)PySocketSock_setsockopt
, METH_VARARGS
,
1736 {"shutdown", (PyCFunction
)PySocketSock_shutdown
, METH_O
,
1739 {"sleeptaskw", (PyCFunction
)PySocketSock_sleeptaskw
, METH_VARARGS
,
1742 {NULL
, NULL
} /* sentinel */
1746 /* Deallocate a socket object in response to the last Py_DECREF().
1747 First close the file description. */
1750 PySocketSock_dealloc(PySocketSockObject
*s
)
1752 if (s
->sock_fd
!= -1)
1753 (void) SOCKETCLOSE(s
->sock_fd
);
1754 s
->ob_type
->tp_free((PyObject
*)s
);
1759 PySocketSock_repr(PySocketSockObject
*s
)
1762 #if SIZEOF_SOCKET_T > SIZEOF_LONG
1763 if (s
->sock_fd
> LONG_MAX
) {
1764 /* this can occur on Win64, and actually there is a special
1765 ugly printf formatter for decimal pointer length integer
1766 printing, only bother if necessary*/
1767 PyErr_SetString(PyExc_OverflowError
,
1768 "no printf formatter to display the socket descriptor in decimal");
1772 PyOS_snprintf(buf
, sizeof(buf
),
1773 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
1774 (long)s
->sock_fd
, s
->sock_family
,
1777 return PyString_FromString(buf
);
1781 /* Create a new, uninitialized socket object. */
1784 PySocketSock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1788 new = type
->tp_alloc(type
, 0);
1790 ((PySocketSockObject
*)new)->sock_fd
= -1;
1795 /* Initialize a new socket object. */
1799 PySocketSock_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1801 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
1803 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
1804 static char *keywords
[] = {"family", "type", "proto", 0};
1806 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
1807 "|iii:socket", keywords
,
1808 &family
, &type
, &proto
))
1810 Py_BEGIN_ALLOW_THREADS
1811 fd
= socket(family
, type
, proto
);
1812 Py_END_ALLOW_THREADS
1814 if (fd
== INVALID_SOCKET
)
1822 init_sockobject(s
, fd
, family
, type
, proto
);
1823 /* From now on, ignore SIGPIPE and let the error checking
1826 (void) signal(SIGPIPE
, SIG_IGN
);
1832 /* Type object for socket objects. */
1834 static char socket_doc
[] =
1835 "socket([family[, type[, proto]]]) -> socket object\n\
1837 Open a socket of the given type. The family argument specifies the\n\
1838 address family; it defaults to AF_INET. The type argument specifies\n\
1839 whether this is a stream (SOCK_STREAM, this is the default)\n\
1840 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
1841 specifying the default protocol.\n\
1843 A socket represents one endpoint of a network connection.\n\
1847 accept() -- accept a connection, returning new socket and client address\n\
1848 bind() -- bind the socket to a local address\n\
1849 close() -- close the socket\n\
1850 connect() -- connect the socket to a remote address\n\
1851 connect_ex() -- connect, return an error code instead of an exception \n\
1852 dup() -- return a new socket object identical to the current one (*)\n\
1853 fileno() -- return underlying file descriptor\n\
1854 getpeername() -- return remote address (*)\n\
1855 getsockname() -- return local address\n\
1856 getsockopt() -- get socket options\n\
1857 listen() -- start listening for incoming connections\n\
1858 makefile() -- return a file object corresponding to the socket (*)\n\
1859 recv() -- receive data\n\
1860 recvfrom() -- receive data and sender's address\n\
1861 send() -- send data, may not send all of it\n\
1862 sendall() -- send all data\n\
1863 sendto() -- send data to a given address\n\
1864 setblocking() -- set or clear the blocking I/O flag\n\
1865 setsockopt() -- set socket options\n\
1866 shutdown() -- shut down traffic in one or both directions\n\
1868 (*) not available on all platforms!)";
1870 static PyTypeObject PySocketSock_Type
= {
1871 PyObject_HEAD_INIT(0) /* Must fill in type value later */
1873 "_socket.socket", /* tp_name */
1874 sizeof(PySocketSockObject
), /* tp_basicsize */
1875 0, /* tp_itemsize */
1876 (destructor
)PySocketSock_dealloc
, /* tp_dealloc */
1881 (reprfunc
)PySocketSock_repr
, /* tp_repr */
1882 0, /* tp_as_number */
1883 0, /* tp_as_sequence */
1884 0, /* tp_as_mapping */
1888 0, /* set below */ /* tp_getattro */
1889 0, /* tp_setattro */
1890 0, /* tp_as_buffer */
1891 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
1892 socket_doc
, /* tp_doc */
1893 0, /* tp_traverse */
1895 0, /* tp_richcompare */
1896 0, /* tp_weaklistoffset */
1898 0, /* tp_iternext */
1899 PySocketSock_methods
, /* tp_methods */
1904 0, /* tp_descr_get */
1905 0, /* tp_descr_set */
1906 0, /* tp_dictoffset */
1907 PySocketSock_init
, /* tp_init */
1908 0, /* set below */ /* tp_alloc */
1909 PySocketSock_new
, /* tp_new */
1910 0, /* set below */ /* tp_free */
1914 /* Python interface to gethostname(). */
1918 PySocket_gethostname(PyObject
*self
, PyObject
*args
)
1922 if (!PyArg_ParseTuple(args
, ":gethostname"))
1924 Py_BEGIN_ALLOW_THREADS
1925 res
= gethostname(buf
, (int) sizeof buf
- 1);
1926 Py_END_ALLOW_THREADS
1928 return PySocket_Err();
1929 buf
[sizeof buf
- 1] = '\0';
1930 return PyString_FromString(buf
);
1933 static char gethostname_doc
[] =
1934 "gethostname() -> string\n\
1936 Return the current host name.";
1939 /* Python interface to gethostbyname(name). */
1943 PySocket_gethostbyname(PyObject
*self
, PyObject
*args
)
1946 struct sockaddr_storage addrbuf
;
1948 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
1950 if (setipaddr(name
, (struct sockaddr
*)&addrbuf
, AF_INET
) < 0)
1952 return makeipaddr((struct sockaddr
*)&addrbuf
,
1953 sizeof(struct sockaddr_in
));
1956 static char gethostbyname_doc
[] =
1957 "gethostbyname(host) -> address\n\
1959 Return the IP address (a string of the form '255.255.255.255') for a host.";
1962 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
1965 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
1968 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
1969 PyObject
*name_list
= (PyObject
*)NULL
;
1970 PyObject
*addr_list
= (PyObject
*)NULL
;
1974 /* Let's get real error message to return */
1978 PyErr_SetString(PySocket_Error
, "host not found");
1982 if (h
->h_addrtype
!= af
) {
1983 #ifdef HAVE_STRERROR
1984 /* Let's get real error message to return */
1985 PyErr_SetString(PySocket_Error
, (char *)strerror(EAFNOSUPPORT
));
1987 PyErr_SetString(PySocket_Error
,
1988 "Address family not supported by protocol family");
1994 if (alen
< sizeof(struct sockaddr_in
))
1999 if (alen
< sizeof(struct sockaddr_in6
))
2004 if ((name_list
= PyList_New(0)) == NULL
)
2006 if ((addr_list
= PyList_New(0)) == NULL
)
2008 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
2010 tmp
= PyString_FromString(*pch
);
2013 status
= PyList_Append(name_list
, tmp
);
2018 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
2023 struct sockaddr_in sin
;
2024 memset(&sin
, 0, sizeof(sin
));
2025 sin
.sin_family
= af
;
2026 #ifdef HAVE_SOCKADDR_SA_LEN
2027 sin
.sin_len
= sizeof(sin
);
2029 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
2030 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
2031 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
2032 memcpy((char *) addr
, &sin
, sizeof(sin
));
2038 struct sockaddr_in6 sin6
;
2039 memset(&sin6
, 0, sizeof(sin6
));
2040 sin6
.sin6_family
= af
;
2041 #ifdef HAVE_SOCKADDR_SA_LEN
2042 sin6
.sin6_len
= sizeof(sin6
);
2044 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
2045 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
2047 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
2048 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
2052 default: /* can't happen */
2053 PyErr_SetString(PySocket_Error
,
2054 "unsupported address family");
2059 status
= PyList_Append(addr_list
, tmp
);
2064 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
2066 Py_XDECREF(name_list
);
2067 Py_XDECREF(addr_list
);
2072 /* Python interface to gethostbyname_ex(name). */
2076 PySocket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
2080 struct sockaddr_storage addr
;
2081 struct sockaddr
*sa
;
2083 #ifdef HAVE_GETHOSTBYNAME_R
2084 struct hostent hp_allocated
;
2085 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2086 struct hostent_data data
;
2089 int buf_len
= (sizeof buf
) - 1;
2092 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2095 #endif /* HAVE_GETHOSTBYNAME_R */
2097 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
2099 if (setipaddr(name
, (struct sockaddr
*)&addr
, PF_INET
) < 0)
2101 Py_BEGIN_ALLOW_THREADS
2102 #ifdef HAVE_GETHOSTBYNAME_R
2103 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2104 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &h
, &errnop
);
2105 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2106 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
2107 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2108 memset((void *) &data
, '\0', sizeof(data
));
2109 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
2110 h
= (result
!= 0) ? NULL
: &hp_allocated
;
2112 #else /* not HAVE_GETHOSTBYNAME_R */
2113 #ifdef USE_GETHOSTBYNAME_LOCK
2114 PyThread_acquire_lock(gethostbyname_lock
, 1);
2116 h
= gethostbyname(name
);
2117 #endif /* HAVE_GETHOSTBYNAME_R */
2118 Py_END_ALLOW_THREADS
2119 /* Some C libraries would require addr.__ss_family instead of addr.ss_family.
2120 Therefore, we cast the sockaddr_storage into sockaddr to access sa_family. */
2121 sa
= (struct sockaddr
*)&addr
;
2122 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), sa
->sa_family
);
2123 #ifdef USE_GETHOSTBYNAME_LOCK
2124 PyThread_release_lock(gethostbyname_lock
);
2129 static char ghbn_ex_doc
[] =
2130 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
2132 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2133 for a host. The host argument is a string giving a host name or IP number.";
2136 /* Python interface to gethostbyaddr(IP). */
2140 PySocket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
2143 struct sockaddr_storage addr
;
2145 struct sockaddr_in addr
;
2147 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
2151 #ifdef HAVE_GETHOSTBYNAME_R
2152 struct hostent hp_allocated
;
2153 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2154 struct hostent_data data
;
2157 int buf_len
= (sizeof buf
) - 1;
2160 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2163 #endif /* HAVE_GETHOSTBYNAME_R */
2168 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
2171 if (setipaddr(ip_num
, sa
, af
) < 0)
2178 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
2179 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
2183 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
2184 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
2188 PyErr_SetString(PySocket_Error
, "unsupported address family");
2191 Py_BEGIN_ALLOW_THREADS
2192 #ifdef HAVE_GETHOSTBYNAME_R
2193 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2194 result
= gethostbyaddr_r(ap
, al
, af
,
2195 &hp_allocated
, buf
, buf_len
,
2197 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2198 h
= gethostbyaddr_r(ap
, al
, af
,
2199 &hp_allocated
, buf
, buf_len
, &errnop
);
2200 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2201 memset((void *) &data
, '\0', sizeof(data
));
2202 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
2203 h
= (result
!= 0) ? NULL
: &hp_allocated
;
2205 #else /* not HAVE_GETHOSTBYNAME_R */
2206 #ifdef USE_GETHOSTBYNAME_LOCK
2207 PyThread_acquire_lock(gethostbyname_lock
, 1);
2209 h
= gethostbyaddr(ap
, al
, af
);
2210 #endif /* HAVE_GETHOSTBYNAME_R */
2211 Py_END_ALLOW_THREADS
2212 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
2213 #ifdef USE_GETHOSTBYNAME_LOCK
2214 PyThread_release_lock(gethostbyname_lock
);
2219 static char gethostbyaddr_doc
[] =
2220 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
2222 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2223 for a host. The host argument is a string giving a host name or IP number.";
2226 /* Python interface to getservbyname(name).
2227 This only returns the port number, since the other info is already
2228 known or not useful (like the list of aliases). */
2232 PySocket_getservbyname(PyObject
*self
, PyObject
*args
)
2236 if (!PyArg_ParseTuple(args
, "ss:getservbyname", &name
, &proto
))
2238 Py_BEGIN_ALLOW_THREADS
2239 sp
= getservbyname(name
, proto
);
2240 Py_END_ALLOW_THREADS
2242 PyErr_SetString(PySocket_Error
, "service/proto not found");
2245 return PyInt_FromLong((long) ntohs(sp
->s_port
));
2248 static char getservbyname_doc
[] =
2249 "getservbyname(servicename, protocolname) -> integer\n\
2251 Return a port number from a service name and protocol name.\n\
2252 The protocol name should be 'tcp' or 'udp'.";
2255 /* Python interface to getprotobyname(name).
2256 This only returns the protocol number, since the other info is
2257 already known or not useful (like the list of aliases). */
2261 PySocket_getprotobyname(PyObject
*self
, PyObject
*args
)
2264 struct protoent
*sp
;
2266 /* Not available in BeOS yet. - [cjh] */
2267 PyErr_SetString( PySocket_Error
, "getprotobyname not supported" );
2270 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
2272 Py_BEGIN_ALLOW_THREADS
2273 sp
= getprotobyname(name
);
2274 Py_END_ALLOW_THREADS
2276 PyErr_SetString(PySocket_Error
, "protocol not found");
2279 return PyInt_FromLong((long) sp
->p_proto
);
2283 static char getprotobyname_doc
[] =
2284 "getprotobyname(name) -> integer\n\
2286 Return the protocol number for the named protocol. (Rarely used.)";
2290 /* Create a socket object from a numeric file description.
2291 Useful e.g. if stdin is a socket.
2292 Additional arguments as for socket(). */
2296 PySocket_fromfd(PyObject
*self
, PyObject
*args
)
2298 PySocketSockObject
*s
;
2300 int family
, type
, proto
= 0;
2301 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
2302 &fd
, &family
, &type
, &proto
))
2304 /* Dup the fd so it and the socket can be closed independently */
2307 return PySocket_Err();
2308 s
= PySocketSock_New(fd
, family
, type
, proto
);
2309 /* From now on, ignore SIGPIPE and let the error checking
2312 (void) signal(SIGPIPE
, SIG_IGN
);
2314 return (PyObject
*) s
;
2317 static char fromfd_doc
[] =
2318 "fromfd(fd, family, type[, proto]) -> socket object\n\
2320 Create a socket object from the given file descriptor.\n\
2321 The remaining arguments are the same as for socket().";
2327 PySocket_ntohs(PyObject
*self
, PyObject
*args
)
2331 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
2334 x2
= (int)ntohs((short)x1
);
2335 return PyInt_FromLong(x2
);
2338 static char ntohs_doc
[] =
2339 "ntohs(integer) -> integer\n\
2341 Convert a 16-bit integer from network to host byte order.";
2345 PySocket_ntohl(PyObject
*self
, PyObject
*args
)
2349 if (!PyArg_ParseTuple(args
, "i:ntohl", &x1
)) {
2353 return PyInt_FromLong(x2
);
2356 static char ntohl_doc
[] =
2357 "ntohl(integer) -> integer\n\
2359 Convert a 32-bit integer from network to host byte order.";
2363 PySocket_htons(PyObject
*self
, PyObject
*args
)
2367 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
2370 x2
= (int)htons((short)x1
);
2371 return PyInt_FromLong(x2
);
2374 static char htons_doc
[] =
2375 "htons(integer) -> integer\n\
2377 Convert a 16-bit integer from host to network byte order.";
2381 PySocket_htonl(PyObject
*self
, PyObject
*args
)
2385 if (!PyArg_ParseTuple(args
, "i:htonl", &x1
)) {
2389 return PyInt_FromLong(x2
);
2392 static char htonl_doc
[] =
2393 "htonl(integer) -> integer\n\
2395 Convert a 32-bit integer from host to network byte order.";
2398 * socket.inet_aton() and socket.inet_ntoa() functions
2400 * written 20 Aug 1999 by Ben Gertzfield <che@debian.org> <- blame him!
2404 static char inet_aton_doc
[] =
2405 "inet_aton(string) -> packed 32-bit IP representation\n\
2407 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
2408 binary format used in low-level network functions.";
2411 PySocket_inet_aton(PyObject
*self
, PyObject
*args
)
2414 #define INADDR_NONE (-1)
2417 /* Have to use inet_addr() instead */
2419 unsigned long packed_addr
;
2421 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
)) {
2425 packed_addr
= inet_addr(ip_addr
).s_addr
;
2427 packed_addr
= inet_addr(ip_addr
);
2430 if (packed_addr
== INADDR_NONE
) { /* invalid address */
2431 PyErr_SetString(PySocket_Error
,
2432 "illegal IP address string passed to inet_aton");
2436 return PyString_FromStringAndSize((char *) &packed_addr
,
2437 sizeof(packed_addr
));
2440 static char inet_ntoa_doc
[] =
2441 "inet_ntoa(packed_ip) -> ip_address_string\n\
2443 Convert an IP address from 32-bit packed binary format to string format";
2446 PySocket_inet_ntoa(PyObject
*self
, PyObject
*args
)
2450 struct in_addr packed_addr
;
2452 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
2456 if (addr_len
!= sizeof(packed_addr
)) {
2457 PyErr_SetString(PySocket_Error
,
2458 "packed IP wrong length for inet_ntoa");
2462 memcpy(&packed_addr
, packed_str
, addr_len
);
2464 return PyString_FromString(inet_ntoa(packed_addr
));
2467 /* Python interface to getaddrinfo(host, port). */
2471 PySocket_getaddrinfo(PyObject
*self
, PyObject
*args
)
2473 struct addrinfo hints
, *res
;
2474 struct addrinfo
*res0
= NULL
;
2475 PyObject
*pobj
= (PyObject
*)NULL
;
2478 int family
, socktype
, protocol
, flags
;
2480 PyObject
*all
= (PyObject
*)NULL
;
2481 PyObject
*single
= (PyObject
*)NULL
;
2483 family
= socktype
= protocol
= flags
= 0;
2485 if (!PyArg_ParseTuple(args
, "zO|iiii:getaddrinfo",
2486 &hptr
, &pobj
, &family
, &socktype
,
2487 &protocol
, &flags
)) {
2490 if (PyInt_Check(pobj
)) {
2491 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", PyInt_AsLong(pobj
));
2493 } else if (PyString_Check(pobj
)) {
2494 pptr
= PyString_AsString(pobj
);
2495 } else if (pobj
== Py_None
) {
2496 pptr
= (char *)NULL
;
2498 PyErr_SetString(PySocket_Error
, "Int or String expected");
2501 memset(&hints
, 0, sizeof(hints
));
2502 hints
.ai_family
= family
;
2503 hints
.ai_socktype
= socktype
;
2504 hints
.ai_protocol
= protocol
;
2505 hints
.ai_flags
= flags
;
2506 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
2512 if ((all
= PyList_New(0)) == NULL
)
2514 for (res
= res0
; res
; res
= res
->ai_next
) {
2516 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
);
2519 single
= Py_BuildValue("iiisO", res
->ai_family
,
2520 res
->ai_socktype
, res
->ai_protocol
,
2521 res
->ai_canonname
? res
->ai_canonname
: "",
2527 if (PyList_Append(all
, single
))
2537 return (PyObject
*)NULL
;
2540 static char getaddrinfo_doc
[] =
2541 "socket.getaddrinfo(host, port [, family, socktype, proto, flags])\n\
2542 --> List of (family, socktype, proto, canonname, sockaddr)\n\
2544 Resolve host and port into addrinfo struct.";
2546 /* Python interface to getnameinfo(sa, flags). */
2550 PySocket_getnameinfo(PyObject
*self
, PyObject
*args
)
2552 PyObject
*sa
= (PyObject
*)NULL
;
2555 int port
, flowinfo
, scope_id
;
2556 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
2557 struct addrinfo hints
, *res
= NULL
;
2559 PyObject
*ret
= (PyObject
*)NULL
;
2561 flags
= flowinfo
= scope_id
= 0;
2562 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
2564 if (!PyArg_ParseTuple(sa
, "si|ii", &hostp
, &port
, &flowinfo
, &scope_id
))
2566 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
2567 memset(&hints
, 0, sizeof(hints
));
2568 hints
.ai_family
= PF_UNSPEC
;
2569 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
2570 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
2576 PyErr_SetString(PySocket_Error
,
2577 "sockaddr resolved to multiple addresses");
2580 switch (res
->ai_family
) {
2585 if (PyArg_ParseTuple(sa
, "si", &t1
, &t2
) == 0) {
2586 PyErr_SetString(PySocket_Error
,
2587 "IPv4 sockaddr must be 2 tuple");
2595 struct sockaddr_in6
*sin6
;
2596 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
2597 sin6
->sin6_flowinfo
= flowinfo
;
2598 sin6
->sin6_scope_id
= scope_id
;
2603 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
2604 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
2609 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
2617 static char getnameinfo_doc
[] =
2618 "socket.getnameinfo(sockaddr, flags) --> (host, port)\n\
2620 Get host and port for a sockaddr.";
2622 /* XXX It might be helpful to augment the error message generated
2623 below with the name of the SSL function that generated the error.
2624 I expect it's obvious most of the time.
2629 PySSL_SetError(SSL
*ssl
, int ret
)
2631 PyObject
*v
, *n
, *s
;
2637 err
= SSL_get_error(ssl
, ret
);
2638 n
= PyInt_FromLong(err
);
2647 switch (SSL_get_error(ssl
, ret
)) {
2648 case SSL_ERROR_ZERO_RETURN
:
2649 errstr
= "TLS/SSL connection has been closed";
2651 case SSL_ERROR_WANT_READ
:
2652 errstr
= "The operation did not complete (read)";
2654 case SSL_ERROR_WANT_WRITE
:
2655 errstr
= "The operation did not complete (write)";
2657 case SSL_ERROR_WANT_X509_LOOKUP
:
2658 errstr
= "The operation did not complete (X509 lookup)";
2660 case SSL_ERROR_SYSCALL
:
2663 unsigned long e
= ERR_get_error();
2665 /* an EOF was observed that violates the protocol */
2666 errstr
= "EOF occurred in violation of protocol";
2667 } else if (e
== -1) {
2668 /* the underlying BIO reported an I/O error */
2671 return PySocket_Err();
2673 /* XXX Protected by global interpreter lock */
2674 errstr
= ERR_error_string(e
, NULL
);
2679 errstr
= "Invalid error code";
2681 s
= PyString_FromString(errstr
);
2686 PyTuple_SET_ITEM(v
, 0, n
);
2687 PyTuple_SET_ITEM(v
, 1, s
);
2688 PyErr_SetObject(PySSLErrorObject
, v
);
2692 /* This is a C function to be called for new object initialization */
2693 static PySSLObject
*
2694 newPySSLObject(PySocketSockObject
*Sock
, char *key_file
, char *cert_file
)
2697 char *errstr
= NULL
;
2700 self
= PyObject_New(PySSLObject
, &PySSL_Type
); /* Create new object */
2702 errstr
= "newPySSLObject error";
2705 memset(self
->server
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
2706 memset(self
->issuer
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
2707 self
->server_cert
= NULL
;
2710 self
->Socket
= NULL
;
2712 if ((key_file
&& !cert_file
) || (!key_file
&& cert_file
)) {
2713 errstr
= "Both the key & certificate files must be specified";
2717 self
->ctx
= SSL_CTX_new(SSLv23_method()); /* Set up context */
2718 if (self
->ctx
== NULL
) {
2719 errstr
= "SSL_CTX_new error";
2724 if (SSL_CTX_use_PrivateKey_file(self
->ctx
, key_file
,
2725 SSL_FILETYPE_PEM
) < 1) {
2726 errstr
= "SSL_CTX_use_PrivateKey_file error";
2730 if (SSL_CTX_use_certificate_chain_file(self
->ctx
,
2732 errstr
= "SSL_CTX_use_certificate_chain_file error";
2737 SSL_CTX_set_verify(self
->ctx
,
2738 SSL_VERIFY_NONE
, NULL
); /* set verify lvl */
2739 self
->ssl
= SSL_new(self
->ctx
); /* New ssl struct */
2740 SSL_set_fd(self
->ssl
, Sock
->sock_fd
); /* Set the socket for SSL */
2741 SSL_set_connect_state(self
->ssl
);
2743 /* Actually negotiate SSL connection */
2744 /* XXX If SSL_connect() returns 0, it's also a failure. */
2745 ret
= SSL_connect(self
->ssl
);
2747 PySSL_SetError(self
->ssl
, ret
);
2750 self
->ssl
->debug
= 1;
2752 if ((self
->server_cert
= SSL_get_peer_certificate(self
->ssl
))) {
2753 X509_NAME_oneline(X509_get_subject_name(self
->server_cert
),
2754 self
->server
, X509_NAME_MAXLEN
);
2755 X509_NAME_oneline(X509_get_issuer_name(self
->server_cert
),
2756 self
->issuer
, X509_NAME_MAXLEN
);
2758 self
->Socket
= Sock
;
2759 Py_INCREF(self
->Socket
);
2763 PyErr_SetString(PySSLErrorObject
, errstr
);
2768 /* This is the Python function called for new object initialization */
2770 PySocket_ssl(PyObject
*self
, PyObject
*args
)
2773 PySocketSockObject
*Sock
;
2774 char *key_file
= NULL
;
2775 char *cert_file
= NULL
;
2777 if (!PyArg_ParseTuple(args
, "O!|zz:ssl",
2778 &PySocketSock_Type
, (PyObject
*)&Sock
,
2779 &key_file
, &cert_file
))
2782 rv
= newPySSLObject(Sock
, key_file
, cert_file
);
2785 return (PyObject
*)rv
;
2788 static char ssl_doc
[] =
2789 "ssl(socket, [keyfile, certfile]) -> sslobject";
2791 /* SSL object methods */
2794 PySSL_server(PySSLObject
*self
)
2796 return PyString_FromString(self
->server
);
2800 PySSL_issuer(PySSLObject
*self
)
2802 return PyString_FromString(self
->issuer
);
2806 static void PySSL_dealloc(PySSLObject
*self
)
2808 if (self
->server_cert
) /* Possible not to have one? */
2809 X509_free (self
->server_cert
);
2811 SSL_free(self
->ssl
);
2813 SSL_CTX_free(self
->ctx
);
2814 Py_XDECREF(self
->Socket
);
2818 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
)
2823 if (!PyArg_ParseTuple(args
, "s#:write", &data
, &len
))
2826 Py_BEGIN_ALLOW_THREADS
2827 len
= SSL_write(self
->ssl
, data
, len
);
2828 Py_END_ALLOW_THREADS
2830 return PyInt_FromLong(len
);
2832 return PySSL_SetError(self
->ssl
, len
);
2835 static char PySSL_SSLwrite_doc
[] =
2838 Writes the string s into the SSL object. Returns the number\n\
2841 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
)
2847 if (!PyArg_ParseTuple(args
, "|i:read", &len
))
2850 if (!(buf
= PyString_FromStringAndSize((char *) 0, len
)))
2853 Py_BEGIN_ALLOW_THREADS
2854 count
= SSL_read(self
->ssl
, PyString_AsString(buf
), len
);
2855 Py_END_ALLOW_THREADS
2858 return PySSL_SetError(self
->ssl
, count
);
2860 if (count
!= len
&& _PyString_Resize(&buf
, count
) < 0)
2865 static char PySSL_SSLread_doc
[] =
2866 "read([len]) -> string\n\
2868 Read up to len bytes from the SSL socket.";
2870 static PyMethodDef PySSLMethods
[] = {
2871 {"write", (PyCFunction
)PySSL_SSLwrite
, 1,
2872 PySSL_SSLwrite_doc
},
2873 {"read", (PyCFunction
)PySSL_SSLread
, 1,
2875 {"server", (PyCFunction
)PySSL_server
, METH_NOARGS
},
2876 {"issuer", (PyCFunction
)PySSL_issuer
, METH_NOARGS
},
2880 static PyObject
*PySSL_getattr(PySSLObject
*self
, char *name
)
2882 return Py_FindMethod(PySSLMethods
, (PyObject
*)self
, name
);
2885 staticforward PyTypeObject PySSL_Type
= {
2886 PyObject_HEAD_INIT(NULL
)
2888 "_socket.SSL", /*tp_name*/
2889 sizeof(PySSLObject
), /*tp_basicsize*/
2892 (destructor
)PySSL_dealloc
, /*tp_dealloc*/
2894 (getattrfunc
)PySSL_getattr
, /*tp_getattr*/
2899 0, /*tp_as_sequence*/
2900 0, /*tp_as_mapping*/
2904 /* helper routines for seeding the SSL PRNG */
2906 PySSL_RAND_add(PyObject
*self
, PyObject
*args
)
2912 if (!PyArg_ParseTuple(args
, "s#d:RAND_add", &buf
, &len
, &entropy
))
2914 RAND_add(buf
, len
, entropy
);
2919 static char PySSL_RAND_add_doc
[] =
2920 "RAND_add(string, entropy)\n\
2922 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
2923 bound on the entropy contained in string.";
2926 PySSL_RAND_status(PyObject
*self
)
2928 return PyInt_FromLong(RAND_status());
2931 static char PySSL_RAND_status_doc
[] =
2932 "RAND_status() -> 0 or 1\n\
2934 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2935 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2936 using the ssl() function.";
2939 PySSL_RAND_egd(PyObject
*self
, PyObject
*arg
)
2943 if (!PyString_Check(arg
))
2944 return PyErr_Format(PyExc_TypeError
,
2945 "RAND_egd() expected string, found %s",
2946 arg
->ob_type
->tp_name
);
2947 bytes
= RAND_egd(PyString_AS_STRING(arg
));
2949 PyErr_SetString(PySSLErrorObject
,
2950 "EGD connection failed or EGD did not return "
2951 "enough data to seed the PRNG");
2954 return PyInt_FromLong(bytes
);
2957 static char PySSL_RAND_egd_doc
[] =
2958 "RAND_egd(path) -> bytes\n\
2960 Queries the entropy gather daemon (EGD) on socket path. Returns number\n\
2961 of bytes read. Raises socket.sslerror if connection to EGD fails or\n\
2962 if it does provide enough data to seed PRNG.";
2964 #endif /* USE_SSL */
2967 /* List of functions exported by this module. */
2969 static PyMethodDef PySocket_methods
[] = {
2970 {"gethostbyname", PySocket_gethostbyname
,
2971 METH_VARARGS
, gethostbyname_doc
},
2972 {"gethostbyname_ex", PySocket_gethostbyname_ex
,
2973 METH_VARARGS
, ghbn_ex_doc
},
2974 {"gethostbyaddr", PySocket_gethostbyaddr
,
2975 METH_VARARGS
, gethostbyaddr_doc
},
2976 {"gethostname", PySocket_gethostname
,
2977 METH_VARARGS
, gethostname_doc
},
2978 {"getservbyname", PySocket_getservbyname
,
2979 METH_VARARGS
, getservbyname_doc
},
2980 {"getprotobyname", PySocket_getprotobyname
,
2981 METH_VARARGS
,getprotobyname_doc
},
2983 {"fromfd", PySocket_fromfd
,
2984 METH_VARARGS
, fromfd_doc
},
2986 {"ntohs", PySocket_ntohs
,
2987 METH_VARARGS
, ntohs_doc
},
2988 {"ntohl", PySocket_ntohl
,
2989 METH_VARARGS
, ntohl_doc
},
2990 {"htons", PySocket_htons
,
2991 METH_VARARGS
, htons_doc
},
2992 {"htonl", PySocket_htonl
,
2993 METH_VARARGS
, htonl_doc
},
2994 {"inet_aton", PySocket_inet_aton
,
2995 METH_VARARGS
, inet_aton_doc
},
2996 {"inet_ntoa", PySocket_inet_ntoa
,
2997 METH_VARARGS
, inet_ntoa_doc
},
2998 {"getaddrinfo", PySocket_getaddrinfo
,
2999 METH_VARARGS
, getaddrinfo_doc
},
3000 {"getnameinfo", PySocket_getnameinfo
,
3001 METH_VARARGS
, getnameinfo_doc
},
3003 {"ssl", PySocket_ssl
,
3004 METH_VARARGS
, ssl_doc
},
3005 {"RAND_add", PySSL_RAND_add
, METH_VARARGS
,
3006 PySSL_RAND_add_doc
},
3007 {"RAND_egd", PySSL_RAND_egd
, METH_O
,
3008 PySSL_RAND_egd_doc
},
3009 {"RAND_status", (PyCFunction
)PySSL_RAND_status
, METH_NOARGS
,
3010 PySSL_RAND_status_doc
},
3011 #endif /* USE_SSL */
3012 {NULL
, NULL
} /* Sentinel */
3016 /* Convenience routine to export an integer value.
3018 * Errors are silently ignored, for better or for worse...
3021 insint(PyObject
*d
, char *name
, int value
)
3023 PyObject
*v
= PyInt_FromLong((long) value
);
3024 if (!v
|| PyDict_SetItemString(d
, name
, v
))
3033 /* Additional initialization and cleanup for NT/Windows */
3047 ret
= WSAStartup(0x0101, &WSAData
);
3049 case 0: /* no error */
3052 case WSASYSNOTREADY
:
3053 PyErr_SetString(PyExc_ImportError
,
3054 "WSAStartup failed: network not ready");
3056 case WSAVERNOTSUPPORTED
:
3058 PyErr_SetString(PyExc_ImportError
,
3059 "WSAStartup failed: requested version not supported");
3062 PyOS_snprintf(buf
, sizeof(buf
),
3063 "WSAStartup failed: error code %d", ret
);
3064 PyErr_SetString(PyExc_ImportError
, buf
);
3070 #endif /* MS_WINDOWS */
3072 #if defined(PYOS_OS2)
3074 /* Additional initialization and cleanup for OS/2 */
3079 /* No cleanup is necessary for OS/2 Sockets */
3086 int rc
= sock_init();
3090 return 1; /* Indicate Success */
3093 PyOS_snprintf(reason
, sizeof(reason
),
3094 "OS/2 TCP/IP Error# %d", sock_errno());
3095 PyErr_SetString(PyExc_ImportError
, reason
);
3097 return 0; /* Indicate Failure */
3100 #endif /* PYOS_OS2 */
3102 /* Initialize this module.
3103 * This is called when the first 'import socket' is done,
3104 * via a table in config.c, if config.c is compiled with USE_SOCKET
3107 * For MS_WINDOWS (which means any Windows variant), this module
3108 * is actually called "_socket", and there's a wrapper "socket.py"
3109 * which implements some missing functionality (such as makefile(),
3110 * dup() and fromfd()). The import of "_socket" may fail with an
3111 * ImportError exception if initialization of WINSOCK fails. When
3112 * WINSOCK is initialized succesfully, a call to WSACleanup() is
3113 * scheduled to be made at exit time.
3115 * For OS/2, this module is also called "_socket" and uses a wrapper
3116 * "socket.py" which implements that functionality that is missing
3117 * when PC operating systems don't put socket descriptors in the
3118 * operating system's filesystem layer.
3121 static char module_doc
[] =
3122 "Implementation module for socket operations. See the socket module\n\
3123 for documentation.";
3132 _kernel_swi(0x43380, &r
, &r
);
3133 taskwindow
= r
.r
[0];
3139 #if defined(__TOS_OS2__)
3142 #endif /* __TOS_OS2__ */
3143 #endif /* MS_WINDOWS */
3145 PySocketSock_Type
.ob_type
= &PyType_Type
;
3146 PySocketSock_Type
.tp_getattro
= PyObject_GenericGetAttr
;
3147 PySocketSock_Type
.tp_alloc
= PyType_GenericAlloc
;
3148 PySocketSock_Type
.tp_free
= _PyObject_Del
;
3150 PySSL_Type
.ob_type
= &PyType_Type
;
3152 m
= Py_InitModule3("_socket", PySocket_methods
, module_doc
);
3153 d
= PyModule_GetDict(m
);
3154 PySocket_Error
= PyErr_NewException("socket.error", NULL
, NULL
);
3155 if (PySocket_Error
== NULL
)
3157 PyDict_SetItemString(d
, "error", PySocket_Error
);
3158 PyH_Error
= PyErr_NewException("socket.herror", PySocket_Error
, NULL
);
3159 if (PyH_Error
== NULL
)
3161 PyDict_SetItemString(d
, "herror", PyH_Error
);
3162 PyGAI_Error
= PyErr_NewException("socket.gaierror", PySocket_Error
,
3164 if (PyGAI_Error
== NULL
)
3166 PyDict_SetItemString(d
, "gaierror", PyGAI_Error
);
3168 SSL_load_error_strings();
3169 SSLeay_add_ssl_algorithms();
3170 PySSLErrorObject
= PyErr_NewException("socket.sslerror", NULL
, NULL
);
3171 if (PySSLErrorObject
== NULL
)
3173 PyDict_SetItemString(d
, "sslerror", PySSLErrorObject
);
3174 if (PyDict_SetItemString(d
, "SSLType",
3175 (PyObject
*)&PySSL_Type
) != 0)
3177 PyModule_AddIntConstant(m
, "SSL_ERROR_ZERO_RETURN",
3178 SSL_ERROR_ZERO_RETURN
);
3179 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_READ",
3180 SSL_ERROR_WANT_READ
);
3181 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_WRITE",
3182 SSL_ERROR_WANT_WRITE
);
3183 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_X509_LOOKUP",
3184 SSL_ERROR_WANT_X509_LOOKUP
);
3185 PyModule_AddIntConstant(m
, "SSL_ERROR_SYSCALL",
3187 PyModule_AddIntConstant(m
, "SSL_ERROR_SSL",
3189 #endif /* USE_SSL */
3190 if (PyDict_SetItemString(d
, "SocketType",
3191 (PyObject
*)&PySocketSock_Type
) != 0)
3193 if (PyDict_SetItemString(d
, "socket",
3194 (PyObject
*)&PySocketSock_Type
) != 0)
3197 /* Address families (we only support AF_INET and AF_UNIX) */
3199 insint(d
, "AF_UNSPEC", AF_UNSPEC
);
3201 insint(d
, "AF_INET", AF_INET
);
3203 insint(d
, "AF_INET6", AF_INET6
);
3204 #endif /* AF_INET6 */
3206 insint(d
, "AF_UNIX", AF_UNIX
);
3207 #endif /* AF_UNIX */
3209 insint(d
, "AF_AX25", AF_AX25
); /* Amateur Radio AX.25 */
3212 insint(d
, "AF_IPX", AF_IPX
); /* Novell IPX */
3215 insint(d
, "AF_APPLETALK", AF_APPLETALK
); /* Appletalk DDP */
3218 insint(d
, "AF_NETROM", AF_NETROM
); /* Amateur radio NetROM */
3221 insint(d
, "AF_BRIDGE", AF_BRIDGE
); /* Multiprotocol bridge */
3224 insint(d
, "AF_AAL5", AF_AAL5
); /* Reserved for Werner's ATM */
3227 insint(d
, "AF_X25", AF_X25
); /* Reserved for X.25 project */
3230 insint(d
, "AF_INET6", AF_INET6
); /* IP version 6 */
3233 insint(d
, "AF_ROSE", AF_ROSE
); /* Amateur Radio X.25 PLP */
3235 #ifdef HAVE_NETPACKET_PACKET_H
3236 insint(d
, "AF_PACKET", AF_PACKET
);
3237 insint(d
, "PF_PACKET", PF_PACKET
);
3238 insint(d
, "PACKET_HOST", PACKET_HOST
);
3239 insint(d
, "PACKET_BROADCAST", PACKET_BROADCAST
);
3240 insint(d
, "PACKET_MULTICAST", PACKET_MULTICAST
);
3241 insint(d
, "PACKET_OTHERHOST", PACKET_OTHERHOST
);
3242 insint(d
, "PACKET_OUTGOING", PACKET_OUTGOING
);
3243 insint(d
, "PACKET_LOOPBACK", PACKET_LOOPBACK
);
3244 insint(d
, "PACKET_FASTROUTE", PACKET_FASTROUTE
);
3248 insint(d
, "SOCK_STREAM", SOCK_STREAM
);
3249 insint(d
, "SOCK_DGRAM", SOCK_DGRAM
);
3251 /* We have incomplete socket support. */
3252 insint(d
, "SOCK_RAW", SOCK_RAW
);
3253 insint(d
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
3254 insint(d
, "SOCK_RDM", SOCK_RDM
);
3258 insint(d
, "SO_DEBUG", SO_DEBUG
);
3260 #ifdef SO_ACCEPTCONN
3261 insint(d
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
3264 insint(d
, "SO_REUSEADDR", SO_REUSEADDR
);
3267 insint(d
, "SO_KEEPALIVE", SO_KEEPALIVE
);
3270 insint(d
, "SO_DONTROUTE", SO_DONTROUTE
);
3273 insint(d
, "SO_BROADCAST", SO_BROADCAST
);
3275 #ifdef SO_USELOOPBACK
3276 insint(d
, "SO_USELOOPBACK", SO_USELOOPBACK
);
3279 insint(d
, "SO_LINGER", SO_LINGER
);
3282 insint(d
, "SO_OOBINLINE", SO_OOBINLINE
);
3285 insint(d
, "SO_REUSEPORT", SO_REUSEPORT
);
3288 insint(d
, "SO_SNDBUF", SO_SNDBUF
);
3291 insint(d
, "SO_RCVBUF", SO_RCVBUF
);
3294 insint(d
, "SO_SNDLOWAT", SO_SNDLOWAT
);
3297 insint(d
, "SO_RCVLOWAT", SO_RCVLOWAT
);
3300 insint(d
, "SO_SNDTIMEO", SO_SNDTIMEO
);
3303 insint(d
, "SO_RCVTIMEO", SO_RCVTIMEO
);
3306 insint(d
, "SO_ERROR", SO_ERROR
);
3309 insint(d
, "SO_TYPE", SO_TYPE
);
3312 /* Maximum number of connections for "listen" */
3314 insint(d
, "SOMAXCONN", SOMAXCONN
);
3316 insint(d
, "SOMAXCONN", 5); /* Common value */
3319 /* Flags for send, recv */
3321 insint(d
, "MSG_OOB", MSG_OOB
);
3324 insint(d
, "MSG_PEEK", MSG_PEEK
);
3326 #ifdef MSG_DONTROUTE
3327 insint(d
, "MSG_DONTROUTE", MSG_DONTROUTE
);
3330 insint(d
, "MSG_DONTWAIT", MSG_DONTWAIT
);
3333 insint(d
, "MSG_EOR", MSG_EOR
);
3336 insint(d
, "MSG_TRUNC", MSG_TRUNC
);
3339 insint(d
, "MSG_CTRUNC", MSG_CTRUNC
);
3342 insint(d
, "MSG_WAITALL", MSG_WAITALL
);
3345 insint(d
, "MSG_BTAG", MSG_BTAG
);
3348 insint(d
, "MSG_ETAG", MSG_ETAG
);
3351 /* Protocol level and numbers, usable for [gs]etsockopt */
3353 insint(d
, "SOL_SOCKET", SOL_SOCKET
);
3356 insint(d
, "SOL_IP", SOL_IP
);
3358 insint(d
, "SOL_IP", 0);
3361 insint(d
, "SOL_IPX", SOL_IPX
);
3364 insint(d
, "SOL_AX25", SOL_AX25
);
3367 insint(d
, "SOL_ATALK", SOL_ATALK
);
3370 insint(d
, "SOL_NETROM", SOL_NETROM
);
3373 insint(d
, "SOL_ROSE", SOL_ROSE
);
3376 insint(d
, "SOL_TCP", SOL_TCP
);
3378 insint(d
, "SOL_TCP", 6);
3381 insint(d
, "SOL_UDP", SOL_UDP
);
3383 insint(d
, "SOL_UDP", 17);
3386 insint(d
, "IPPROTO_IP", IPPROTO_IP
);
3388 insint(d
, "IPPROTO_IP", 0);
3390 #ifdef IPPROTO_HOPOPTS
3391 insint(d
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
3394 insint(d
, "IPPROTO_ICMP", IPPROTO_ICMP
);
3396 insint(d
, "IPPROTO_ICMP", 1);
3399 insint(d
, "IPPROTO_IGMP", IPPROTO_IGMP
);
3402 insint(d
, "IPPROTO_GGP", IPPROTO_GGP
);
3405 insint(d
, "IPPROTO_IPV4", IPPROTO_IPV4
);
3408 insint(d
, "IPPROTO_IPIP", IPPROTO_IPIP
);
3411 insint(d
, "IPPROTO_TCP", IPPROTO_TCP
);
3413 insint(d
, "IPPROTO_TCP", 6);
3416 insint(d
, "IPPROTO_EGP", IPPROTO_EGP
);
3419 insint(d
, "IPPROTO_PUP", IPPROTO_PUP
);
3422 insint(d
, "IPPROTO_UDP", IPPROTO_UDP
);
3424 insint(d
, "IPPROTO_UDP", 17);
3427 insint(d
, "IPPROTO_IDP", IPPROTO_IDP
);
3429 #ifdef IPPROTO_HELLO
3430 insint(d
, "IPPROTO_HELLO", IPPROTO_HELLO
);
3433 insint(d
, "IPPROTO_ND", IPPROTO_ND
);
3436 insint(d
, "IPPROTO_TP", IPPROTO_TP
);
3439 insint(d
, "IPPROTO_IPV6", IPPROTO_IPV6
);
3441 #ifdef IPPROTO_ROUTING
3442 insint(d
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
3444 #ifdef IPPROTO_FRAGMENT
3445 insint(d
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
3448 insint(d
, "IPPROTO_RSVP", IPPROTO_RSVP
);
3451 insint(d
, "IPPROTO_GRE", IPPROTO_GRE
);
3454 insint(d
, "IPPROTO_ESP", IPPROTO_ESP
);
3457 insint(d
, "IPPROTO_AH", IPPROTO_AH
);
3459 #ifdef IPPROTO_MOBILE
3460 insint(d
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
3462 #ifdef IPPROTO_ICMPV6
3463 insint(d
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
3466 insint(d
, "IPPROTO_NONE", IPPROTO_NONE
);
3468 #ifdef IPPROTO_DSTOPTS
3469 insint(d
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
3472 insint(d
, "IPPROTO_XTP", IPPROTO_XTP
);
3475 insint(d
, "IPPROTO_EON", IPPROTO_EON
);
3478 insint(d
, "IPPROTO_PIM", IPPROTO_PIM
);
3480 #ifdef IPPROTO_IPCOMP
3481 insint(d
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
3484 insint(d
, "IPPROTO_VRRP", IPPROTO_VRRP
);
3487 insint(d
, "IPPROTO_BIP", IPPROTO_BIP
);
3491 insint(d
, "IPPROTO_RAW", IPPROTO_RAW
);
3493 insint(d
, "IPPROTO_RAW", 255);
3496 insint(d
, "IPPROTO_MAX", IPPROTO_MAX
);
3499 /* Some port configuration */
3500 #ifdef IPPORT_RESERVED
3501 insint(d
, "IPPORT_RESERVED", IPPORT_RESERVED
);
3503 insint(d
, "IPPORT_RESERVED", 1024);
3505 #ifdef IPPORT_USERRESERVED
3506 insint(d
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
3508 insint(d
, "IPPORT_USERRESERVED", 5000);
3511 /* Some reserved IP v.4 addresses */
3513 insint(d
, "INADDR_ANY", INADDR_ANY
);
3515 insint(d
, "INADDR_ANY", 0x00000000);
3517 #ifdef INADDR_BROADCAST
3518 insint(d
, "INADDR_BROADCAST", INADDR_BROADCAST
);
3520 insint(d
, "INADDR_BROADCAST", 0xffffffff);
3522 #ifdef INADDR_LOOPBACK
3523 insint(d
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
3525 insint(d
, "INADDR_LOOPBACK", 0x7F000001);
3527 #ifdef INADDR_UNSPEC_GROUP
3528 insint(d
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
3530 insint(d
, "INADDR_UNSPEC_GROUP", 0xe0000000);
3532 #ifdef INADDR_ALLHOSTS_GROUP
3533 insint(d
, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP
);
3535 insint(d
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
3537 #ifdef INADDR_MAX_LOCAL_GROUP
3538 insint(d
, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP
);
3540 insint(d
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
3543 insint(d
, "INADDR_NONE", INADDR_NONE
);
3545 insint(d
, "INADDR_NONE", 0xffffffff);
3548 /* IPv4 [gs]etsockopt options */
3550 insint(d
, "IP_OPTIONS", IP_OPTIONS
);
3553 insint(d
, "IP_HDRINCL", IP_HDRINCL
);
3556 insint(d
, "IP_TOS", IP_TOS
);
3559 insint(d
, "IP_TTL", IP_TTL
);
3562 insint(d
, "IP_RECVOPTS", IP_RECVOPTS
);
3564 #ifdef IP_RECVRETOPTS
3565 insint(d
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
3567 #ifdef IP_RECVDSTADDR
3568 insint(d
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
3571 insint(d
, "IP_RETOPTS", IP_RETOPTS
);
3573 #ifdef IP_MULTICAST_IF
3574 insint(d
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
3576 #ifdef IP_MULTICAST_TTL
3577 insint(d
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
3579 #ifdef IP_MULTICAST_LOOP
3580 insint(d
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
3582 #ifdef IP_ADD_MEMBERSHIP
3583 insint(d
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
3585 #ifdef IP_DROP_MEMBERSHIP
3586 insint(d
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
3588 #ifdef IP_DEFAULT_MULTICAST_TTL
3589 insint(d
, "IP_DEFAULT_MULTICAST_TTL", IP_DEFAULT_MULTICAST_TTL
);
3591 #ifdef IP_DEFAULT_MULTICAST_LOOP
3592 insint(d
, "IP_DEFAULT_MULTICAST_LOOP", IP_DEFAULT_MULTICAST_LOOP
);
3594 #ifdef IP_MAX_MEMBERSHIPS
3595 insint(d
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
3598 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
3599 #ifdef IPV6_JOIN_GROUP
3600 insint(d
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
3602 #ifdef IPV6_LEAVE_GROUP
3603 insint(d
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
3605 #ifdef IPV6_MULTICAST_HOPS
3606 insint(d
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
3608 #ifdef IPV6_MULTICAST_IF
3609 insint(d
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
3611 #ifdef IPV6_MULTICAST_LOOP
3612 insint(d
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
3614 #ifdef IPV6_UNICAST_HOPS
3615 insint(d
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
3620 insint(d
, "TCP_NODELAY", TCP_NODELAY
);
3623 insint(d
, "TCP_MAXSEG", TCP_MAXSEG
);
3626 insint(d
, "TCP_CORK", TCP_CORK
);
3629 insint(d
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
3631 #ifdef TCP_KEEPINTVL
3632 insint(d
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
3635 insint(d
, "TCP_KEEPCNT", TCP_KEEPCNT
);
3638 insint(d
, "TCP_SYNCNT", TCP_SYNCNT
);
3641 insint(d
, "TCP_LINGER2", TCP_LINGER2
);
3643 #ifdef TCP_DEFER_ACCEPT
3644 insint(d
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
3646 #ifdef TCP_WINDOW_CLAMP
3647 insint(d
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
3650 insint(d
, "TCP_INFO", TCP_INFO
);
3653 insint(d
, "TCP_QUICKACK", TCP_QUICKACK
);
3659 insint(d
, "IPX_TYPE", IPX_TYPE
);
3662 /* get{addr,name}info parameters */
3663 #ifdef EAI_ADDRFAMILY
3664 insint(d
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
3667 insint(d
, "EAI_AGAIN", EAI_AGAIN
);
3670 insint(d
, "EAI_BADFLAGS", EAI_BADFLAGS
);
3673 insint(d
, "EAI_FAIL", EAI_FAIL
);
3676 insint(d
, "EAI_FAMILY", EAI_FAMILY
);
3679 insint(d
, "EAI_MEMORY", EAI_MEMORY
);
3682 insint(d
, "EAI_NODATA", EAI_NODATA
);
3685 insint(d
, "EAI_NONAME", EAI_NONAME
);
3688 insint(d
, "EAI_SERVICE", EAI_SERVICE
);
3691 insint(d
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
3694 insint(d
, "EAI_SYSTEM", EAI_SYSTEM
);
3697 insint(d
, "EAI_BADHINTS", EAI_BADHINTS
);
3700 insint(d
, "EAI_PROTOCOL", EAI_PROTOCOL
);
3703 insint(d
, "EAI_MAX", EAI_MAX
);
3706 insint(d
, "AI_PASSIVE", AI_PASSIVE
);
3709 insint(d
, "AI_CANONNAME", AI_CANONNAME
);
3711 #ifdef AI_NUMERICHOST
3712 insint(d
, "AI_NUMERICHOST", AI_NUMERICHOST
);
3715 insint(d
, "AI_MASK", AI_MASK
);
3718 insint(d
, "AI_ALL", AI_ALL
);
3720 #ifdef AI_V4MAPPED_CFG
3721 insint(d
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
3723 #ifdef AI_ADDRCONFIG
3724 insint(d
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
3727 insint(d
, "AI_V4MAPPED", AI_V4MAPPED
);
3730 insint(d
, "AI_DEFAULT", AI_DEFAULT
);
3733 insint(d
, "NI_MAXHOST", NI_MAXHOST
);
3736 insint(d
, "NI_MAXSERV", NI_MAXSERV
);
3739 insint(d
, "NI_NOFQDN", NI_NOFQDN
);
3741 #ifdef NI_NUMERICHOST
3742 insint(d
, "NI_NUMERICHOST", NI_NUMERICHOST
);
3745 insint(d
, "NI_NAMEREQD", NI_NAMEREQD
);
3747 #ifdef NI_NUMERICSERV
3748 insint(d
, "NI_NUMERICSERV", NI_NUMERICSERV
);
3751 insint(d
, "NI_DGRAM", NI_DGRAM
);
3754 /* Initialize gethostbyname lock */
3755 #ifdef USE_GETHOSTBYNAME_LOCK
3756 gethostbyname_lock
= PyThread_allocate_lock();
3760 /* Simplistic emulation code for inet_pton that only works for IPv4 */
3761 #ifndef HAVE_INET_PTON
3763 inet_pton (int af
, const char *src
, void *dst
)
3768 packed_addr
= (long)inet_addr(src
).s_addr
;
3770 packed_addr
= inet_addr(src
);
3772 if (packed_addr
== INADDR_NONE
)
3774 memcpy(dst
, &packed_addr
, 4);
3777 /* Should set errno to EAFNOSUPPORT */
3782 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
3784 if (af
== AF_INET
) {
3785 struct in_addr packed_addr
;
3787 /* Should set errno to ENOSPC. */
3789 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
3790 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
3792 /* Should set errno to EAFNOSUPPORT */