This commit was manufactured by cvs2svn to create tag 'r221c2'.
[python/dscho.git] / Modules / socketmodule.c
blob182496c2b173e4840ffa8436e5d4773941ec2438
1 /* Socket module */
3 /* SSL support based on patches by Brian E Gallew and Laszlo Kovacs */
5 /*
6 This module provides an interface to Berkeley socket IPC.
8 Limitations:
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)
15 Module interface:
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
50 getsockname() method.
52 Socket methods:
54 - s.accept() --> new socket object, sockaddr
55 - s.bind(sockaddr) --> None
56 - s.close() --> 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>"
78 #include "Python.h"
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! */
88 #ifndef linux
89 #undef HAVE_GETHOSTBYNAME_R_3_ARG
90 #undef HAVE_GETHOSTBYNAME_R_5_ARG
91 #undef HAVE_GETHOSTBYNAME_R_6_ARG
92 #endif
94 #ifndef WITH_THREAD
95 #undef HAVE_GETHOSTBYNAME_R
96 #endif
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
103 #elif defined(linux)
104 /* Rely on the configure script */
105 #else
106 #undef HAVE_GETHOSTBYNAME_R
107 #endif
108 #endif
110 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && !defined(MS_WINDOWS)
111 #define USE_GETHOSTBYNAME_LOCK
112 #endif
114 #ifdef USE_GETHOSTBYNAME_LOCK
115 #include "pythread.h"
116 #endif
118 #if defined(PYCC_VACPP)
119 #include <types.h>
120 #include <io.h>
121 #include <sys/ioctl.h>
122 #include <utils.h>
123 #include <ctype.h>
124 #endif
126 #if defined(PYOS_OS2)
127 #define INCL_DOS
128 #define INCL_DOSERRORS
129 #define INCL_NOPMAPI
130 #include <os2.h>
131 #endif
134 #include <sys/types.h>
136 #include <signal.h>
137 #ifndef MS_WINDOWS
138 #include <netdb.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>
143 #endif
145 /* Headers needed for inet_ntoa() and inet_addr() */
146 #ifdef __BEOS__
147 #include <net/netdb.h>
148 #elif defined(PYOS_OS2) && defined(PYCC_VACPP)
149 #include <netdb.h>
150 typedef size_t socklen_t;
151 #else
152 #ifndef USE_GUSI1
153 #include <arpa/inet.h>
154 #endif
155 #endif
157 #ifndef RISCOS
158 #include <fcntl.h>
159 #else
160 #include <sys/fcntl.h>
161 #define NO_DUP
162 int h_errno; /* not used */
163 #endif
164 #else
165 #include <winsock.h>
166 #include <fcntl.h>
167 #endif
170 #ifdef HAVE_SYS_UN_H
171 #include <sys/un.h>
172 #else
173 #undef AF_UNIX
174 #endif
176 #ifdef HAVE_NETPACKET_PACKET_H
177 #include <sys/ioctl.h>
178 #include <net/if.h>
179 #include <netpacket/packet.h>
180 #endif
182 #ifdef HAVE_STDDEF_H
183 #include <stddef.h>
184 #endif
186 #ifndef offsetof
187 #define offsetof(type, member) ((size_t)(&((type *)0)->member))
188 #endif
190 #ifndef O_NDELAY
191 #define O_NDELAY O_NONBLOCK /* For QNX only? */
192 #endif
194 #ifdef USE_GUSI1
195 /* fdopen() isn't declared in stdio.h (sigh) */
196 #include <GUSI.h>
197 #endif
199 #include "addrinfo.h"
201 #ifdef USE_SSL
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"
209 #endif /* USE_SSL */
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);
214 #endif
216 #ifdef __APPLE__
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
228 #endif
230 /* I know this is a bad practice, but it is the easiest... */
231 #if !defined(HAVE_GETADDRINFO)
232 #include "getaddrinfo.c"
233 #endif
234 #if !defined(HAVE_GETNAMEINFO)
235 #include "getnameinfo.c"
236 #endif
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... */
243 #endif
245 /* abstract the socket file descriptor type */
246 #ifdef MS_WINDOWS
247 typedef SOCKET SOCKET_T;
248 # ifdef MS_WIN64
249 # define SIZEOF_SOCKET_T 8
250 # else
251 # define SIZEOF_SOCKET_T 4
252 # endif
253 #else
254 typedef int SOCKET_T;
255 # define SIZEOF_SOCKET_T SIZEOF_INT
256 #endif
258 #ifdef MS_WIN32
259 # define EAFNOSUPPORT WSAEAFNOSUPPORT
260 # define snprintf _snprintf
261 #endif
263 #if defined(PYOS_OS2)
264 #define SOCKETCLOSE soclose
265 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
266 #endif
268 #ifndef SOCKETCLOSE
269 #define SOCKETCLOSE close
270 #endif
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;
283 #ifdef USE_SSL
284 static PyObject *PySSLErrorObject;
285 #endif /* USE_SSL */
288 #ifdef RISCOS
289 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
290 static int taskwindow;
291 #endif
294 /* Convenience function to raise an error according to errno
295 and return a NULL pointer from a function. */
297 static PyObject *
298 PySocket_Err(void)
300 #ifdef MS_WINDOWS
301 int err_no = WSAGetLastError();
302 if (err_no) {
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" },
310 { WSAEWOULDBLOCK,
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" },
326 { WSAEADDRNOTAVAIL,
327 "Can't assign requested address" },
328 { WSAENETDOWN, "Network is down" },
329 { WSAENETUNREACH, "Network is unreachable" },
330 { WSAENETRESET,
331 "Network dropped connection on reset" },
332 { WSAECONNABORTED,
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" },
339 { WSAETOOMANYREFS,
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" },
353 { WSASYSNOTREADY,
354 "Network subsystem is unvailable" },
355 { WSAVERNOTSUPPORTED,
356 "WinSock version is not supported" },
357 { WSANOTINITIALISED,
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" },
363 { WSANO_RECOVERY,
364 "Unexpected server error encountered" },
365 { WSANO_DATA, "Valid name without requested data" },
366 { WSANO_ADDRESS, "No address, look for MX record" },
367 { 0, NULL }
369 PyObject *v;
370 const char *msg = "winsock error";
372 for (msgp = msgs; msgp->msg; msgp++) {
373 if (err_no == msgp->no) {
374 msg = msgp->msg;
375 break;
379 v = Py_BuildValue("(is)", err_no, msg);
380 if (v != NULL) {
381 PyErr_SetObject(PySocket_Error, v);
382 Py_DECREF(v);
384 return NULL;
386 else
387 #endif
389 #if defined(PYOS_OS2)
390 if (sock_errno() != NO_ERROR) {
391 APIRET rc;
392 ULONG msglen;
393 char outbuf[100];
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) {
400 PyObject *v;
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);
409 if (v != NULL) {
410 PyErr_SetObject(PySocket_Error, v);
411 Py_DECREF(v);
413 return NULL;
416 #endif
418 return PyErr_SetFromErrno(PySocket_Error);
422 static PyObject *
423 PyH_Err(int h_error)
425 PyObject *v;
427 #ifdef HAVE_HSTRERROR
428 v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
429 #else
430 v = Py_BuildValue("(is)", h_error, "host not found");
431 #endif
432 if (v != NULL) {
433 PyErr_SetObject(PyH_Error, v);
434 Py_DECREF(v);
437 return NULL;
441 static PyObject *
442 PyGAI_Err(int error)
444 PyObject *v;
446 if (error == EAI_SYSTEM)
447 return PySocket_Err();
449 #ifdef HAVE_GAI_STRERROR
450 v = Py_BuildValue("(is)", error, gai_strerror(error));
451 #else
452 v = Py_BuildValue("(is)", error, "getaddrinfo failed");
453 #endif
454 if (v != NULL) {
455 PyErr_SetObject(PyGAI_Error, v);
456 Py_DECREF(v);
459 return NULL;
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. */
467 typedef struct {
468 PyObject_HEAD
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 */
473 union sock_addr {
474 struct sockaddr_in in;
475 #ifdef AF_UNIX
476 struct sockaddr_un un;
477 #endif
478 #ifdef ENABLE_IPV6
479 struct sockaddr_in6 in6;
480 struct sockaddr_storage storage;
481 #endif
482 #ifdef HAVE_NETPACKET_PACKET_H
483 struct sockaddr_ll ll;
484 #endif
485 } sock_addr;
486 } PySocketSockObject;
488 #ifdef USE_SSL
490 #define X509_NAME_MAXLEN 256
492 typedef struct {
493 PyObject_HEAD
494 PySocketSockObject *Socket; /* Socket on which we're layered */
495 SSL_CTX* ctx;
496 SSL* ssl;
497 X509* server_cert;
498 BIO* sbio;
499 char server[X509_NAME_MAXLEN];
500 char issuer[X509_NAME_MAXLEN];
502 } PySSLObject;
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)
510 #endif /* USE_SSL */
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. */
522 static void
523 init_sockobject(PySocketSockObject *s,
524 SOCKET_T fd, int family, int type, int proto)
526 #ifdef RISCOS
527 int block = 1;
528 #endif
529 s->sock_fd = fd;
530 s->sock_family = family;
531 s->sock_type = type;
532 s->sock_proto = proto;
533 #ifdef RISCOS
534 if(taskwindow) {
535 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
537 #endif
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
544 in NEWOBJ()). */
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);
552 if (s != NULL)
553 init_sockobject(s, fd, family, type, proto);
554 return s;
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;
562 #endif
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. */
571 static int
572 setipaddr(char* name, struct sockaddr * addr_ret, int af)
574 struct addrinfo hints, *res;
575 int error;
577 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
578 if (name[0] == '\0') {
579 int siz;
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);
585 if (error) {
586 PyGAI_Err(error);
587 return -1;
589 switch (res->ai_family) {
590 case AF_INET:
591 siz = 4;
592 break;
593 #ifdef ENABLE_IPV6
594 case AF_INET6:
595 siz = 16;
596 break;
597 #endif
598 default:
599 freeaddrinfo(res);
600 PyErr_SetString(PySocket_Error,
601 "unsupported address family");
602 return -1;
604 if (res->ai_next) {
605 freeaddrinfo(res);
606 PyErr_SetString(PySocket_Error,
607 "wildcard resolved to multiple address");
608 return -1;
610 memcpy(addr_ret, res->ai_addr, res->ai_addrlen);
611 freeaddrinfo(res);
612 return siz;
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");
619 return -1;
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);
626 #endif
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);
640 #endif
641 if (error) {
642 PyGAI_Err(error);
643 return -1;
645 memcpy((char *) addr_ret, res->ai_addr, res->ai_addrlen);
646 freeaddrinfo(res);
647 switch (addr_ret->sa_family) {
648 case AF_INET:
649 return 4;
650 #ifdef ENABLE_IPV6
651 case AF_INET6:
652 return 16;
653 #endif
654 default:
655 PyErr_SetString(PySocket_Error, "unknown address family");
656 return -1;
661 /* Create a string object representing an IP address.
662 This is always a string of the form 'dd.dd.dd.dd' (with variable
663 size numbers). */
665 static PyObject *
666 makeipaddr(struct sockaddr *addr, int addrlen)
668 char buf[NI_MAXHOST];
669 int error;
671 error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
672 NI_NUMERICHOST);
673 if (error) {
674 PyGAI_Err(error);
675 return NULL;
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. */
686 /*ARGSUSED*/
687 static PyObject *
688 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen)
690 if (addrlen == 0) {
691 /* No address -- may be recvfrom() from known socket */
692 Py_INCREF(Py_None);
693 return Py_None;
696 #ifdef __BEOS__
697 /* XXX: BeOS version of accept() doesn't set family correctly */
698 addr->sa_family = AF_INET;
699 #endif
701 switch (addr->sa_family) {
703 case AF_INET:
705 struct sockaddr_in *a;
706 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
707 PyObject *ret = NULL;
708 if (addrobj) {
709 a = (struct sockaddr_in *)addr;
710 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
711 Py_DECREF(addrobj);
713 return ret;
716 #ifdef AF_UNIX
717 case AF_UNIX:
719 struct sockaddr_un *a = (struct sockaddr_un *) addr;
720 return PyString_FromString(a->sun_path);
722 #endif /* AF_UNIX */
724 #ifdef ENABLE_IPV6
725 case AF_INET6:
727 struct sockaddr_in6 *a;
728 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
729 PyObject *ret = NULL;
730 if (addrobj) {
731 a = (struct sockaddr_in6 *)addr;
732 ret = Py_BuildValue("Oiii", addrobj, ntohs(a->sin6_port),
733 a->sin6_flowinfo, a->sin6_scope_id);
734 Py_DECREF(addrobj);
736 return ret;
738 #endif
740 #ifdef HAVE_NETPACKET_PACKET_H
741 case AF_PACKET:
743 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
744 char *ifname = "";
745 struct ifreq ifr;
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);
756 #endif
758 /* More cases here... */
760 default:
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#",
764 addr->sa_family,
765 addr->sa_data,
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
775 through len_ret. */
777 static int
778 getsockaddrarg(PySocketSockObject *s, PyObject *args,
779 struct sockaddr **addr_ret, int *len_ret)
781 switch (s->sock_family) {
783 #ifdef AF_UNIX
784 case AF_UNIX:
786 struct sockaddr_un* addr;
787 char *path;
788 int len;
789 addr = (struct sockaddr_un* )&(s->sock_addr).un;
790 if (!PyArg_Parse(args, "t#", &path, &len))
791 return 0;
792 if (len > sizeof addr->sun_path) {
793 PyErr_SetString(PySocket_Error,
794 "AF_UNIX path too long");
795 return 0;
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);
802 return 1;
804 #endif /* AF_UNIX */
806 case AF_INET:
808 struct sockaddr_in* addr;
809 char *host;
810 int port;
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);
816 return 0;
818 if (!PyArg_ParseTuple(args, "si:getsockaddrarg", &host, &port))
819 return 0;
820 if (setipaddr(host, (struct sockaddr *)addr, AF_INET) < 0)
821 return 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;
826 return 1;
829 #ifdef ENABLE_IPV6
830 case AF_INET6:
832 struct sockaddr_in6* addr;
833 char *host;
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,
838 &scope_id)) {
839 return 0;
841 if (setipaddr(host, (struct sockaddr *)addr, AF_INET6) < 0)
842 return 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;
849 return 1;
851 #endif
853 #ifdef HAVE_NETPACKET_PACKET_H
854 case AF_PACKET:
856 struct sockaddr_ll* addr;
857 struct ifreq ifr;
858 char *interfaceName;
859 int protoNumber;
860 int hatype = 0;
861 int pkttype = 0;
862 char *haddr;
864 if (!PyArg_ParseTuple(args, "si|iis", &interfaceName,
865 &protoNumber, &pkttype, &hatype, &haddr))
866 return 0;
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) {
870 PySocket_Err();
871 return 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;
881 return 1;
883 #endif
885 /* More cases here... */
887 default:
888 PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
889 return 0;
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
897 through len_ret. */
899 static int
900 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
902 switch (s->sock_family) {
904 #ifdef AF_UNIX
905 case AF_UNIX:
907 *len_ret = sizeof (struct sockaddr_un);
908 return 1;
910 #endif /* AF_UNIX */
912 case AF_INET:
914 *len_ret = sizeof (struct sockaddr_in);
915 return 1;
918 #ifdef ENABLE_IPV6
919 case AF_INET6:
921 *len_ret = sizeof (struct sockaddr_in6);
922 return 1;
924 #endif
926 #ifdef HAVE_NETPACKET_PACKET_H
927 case AF_PACKET:
929 *len_ret = sizeof (struct sockaddr_ll);
930 return 1;
932 #endif
934 /* More cases here... */
936 default:
937 PyErr_SetString(PySocket_Error, "getsockaddrlen: bad family");
938 return 0;
944 /* s.accept() method */
946 static PyObject *
947 PySocketSock_accept(PySocketSockObject *s)
949 char addrbuf[256];
950 SOCKET_T newfd;
951 socklen_t addrlen;
952 PyObject *sock = NULL;
953 PyObject *addr = NULL;
954 PyObject *res = NULL;
956 if (!getsockaddrlen(s, &addrlen))
957 return NULL;
958 memset(addrbuf, 0, addrlen);
959 Py_BEGIN_ALLOW_THREADS
960 newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
961 Py_END_ALLOW_THREADS
962 #ifdef MS_WINDOWS
963 if (newfd == INVALID_SOCKET)
964 #else
965 if (newfd < 0)
966 #endif
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,
972 s->sock_family,
973 s->sock_type,
974 s->sock_proto);
975 if (sock == NULL) {
976 SOCKETCLOSE(newfd);
977 goto finally;
979 addr = makesockaddr(s->sock_fd, (struct sockaddr *)addrbuf,
980 addrlen);
981 if (addr == NULL)
982 goto finally;
984 res = Py_BuildValue("OO", sock, addr);
986 finally:
987 Py_XDECREF(sock);
988 Py_XDECREF(addr);
989 return res;
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 */
1002 static PyObject *
1003 PySocketSock_setblocking(PySocketSockObject *s, PyObject *arg)
1005 int block;
1006 #ifndef RISCOS
1007 #ifndef MS_WINDOWS
1008 int delay_flag;
1009 #endif
1010 #endif
1011 block = PyInt_AsLong(arg);
1012 if (block == -1 && PyErr_Occurred())
1013 return NULL;
1014 Py_BEGIN_ALLOW_THREADS
1015 #ifdef __BEOS__
1016 block = !block;
1017 setsockopt( s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
1018 (void *)(&block), sizeof( int ) );
1019 #else
1020 #ifndef RISCOS
1021 #ifndef MS_WINDOWS
1022 #ifdef PYOS_OS2
1023 block = !block;
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);
1027 if (block)
1028 delay_flag &= (~O_NDELAY);
1029 else
1030 delay_flag |= O_NDELAY;
1031 fcntl (s->sock_fd, F_SETFL, delay_flag);
1032 #endif /* !PYOS_OS2 */
1033 #else /* MS_WINDOWS */
1034 block = !block;
1035 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
1036 #endif /* MS_WINDOWS */
1037 #endif /* __BEOS__ */
1038 #endif /* RISCOS */
1039 Py_END_ALLOW_THREADS
1041 Py_INCREF(Py_None);
1042 return Py_None;
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.";
1052 #ifdef RISCOS
1053 /* s.sleeptaskw(1 | 0) method */
1055 static PyObject *
1056 PySocketSock_sleeptaskw(PySocketSockObject *s,PyObject *args)
1058 int block;
1059 int delay_flag;
1060 if (!PyArg_GetInt(args, &block))
1061 return NULL;
1062 Py_BEGIN_ALLOW_THREADS
1063 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1064 Py_END_ALLOW_THREADS
1066 Py_INCREF(Py_None);
1067 return Py_None;
1069 static char sleeptaskw_doc[] =
1070 "sleeptaskw(flag)\n\
1072 Allow sleeps in taskwindows.";
1073 #endif
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. */
1081 static PyObject *
1082 PySocketSock_setsockopt(PySocketSockObject *s, PyObject *args)
1084 int level;
1085 int optname;
1086 int res;
1087 char *buf;
1088 int buflen;
1089 int flag;
1091 if (PyArg_ParseTuple(args, "iii:setsockopt",
1092 &level, &optname, &flag)) {
1093 buf = (char *) &flag;
1094 buflen = sizeof flag;
1096 else {
1097 PyErr_Clear();
1098 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1099 &level, &optname, &buf, &buflen))
1100 return NULL;
1102 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1103 if (res < 0)
1104 return PySocket_Err();
1105 Py_INCREF(Py_None);
1106 return Py_None;
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. */
1121 static PyObject *
1122 PySocketSock_getsockopt(PySocketSockObject *s, PyObject *args)
1124 int level;
1125 int optname;
1126 int res;
1127 PyObject *buf;
1128 socklen_t buflen = 0;
1130 #ifdef __BEOS__
1131 /* We have incomplete socket support. */
1132 PyErr_SetString(PySocket_Error, "getsockopt not supported");
1133 return NULL;
1134 #else
1136 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1137 &level, &optname, &buflen))
1138 return NULL;
1140 if (buflen == 0) {
1141 int flag = 0;
1142 socklen_t flagsize = sizeof flag;
1143 res = getsockopt(s->sock_fd, level, optname,
1144 (void *)&flag, &flagsize);
1145 if (res < 0)
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");
1152 return NULL;
1154 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1155 if (buf == NULL)
1156 return NULL;
1157 res = getsockopt(s->sock_fd, level, optname,
1158 (void *)PyString_AS_STRING(buf), &buflen);
1159 if (res < 0) {
1160 Py_DECREF(buf);
1161 return PySocket_Err();
1163 _PyString_Resize(&buf, buflen);
1164 return buf;
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 */
1178 static PyObject *
1179 PySocketSock_bind(PySocketSockObject *s, PyObject *addro)
1181 struct sockaddr *addr;
1182 int addrlen;
1183 int res;
1185 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1186 return NULL;
1187 Py_BEGIN_ALLOW_THREADS
1188 res = bind(s->sock_fd, addr, addrlen);
1189 Py_END_ALLOW_THREADS
1190 if (res < 0)
1191 return PySocket_Err();
1192 Py_INCREF(Py_None);
1193 return Py_None;
1196 static char bind_doc[] =
1197 "bind(address)\n\
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. */
1208 static PyObject *
1209 PySocketSock_close(PySocketSockObject *s)
1211 SOCKET_T fd;
1213 if ((fd = s->sock_fd) != -1) {
1214 s->sock_fd = -1;
1215 Py_BEGIN_ALLOW_THREADS
1216 (void) SOCKETCLOSE(fd);
1217 Py_END_ALLOW_THREADS
1219 Py_INCREF(Py_None);
1220 return Py_None;
1223 static char close_doc[] =
1224 "close()\n\
1226 Close the socket. It cannot be used after this call.";
1229 /* s.connect(sockaddr) method */
1231 static PyObject *
1232 PySocketSock_connect(PySocketSockObject *s, PyObject *addro)
1234 struct sockaddr *addr;
1235 int addrlen;
1236 int res;
1238 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1239 return NULL;
1240 Py_BEGIN_ALLOW_THREADS
1241 res = connect(s->sock_fd, addr, addrlen);
1242 Py_END_ALLOW_THREADS
1243 if (res < 0)
1244 return PySocket_Err();
1245 Py_INCREF(Py_None);
1246 return Py_None;
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 */
1258 static PyObject *
1259 PySocketSock_connect_ex(PySocketSockObject *s, PyObject *addro)
1261 struct sockaddr *addr;
1262 int addrlen;
1263 int res;
1265 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1266 return NULL;
1267 Py_BEGIN_ALLOW_THREADS
1268 res = connect(s->sock_fd, addr, addrlen);
1269 Py_END_ALLOW_THREADS
1270 if (res != 0) {
1271 #ifdef MS_WINDOWS
1272 res = WSAGetLastError();
1273 #else
1274 res = errno;
1275 #endif
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 */
1289 static PyObject *
1290 PySocketSock_fileno(PySocketSockObject *s)
1292 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1293 return PyInt_FromLong((long) s->sock_fd);
1294 #else
1295 return PyLong_FromLongLong((LONG_LONG)s->sock_fd);
1296 #endif
1299 static char fileno_doc[] =
1300 "fileno() -> integer\n\
1302 Return the integer file descriptor of the socket.";
1305 #ifndef NO_DUP
1306 /* s.dup() method */
1308 static PyObject *
1309 PySocketSock_dup(PySocketSockObject *s)
1311 SOCKET_T newfd;
1312 PyObject *sock;
1314 newfd = dup(s->sock_fd);
1315 if (newfd < 0)
1316 return PySocket_Err();
1317 sock = (PyObject *) PySocketSock_New(newfd,
1318 s->sock_family,
1319 s->sock_type,
1320 s->sock_proto);
1321 if (sock == NULL)
1322 SOCKETCLOSE(newfd);
1323 return sock;
1326 static char dup_doc[] =
1327 "dup() -> socket object\n\
1329 Return a new socket object connected to the same system resource.";
1331 #endif
1334 /* s.getsockname() method */
1336 static PyObject *
1337 PySocketSock_getsockname(PySocketSockObject *s)
1339 char addrbuf[256];
1340 int res;
1341 socklen_t addrlen;
1343 if (!getsockaddrlen(s, &addrlen))
1344 return NULL;
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
1349 if (res < 0)
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 */
1364 static PyObject *
1365 PySocketSock_getpeername(PySocketSockObject *s)
1367 char addrbuf[256];
1368 int res;
1369 socklen_t addrlen;
1371 if (!getsockaddrlen(s, &addrlen))
1372 return NULL;
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
1377 if (res < 0)
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 */
1393 static PyObject *
1394 PySocketSock_listen(PySocketSockObject *s, PyObject *arg)
1396 int backlog;
1397 int res;
1399 backlog = PyInt_AsLong(arg);
1400 if (backlog == -1 && PyErr_Occurred())
1401 return NULL;
1402 Py_BEGIN_ALLOW_THREADS
1403 if (backlog < 1)
1404 backlog = 1;
1405 res = listen(s->sock_fd, backlog);
1406 Py_END_ALLOW_THREADS
1407 if (res < 0)
1408 return PySocket_Err();
1409 Py_INCREF(Py_None);
1410 return Py_None;
1413 static char listen_doc[] =
1414 "listen(backlog)\n\
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.";
1421 #ifndef NO_DUP
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
1426 of each other.)
1427 The mode argument specifies 'r' or 'w' passed to fdopen(). */
1429 static PyObject *
1430 PySocketSock_makefile(PySocketSockObject *s, PyObject *args)
1432 extern int fclose(FILE *);
1433 char *mode = "r";
1434 int bufsize = -1;
1435 #ifdef MS_WIN32
1436 Py_intptr_t fd;
1437 #else
1438 int fd;
1439 #endif
1440 FILE *fp;
1441 PyObject *f;
1443 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
1444 return NULL;
1445 #ifdef MS_WIN32
1446 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
1447 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
1448 #else
1449 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
1450 #endif
1452 if (fd >= 0)
1453 SOCKETCLOSE(fd);
1454 return PySocket_Err();
1456 #ifdef USE_GUSI2
1457 /* Workaround for bug in Metrowerks MSL vs. GUSI I/O library */
1458 if (strchr(mode, 'b') != NULL )
1459 bufsize = 0;
1460 #endif
1461 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
1462 if (f != NULL)
1463 PyFile_SetBufSize(f, bufsize);
1464 return f;
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.";
1473 #endif /* NO_DUP */
1476 /* s.recv(nbytes [,flags]) method */
1478 static PyObject *
1479 PySocketSock_recv(PySocketSockObject *s, PyObject *args)
1481 int len, n, flags = 0;
1482 PyObject *buf;
1483 if (!PyArg_ParseTuple(args, "i|i:recv", &len, &flags))
1484 return NULL;
1485 if (len < 0) {
1486 PyErr_SetString(PyExc_ValueError,
1487 "negative buffersize in connect");
1488 return NULL;
1490 buf = PyString_FromStringAndSize((char *) 0, len);
1491 if (buf == NULL)
1492 return NULL;
1493 Py_BEGIN_ALLOW_THREADS
1494 n = recv(s->sock_fd, PyString_AS_STRING(buf), len, flags);
1495 Py_END_ALLOW_THREADS
1496 if (n < 0) {
1497 Py_DECREF(buf);
1498 return PySocket_Err();
1500 if (n != len && _PyString_Resize(&buf, n) < 0)
1501 return NULL;
1502 return buf;
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 */
1516 static PyObject *
1517 PySocketSock_recvfrom(PySocketSockObject *s, PyObject *args)
1519 char addrbuf[256];
1520 PyObject *buf = NULL;
1521 PyObject *addr = NULL;
1522 PyObject *ret = NULL;
1524 int len, n, flags = 0;
1525 socklen_t addrlen;
1526 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &len, &flags))
1527 return NULL;
1528 if (!getsockaddrlen(s, &addrlen))
1529 return NULL;
1530 buf = PyString_FromStringAndSize((char *) 0, len);
1531 if (buf == NULL)
1532 return NULL;
1533 Py_BEGIN_ALLOW_THREADS
1534 memset(addrbuf, 0, addrlen);
1535 n = recvfrom(s->sock_fd, PyString_AS_STRING(buf), len, flags,
1536 #ifndef MS_WINDOWS
1537 #if defined(PYOS_OS2)
1538 (struct sockaddr *)addrbuf, &addrlen
1539 #else
1540 (void *)addrbuf, &addrlen
1541 #endif
1542 #else
1543 (struct sockaddr *)addrbuf, &addrlen
1544 #endif
1546 Py_END_ALLOW_THREADS
1547 if (n < 0) {
1548 Py_DECREF(buf);
1549 return PySocket_Err();
1551 if (n != len && _PyString_Resize(&buf, n) < 0)
1552 return NULL;
1554 if (!(addr = makesockaddr(s->sock_fd, (struct sockaddr *)addrbuf, addrlen)))
1555 goto finally;
1557 ret = Py_BuildValue("OO", buf, addr);
1558 finally:
1559 Py_XDECREF(addr);
1560 Py_XDECREF(buf);
1561 return ret;
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 */
1572 static PyObject *
1573 PySocketSock_send(PySocketSockObject *s, PyObject *args)
1575 char *buf;
1576 int len, n, flags = 0;
1577 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
1578 return NULL;
1579 Py_BEGIN_ALLOW_THREADS
1580 n = send(s->sock_fd, buf, len, flags);
1581 Py_END_ALLOW_THREADS
1582 if (n < 0)
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 */
1597 static PyObject *
1598 PySocketSock_sendall(PySocketSockObject *s, PyObject *args)
1600 char *buf;
1601 int len, n, flags = 0, total = 0;
1602 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
1603 return NULL;
1604 Py_BEGIN_ALLOW_THREADS
1605 do {
1606 n = send(s->sock_fd, buf, len, flags);
1607 if (n < 0)
1608 break;
1609 total += n;
1610 buf += n;
1611 len -= n;
1612 } while (len > 0);
1613 Py_END_ALLOW_THREADS
1614 if (n < 0)
1615 return PySocket_Err();
1616 Py_INCREF(Py_None);
1617 return Py_None;
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 */
1631 static PyObject *
1632 PySocketSock_sendto(PySocketSockObject *s, PyObject *args)
1634 PyObject *addro;
1635 char *buf;
1636 struct sockaddr *addr;
1637 int addrlen, len, n, flags;
1638 flags = 0;
1639 if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
1640 PyErr_Clear();
1641 if (!PyArg_ParseTuple(args, "s#iO:sendto",
1642 &buf, &len, &flags, &addro))
1643 return NULL;
1645 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1646 return NULL;
1647 Py_BEGIN_ALLOW_THREADS
1648 n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
1649 Py_END_ALLOW_THREADS
1650 if (n < 0)
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 */
1664 static PyObject *
1665 PySocketSock_shutdown(PySocketSockObject *s, PyObject *arg)
1667 int how;
1668 int res;
1670 how = PyInt_AsLong(arg);
1671 if (how == -1 && PyErr_Occurred())
1672 return NULL;
1673 Py_BEGIN_ALLOW_THREADS
1674 res = shutdown(s->sock_fd, how);
1675 Py_END_ALLOW_THREADS
1676 if (res < 0)
1677 return PySocket_Err();
1678 Py_INCREF(Py_None);
1679 return Py_None;
1682 static char shutdown_doc[] =
1683 "shutdown(flag)\n\
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,
1693 accept_doc},
1694 {"bind", (PyCFunction)PySocketSock_bind, METH_O,
1695 bind_doc},
1696 {"close", (PyCFunction)PySocketSock_close, METH_NOARGS,
1697 close_doc},
1698 {"connect", (PyCFunction)PySocketSock_connect, METH_O,
1699 connect_doc},
1700 {"connect_ex", (PyCFunction)PySocketSock_connect_ex, METH_O,
1701 connect_ex_doc},
1702 #ifndef NO_DUP
1703 {"dup", (PyCFunction)PySocketSock_dup, METH_NOARGS,
1704 dup_doc},
1705 #endif
1706 {"fileno", (PyCFunction)PySocketSock_fileno, METH_NOARGS,
1707 fileno_doc},
1708 #ifdef HAVE_GETPEERNAME
1709 {"getpeername", (PyCFunction)PySocketSock_getpeername,
1710 METH_NOARGS, getpeername_doc},
1711 #endif
1712 {"getsockname", (PyCFunction)PySocketSock_getsockname,
1713 METH_NOARGS, getsockname_doc},
1714 {"getsockopt", (PyCFunction)PySocketSock_getsockopt, METH_VARARGS,
1715 getsockopt_doc},
1716 {"listen", (PyCFunction)PySocketSock_listen, METH_O,
1717 listen_doc},
1718 #ifndef NO_DUP
1719 {"makefile", (PyCFunction)PySocketSock_makefile, METH_VARARGS,
1720 makefile_doc},
1721 #endif
1722 {"recv", (PyCFunction)PySocketSock_recv, METH_VARARGS,
1723 recv_doc},
1724 {"recvfrom", (PyCFunction)PySocketSock_recvfrom, METH_VARARGS,
1725 recvfrom_doc},
1726 {"send", (PyCFunction)PySocketSock_send, METH_VARARGS,
1727 send_doc},
1728 {"sendall", (PyCFunction)PySocketSock_sendall, METH_VARARGS,
1729 sendall_doc},
1730 {"sendto", (PyCFunction)PySocketSock_sendto, METH_VARARGS,
1731 sendto_doc},
1732 {"setblocking", (PyCFunction)PySocketSock_setblocking, METH_O,
1733 setblocking_doc},
1734 {"setsockopt", (PyCFunction)PySocketSock_setsockopt, METH_VARARGS,
1735 setsockopt_doc},
1736 {"shutdown", (PyCFunction)PySocketSock_shutdown, METH_O,
1737 shutdown_doc},
1738 #ifdef RISCOS
1739 {"sleeptaskw", (PyCFunction)PySocketSock_sleeptaskw, METH_VARARGS,
1740 sleeptaskw_doc},
1741 #endif
1742 {NULL, NULL} /* sentinel */
1746 /* Deallocate a socket object in response to the last Py_DECREF().
1747 First close the file description. */
1749 static void
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);
1758 static PyObject *
1759 PySocketSock_repr(PySocketSockObject *s)
1761 char buf[512];
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");
1769 return NULL;
1771 #endif
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,
1775 s->sock_type,
1776 s->sock_proto);
1777 return PyString_FromString(buf);
1781 /* Create a new, uninitialized socket object. */
1783 static PyObject *
1784 PySocketSock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1786 PyObject *new;
1788 new = type->tp_alloc(type, 0);
1789 if (new != NULL)
1790 ((PySocketSockObject *)new)->sock_fd = -1;
1791 return new;
1795 /* Initialize a new socket object. */
1797 /*ARGSUSED*/
1798 static int
1799 PySocketSock_init(PyObject *self, PyObject *args, PyObject *kwds)
1801 PySocketSockObject *s = (PySocketSockObject *)self;
1802 SOCKET_T fd;
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))
1809 return -1;
1810 Py_BEGIN_ALLOW_THREADS
1811 fd = socket(family, type, proto);
1812 Py_END_ALLOW_THREADS
1813 #ifdef MS_WINDOWS
1814 if (fd == INVALID_SOCKET)
1815 #else
1816 if (fd < 0)
1817 #endif
1819 PySocket_Err();
1820 return -1;
1822 init_sockobject(s, fd, family, type, proto);
1823 /* From now on, ignore SIGPIPE and let the error checking
1824 do the work. */
1825 #ifdef SIGPIPE
1826 (void) signal(SIGPIPE, SIG_IGN);
1827 #endif
1828 return 0;
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\
1845 Methods:\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 */
1872 0, /* ob_size */
1873 "_socket.socket", /* tp_name */
1874 sizeof(PySocketSockObject), /* tp_basicsize */
1875 0, /* tp_itemsize */
1876 (destructor)PySocketSock_dealloc, /* tp_dealloc */
1877 0, /* tp_print */
1878 0, /* tp_getattr */
1879 0, /* tp_setattr */
1880 0, /* tp_compare */
1881 (reprfunc)PySocketSock_repr, /* tp_repr */
1882 0, /* tp_as_number */
1883 0, /* tp_as_sequence */
1884 0, /* tp_as_mapping */
1885 0, /* tp_hash */
1886 0, /* tp_call */
1887 0, /* tp_str */
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 */
1894 0, /* tp_clear */
1895 0, /* tp_richcompare */
1896 0, /* tp_weaklistoffset */
1897 0, /* tp_iter */
1898 0, /* tp_iternext */
1899 PySocketSock_methods, /* tp_methods */
1900 0, /* tp_members */
1901 0, /* tp_getset */
1902 0, /* tp_base */
1903 0, /* tp_dict */
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(). */
1916 /*ARGSUSED*/
1917 static PyObject *
1918 PySocket_gethostname(PyObject *self, PyObject *args)
1920 char buf[1024];
1921 int res;
1922 if (!PyArg_ParseTuple(args, ":gethostname"))
1923 return NULL;
1924 Py_BEGIN_ALLOW_THREADS
1925 res = gethostname(buf, (int) sizeof buf - 1);
1926 Py_END_ALLOW_THREADS
1927 if (res < 0)
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). */
1941 /*ARGSUSED*/
1942 static PyObject *
1943 PySocket_gethostbyname(PyObject *self, PyObject *args)
1945 char *name;
1946 struct sockaddr_storage addrbuf;
1948 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
1949 return NULL;
1950 if (setipaddr(name, (struct sockaddr *)&addrbuf, AF_INET) < 0)
1951 return NULL;
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 */
1964 static PyObject *
1965 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
1967 char **pch;
1968 PyObject *rtn_tuple = (PyObject *)NULL;
1969 PyObject *name_list = (PyObject *)NULL;
1970 PyObject *addr_list = (PyObject *)NULL;
1971 PyObject *tmp;
1973 if (h == NULL) {
1974 /* Let's get real error message to return */
1975 #ifndef RISCOS
1976 PyH_Err(h_errno);
1977 #else
1978 PyErr_SetString(PySocket_Error, "host not found");
1979 #endif
1980 return NULL;
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));
1986 #else
1987 PyErr_SetString(PySocket_Error,
1988 "Address family not supported by protocol family");
1989 #endif
1990 return NULL;
1992 switch (af) {
1993 case AF_INET:
1994 if (alen < sizeof(struct sockaddr_in))
1995 return NULL;
1996 break;
1997 #ifdef ENABLE_IPV6
1998 case AF_INET6:
1999 if (alen < sizeof(struct sockaddr_in6))
2000 return NULL;
2001 break;
2002 #endif
2004 if ((name_list = PyList_New(0)) == NULL)
2005 goto err;
2006 if ((addr_list = PyList_New(0)) == NULL)
2007 goto err;
2008 for (pch = h->h_aliases; *pch != NULL; pch++) {
2009 int status;
2010 tmp = PyString_FromString(*pch);
2011 if (tmp == NULL)
2012 goto err;
2013 status = PyList_Append(name_list, tmp);
2014 Py_DECREF(tmp);
2015 if (status)
2016 goto err;
2018 for (pch = h->h_addr_list; *pch != NULL; pch++) {
2019 int status;
2020 switch (af) {
2021 case AF_INET:
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);
2028 #endif
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));
2033 break;
2035 #ifdef ENABLE_IPV6
2036 case AF_INET6:
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);
2043 #endif
2044 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
2045 tmp = makeipaddr((struct sockaddr *)&sin6,
2046 sizeof(sin6));
2047 if (pch == h->h_addr_list && alen >= sizeof(sin6))
2048 memcpy((char *) addr, &sin6, sizeof(sin6));
2049 break;
2051 #endif
2052 default: /* can't happen */
2053 PyErr_SetString(PySocket_Error,
2054 "unsupported address family");
2055 return NULL;
2057 if (tmp == NULL)
2058 goto err;
2059 status = PyList_Append(addr_list, tmp);
2060 Py_DECREF(tmp);
2061 if (status)
2062 goto err;
2064 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
2065 err:
2066 Py_XDECREF(name_list);
2067 Py_XDECREF(addr_list);
2068 return rtn_tuple;
2072 /* Python interface to gethostbyname_ex(name). */
2074 /*ARGSUSED*/
2075 static PyObject *
2076 PySocket_gethostbyname_ex(PyObject *self, PyObject *args)
2078 char *name;
2079 struct hostent *h;
2080 struct sockaddr_storage addr;
2081 struct sockaddr *sa;
2082 PyObject *ret;
2083 #ifdef HAVE_GETHOSTBYNAME_R
2084 struct hostent hp_allocated;
2085 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2086 struct hostent_data data;
2087 #else
2088 char buf[16384];
2089 int buf_len = (sizeof buf) - 1;
2090 int errnop;
2091 #endif
2092 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2093 int result;
2094 #endif
2095 #endif /* HAVE_GETHOSTBYNAME_R */
2097 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
2098 return NULL;
2099 if (setipaddr(name, (struct sockaddr *)&addr, PF_INET) < 0)
2100 return NULL;
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;
2111 #endif
2112 #else /* not HAVE_GETHOSTBYNAME_R */
2113 #ifdef USE_GETHOSTBYNAME_LOCK
2114 PyThread_acquire_lock(gethostbyname_lock, 1);
2115 #endif
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);
2125 #endif
2126 return ret;
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). */
2138 /*ARGSUSED*/
2139 static PyObject *
2140 PySocket_gethostbyaddr(PyObject *self, PyObject *args)
2142 #ifdef ENABLE_IPV6
2143 struct sockaddr_storage addr;
2144 #else
2145 struct sockaddr_in addr;
2146 #endif
2147 struct sockaddr *sa = (struct sockaddr *)&addr;
2148 char *ip_num;
2149 struct hostent *h;
2150 PyObject *ret;
2151 #ifdef HAVE_GETHOSTBYNAME_R
2152 struct hostent hp_allocated;
2153 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2154 struct hostent_data data;
2155 #else
2156 char buf[16384];
2157 int buf_len = (sizeof buf) - 1;
2158 int errnop;
2159 #endif
2160 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2161 int result;
2162 #endif
2163 #endif /* HAVE_GETHOSTBYNAME_R */
2164 char *ap;
2165 int al;
2166 int af;
2168 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
2169 return NULL;
2170 af = PF_UNSPEC;
2171 if (setipaddr(ip_num, sa, af) < 0)
2172 return NULL;
2173 af = sa->sa_family;
2174 ap = NULL;
2175 al = 0;
2176 switch (af) {
2177 case AF_INET:
2178 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
2179 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
2180 break;
2181 #ifdef ENABLE_IPV6
2182 case AF_INET6:
2183 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
2184 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
2185 break;
2186 #endif
2187 default:
2188 PyErr_SetString(PySocket_Error, "unsupported address family");
2189 return NULL;
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,
2196 &h, &errnop);
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;
2204 #endif
2205 #else /* not HAVE_GETHOSTBYNAME_R */
2206 #ifdef USE_GETHOSTBYNAME_LOCK
2207 PyThread_acquire_lock(gethostbyname_lock, 1);
2208 #endif
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);
2215 #endif
2216 return ret;
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). */
2230 /*ARGSUSED*/
2231 static PyObject *
2232 PySocket_getservbyname(PyObject *self, PyObject *args)
2234 char *name, *proto;
2235 struct servent *sp;
2236 if (!PyArg_ParseTuple(args, "ss:getservbyname", &name, &proto))
2237 return NULL;
2238 Py_BEGIN_ALLOW_THREADS
2239 sp = getservbyname(name, proto);
2240 Py_END_ALLOW_THREADS
2241 if (sp == NULL) {
2242 PyErr_SetString(PySocket_Error, "service/proto not found");
2243 return NULL;
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). */
2259 /*ARGSUSED*/
2260 static PyObject *
2261 PySocket_getprotobyname(PyObject *self, PyObject *args)
2263 char *name;
2264 struct protoent *sp;
2265 #ifdef __BEOS__
2266 /* Not available in BeOS yet. - [cjh] */
2267 PyErr_SetString( PySocket_Error, "getprotobyname not supported" );
2268 return NULL;
2269 #else
2270 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
2271 return NULL;
2272 Py_BEGIN_ALLOW_THREADS
2273 sp = getprotobyname(name);
2274 Py_END_ALLOW_THREADS
2275 if (sp == NULL) {
2276 PyErr_SetString(PySocket_Error, "protocol not found");
2277 return NULL;
2279 return PyInt_FromLong((long) sp->p_proto);
2280 #endif
2283 static char getprotobyname_doc[] =
2284 "getprotobyname(name) -> integer\n\
2286 Return the protocol number for the named protocol. (Rarely used.)";
2289 #ifndef NO_DUP
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(). */
2294 /*ARGSUSED*/
2295 static PyObject *
2296 PySocket_fromfd(PyObject *self, PyObject *args)
2298 PySocketSockObject *s;
2299 SOCKET_T fd;
2300 int family, type, proto = 0;
2301 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
2302 &fd, &family, &type, &proto))
2303 return NULL;
2304 /* Dup the fd so it and the socket can be closed independently */
2305 fd = dup(fd);
2306 if (fd < 0)
2307 return PySocket_Err();
2308 s = PySocketSock_New(fd, family, type, proto);
2309 /* From now on, ignore SIGPIPE and let the error checking
2310 do the work. */
2311 #ifdef SIGPIPE
2312 (void) signal(SIGPIPE, SIG_IGN);
2313 #endif
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().";
2323 #endif /* NO_DUP */
2326 static PyObject *
2327 PySocket_ntohs(PyObject *self, PyObject *args)
2329 int x1, x2;
2331 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
2332 return NULL;
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.";
2344 static PyObject *
2345 PySocket_ntohl(PyObject *self, PyObject *args)
2347 int x1, x2;
2349 if (!PyArg_ParseTuple(args, "i:ntohl", &x1)) {
2350 return NULL;
2352 x2 = 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.";
2362 static PyObject *
2363 PySocket_htons(PyObject *self, PyObject *args)
2365 int x1, x2;
2367 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
2368 return NULL;
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.";
2380 static PyObject *
2381 PySocket_htonl(PyObject *self, PyObject *args)
2383 int x1, x2;
2385 if (!PyArg_ParseTuple(args, "i:htonl", &x1)) {
2386 return NULL;
2388 x2 = 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.";
2410 static PyObject*
2411 PySocket_inet_aton(PyObject *self, PyObject *args)
2413 #ifndef INADDR_NONE
2414 #define INADDR_NONE (-1)
2415 #endif
2417 /* Have to use inet_addr() instead */
2418 char *ip_addr;
2419 unsigned long packed_addr;
2421 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) {
2422 return NULL;
2424 #ifdef USE_GUSI1
2425 packed_addr = inet_addr(ip_addr).s_addr;
2426 #else
2427 packed_addr = inet_addr(ip_addr);
2428 #endif
2430 if (packed_addr == INADDR_NONE) { /* invalid address */
2431 PyErr_SetString(PySocket_Error,
2432 "illegal IP address string passed to inet_aton");
2433 return NULL;
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";
2445 static PyObject*
2446 PySocket_inet_ntoa(PyObject *self, PyObject *args)
2448 char *packed_str;
2449 int addr_len;
2450 struct in_addr packed_addr;
2452 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
2453 return NULL;
2456 if (addr_len != sizeof(packed_addr)) {
2457 PyErr_SetString(PySocket_Error,
2458 "packed IP wrong length for inet_ntoa");
2459 return NULL;
2462 memcpy(&packed_addr, packed_str, addr_len);
2464 return PyString_FromString(inet_ntoa(packed_addr));
2467 /* Python interface to getaddrinfo(host, port). */
2469 /*ARGSUSED*/
2470 static PyObject *
2471 PySocket_getaddrinfo(PyObject *self, PyObject *args)
2473 struct addrinfo hints, *res;
2474 struct addrinfo *res0 = NULL;
2475 PyObject *pobj = (PyObject *)NULL;
2476 char pbuf[30];
2477 char *hptr, *pptr;
2478 int family, socktype, protocol, flags;
2479 int error;
2480 PyObject *all = (PyObject *)NULL;
2481 PyObject *single = (PyObject *)NULL;
2483 family = socktype = protocol = flags = 0;
2484 family = PF_UNSPEC;
2485 if (!PyArg_ParseTuple(args, "zO|iiii:getaddrinfo",
2486 &hptr, &pobj, &family, &socktype,
2487 &protocol, &flags)) {
2488 return NULL;
2490 if (PyInt_Check(pobj)) {
2491 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
2492 pptr = pbuf;
2493 } else if (PyString_Check(pobj)) {
2494 pptr = PyString_AsString(pobj);
2495 } else if (pobj == Py_None) {
2496 pptr = (char *)NULL;
2497 } else {
2498 PyErr_SetString(PySocket_Error, "Int or String expected");
2499 return NULL;
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);
2507 if (error) {
2508 PyGAI_Err(error);
2509 return NULL;
2512 if ((all = PyList_New(0)) == NULL)
2513 goto err;
2514 for (res = res0; res; res = res->ai_next) {
2515 PyObject *addr =
2516 makesockaddr(-1, res->ai_addr, res->ai_addrlen);
2517 if (addr == NULL)
2518 goto err;
2519 single = Py_BuildValue("iiisO", res->ai_family,
2520 res->ai_socktype, res->ai_protocol,
2521 res->ai_canonname ? res->ai_canonname : "",
2522 addr);
2523 Py_DECREF(addr);
2524 if (single == NULL)
2525 goto err;
2527 if (PyList_Append(all, single))
2528 goto err;
2529 Py_XDECREF(single);
2531 return all;
2532 err:
2533 Py_XDECREF(single);
2534 Py_XDECREF(all);
2535 if (res0)
2536 freeaddrinfo(res0);
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). */
2548 /*ARGSUSED*/
2549 static PyObject *
2550 PySocket_getnameinfo(PyObject *self, PyObject *args)
2552 PyObject *sa = (PyObject *)NULL;
2553 int flags;
2554 char *hostp;
2555 int port, flowinfo, scope_id;
2556 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
2557 struct addrinfo hints, *res = NULL;
2558 int error;
2559 PyObject *ret = (PyObject *)NULL;
2561 flags = flowinfo = scope_id = 0;
2562 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
2563 return NULL;
2564 if (!PyArg_ParseTuple(sa, "si|ii", &hostp, &port, &flowinfo, &scope_id))
2565 return NULL;
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);
2571 if (error) {
2572 PyGAI_Err(error);
2573 goto fail;
2575 if (res->ai_next) {
2576 PyErr_SetString(PySocket_Error,
2577 "sockaddr resolved to multiple addresses");
2578 goto fail;
2580 switch (res->ai_family) {
2581 case AF_INET:
2583 char *t1;
2584 int t2;
2585 if (PyArg_ParseTuple(sa, "si", &t1, &t2) == 0) {
2586 PyErr_SetString(PySocket_Error,
2587 "IPv4 sockaddr must be 2 tuple");
2588 goto fail;
2590 break;
2592 #ifdef ENABLE_IPV6
2593 case AF_INET6:
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;
2599 break;
2601 #endif
2603 error = getnameinfo(res->ai_addr, res->ai_addrlen,
2604 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
2605 if (error) {
2606 PyGAI_Err(error);
2607 goto fail;
2609 ret = Py_BuildValue("ss", hbuf, pbuf);
2611 fail:
2612 if (res)
2613 freeaddrinfo(res);
2614 return ret;
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.
2627 #ifdef USE_SSL
2628 static PyObject *
2629 PySSL_SetError(SSL *ssl, int ret)
2631 PyObject *v, *n, *s;
2632 char *errstr;
2633 int err;
2635 assert(ret <= 0);
2637 err = SSL_get_error(ssl, ret);
2638 n = PyInt_FromLong(err);
2639 if (n == NULL)
2640 return NULL;
2641 v = PyTuple_New(2);
2642 if (v == NULL) {
2643 Py_DECREF(n);
2644 return NULL;
2647 switch (SSL_get_error(ssl, ret)) {
2648 case SSL_ERROR_ZERO_RETURN:
2649 errstr = "TLS/SSL connection has been closed";
2650 break;
2651 case SSL_ERROR_WANT_READ:
2652 errstr = "The operation did not complete (read)";
2653 break;
2654 case SSL_ERROR_WANT_WRITE:
2655 errstr = "The operation did not complete (write)";
2656 break;
2657 case SSL_ERROR_WANT_X509_LOOKUP:
2658 errstr = "The operation did not complete (X509 lookup)";
2659 break;
2660 case SSL_ERROR_SYSCALL:
2661 case SSL_ERROR_SSL:
2663 unsigned long e = ERR_get_error();
2664 if (e == 0) {
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 */
2669 Py_DECREF(v);
2670 Py_DECREF(n);
2671 return PySocket_Err();
2672 } else {
2673 /* XXX Protected by global interpreter lock */
2674 errstr = ERR_error_string(e, NULL);
2676 break;
2678 default:
2679 errstr = "Invalid error code";
2681 s = PyString_FromString(errstr);
2682 if (s == NULL) {
2683 Py_DECREF(v);
2684 Py_DECREF(n);
2686 PyTuple_SET_ITEM(v, 0, n);
2687 PyTuple_SET_ITEM(v, 1, s);
2688 PyErr_SetObject(PySSLErrorObject, v);
2689 return NULL;
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)
2696 PySSLObject *self;
2697 char *errstr = NULL;
2698 int ret;
2700 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
2701 if (self == NULL){
2702 errstr = "newPySSLObject error";
2703 goto fail;
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;
2708 self->ssl = NULL;
2709 self->ctx = 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";
2714 goto fail;
2717 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
2718 if (self->ctx == NULL) {
2719 errstr = "SSL_CTX_new error";
2720 goto fail;
2723 if (key_file) {
2724 if (SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
2725 SSL_FILETYPE_PEM) < 1) {
2726 errstr = "SSL_CTX_use_PrivateKey_file error";
2727 goto fail;
2730 if (SSL_CTX_use_certificate_chain_file(self->ctx,
2731 cert_file) < 1) {
2732 errstr = "SSL_CTX_use_certificate_chain_file error";
2733 goto fail;
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);
2746 if (ret <= 0) {
2747 PySSL_SetError(self->ssl, ret);
2748 goto fail;
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);
2760 return self;
2761 fail:
2762 if (errstr)
2763 PyErr_SetString(PySSLErrorObject, errstr);
2764 Py_DECREF(self);
2765 return NULL;
2768 /* This is the Python function called for new object initialization */
2769 static PyObject *
2770 PySocket_ssl(PyObject *self, PyObject *args)
2772 PySSLObject *rv;
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))
2780 return NULL;
2782 rv = newPySSLObject(Sock, key_file, cert_file);
2783 if (rv == NULL)
2784 return NULL;
2785 return (PyObject *)rv;
2788 static char ssl_doc[] =
2789 "ssl(socket, [keyfile, certfile]) -> sslobject";
2791 /* SSL object methods */
2793 static PyObject *
2794 PySSL_server(PySSLObject *self)
2796 return PyString_FromString(self->server);
2799 static PyObject *
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);
2810 if (self->ssl)
2811 SSL_free(self->ssl);
2812 if (self->ctx)
2813 SSL_CTX_free(self->ctx);
2814 Py_XDECREF(self->Socket);
2815 PyObject_Del(self);
2818 static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
2820 char *data;
2821 int len;
2823 if (!PyArg_ParseTuple(args, "s#:write", &data, &len))
2824 return NULL;
2826 Py_BEGIN_ALLOW_THREADS
2827 len = SSL_write(self->ssl, data, len);
2828 Py_END_ALLOW_THREADS
2829 if (len > 0)
2830 return PyInt_FromLong(len);
2831 else
2832 return PySSL_SetError(self->ssl, len);
2835 static char PySSL_SSLwrite_doc[] =
2836 "write(s) -> len\n\
2838 Writes the string s into the SSL object. Returns the number\n\
2839 of bytes written.";
2841 static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
2843 PyObject *buf;
2844 int count = 0;
2845 int len = 1024;
2847 if (!PyArg_ParseTuple(args, "|i:read", &len))
2848 return NULL;
2850 if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
2851 return NULL;
2853 Py_BEGIN_ALLOW_THREADS
2854 count = SSL_read(self->ssl, PyString_AsString(buf), len);
2855 Py_END_ALLOW_THREADS
2856 if (count <= 0) {
2857 Py_DECREF(buf);
2858 return PySSL_SetError(self->ssl, count);
2860 if (count != len && _PyString_Resize(&buf, count) < 0)
2861 return NULL;
2862 return buf;
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,
2874 PySSL_SSLread_doc},
2875 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
2876 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
2877 {NULL, NULL}
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)
2887 0, /*ob_size*/
2888 "_socket.SSL", /*tp_name*/
2889 sizeof(PySSLObject), /*tp_basicsize*/
2890 0, /*tp_itemsize*/
2891 /* methods */
2892 (destructor)PySSL_dealloc, /*tp_dealloc*/
2893 0, /*tp_print*/
2894 (getattrfunc)PySSL_getattr, /*tp_getattr*/
2895 0, /*tp_setattr*/
2896 0, /*tp_compare*/
2897 0, /*tp_repr*/
2898 0, /*tp_as_number*/
2899 0, /*tp_as_sequence*/
2900 0, /*tp_as_mapping*/
2901 0, /*tp_hash*/
2904 /* helper routines for seeding the SSL PRNG */
2905 static PyObject *
2906 PySSL_RAND_add(PyObject *self, PyObject *args)
2908 char *buf;
2909 int len;
2910 double entropy;
2912 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
2913 return NULL;
2914 RAND_add(buf, len, entropy);
2915 Py_INCREF(Py_None);
2916 return Py_None;
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.";
2925 static PyObject *
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.";
2938 static PyObject *
2939 PySSL_RAND_egd(PyObject *self, PyObject *arg)
2941 int bytes;
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));
2948 if (bytes == -1) {
2949 PyErr_SetString(PySSLErrorObject,
2950 "EGD connection failed or EGD did not return "
2951 "enough data to seed the PRNG");
2952 return NULL;
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},
2982 #ifndef NO_DUP
2983 {"fromfd", PySocket_fromfd,
2984 METH_VARARGS, fromfd_doc},
2985 #endif
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},
3002 #ifdef USE_SSL
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...
3020 static void
3021 insint(PyObject *d, char *name, int value)
3023 PyObject *v = PyInt_FromLong((long) value);
3024 if (!v || PyDict_SetItemString(d, name, v))
3025 PyErr_Clear();
3027 Py_XDECREF(v);
3031 #ifdef MS_WINDOWS
3033 /* Additional initialization and cleanup for NT/Windows */
3035 static void
3036 NTcleanup(void)
3038 WSACleanup();
3041 static int
3042 NTinit(void)
3044 WSADATA WSAData;
3045 int ret;
3046 char buf[100];
3047 ret = WSAStartup(0x0101, &WSAData);
3048 switch (ret) {
3049 case 0: /* no error */
3050 atexit(NTcleanup);
3051 return 1;
3052 case WSASYSNOTREADY:
3053 PyErr_SetString(PyExc_ImportError,
3054 "WSAStartup failed: network not ready");
3055 break;
3056 case WSAVERNOTSUPPORTED:
3057 case WSAEINVAL:
3058 PyErr_SetString(PyExc_ImportError,
3059 "WSAStartup failed: requested version not supported");
3060 break;
3061 default:
3062 PyOS_snprintf(buf, sizeof(buf),
3063 "WSAStartup failed: error code %d", ret);
3064 PyErr_SetString(PyExc_ImportError, buf);
3065 break;
3067 return 0;
3070 #endif /* MS_WINDOWS */
3072 #if defined(PYOS_OS2)
3074 /* Additional initialization and cleanup for OS/2 */
3076 static void
3077 OS2cleanup(void)
3079 /* No cleanup is necessary for OS/2 Sockets */
3082 static int
3083 OS2init(void)
3085 char reason[64];
3086 int rc = sock_init();
3088 if (rc == 0) {
3089 atexit(OS2cleanup);
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
3105 * defined.
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.";
3125 DL_EXPORT(void)
3126 init_socket(void)
3128 PyObject *m, *d;
3129 #ifdef RISCOS
3130 _kernel_swi_regs r;
3131 r.r[0]=0;
3132 _kernel_swi(0x43380, &r, &r);
3133 taskwindow = r.r[0];
3134 #else
3135 #ifdef MS_WINDOWS
3136 if (!NTinit())
3137 return;
3138 #else
3139 #if defined(__TOS_OS2__)
3140 if (!OS2init())
3141 return;
3142 #endif /* __TOS_OS2__ */
3143 #endif /* MS_WINDOWS */
3144 #endif /* RISCOS */
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;
3149 #ifdef USE_SSL
3150 PySSL_Type.ob_type = &PyType_Type;
3151 #endif
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)
3156 return;
3157 PyDict_SetItemString(d, "error", PySocket_Error);
3158 PyH_Error = PyErr_NewException("socket.herror", PySocket_Error, NULL);
3159 if (PyH_Error == NULL)
3160 return;
3161 PyDict_SetItemString(d, "herror", PyH_Error);
3162 PyGAI_Error = PyErr_NewException("socket.gaierror", PySocket_Error,
3163 NULL);
3164 if (PyGAI_Error == NULL)
3165 return;
3166 PyDict_SetItemString(d, "gaierror", PyGAI_Error);
3167 #ifdef USE_SSL
3168 SSL_load_error_strings();
3169 SSLeay_add_ssl_algorithms();
3170 PySSLErrorObject = PyErr_NewException("socket.sslerror", NULL, NULL);
3171 if (PySSLErrorObject == NULL)
3172 return;
3173 PyDict_SetItemString(d, "sslerror", PySSLErrorObject);
3174 if (PyDict_SetItemString(d, "SSLType",
3175 (PyObject *)&PySSL_Type) != 0)
3176 return;
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",
3186 SSL_ERROR_SYSCALL);
3187 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3188 SSL_ERROR_SSL);
3189 #endif /* USE_SSL */
3190 if (PyDict_SetItemString(d, "SocketType",
3191 (PyObject *)&PySocketSock_Type) != 0)
3192 return;
3193 if (PyDict_SetItemString(d, "socket",
3194 (PyObject *)&PySocketSock_Type) != 0)
3195 return;
3197 /* Address families (we only support AF_INET and AF_UNIX) */
3198 #ifdef AF_UNSPEC
3199 insint(d, "AF_UNSPEC", AF_UNSPEC);
3200 #endif
3201 insint(d, "AF_INET", AF_INET);
3202 #ifdef AF_INET6
3203 insint(d, "AF_INET6", AF_INET6);
3204 #endif /* AF_INET6 */
3205 #ifdef AF_UNIX
3206 insint(d, "AF_UNIX", AF_UNIX);
3207 #endif /* AF_UNIX */
3208 #ifdef AF_AX25
3209 insint(d, "AF_AX25", AF_AX25); /* Amateur Radio AX.25 */
3210 #endif
3211 #ifdef AF_IPX
3212 insint(d, "AF_IPX", AF_IPX); /* Novell IPX */
3213 #endif
3214 #ifdef AF_APPLETALK
3215 insint(d, "AF_APPLETALK", AF_APPLETALK); /* Appletalk DDP */
3216 #endif
3217 #ifdef AF_NETROM
3218 insint(d, "AF_NETROM", AF_NETROM); /* Amateur radio NetROM */
3219 #endif
3220 #ifdef AF_BRIDGE
3221 insint(d, "AF_BRIDGE", AF_BRIDGE); /* Multiprotocol bridge */
3222 #endif
3223 #ifdef AF_AAL5
3224 insint(d, "AF_AAL5", AF_AAL5); /* Reserved for Werner's ATM */
3225 #endif
3226 #ifdef AF_X25
3227 insint(d, "AF_X25", AF_X25); /* Reserved for X.25 project */
3228 #endif
3229 #ifdef AF_INET6
3230 insint(d, "AF_INET6", AF_INET6); /* IP version 6 */
3231 #endif
3232 #ifdef AF_ROSE
3233 insint(d, "AF_ROSE", AF_ROSE); /* Amateur Radio X.25 PLP */
3234 #endif
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);
3245 #endif
3247 /* Socket types */
3248 insint(d, "SOCK_STREAM", SOCK_STREAM);
3249 insint(d, "SOCK_DGRAM", SOCK_DGRAM);
3250 #ifndef __BEOS__
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);
3255 #endif
3257 #ifdef SO_DEBUG
3258 insint(d, "SO_DEBUG", SO_DEBUG);
3259 #endif
3260 #ifdef SO_ACCEPTCONN
3261 insint(d, "SO_ACCEPTCONN", SO_ACCEPTCONN);
3262 #endif
3263 #ifdef SO_REUSEADDR
3264 insint(d, "SO_REUSEADDR", SO_REUSEADDR);
3265 #endif
3266 #ifdef SO_KEEPALIVE
3267 insint(d, "SO_KEEPALIVE", SO_KEEPALIVE);
3268 #endif
3269 #ifdef SO_DONTROUTE
3270 insint(d, "SO_DONTROUTE", SO_DONTROUTE);
3271 #endif
3272 #ifdef SO_BROADCAST
3273 insint(d, "SO_BROADCAST", SO_BROADCAST);
3274 #endif
3275 #ifdef SO_USELOOPBACK
3276 insint(d, "SO_USELOOPBACK", SO_USELOOPBACK);
3277 #endif
3278 #ifdef SO_LINGER
3279 insint(d, "SO_LINGER", SO_LINGER);
3280 #endif
3281 #ifdef SO_OOBINLINE
3282 insint(d, "SO_OOBINLINE", SO_OOBINLINE);
3283 #endif
3284 #ifdef SO_REUSEPORT
3285 insint(d, "SO_REUSEPORT", SO_REUSEPORT);
3286 #endif
3287 #ifdef SO_SNDBUF
3288 insint(d, "SO_SNDBUF", SO_SNDBUF);
3289 #endif
3290 #ifdef SO_RCVBUF
3291 insint(d, "SO_RCVBUF", SO_RCVBUF);
3292 #endif
3293 #ifdef SO_SNDLOWAT
3294 insint(d, "SO_SNDLOWAT", SO_SNDLOWAT);
3295 #endif
3296 #ifdef SO_RCVLOWAT
3297 insint(d, "SO_RCVLOWAT", SO_RCVLOWAT);
3298 #endif
3299 #ifdef SO_SNDTIMEO
3300 insint(d, "SO_SNDTIMEO", SO_SNDTIMEO);
3301 #endif
3302 #ifdef SO_RCVTIMEO
3303 insint(d, "SO_RCVTIMEO", SO_RCVTIMEO);
3304 #endif
3305 #ifdef SO_ERROR
3306 insint(d, "SO_ERROR", SO_ERROR);
3307 #endif
3308 #ifdef SO_TYPE
3309 insint(d, "SO_TYPE", SO_TYPE);
3310 #endif
3312 /* Maximum number of connections for "listen" */
3313 #ifdef SOMAXCONN
3314 insint(d, "SOMAXCONN", SOMAXCONN);
3315 #else
3316 insint(d, "SOMAXCONN", 5); /* Common value */
3317 #endif
3319 /* Flags for send, recv */
3320 #ifdef MSG_OOB
3321 insint(d, "MSG_OOB", MSG_OOB);
3322 #endif
3323 #ifdef MSG_PEEK
3324 insint(d, "MSG_PEEK", MSG_PEEK);
3325 #endif
3326 #ifdef MSG_DONTROUTE
3327 insint(d, "MSG_DONTROUTE", MSG_DONTROUTE);
3328 #endif
3329 #ifdef MSG_DONTWAIT
3330 insint(d, "MSG_DONTWAIT", MSG_DONTWAIT);
3331 #endif
3332 #ifdef MSG_EOR
3333 insint(d, "MSG_EOR", MSG_EOR);
3334 #endif
3335 #ifdef MSG_TRUNC
3336 insint(d, "MSG_TRUNC", MSG_TRUNC);
3337 #endif
3338 #ifdef MSG_CTRUNC
3339 insint(d, "MSG_CTRUNC", MSG_CTRUNC);
3340 #endif
3341 #ifdef MSG_WAITALL
3342 insint(d, "MSG_WAITALL", MSG_WAITALL);
3343 #endif
3344 #ifdef MSG_BTAG
3345 insint(d, "MSG_BTAG", MSG_BTAG);
3346 #endif
3347 #ifdef MSG_ETAG
3348 insint(d, "MSG_ETAG", MSG_ETAG);
3349 #endif
3351 /* Protocol level and numbers, usable for [gs]etsockopt */
3352 #ifdef SOL_SOCKET
3353 insint(d, "SOL_SOCKET", SOL_SOCKET);
3354 #endif
3355 #ifdef SOL_IP
3356 insint(d, "SOL_IP", SOL_IP);
3357 #else
3358 insint(d, "SOL_IP", 0);
3359 #endif
3360 #ifdef SOL_IPX
3361 insint(d, "SOL_IPX", SOL_IPX);
3362 #endif
3363 #ifdef SOL_AX25
3364 insint(d, "SOL_AX25", SOL_AX25);
3365 #endif
3366 #ifdef SOL_ATALK
3367 insint(d, "SOL_ATALK", SOL_ATALK);
3368 #endif
3369 #ifdef SOL_NETROM
3370 insint(d, "SOL_NETROM", SOL_NETROM);
3371 #endif
3372 #ifdef SOL_ROSE
3373 insint(d, "SOL_ROSE", SOL_ROSE);
3374 #endif
3375 #ifdef SOL_TCP
3376 insint(d, "SOL_TCP", SOL_TCP);
3377 #else
3378 insint(d, "SOL_TCP", 6);
3379 #endif
3380 #ifdef SOL_UDP
3381 insint(d, "SOL_UDP", SOL_UDP);
3382 #else
3383 insint(d, "SOL_UDP", 17);
3384 #endif
3385 #ifdef IPPROTO_IP
3386 insint(d, "IPPROTO_IP", IPPROTO_IP);
3387 #else
3388 insint(d, "IPPROTO_IP", 0);
3389 #endif
3390 #ifdef IPPROTO_HOPOPTS
3391 insint(d, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
3392 #endif
3393 #ifdef IPPROTO_ICMP
3394 insint(d, "IPPROTO_ICMP", IPPROTO_ICMP);
3395 #else
3396 insint(d, "IPPROTO_ICMP", 1);
3397 #endif
3398 #ifdef IPPROTO_IGMP
3399 insint(d, "IPPROTO_IGMP", IPPROTO_IGMP);
3400 #endif
3401 #ifdef IPPROTO_GGP
3402 insint(d, "IPPROTO_GGP", IPPROTO_GGP);
3403 #endif
3404 #ifdef IPPROTO_IPV4
3405 insint(d, "IPPROTO_IPV4", IPPROTO_IPV4);
3406 #endif
3407 #ifdef IPPROTO_IPIP
3408 insint(d, "IPPROTO_IPIP", IPPROTO_IPIP);
3409 #endif
3410 #ifdef IPPROTO_TCP
3411 insint(d, "IPPROTO_TCP", IPPROTO_TCP);
3412 #else
3413 insint(d, "IPPROTO_TCP", 6);
3414 #endif
3415 #ifdef IPPROTO_EGP
3416 insint(d, "IPPROTO_EGP", IPPROTO_EGP);
3417 #endif
3418 #ifdef IPPROTO_PUP
3419 insint(d, "IPPROTO_PUP", IPPROTO_PUP);
3420 #endif
3421 #ifdef IPPROTO_UDP
3422 insint(d, "IPPROTO_UDP", IPPROTO_UDP);
3423 #else
3424 insint(d, "IPPROTO_UDP", 17);
3425 #endif
3426 #ifdef IPPROTO_IDP
3427 insint(d, "IPPROTO_IDP", IPPROTO_IDP);
3428 #endif
3429 #ifdef IPPROTO_HELLO
3430 insint(d, "IPPROTO_HELLO", IPPROTO_HELLO);
3431 #endif
3432 #ifdef IPPROTO_ND
3433 insint(d, "IPPROTO_ND", IPPROTO_ND);
3434 #endif
3435 #ifdef IPPROTO_TP
3436 insint(d, "IPPROTO_TP", IPPROTO_TP);
3437 #endif
3438 #ifdef IPPROTO_IPV6
3439 insint(d, "IPPROTO_IPV6", IPPROTO_IPV6);
3440 #endif
3441 #ifdef IPPROTO_ROUTING
3442 insint(d, "IPPROTO_ROUTING", IPPROTO_ROUTING);
3443 #endif
3444 #ifdef IPPROTO_FRAGMENT
3445 insint(d, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
3446 #endif
3447 #ifdef IPPROTO_RSVP
3448 insint(d, "IPPROTO_RSVP", IPPROTO_RSVP);
3449 #endif
3450 #ifdef IPPROTO_GRE
3451 insint(d, "IPPROTO_GRE", IPPROTO_GRE);
3452 #endif
3453 #ifdef IPPROTO_ESP
3454 insint(d, "IPPROTO_ESP", IPPROTO_ESP);
3455 #endif
3456 #ifdef IPPROTO_AH
3457 insint(d, "IPPROTO_AH", IPPROTO_AH);
3458 #endif
3459 #ifdef IPPROTO_MOBILE
3460 insint(d, "IPPROTO_MOBILE", IPPROTO_MOBILE);
3461 #endif
3462 #ifdef IPPROTO_ICMPV6
3463 insint(d, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
3464 #endif
3465 #ifdef IPPROTO_NONE
3466 insint(d, "IPPROTO_NONE", IPPROTO_NONE);
3467 #endif
3468 #ifdef IPPROTO_DSTOPTS
3469 insint(d, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
3470 #endif
3471 #ifdef IPPROTO_XTP
3472 insint(d, "IPPROTO_XTP", IPPROTO_XTP);
3473 #endif
3474 #ifdef IPPROTO_EON
3475 insint(d, "IPPROTO_EON", IPPROTO_EON);
3476 #endif
3477 #ifdef IPPROTO_PIM
3478 insint(d, "IPPROTO_PIM", IPPROTO_PIM);
3479 #endif
3480 #ifdef IPPROTO_IPCOMP
3481 insint(d, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
3482 #endif
3483 #ifdef IPPROTO_VRRP
3484 insint(d, "IPPROTO_VRRP", IPPROTO_VRRP);
3485 #endif
3486 #ifdef IPPROTO_BIP
3487 insint(d, "IPPROTO_BIP", IPPROTO_BIP);
3488 #endif
3489 /**/
3490 #ifdef IPPROTO_RAW
3491 insint(d, "IPPROTO_RAW", IPPROTO_RAW);
3492 #else
3493 insint(d, "IPPROTO_RAW", 255);
3494 #endif
3495 #ifdef IPPROTO_MAX
3496 insint(d, "IPPROTO_MAX", IPPROTO_MAX);
3497 #endif
3499 /* Some port configuration */
3500 #ifdef IPPORT_RESERVED
3501 insint(d, "IPPORT_RESERVED", IPPORT_RESERVED);
3502 #else
3503 insint(d, "IPPORT_RESERVED", 1024);
3504 #endif
3505 #ifdef IPPORT_USERRESERVED
3506 insint(d, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
3507 #else
3508 insint(d, "IPPORT_USERRESERVED", 5000);
3509 #endif
3511 /* Some reserved IP v.4 addresses */
3512 #ifdef INADDR_ANY
3513 insint(d, "INADDR_ANY", INADDR_ANY);
3514 #else
3515 insint(d, "INADDR_ANY", 0x00000000);
3516 #endif
3517 #ifdef INADDR_BROADCAST
3518 insint(d, "INADDR_BROADCAST", INADDR_BROADCAST);
3519 #else
3520 insint(d, "INADDR_BROADCAST", 0xffffffff);
3521 #endif
3522 #ifdef INADDR_LOOPBACK
3523 insint(d, "INADDR_LOOPBACK", INADDR_LOOPBACK);
3524 #else
3525 insint(d, "INADDR_LOOPBACK", 0x7F000001);
3526 #endif
3527 #ifdef INADDR_UNSPEC_GROUP
3528 insint(d, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
3529 #else
3530 insint(d, "INADDR_UNSPEC_GROUP", 0xe0000000);
3531 #endif
3532 #ifdef INADDR_ALLHOSTS_GROUP
3533 insint(d, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP);
3534 #else
3535 insint(d, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
3536 #endif
3537 #ifdef INADDR_MAX_LOCAL_GROUP
3538 insint(d, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP);
3539 #else
3540 insint(d, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
3541 #endif
3542 #ifdef INADDR_NONE
3543 insint(d, "INADDR_NONE", INADDR_NONE);
3544 #else
3545 insint(d, "INADDR_NONE", 0xffffffff);
3546 #endif
3548 /* IPv4 [gs]etsockopt options */
3549 #ifdef IP_OPTIONS
3550 insint(d, "IP_OPTIONS", IP_OPTIONS);
3551 #endif
3552 #ifdef IP_HDRINCL
3553 insint(d, "IP_HDRINCL", IP_HDRINCL);
3554 #endif
3555 #ifdef IP_TOS
3556 insint(d, "IP_TOS", IP_TOS);
3557 #endif
3558 #ifdef IP_TTL
3559 insint(d, "IP_TTL", IP_TTL);
3560 #endif
3561 #ifdef IP_RECVOPTS
3562 insint(d, "IP_RECVOPTS", IP_RECVOPTS);
3563 #endif
3564 #ifdef IP_RECVRETOPTS
3565 insint(d, "IP_RECVRETOPTS", IP_RECVRETOPTS);
3566 #endif
3567 #ifdef IP_RECVDSTADDR
3568 insint(d, "IP_RECVDSTADDR", IP_RECVDSTADDR);
3569 #endif
3570 #ifdef IP_RETOPTS
3571 insint(d, "IP_RETOPTS", IP_RETOPTS);
3572 #endif
3573 #ifdef IP_MULTICAST_IF
3574 insint(d, "IP_MULTICAST_IF", IP_MULTICAST_IF);
3575 #endif
3576 #ifdef IP_MULTICAST_TTL
3577 insint(d, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
3578 #endif
3579 #ifdef IP_MULTICAST_LOOP
3580 insint(d, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
3581 #endif
3582 #ifdef IP_ADD_MEMBERSHIP
3583 insint(d, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
3584 #endif
3585 #ifdef IP_DROP_MEMBERSHIP
3586 insint(d, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
3587 #endif
3588 #ifdef IP_DEFAULT_MULTICAST_TTL
3589 insint(d, "IP_DEFAULT_MULTICAST_TTL", IP_DEFAULT_MULTICAST_TTL);
3590 #endif
3591 #ifdef IP_DEFAULT_MULTICAST_LOOP
3592 insint(d, "IP_DEFAULT_MULTICAST_LOOP", IP_DEFAULT_MULTICAST_LOOP);
3593 #endif
3594 #ifdef IP_MAX_MEMBERSHIPS
3595 insint(d, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
3596 #endif
3598 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
3599 #ifdef IPV6_JOIN_GROUP
3600 insint(d, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
3601 #endif
3602 #ifdef IPV6_LEAVE_GROUP
3603 insint(d, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
3604 #endif
3605 #ifdef IPV6_MULTICAST_HOPS
3606 insint(d, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
3607 #endif
3608 #ifdef IPV6_MULTICAST_IF
3609 insint(d, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
3610 #endif
3611 #ifdef IPV6_MULTICAST_LOOP
3612 insint(d, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
3613 #endif
3614 #ifdef IPV6_UNICAST_HOPS
3615 insint(d, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
3616 #endif
3618 /* TCP options */
3619 #ifdef TCP_NODELAY
3620 insint(d, "TCP_NODELAY", TCP_NODELAY);
3621 #endif
3622 #ifdef TCP_MAXSEG
3623 insint(d, "TCP_MAXSEG", TCP_MAXSEG);
3624 #endif
3625 #ifdef TCP_CORK
3626 insint(d, "TCP_CORK", TCP_CORK);
3627 #endif
3628 #ifdef TCP_KEEPIDLE
3629 insint(d, "TCP_KEEPIDLE", TCP_KEEPIDLE);
3630 #endif
3631 #ifdef TCP_KEEPINTVL
3632 insint(d, "TCP_KEEPINTVL", TCP_KEEPINTVL);
3633 #endif
3634 #ifdef TCP_KEEPCNT
3635 insint(d, "TCP_KEEPCNT", TCP_KEEPCNT);
3636 #endif
3637 #ifdef TCP_SYNCNT
3638 insint(d, "TCP_SYNCNT", TCP_SYNCNT);
3639 #endif
3640 #ifdef TCP_LINGER2
3641 insint(d, "TCP_LINGER2", TCP_LINGER2);
3642 #endif
3643 #ifdef TCP_DEFER_ACCEPT
3644 insint(d, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
3645 #endif
3646 #ifdef TCP_WINDOW_CLAMP
3647 insint(d, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
3648 #endif
3649 #ifdef TCP_INFO
3650 insint(d, "TCP_INFO", TCP_INFO);
3651 #endif
3652 #ifdef TCP_QUICKACK
3653 insint(d, "TCP_QUICKACK", TCP_QUICKACK);
3654 #endif
3657 /* IPX options */
3658 #ifdef IPX_TYPE
3659 insint(d, "IPX_TYPE", IPX_TYPE);
3660 #endif
3662 /* get{addr,name}info parameters */
3663 #ifdef EAI_ADDRFAMILY
3664 insint(d, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
3665 #endif
3666 #ifdef EAI_AGAIN
3667 insint(d, "EAI_AGAIN", EAI_AGAIN);
3668 #endif
3669 #ifdef EAI_BADFLAGS
3670 insint(d, "EAI_BADFLAGS", EAI_BADFLAGS);
3671 #endif
3672 #ifdef EAI_FAIL
3673 insint(d, "EAI_FAIL", EAI_FAIL);
3674 #endif
3675 #ifdef EAI_FAMILY
3676 insint(d, "EAI_FAMILY", EAI_FAMILY);
3677 #endif
3678 #ifdef EAI_MEMORY
3679 insint(d, "EAI_MEMORY", EAI_MEMORY);
3680 #endif
3681 #ifdef EAI_NODATA
3682 insint(d, "EAI_NODATA", EAI_NODATA);
3683 #endif
3684 #ifdef EAI_NONAME
3685 insint(d, "EAI_NONAME", EAI_NONAME);
3686 #endif
3687 #ifdef EAI_SERVICE
3688 insint(d, "EAI_SERVICE", EAI_SERVICE);
3689 #endif
3690 #ifdef EAI_SOCKTYPE
3691 insint(d, "EAI_SOCKTYPE", EAI_SOCKTYPE);
3692 #endif
3693 #ifdef EAI_SYSTEM
3694 insint(d, "EAI_SYSTEM", EAI_SYSTEM);
3695 #endif
3696 #ifdef EAI_BADHINTS
3697 insint(d, "EAI_BADHINTS", EAI_BADHINTS);
3698 #endif
3699 #ifdef EAI_PROTOCOL
3700 insint(d, "EAI_PROTOCOL", EAI_PROTOCOL);
3701 #endif
3702 #ifdef EAI_MAX
3703 insint(d, "EAI_MAX", EAI_MAX);
3704 #endif
3705 #ifdef AI_PASSIVE
3706 insint(d, "AI_PASSIVE", AI_PASSIVE);
3707 #endif
3708 #ifdef AI_CANONNAME
3709 insint(d, "AI_CANONNAME", AI_CANONNAME);
3710 #endif
3711 #ifdef AI_NUMERICHOST
3712 insint(d, "AI_NUMERICHOST", AI_NUMERICHOST);
3713 #endif
3714 #ifdef AI_MASK
3715 insint(d, "AI_MASK", AI_MASK);
3716 #endif
3717 #ifdef AI_ALL
3718 insint(d, "AI_ALL", AI_ALL);
3719 #endif
3720 #ifdef AI_V4MAPPED_CFG
3721 insint(d, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
3722 #endif
3723 #ifdef AI_ADDRCONFIG
3724 insint(d, "AI_ADDRCONFIG", AI_ADDRCONFIG);
3725 #endif
3726 #ifdef AI_V4MAPPED
3727 insint(d, "AI_V4MAPPED", AI_V4MAPPED);
3728 #endif
3729 #ifdef AI_DEFAULT
3730 insint(d, "AI_DEFAULT", AI_DEFAULT);
3731 #endif
3732 #ifdef NI_MAXHOST
3733 insint(d, "NI_MAXHOST", NI_MAXHOST);
3734 #endif
3735 #ifdef NI_MAXSERV
3736 insint(d, "NI_MAXSERV", NI_MAXSERV);
3737 #endif
3738 #ifdef NI_NOFQDN
3739 insint(d, "NI_NOFQDN", NI_NOFQDN);
3740 #endif
3741 #ifdef NI_NUMERICHOST
3742 insint(d, "NI_NUMERICHOST", NI_NUMERICHOST);
3743 #endif
3744 #ifdef NI_NAMEREQD
3745 insint(d, "NI_NAMEREQD", NI_NAMEREQD);
3746 #endif
3747 #ifdef NI_NUMERICSERV
3748 insint(d, "NI_NUMERICSERV", NI_NUMERICSERV);
3749 #endif
3750 #ifdef NI_DGRAM
3751 insint(d, "NI_DGRAM", NI_DGRAM);
3752 #endif
3754 /* Initialize gethostbyname lock */
3755 #ifdef USE_GETHOSTBYNAME_LOCK
3756 gethostbyname_lock = PyThread_allocate_lock();
3757 #endif
3760 /* Simplistic emulation code for inet_pton that only works for IPv4 */
3761 #ifndef HAVE_INET_PTON
3762 int
3763 inet_pton (int af, const char *src, void *dst)
3765 if(af == AF_INET){
3766 long packed_addr;
3767 #ifdef USE_GUSI1
3768 packed_addr = (long)inet_addr(src).s_addr;
3769 #else
3770 packed_addr = inet_addr(src);
3771 #endif
3772 if (packed_addr == INADDR_NONE)
3773 return 0;
3774 memcpy(dst, &packed_addr, 4);
3775 return 1;
3777 /* Should set errno to EAFNOSUPPORT */
3778 return -1;
3781 const char *
3782 inet_ntop(int af, const void *src, char *dst, socklen_t size)
3784 if (af == AF_INET) {
3785 struct in_addr packed_addr;
3786 if (size < 16)
3787 /* Should set errno to ENOSPC. */
3788 return NULL;
3789 memcpy(&packed_addr, src, sizeof(packed_addr));
3790 return strncpy(dst, inet_ntoa(packed_addr), size);
3792 /* Should set errno to EAFNOSUPPORT */
3793 return NULL;
3795 #endif