home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Modules / socketmodule.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  68.8 KB  |  2,798 lines

  1. /* Socket module */
  2.  
  3. /* SSL support based on patches by Brian E Gallew and Laszlo Kovacs */
  4.  
  5. /*
  6. This module provides an interface to Berkeley socket IPC.
  7.  
  8. Limitations:
  9.  
  10. - only AF_INET and AF_UNIX address families are supported
  11. - no read/write operations (use send/recv or makefile instead)
  12. - additional restrictions apply on Windows
  13.  
  14. Module interface:
  15.  
  16. - socket.error: exception raised for socket specific errors
  17. - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
  18. - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
  19. - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
  20. - socket.getprotobyname(protocolname) --> protocol number
  21. - socket.getservbyname(servicename, protocolname) --> port number
  22. - socket.socket(family, type [, proto]) --> new socket object
  23. - socket.ntohs(16 bit value) --> new int object
  24. - socket.ntohl(32 bit value) --> new int object
  25. - socket.htons(16 bit value) --> new int object
  26. - socket.htonl(32 bit value) --> new int object
  27. - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
  28. - socket.inet_aton(IP address) -> 32-bit packed IP representation
  29. - socket.inet_ntoa(packed IP) -> IP address string
  30. - socket.ssl(socket, keyfile, certfile) -> new ssl object
  31. - an Internet socket address is a pair (hostname, port)
  32.   where hostname can be anything recognized by gethostbyname()
  33.   (including the dd.dd.dd.dd notation) and port is in host byte order
  34. - where a hostname is returned, the dd.dd.dd.dd notation is used
  35. - a UNIX domain socket address is a string specifying the pathname
  36.  
  37. Socket methods:
  38.  
  39. - s.accept() --> new socket object, sockaddr
  40. - s.bind(sockaddr) --> None
  41. - s.close() --> None
  42. - s.connect(sockaddr) --> None
  43. - s.connect_ex(sockaddr) --> 0 or errno (handy for e.g. async connect)
  44. - s.fileno() --> file descriptor
  45. - s.dup() --> same as socket.fromfd(os.dup(s.fileno(), ...)
  46. - s.getpeername() --> sockaddr
  47. - s.getsockname() --> sockaddr
  48. - s.getsockopt(level, optname[, buflen]) --> int or string
  49. - s.listen(backlog) --> None
  50. - s.makefile([mode[, bufsize]]) --> file object
  51. - s.recv(buflen [,flags]) --> string
  52. - s.recvfrom(buflen [,flags]) --> string, sockaddr
  53. - s.send(string [,flags]) --> nbytes
  54. - s.sendto(string, [flags,] sockaddr) --> nbytes
  55. - s.setblocking(0 | 1) --> None
  56. - s.setsockopt(level, optname, value) --> None
  57. - s.shutdown(how) --> None
  58. - repr(s) --> "<socket object, fd=%d, family=%d, type=%d, protocol=%d>"
  59.  
  60. */
  61.  
  62. #include "Python.h"
  63.  
  64. /* Hacks for gethostbyname_r().  On some non-Linux platforms, the configure
  65.    script doesn't get this right, so we hardcode some platform checks below.
  66.    On the other hand, not all Linux versions agree, so there the settings
  67.    computed by the configure script are needed! */
  68.  
  69. #ifndef linux
  70. #undef HAVE_GETHOSTBYNAME_R_3_ARG
  71. #undef HAVE_GETHOSTBYNAME_R_5_ARG
  72. #undef HAVE_GETHOSTBYNAME_R_6_ARG
  73. #endif
  74.  
  75. #ifndef WITH_THREAD
  76. #undef HAVE_GETHOSTBYNAME_R
  77. #endif
  78.  
  79. #ifdef HAVE_GETHOSTBYNAME_R
  80. #if defined(_AIX) || defined(__osf__)
  81. #define HAVE_GETHOSTBYNAME_R_3_ARG
  82. #elif defined(__sun__) || defined(__sgi)
  83. #define HAVE_GETHOSTBYNAME_R_5_ARG
  84. #elif defined(linux)
  85. /* Rely on the configure script */
  86. #else
  87. #undef HAVE_GETHOSTBYNAME_R
  88. #endif
  89. #endif
  90.  
  91. #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && !defined(MS_WINDOWS)
  92. #define USE_GETHOSTBYNAME_LOCK
  93. #endif
  94.  
  95. #ifdef USE_GETHOSTBYNAME_LOCK
  96. #include "pythread.h"
  97. #endif
  98.  
  99. #ifdef HAVE_SYS_PARAM_H
  100. #include <sys/param.h>
  101. #endif
  102.  
  103. #ifdef HAVE_UNISTD_H
  104. #include <unistd.h>
  105. #endif
  106.  
  107. #if defined(PYCC_VACPP)
  108. #include <types.h>
  109. #include <io.h>
  110. #include <sys/ioctl.h>
  111. #include <utils.h>
  112. #include <ctype.h>
  113. #endif
  114.  
  115. #if defined(PYOS_OS2)
  116. #define  INCL_DOS
  117. #define  INCL_DOSERRORS
  118. #define  INCL_NOPMAPI
  119. #include <os2.h>
  120. #endif
  121.  
  122. #include <sys/types.h>
  123.  
  124. #include <signal.h>
  125. #ifndef MS_WINDOWS
  126. #include <netdb.h>
  127. #include <sys/socket.h>
  128. #include <netinet/in.h>
  129. #if !(defined(__BEOS__) || defined(__CYGWIN__))
  130. #include <netinet/tcp.h>
  131. #endif
  132.  
  133. /* Headers needed for inet_ntoa() and inet_addr() */
  134. #ifdef __BEOS__
  135. #include <net/netdb.h>
  136. #else
  137. #ifndef USE_GUSI1
  138. #include <arpa/inet.h>
  139. #endif
  140. #endif
  141.  
  142. #include <fcntl.h>
  143. #else
  144. #include <winsock.h>
  145. #include <fcntl.h>
  146. #endif
  147. #if defined(AMITCP) || defined(INET225)
  148. #define SYS_TTYCHARS_H
  149. #include <sys/ioctl.h>
  150. #include <proto/socket.h>
  151. typedef LONG socklen_t;
  152. #endif
  153. #ifdef HAVE_SYS_UN_H
  154. #include <sys/un.h>
  155. #else
  156. #undef AF_UNIX
  157. #endif
  158.  
  159. #ifndef O_NDELAY
  160. #define O_NDELAY O_NONBLOCK    /* For QNX only? */
  161. #endif
  162.  
  163. #ifdef USE_GUSI1
  164. /* fdopen() isn't declared in stdio.h (sigh) */
  165. #include <GUSI.h>
  166. #endif
  167.  
  168. #ifdef USE_SSL
  169. #include "rsa.h"
  170. #include "crypto.h"
  171. #include "x509.h"
  172. #include "pem.h"
  173. #include "ssl.h"
  174. #include "err.h"
  175. #endif /* USE_SSL */
  176.  
  177. #if defined(MS_WINDOWS) || defined(__BEOS__)
  178. /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
  179. /* seem to be a few differences in the API */
  180. #define SOCKETCLOSE closesocket
  181. #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
  182. #endif
  183.  
  184. /* abstract the socket file descriptor type */
  185. #ifdef MS_WINDOWS
  186. typedef SOCKET SOCKET_T;
  187. #    ifdef MS_WIN64
  188. #        define SIZEOF_SOCKET_T 8
  189. #    else
  190. #        define SIZEOF_SOCKET_T 4
  191. #    endif
  192. #else
  193. typedef int SOCKET_T;
  194. #    define SIZEOF_SOCKET_T SIZEOF_INT
  195. #endif
  196.  
  197.  
  198. #if defined(PYOS_OS2)
  199. #define SOCKETCLOSE soclose
  200. #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
  201. #endif
  202.  
  203. #ifdef AMITCP
  204. /* seem to be a few differences in the API */
  205. //#define close CloseSocket
  206. #define ioctlsocket IoctlSocket
  207. #undef NO_DUP
  208. #undef AF_UNIX
  209. #endif
  210.  
  211. #ifdef INET225
  212. /* seem to be a few differences in the API */
  213. #define close s_close
  214. #define ioctlsocket s_ioctl
  215. #undef NO_DUP
  216. static __inline int dup(int oldsd) { return s_dup(oldsd); }
  217. #undef AF_UNIX
  218. #endif
  219.  
  220. #ifndef SOCKETCLOSE
  221. #define SOCKETCLOSE close
  222. #endif
  223.  
  224. /* Global variable holding the exception type for errors detected
  225.    by this module (but not argument type or memory errors, etc.). */
  226.  
  227. static PyObject *PySocket_Error;
  228.  
  229. #ifdef USE_SSL
  230. static PyObject *SSLErrorObject;
  231. #endif /* USE_SSL */
  232.  
  233.  
  234. /* Convenience function to raise an error according to errno
  235.    and return a NULL pointer from a function. */
  236.  
  237. static PyObject *
  238. PySocket_Err(void)
  239. {
  240. #ifdef MS_WINDOWS
  241.     int err_no = WSAGetLastError();
  242.     if (err_no) {
  243.         static struct { int no; const char *msg; } *msgp, msgs[] = {
  244.             { WSAEINTR, "Interrupted system call" },
  245.             { WSAEBADF, "Bad file descriptor" },
  246.             { WSAEACCES, "Permission denied" },
  247.             { WSAEFAULT, "Bad address" },
  248.             { WSAEINVAL, "Invalid argument" },
  249.             { WSAEMFILE, "Too many open files" },
  250.             { WSAEWOULDBLOCK, 
  251.                 "The socket operation could not complete "
  252.                 "without blocking" },
  253.             { WSAEINPROGRESS, "Operation now in progress" },
  254.             { WSAEALREADY, "Operation already in progress" },
  255.             { WSAENOTSOCK, "Socket operation on non-socket" },
  256.             { WSAEDESTADDRREQ, "Destination address required" },
  257.             { WSAEMSGSIZE, "Message too long" },
  258.             { WSAEPROTOTYPE, "Protocol wrong type for socket" },
  259.             { WSAENOPROTOOPT, "Protocol not available" },
  260.             { WSAEPROTONOSUPPORT, "Protocol not supported" },
  261.             { WSAESOCKTNOSUPPORT, "Socket type not supported" },
  262.             { WSAEOPNOTSUPP, "Operation not supported" },
  263.             { WSAEPFNOSUPPORT, "Protocol family not supported" },
  264.             { WSAEAFNOSUPPORT, "Address family not supported" },
  265.             { WSAEADDRINUSE, "Address already in use" },
  266.             { WSAEADDRNOTAVAIL,
  267.                 "Can't assign requested address" },
  268.             { WSAENETDOWN, "Network is down" },
  269.             { WSAENETUNREACH, "Network is unreachable" },
  270.             { WSAENETRESET, 
  271.                 "Network dropped connection on reset" },
  272.             { WSAECONNABORTED, 
  273.                 "Software caused connection abort" },
  274.             { WSAECONNRESET, "Connection reset by peer" },
  275.             { WSAENOBUFS, "No buffer space available" },
  276.             { WSAEISCONN, "Socket is already connected" },
  277.             { WSAENOTCONN, "Socket is not connected" },
  278.             { WSAESHUTDOWN, "Can't send after socket shutdown" },
  279.             { WSAETOOMANYREFS,
  280.                 "Too many references: can't splice" },
  281.             { WSAETIMEDOUT, "Operation timed out" },
  282.             { WSAECONNREFUSED, "Connection refused" },
  283.             { WSAELOOP, "Too many levels of symbolic links" },
  284.             { WSAENAMETOOLONG, "File name too long" },
  285.             { WSAEHOSTDOWN, "Host is down" },
  286.             { WSAEHOSTUNREACH, "No route to host" },
  287.             { WSAENOTEMPTY, "Directory not empty" },
  288.             { WSAEPROCLIM, "Too many processes" },
  289.             { WSAEUSERS, "Too many users" },
  290.             { WSAEDQUOT, "Disc quota exceeded" },
  291.             { WSAESTALE, "Stale NFS file handle" },
  292.             { WSAEREMOTE, "Too many levels of remote in path" },
  293.             { WSASYSNOTREADY,
  294.                 "Network subsystem is unvailable" },
  295.             { WSAVERNOTSUPPORTED,
  296.                 "WinSock version is not supported" },
  297.             { WSANOTINITIALISED, 
  298.                 "Successful WSAStartup() not yet performed" },
  299.             { WSAEDISCON, "Graceful shutdown in progress" },
  300.             /* Resolver errors */
  301.             { WSAHOST_NOT_FOUND, "No such host is known" },
  302.             { WSATRY_AGAIN, "Host not found, or server failed" },
  303.             { WSANO_RECOVERY,
  304.                 "Unexpected server error encountered" },
  305.             { WSANO_DATA, "Valid name without requested data" },
  306.             { WSANO_ADDRESS, "No address, look for MX record" },
  307.             { 0, NULL }
  308.         };
  309.         PyObject *v;
  310.         const char *msg = "winsock error";
  311.         
  312.         for (msgp = msgs; msgp->msg; msgp++) {
  313.             if (err_no == msgp->no) {
  314.                 msg = msgp->msg;
  315.                 break;
  316.             }
  317.         }
  318.  
  319.         v = Py_BuildValue("(is)", err_no, msg);
  320.         if (v != NULL) {
  321.             PyErr_SetObject(PySocket_Error, v);
  322.             Py_DECREF(v);
  323.         }
  324.         return NULL;
  325.     }
  326.     else
  327. #endif
  328.  
  329. #if defined(PYOS_OS2)
  330.     if (sock_errno() != NO_ERROR) {
  331.         APIRET rc;
  332.         ULONG  msglen;
  333.         char   outbuf[100];
  334.         int    myerrorcode = sock_errno();
  335.  
  336.         /* Retrieve Socket-Related Error Message from MPTN.MSG File */
  337.         rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
  338.                            myerrorcode - SOCBASEERR + 26, "mptn.msg", &msglen);
  339.         if (rc == NO_ERROR) {
  340.             PyObject *v;
  341.  
  342.             outbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
  343.             if (strlen(outbuf) > 0) { /* If Non-Empty Msg, Trim CRLF */
  344.                 char *lastc = &outbuf[ strlen(outbuf)-1 ];
  345.                 while (lastc > outbuf && isspace(*lastc))
  346.                     *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
  347.             }
  348.             v = Py_BuildValue("(is)", myerrorcode, outbuf);
  349.             if (v != NULL) {
  350.                 PyErr_SetObject(PySocket_Error, v);
  351.                 Py_DECREF(v);
  352.             }
  353.             return NULL;
  354.         }
  355.     }
  356. #endif
  357.  
  358.     return PyErr_SetFromErrno(PySocket_Error);
  359. }
  360.  
  361.  
  362. /* The object holding a socket.  It holds some extra information,
  363.    like the address family, which is used to decode socket address
  364.    arguments properly. */
  365.  
  366. typedef struct {
  367.     PyObject_HEAD
  368.     SOCKET_T sock_fd;        /* Socket file descriptor */
  369.     int sock_family;    /* Address family, e.g., AF_INET */
  370.     int sock_type;        /* Socket type, e.g., SOCK_STREAM */
  371.     int sock_proto;        /* Protocol type, usually 0 */
  372.     union sock_addr {
  373.         struct sockaddr_in in;
  374. #ifdef AF_UNIX
  375.         struct sockaddr_un un;
  376. #endif
  377.     } sock_addr;
  378. } PySocketSockObject;
  379.  
  380. #ifdef USE_SSL
  381.  
  382. typedef struct {
  383.     PyObject_HEAD
  384.     PySocketSockObject *Socket;    /* Socket on which we're layered */
  385.     PyObject     *x_attr;    /* Attributes dictionary */
  386.     SSL_CTX*     ctx;
  387.     SSL*         ssl;
  388.     X509*        server_cert;
  389.     BIO*        sbio;
  390.     char        server[256];
  391.     char        issuer[256];
  392.  
  393. } SSLObject;
  394.  
  395. staticforward PyTypeObject SSL_Type;
  396. staticforward PyObject *SSL_SSLwrite(SSLObject *self, PyObject *args);
  397. staticforward PyObject *SSL_SSLread(SSLObject *self, PyObject *args);
  398.  
  399. #define SSLObject_Check(v)    ((v)->ob_type == &SSL_Type)
  400.  
  401. #endif /* USE_SSL */
  402.  
  403. /* A forward reference to the Socktype type object.
  404.    The Socktype variable contains pointers to various functions,
  405.    some of which call newsockobject(), which uses Socktype, so
  406.    there has to be a circular reference. */
  407.  
  408. staticforward PyTypeObject PySocketSock_Type;
  409.  
  410.  
  411. /* Create a new socket object.
  412.    This just creates the object and initializes it.
  413.    If the creation fails, return NULL and set an exception (implicit
  414.    in NEWOBJ()). */
  415.  
  416. static PySocketSockObject *
  417. PySocketSock_New(SOCKET_T fd, int family, int type, int proto)
  418. {
  419.     PySocketSockObject *s;
  420.     PySocketSock_Type.ob_type = &PyType_Type;
  421.     s = PyObject_New(PySocketSockObject, &PySocketSock_Type);
  422.     if (s != NULL) {
  423.         s->sock_fd = fd;
  424.         s->sock_family = family;
  425.         s->sock_type = type;
  426.         s->sock_proto = proto;
  427. #if defined(AMITCP) || defined (INET225)
  428.         /* Amiga's TCP stacks want a zeroed out sock_addr structure */
  429.         memset(&s->sock_addr, 0, sizeof(s->sock_addr));
  430. #ifdef AMITCP
  431.         if(family==AF_INET) s->sock_addr.in.sin_len=sizeof(struct sockaddr_in);
  432. #ifdef AF_UNIX
  433.         if(family==AF_UNIX) s->sock_addr.un.sun_len=sizeof(struct sockaddr_un);
  434. #endif /* AF_UNIX */
  435. #endif /* AMITCP */
  436. #endif /* AMITCP || INET225 */
  437.     }
  438.     return s;
  439. }
  440.  
  441.  
  442. /* Lock to allow python interpreter to continue, but only allow one 
  443.    thread to be in gethostbyname */
  444. #ifdef USE_GETHOSTBYNAME_LOCK
  445. PyThread_type_lock gethostbyname_lock;
  446. #endif
  447.  
  448.  
  449. /* Convert a string specifying a host name or one of a few symbolic
  450.    names to a numeric IP address.  This usually calls gethostbyname()
  451.    to do the work; the names "" and "<broadcast>" are special.
  452.    Return the length (should always be 4 bytes), or negative if
  453.    an error occurred; then an exception is raised. */
  454.  
  455. static int
  456. setipaddr(char* name, struct sockaddr_in * addr_ret)
  457. {
  458.     struct hostent *hp;
  459.     int d1, d2, d3, d4;
  460.     int h_length;
  461.     char ch;
  462. #ifdef HAVE_GETHOSTBYNAME_R
  463.     struct hostent hp_allocated;
  464. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  465.     struct hostent_data data;
  466. #else
  467.     char buf[1001];
  468.     int buf_len = (sizeof buf) - 1;
  469.     int errnop;
  470. #endif
  471. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  472.     int result;
  473. #endif
  474. #endif /* HAVE_GETHOSTBYNAME_R */
  475.  
  476.     memset((void *) addr_ret, '\0', sizeof(*addr_ret));
  477.     if (name[0] == '\0') {
  478.         addr_ret->sin_addr.s_addr = INADDR_ANY;
  479.         return 4;
  480.     }
  481.     if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
  482.         addr_ret->sin_addr.s_addr = INADDR_BROADCAST;
  483.         return 4;
  484.     }
  485.     if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
  486.         0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
  487.         0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
  488.         addr_ret->sin_addr.s_addr = htonl(
  489.             ((long) d1 << 24) | ((long) d2 << 16) |
  490.             ((long) d3 << 8) | ((long) d4 << 0));
  491.         return 4;
  492.     }
  493.     Py_BEGIN_ALLOW_THREADS
  494. #ifdef HAVE_GETHOSTBYNAME_R
  495. #if    defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  496.     result = gethostbyname_r(name, &hp_allocated, buf, buf_len, &hp, &errnop);
  497. #elif  defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  498.     hp = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  499. #else  /* HAVE_GETHOSTBYNAME_R_3_ARG */
  500.     memset((void *) &data, '\0', sizeof(data));
  501.     result = gethostbyname_r(name, &hp_allocated, &data);
  502.     hp = (result != 0) ? NULL : &hp_allocated;
  503. #endif
  504. #else /* not HAVE_GETHOSTBYNAME_R */
  505. #ifdef USE_GETHOSTBYNAME_LOCK
  506.     PyThread_acquire_lock(gethostbyname_lock, 1);
  507. #endif
  508.     hp = gethostbyname(name);
  509. #endif /* HAVE_GETHOSTBYNAME_R */
  510.     Py_END_ALLOW_THREADS
  511.  
  512.     if (hp == NULL) {
  513. #ifdef HAVE_HSTRERROR
  514.             /* Let's get real error message to return */
  515.             extern int h_errno;
  516.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  517. #else
  518.         PyErr_SetString(PySocket_Error, "host not found");
  519. #endif
  520. #ifdef USE_GETHOSTBYNAME_LOCK
  521.         PyThread_release_lock(gethostbyname_lock);
  522. #endif
  523.         return -1;
  524.     }
  525.     memcpy((char *) &addr_ret->sin_addr, hp->h_addr, hp->h_length);
  526.     h_length = hp->h_length;
  527. #ifdef USE_GETHOSTBYNAME_LOCK
  528.     PyThread_release_lock(gethostbyname_lock);
  529. #endif
  530.     return h_length;
  531. }
  532.  
  533.  
  534. /* Create a string object representing an IP address.
  535.    This is always a string of the form 'dd.dd.dd.dd' (with variable
  536.    size numbers). */
  537.  
  538. static PyObject *
  539. makeipaddr(struct sockaddr_in *addr)
  540. {
  541.     long x = ntohl(addr->sin_addr.s_addr);
  542.     char buf[100];
  543.     sprintf(buf, "%d.%d.%d.%d",
  544.         (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
  545.         (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff);
  546.     return PyString_FromString(buf);
  547. }
  548.  
  549.  
  550. /* Create an object representing the given socket address,
  551.    suitable for passing it back to bind(), connect() etc.
  552.    The family field of the sockaddr structure is inspected
  553.    to determine what kind of address it really is. */
  554.  
  555. /*ARGSUSED*/
  556. static PyObject *
  557. makesockaddr(struct sockaddr *addr, int addrlen)
  558. {
  559.     if (addrlen == 0) {
  560.         /* No address -- may be recvfrom() from known socket */
  561.         Py_INCREF(Py_None);
  562.         return Py_None;
  563.     }
  564.  
  565. #ifdef __BEOS__
  566.     /* XXX: BeOS version of accept() doesn't set family correctly */
  567.     addr->sa_family = AF_INET;
  568. #endif
  569.  
  570.     switch (addr->sa_family) {
  571.  
  572.     case AF_INET:
  573.     {
  574.         struct sockaddr_in *a = (struct sockaddr_in *) addr;
  575.         PyObject *addrobj = makeipaddr(a);
  576.         PyObject *ret = NULL;
  577.         if (addrobj) {
  578.             ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
  579.             Py_DECREF(addrobj);
  580.         }
  581.         return ret;
  582.     }
  583.  
  584. #ifdef AF_UNIX
  585.     case AF_UNIX:
  586.     {
  587.         struct sockaddr_un *a = (struct sockaddr_un *) addr;
  588.         return PyString_FromString(a->sun_path);
  589.     }
  590. #endif /* AF_UNIX */
  591.  
  592.     /* More cases here... */
  593.  
  594.     default:
  595.         /* If we don't know the address family, don't raise an
  596.            exception -- return it as a tuple. */
  597.         return Py_BuildValue("is#",
  598.                      addr->sa_family,
  599.                      addr->sa_data,
  600.                      sizeof(addr->sa_data));
  601.  
  602.     }
  603. }
  604.  
  605.  
  606. /* Parse a socket address argument according to the socket object's
  607.    address family.  Return 1 if the address was in the proper format,
  608.    0 of not.  The address is returned through addr_ret, its length
  609.    through len_ret. */
  610.  
  611. static int
  612. getsockaddrarg(PySocketSockObject *s, PyObject *args, struct sockaddr **addr_ret, int *len_ret)
  613. {
  614.     switch (s->sock_family) {
  615.  
  616. #ifdef AF_UNIX
  617.     case AF_UNIX:
  618.     {
  619.         struct sockaddr_un* addr;
  620.         char *path;
  621.         int len;
  622.         addr = (struct sockaddr_un* )&(s->sock_addr).un;
  623.         if (!PyArg_Parse(args, "t#", &path, &len))
  624.             return 0;
  625.         if (len > sizeof addr->sun_path) {
  626.             PyErr_SetString(PySocket_Error,
  627.                     "AF_UNIX path too long");
  628.             return 0;
  629.         }
  630.         addr->sun_family = AF_UNIX;
  631.         memcpy(addr->sun_path, path, len);
  632.         addr->sun_path[len] = 0;
  633.         *addr_ret = (struct sockaddr *) addr;
  634.         *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
  635.         return 1;
  636.     }
  637. #endif /* AF_UNIX */
  638.  
  639.     case AF_INET:
  640.     {
  641.         struct sockaddr_in* addr;
  642.         char *host;
  643.         int port;
  644.          addr=(struct sockaddr_in*)&(s->sock_addr).in;
  645.         if (!PyArg_Parse(args, "(si)", &host, &port))
  646.             return 0;
  647.         if (setipaddr(host, addr) < 0)
  648.             return 0;
  649.         addr->sin_family = AF_INET;
  650.         addr->sin_port = htons((short)port);
  651.         *addr_ret = (struct sockaddr *) addr;
  652.         *len_ret = sizeof *addr;
  653.         return 1;
  654.     }
  655.  
  656.     /* More cases here... */
  657.  
  658.     default:
  659.         PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
  660.         return 0;
  661.  
  662.     }
  663. }
  664.  
  665.  
  666. /* Get the address length according to the socket object's address family. 
  667.    Return 1 if the family is known, 0 otherwise.  The length is returned
  668.    through len_ret. */
  669.  
  670. static int
  671. getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
  672. {
  673.     switch (s->sock_family) {
  674.  
  675. #ifdef AF_UNIX
  676.     case AF_UNIX:
  677.     {
  678.         *len_ret = sizeof (struct sockaddr_un);
  679.         return 1;
  680.     }
  681. #endif /* AF_UNIX */
  682.  
  683.     case AF_INET:
  684.     {
  685.         *len_ret = sizeof (struct sockaddr_in);
  686.         return 1;
  687.     }
  688.  
  689.     /* More cases here... */
  690.  
  691.     default:
  692.         PyErr_SetString(PySocket_Error, "getsockaddrlen: bad family");
  693.         return 0;
  694.  
  695.     }
  696. }
  697.  
  698.  
  699. /* s.accept() method */
  700.  
  701. static PyObject *
  702. PySocketSock_accept(PySocketSockObject *s, PyObject *args)
  703. {
  704.     char addrbuf[256];
  705.     SOCKET_T newfd;
  706.     socklen_t addrlen;
  707.     PyObject *sock = NULL;
  708.     PyObject *addr = NULL;
  709.     PyObject *res = NULL;
  710.  
  711.     if (!PyArg_ParseTuple(args, ":accept"))
  712.         return NULL;
  713.     if (!getsockaddrlen(s, &addrlen))
  714.         return NULL;
  715.     Py_BEGIN_ALLOW_THREADS
  716.     newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  717.     Py_END_ALLOW_THREADS
  718. #ifdef MS_WINDOWS
  719.     if (newfd == INVALID_SOCKET)
  720. #else
  721.     if (newfd < 0)
  722. #endif
  723.         return PySocket_Err();
  724.  
  725.     /* Create the new object with unspecified family,
  726.        to avoid calls to bind() etc. on it. */
  727.     sock = (PyObject *) PySocketSock_New(newfd,
  728.                     s->sock_family,
  729.                     s->sock_type,
  730.                     s->sock_proto);
  731.     if (sock == NULL) {
  732.         SOCKETCLOSE(newfd);
  733.         goto finally;
  734.     }
  735.     if (!(addr = makesockaddr((struct sockaddr *) addrbuf, addrlen)))
  736.         goto finally;
  737.  
  738.     if (!(res = Py_BuildValue("OO", sock, addr)))
  739.         goto finally;
  740.  
  741.   finally:
  742.     Py_XDECREF(sock);
  743.     Py_XDECREF(addr);
  744.     return res;
  745. }
  746.  
  747. static char accept_doc[] =
  748. "accept() -> (socket object, address info)\n\
  749. \n\
  750. Wait for an incoming connection.  Return a new socket representing the\n\
  751. connection, and the address of the client.  For IP sockets, the address\n\
  752. info is a pair (hostaddr, port).";
  753.  
  754.  
  755. /* s.setblocking(1 | 0) method */
  756.  
  757. static PyObject *
  758. PySocketSock_setblocking(PySocketSockObject *s, PyObject *args)
  759. {
  760.     int block;
  761. #ifndef MS_WINDOWS
  762.     int delay_flag;
  763. #endif
  764.     if (!PyArg_ParseTuple(args, "i:setblocking", &block))
  765.         return NULL;
  766.     Py_BEGIN_ALLOW_THREADS
  767. #ifdef __BEOS__
  768.     block = !block;
  769.     setsockopt( s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
  770.                 (void *)(&block), sizeof( int ) );
  771. #else
  772. #ifndef MS_WINDOWS
  773. #ifdef PYOS_OS2
  774.     block = !block;
  775.     ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
  776. #else /* !PYOS_OS2 */
  777.  #if defined(AMITCP) || defined (INET225)
  778.     block = !block;
  779.     ioctlsocket(s->sock_fd, FIONBIO, &block);
  780.  #else
  781.     delay_flag = fcntl (s->sock_fd, F_GETFL, 0);
  782.     if (block)
  783.         delay_flag &= (~O_NDELAY);
  784.     else
  785.         delay_flag |= O_NDELAY;
  786.     fcntl (s->sock_fd, F_SETFL, delay_flag);
  787.  #endif /* !AMITCP || INET225 */
  788. #endif /* !PYOS_OS2 */
  789. #else /* MS_WINDOWS */
  790.     block = !block;
  791.     ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
  792. #endif /* MS_WINDOWS */
  793. #endif /* __BEOS__ */
  794.     Py_END_ALLOW_THREADS
  795.  
  796.     Py_INCREF(Py_None);
  797.     return Py_None;
  798. }
  799.  
  800. static char setblocking_doc[] =
  801. "setblocking(flag)\n\
  802. \n\
  803. Set the socket to blocking (flag is true) or non-blocking (false).\n\
  804. This uses the FIONBIO ioctl with the O_NDELAY flag.";
  805.  
  806.  
  807. /* s.setsockopt() method.
  808.    With an integer third argument, sets an integer option.
  809.    With a string third argument, sets an option from a buffer;
  810.    use optional built-in module 'struct' to encode the string. */
  811.  
  812. static PyObject *
  813. PySocketSock_setsockopt(PySocketSockObject *s, PyObject *args)
  814. {
  815.     int level;
  816.     int optname;
  817.     int res;
  818.     char *buf;
  819.     int buflen;
  820.     int flag;
  821.  
  822.     if (PyArg_ParseTuple(args, "iii:setsockopt",
  823.                  &level, &optname, &flag)) {
  824.         buf = (char *) &flag;
  825.         buflen = sizeof flag;
  826.     }
  827.     else {
  828.         PyErr_Clear();
  829.         if (!PyArg_ParseTuple(args, "iis#:setsockopt",
  830.                       &level, &optname, &buf, &buflen))
  831.             return NULL;
  832.     }
  833.     res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
  834.     if (res < 0)
  835.         return PySocket_Err();
  836.     Py_INCREF(Py_None);
  837.     return Py_None;
  838. }
  839.  
  840. static char setsockopt_doc[] =
  841. "setsockopt(level, option, value)\n\
  842. \n\
  843. Set a socket option.  See the Unix manual for level and option.\n\
  844. The value argument can either be an integer or a string.";
  845.  
  846.  
  847. /* s.getsockopt() method.
  848.    With two arguments, retrieves an integer option.
  849.    With a third integer argument, retrieves a string buffer of that size;
  850.    use optional built-in module 'struct' to decode the string. */
  851.  
  852. static PyObject *
  853. PySocketSock_getsockopt(PySocketSockObject *s, PyObject *args)
  854. {
  855.     int level;
  856.     int optname;
  857.     int res;
  858.     PyObject *buf;
  859.     socklen_t buflen = 0;
  860.  
  861. #ifdef __BEOS__
  862. /* We have incomplete socket support. */
  863.     PyErr_SetString( PySocket_Error, "getsockopt not supported" );
  864.     return NULL;
  865. #else
  866.  
  867.     if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
  868.                   &level, &optname, &buflen))
  869.         return NULL;
  870.     
  871.     if (buflen == 0) {
  872.         int flag = 0;
  873.         socklen_t flagsize = sizeof flag;
  874.         res = getsockopt(s->sock_fd, level, optname,
  875.                  (void *)&flag, &flagsize);
  876.         if (res < 0)
  877.             return PySocket_Err();
  878.         return PyInt_FromLong(flag);
  879.     }
  880.     if (buflen <= 0 || buflen > 1024) {
  881.         PyErr_SetString(PySocket_Error,
  882.                 "getsockopt buflen out of range");
  883.         return NULL;
  884.     }
  885.     buf = PyString_FromStringAndSize((char *)NULL, buflen);
  886.     if (buf == NULL)
  887.         return NULL;
  888.     res = getsockopt(s->sock_fd, level, optname,
  889.              (void *)PyString_AsString(buf), &buflen);
  890.     if (res < 0) {
  891.         Py_DECREF(buf);
  892.         return PySocket_Err();
  893.     }
  894.     _PyString_Resize(&buf, buflen);
  895.     return buf;
  896. #endif /* __BEOS__ */
  897. }
  898.  
  899. static char getsockopt_doc[] =
  900. "getsockopt(level, option[, buffersize]) -> value\n\
  901. \n\
  902. Get a socket option.  See the Unix manual for level and option.\n\
  903. If a nonzero buffersize argument is given, the return value is a\n\
  904. string of that length; otherwise it is an integer.";
  905.  
  906.  
  907. /* s.bind(sockaddr) method */
  908.  
  909. static PyObject *
  910. PySocketSock_bind(PySocketSockObject *s, PyObject *args)
  911. {
  912.     struct sockaddr *addr;
  913.     int addrlen;
  914.     int res;
  915.     PyObject *addro;
  916.     if (!PyArg_ParseTuple(args, "O:bind", &addro))
  917.         return NULL;
  918.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  919.         return NULL;
  920.     Py_BEGIN_ALLOW_THREADS
  921.     res = bind(s->sock_fd, addr, addrlen);
  922.     Py_END_ALLOW_THREADS
  923.     if (res < 0)
  924.         return PySocket_Err();
  925.     Py_INCREF(Py_None);
  926.     return Py_None;
  927. }
  928.  
  929. static char bind_doc[] =
  930. "bind(address)\n\
  931. \n\
  932. Bind the socket to a local address.  For IP sockets, the address is a\n\
  933. pair (host, port); the host must refer to the local host.";
  934.  
  935.  
  936. /* s.close() method.
  937.    Set the file descriptor to -1 so operations tried subsequently
  938.    will surely fail. */
  939.  
  940. static PyObject *
  941. PySocketSock_close(PySocketSockObject *s, PyObject *args)
  942. {
  943.     if (!PyArg_ParseTuple(args, ":close"))
  944.         return NULL;
  945.     if (s->sock_fd != -1) {
  946.         Py_BEGIN_ALLOW_THREADS
  947.         (void) SOCKETCLOSE(s->sock_fd);
  948.         Py_END_ALLOW_THREADS
  949.     }
  950.     s->sock_fd = -1;
  951.     Py_INCREF(Py_None);
  952.     return Py_None;
  953. }
  954.  
  955. static char close_doc[] =
  956. "close()\n\
  957. \n\
  958. Close the socket.  It cannot be used after this call.";
  959.  
  960.  
  961. /* s.connect(sockaddr) method */
  962.  
  963. static PyObject *
  964. PySocketSock_connect(PySocketSockObject *s, PyObject *args)
  965. {
  966.     struct sockaddr *addr;
  967.     int addrlen;
  968.     int res;
  969.     PyObject *addro;
  970.     if (!PyArg_ParseTuple(args, "O:connect", &addro))
  971.         return NULL;
  972.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  973.         return NULL;
  974.     Py_BEGIN_ALLOW_THREADS
  975.     res = connect(s->sock_fd, addr, addrlen);
  976.     Py_END_ALLOW_THREADS
  977.     if (res < 0)
  978.         return PySocket_Err();
  979.     Py_INCREF(Py_None);
  980.     return Py_None;
  981. }
  982.  
  983. static char connect_doc[] =
  984. "connect(address)\n\
  985. \n\
  986. Connect the socket to a remote address.  For IP sockets, the address\n\
  987. is a pair (host, port).";
  988.  
  989.  
  990. /* s.connect_ex(sockaddr) method */
  991.  
  992. static PyObject *
  993. PySocketSock_connect_ex(PySocketSockObject *s, PyObject *args)
  994. {
  995.     struct sockaddr *addr;
  996.     int addrlen;
  997.     int res;
  998.     PyObject *addro;
  999.     if (!PyArg_ParseTuple(args, "O:connect_ex", &addro))
  1000.         return NULL;
  1001.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  1002.         return NULL;
  1003.     Py_BEGIN_ALLOW_THREADS
  1004.     res = connect(s->sock_fd, addr, addrlen);
  1005.     Py_END_ALLOW_THREADS
  1006.     if (res != 0)
  1007.         res = errno;
  1008.     return PyInt_FromLong((long) res);
  1009. }
  1010.  
  1011. static char connect_ex_doc[] =
  1012. "connect_ex(address)\n\
  1013. \n\
  1014. This is like connect(address), but returns an error code (the errno value)\n\
  1015. instead of raising an exception when an error occurs.";
  1016.  
  1017.  
  1018. /* s.fileno() method */
  1019.  
  1020. static PyObject *
  1021. PySocketSock_fileno(PySocketSockObject *s, PyObject *args)
  1022. {
  1023.     if (!PyArg_ParseTuple(args, ":fileno"))
  1024.         return NULL;
  1025. #if SIZEOF_SOCKET_T <= SIZEOF_LONG
  1026.     return PyInt_FromLong((long) s->sock_fd);
  1027. #else
  1028.     return PyLong_FromLongLong((LONG_LONG)s->sock_fd);
  1029. #endif
  1030. }
  1031.  
  1032. static char fileno_doc[] =
  1033. "fileno() -> integer\n\
  1034. \n\
  1035. Return the integer file descriptor of the socket.";
  1036.  
  1037.  
  1038. #ifndef NO_DUP
  1039. /* s.dup() method */
  1040.  
  1041. static PyObject *
  1042. PySocketSock_dup(PySocketSockObject *s, PyObject *args)
  1043. {
  1044.     SOCKET_T newfd;
  1045.     PyObject *sock;
  1046.     if (!PyArg_ParseTuple(args, ":dup"))
  1047.         return NULL;
  1048.     newfd = dup(s->sock_fd);
  1049.     if (newfd < 0)
  1050.         return PySocket_Err();
  1051.     sock = (PyObject *) PySocketSock_New(newfd,
  1052.                          s->sock_family,
  1053.                          s->sock_type,
  1054.                          s->sock_proto);
  1055.     if (sock == NULL)
  1056.         SOCKETCLOSE(newfd);
  1057.     return sock;
  1058. }
  1059.  
  1060. static char dup_doc[] =
  1061. "dup() -> socket object\n\
  1062. \n\
  1063. Return a new socket object connected to the same system resource.";
  1064.  
  1065. #endif
  1066.  
  1067.  
  1068. /* s.getsockname() method */
  1069.  
  1070. static PyObject *
  1071. PySocketSock_getsockname(PySocketSockObject *s, PyObject *args)
  1072. {
  1073.     char addrbuf[256];
  1074.     int res;
  1075.     socklen_t addrlen;
  1076.  
  1077.     if (!PyArg_ParseTuple(args, ":getsockname"))
  1078.         return NULL;
  1079.     if (!getsockaddrlen(s, &addrlen))
  1080.         return NULL;
  1081.     memset(addrbuf, 0, addrlen);
  1082.     Py_BEGIN_ALLOW_THREADS
  1083.     res = getsockname(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  1084.     Py_END_ALLOW_THREADS
  1085.     if (res < 0)
  1086.         return PySocket_Err();
  1087.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  1088. }
  1089.  
  1090. static char getsockname_doc[] =
  1091. "getsockname() -> address info\n\
  1092. \n\
  1093. Return the address of the local endpoint.  For IP sockets, the address\n\
  1094. info is a pair (hostaddr, port).";
  1095.  
  1096.  
  1097. #ifdef HAVE_GETPEERNAME        /* Cray APP doesn't have this :-( */
  1098. /* s.getpeername() method */
  1099.  
  1100. static PyObject *
  1101. PySocketSock_getpeername(PySocketSockObject *s, PyObject *args)
  1102. {
  1103.     char addrbuf[256];
  1104.     int res;
  1105.     socklen_t addrlen;
  1106.  
  1107.     if (!PyArg_ParseTuple(args, ":getpeername"))
  1108.         return NULL;
  1109.     if (!getsockaddrlen(s, &addrlen))
  1110.         return NULL;
  1111.     Py_BEGIN_ALLOW_THREADS
  1112.     res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  1113.     Py_END_ALLOW_THREADS
  1114.     if (res < 0)
  1115.         return PySocket_Err();
  1116.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  1117. }
  1118.  
  1119. static char getpeername_doc[] =
  1120. "getpeername() -> address info\n\
  1121. \n\
  1122. Return the address of the remote endpoint.  For IP sockets, the address\n\
  1123. info is a pair (hostaddr, port).";
  1124.  
  1125. #endif /* HAVE_GETPEERNAME */
  1126.  
  1127.  
  1128. /* s.listen(n) method */
  1129.  
  1130. static PyObject *
  1131. PySocketSock_listen(PySocketSockObject *s, PyObject *args)
  1132. {
  1133.     int backlog;
  1134.     int res;
  1135.     if (!PyArg_ParseTuple(args, "i:listen", &backlog))
  1136.         return NULL;
  1137.     Py_BEGIN_ALLOW_THREADS
  1138.     if (backlog < 1)
  1139.         backlog = 1;
  1140.     res = listen(s->sock_fd, backlog);
  1141.     Py_END_ALLOW_THREADS
  1142.     if (res < 0)
  1143.         return PySocket_Err();
  1144.     Py_INCREF(Py_None);
  1145.     return Py_None;
  1146. }
  1147.  
  1148. static char listen_doc[] =
  1149. "listen(backlog)\n\
  1150. \n\
  1151. Enable a server to accept connections.  The backlog argument must be at\n\
  1152. least 1; it specifies the number of unaccepted connection that the system\n\
  1153. will allow before refusing new connections.";
  1154.  
  1155.  
  1156. #ifndef NO_DUP
  1157. /* s.makefile(mode) method.
  1158.    Create a new open file object referring to a dupped version of
  1159.    the socket's file descriptor.  (The dup() call is necessary so
  1160.    that the open file and socket objects may be closed independent
  1161.    of each other.)
  1162.    The mode argument specifies 'r' or 'w' passed to fdopen(). */
  1163.  
  1164. static PyObject *
  1165. PySocketSock_makefile(PySocketSockObject *s, PyObject *args)
  1166. {
  1167.     extern int fclose(FILE *);
  1168.     char *mode = "r";
  1169.     int bufsize = -1;
  1170. #ifdef MS_WIN32
  1171.     intptr_t fd;
  1172. #else
  1173.     int fd;
  1174. #endif    
  1175.     FILE *fp;
  1176.     PyObject *f;
  1177.  
  1178.     if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
  1179.         return NULL;
  1180. #ifdef MS_WIN32
  1181.     if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
  1182.         ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
  1183. #else
  1184.     if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
  1185. #endif
  1186.     {
  1187.         if (fd >= 0)
  1188.             SOCKETCLOSE(fd);
  1189.         return PySocket_Err();
  1190.     }
  1191.     f = PyFile_FromFile(fp, "<socket>", mode, fclose);
  1192.     if (f != NULL)
  1193.         PyFile_SetBufSize(f, bufsize);
  1194.     return f;
  1195. }
  1196.  
  1197. static char makefile_doc[] =
  1198. "makefile([mode[, buffersize]]) -> file object\n\
  1199. \n\
  1200. Return a regular file object corresponding to the socket.\n\
  1201. The mode and buffersize arguments are as for the built-in open() function.";
  1202.  
  1203. #endif /* NO_DUP */
  1204.  
  1205.  
  1206. /* s.recv(nbytes [,flags]) method */
  1207.  
  1208. static PyObject *
  1209. PySocketSock_recv(PySocketSockObject *s, PyObject *args)
  1210. {
  1211.     int len, n, flags = 0;
  1212.     PyObject *buf;
  1213.     if (!PyArg_ParseTuple(args, "i|i:recv", &len, &flags))
  1214.         return NULL;
  1215.     buf = PyString_FromStringAndSize((char *) 0, len);
  1216.     if (buf == NULL)
  1217.         return NULL;
  1218.     Py_BEGIN_ALLOW_THREADS
  1219.     n = recv(s->sock_fd, PyString_AsString(buf), len, flags);
  1220.     Py_END_ALLOW_THREADS
  1221.     if (n < 0) {
  1222.         Py_DECREF(buf);
  1223.         return PySocket_Err();
  1224.     }
  1225.     if (n != len && _PyString_Resize(&buf, n) < 0)
  1226.         return NULL;
  1227.     return buf;
  1228. }
  1229.  
  1230. static char recv_doc[] =
  1231. "recv(buffersize[, flags]) -> data\n\
  1232. \n\
  1233. Receive up to buffersize bytes from the socket.  For the optional flags\n\
  1234. argument, see the Unix manual.  When no data is available, block until\n\
  1235. at least one byte is available or until the remote end is closed.  When\n\
  1236. the remote end is closed and all data is read, return the empty string.";
  1237.  
  1238.  
  1239. /* s.recvfrom(nbytes [,flags]) method */
  1240.  
  1241. static PyObject *
  1242. PySocketSock_recvfrom(PySocketSockObject *s, PyObject *args)
  1243. {
  1244.     char addrbuf[256];
  1245.     PyObject *buf = NULL;
  1246.     PyObject *addr = NULL;
  1247.     PyObject *ret = NULL;
  1248.  
  1249.     int len, n, flags = 0;
  1250.     socklen_t addrlen;
  1251.     if (!PyArg_ParseTuple(args, "i|i:recvfrom", &len, &flags))
  1252.         return NULL;
  1253.     if (!getsockaddrlen(s, &addrlen))
  1254.         return NULL;
  1255.     buf = PyString_FromStringAndSize((char *) 0, len);
  1256.     if (buf == NULL)
  1257.         return NULL;
  1258.     Py_BEGIN_ALLOW_THREADS
  1259.     n = recvfrom(s->sock_fd, PyString_AsString(buf), len, flags,
  1260. #ifndef MS_WINDOWS
  1261. #if defined(PYOS_OS2)
  1262.              (struct sockaddr *)addrbuf, &addrlen
  1263. #else
  1264.              (void *)addrbuf, &addrlen
  1265. #endif
  1266. #else
  1267.              (struct sockaddr *)addrbuf, &addrlen
  1268. #endif
  1269.              );
  1270.     Py_END_ALLOW_THREADS
  1271.     if (n < 0) {
  1272.         Py_DECREF(buf);
  1273.         return PySocket_Err();
  1274.     }
  1275.     if (n != len && _PyString_Resize(&buf, n) < 0)
  1276.         return NULL;
  1277.         
  1278.     if (!(addr = makesockaddr((struct sockaddr *)addrbuf, addrlen)))
  1279.         goto finally;
  1280.  
  1281.     ret = Py_BuildValue("OO", buf, addr);
  1282.   finally:
  1283.     Py_XDECREF(addr);
  1284.     Py_XDECREF(buf);
  1285.     return ret;
  1286. }
  1287.  
  1288. static char recvfrom_doc[] =
  1289. "recvfrom(buffersize[, flags]) -> (data, address info)\n\
  1290. \n\
  1291. Like recv(buffersize, flags) but also return the sender's address info.";
  1292.  
  1293.  
  1294. /* s.send(data [,flags]) method */
  1295.  
  1296. static PyObject *
  1297. PySocketSock_send(PySocketSockObject *s, PyObject *args)
  1298. {
  1299.     char *buf;
  1300.     int len, n, flags = 0;
  1301.     if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
  1302.         return NULL;
  1303.     Py_BEGIN_ALLOW_THREADS
  1304.     n = send(s->sock_fd, buf, len, flags);
  1305.     Py_END_ALLOW_THREADS
  1306.     if (n < 0)
  1307.         return PySocket_Err();
  1308.     return PyInt_FromLong((long)n);
  1309. }
  1310.  
  1311. static char send_doc[] =
  1312. "send(data[, flags])\n\
  1313. \n\
  1314. Send a data string to the socket.  For the optional flags\n\
  1315. argument, see the Unix manual.";
  1316.  
  1317.  
  1318. /* s.sendto(data, [flags,] sockaddr) method */
  1319.  
  1320. static PyObject *
  1321. PySocketSock_sendto(PySocketSockObject *s, PyObject *args)
  1322. {
  1323.     PyObject *addro;
  1324.     char *buf;
  1325.     struct sockaddr *addr;
  1326.     int addrlen, len, n, flags;
  1327.     flags = 0;
  1328.     if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
  1329.         PyErr_Clear();
  1330.         if (!PyArg_ParseTuple(args, "s#iO:sendto",
  1331.                       &buf, &len, &flags, &addro))
  1332.             return NULL;
  1333.     }
  1334.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  1335.         return NULL;
  1336.     Py_BEGIN_ALLOW_THREADS
  1337.     n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
  1338.     Py_END_ALLOW_THREADS
  1339.     if (n < 0)
  1340.         return PySocket_Err();
  1341.     return PyInt_FromLong((long)n);
  1342. }
  1343.  
  1344. static char sendto_doc[] =
  1345. "sendto(data[, flags], address)\n\
  1346. \n\
  1347. Like send(data, flags) but allows specifying the destination address.\n\
  1348. For IP sockets, the address is a pair (hostaddr, port).";
  1349.  
  1350.  
  1351. /* s.shutdown(how) method */
  1352.  
  1353. static PyObject *
  1354. PySocketSock_shutdown(PySocketSockObject *s, PyObject *args)
  1355. {
  1356.     int how;
  1357.     int res;
  1358.     if (!PyArg_ParseTuple(args, "i:shutdown", &how))
  1359.         return NULL;
  1360.     Py_BEGIN_ALLOW_THREADS
  1361.     res = shutdown(s->sock_fd, how);
  1362.     Py_END_ALLOW_THREADS
  1363.     if (res < 0)
  1364.         return PySocket_Err();
  1365.     Py_INCREF(Py_None);
  1366.     return Py_None;
  1367. }
  1368.  
  1369. static char shutdown_doc[] =
  1370. "shutdown(flag)\n\
  1371. \n\
  1372. Shut down the reading side of the socket (flag == 0), the writing side\n\
  1373. of the socket (flag == 1), or both ends (flag == 2).";
  1374.  
  1375.  
  1376. /* List of methods for socket objects */
  1377.  
  1378. static PyMethodDef PySocketSock_methods[] = {
  1379.     {"accept",        (PyCFunction)PySocketSock_accept, METH_VARARGS,
  1380.                 accept_doc},
  1381.     {"bind",        (PyCFunction)PySocketSock_bind, METH_VARARGS,
  1382.                 bind_doc},
  1383.     {"close",        (PyCFunction)PySocketSock_close, METH_VARARGS,
  1384.                 close_doc},
  1385.     {"connect",        (PyCFunction)PySocketSock_connect, METH_VARARGS,
  1386.                 connect_doc},
  1387.     {"connect_ex",        (PyCFunction)PySocketSock_connect_ex, METH_VARARGS,
  1388.                 connect_ex_doc},
  1389. #ifndef NO_DUP
  1390.     {"dup",            (PyCFunction)PySocketSock_dup, METH_VARARGS,
  1391.                 dup_doc},
  1392. #endif
  1393.     {"fileno",        (PyCFunction)PySocketSock_fileno, METH_VARARGS,
  1394.                 fileno_doc},
  1395. #ifdef HAVE_GETPEERNAME
  1396.     {"getpeername",        (PyCFunction)PySocketSock_getpeername, METH_VARARGS,
  1397.                 getpeername_doc},
  1398. #endif
  1399.     {"getsockname",        (PyCFunction)PySocketSock_getsockname, METH_VARARGS,
  1400.                 getsockname_doc},
  1401.     {"getsockopt",        (PyCFunction)PySocketSock_getsockopt, METH_VARARGS,
  1402.                 getsockopt_doc},
  1403.     {"listen",        (PyCFunction)PySocketSock_listen, METH_VARARGS,
  1404.                 listen_doc},
  1405. #ifndef NO_DUP
  1406.     {"makefile",        (PyCFunction)PySocketSock_makefile, METH_VARARGS,
  1407.                 makefile_doc},
  1408. #endif
  1409.     {"recv",        (PyCFunction)PySocketSock_recv, METH_VARARGS,
  1410.                 recv_doc},
  1411.     {"recvfrom",        (PyCFunction)PySocketSock_recvfrom, METH_VARARGS,
  1412.                 recvfrom_doc},
  1413.     {"send",        (PyCFunction)PySocketSock_send, METH_VARARGS,
  1414.                 send_doc},
  1415.     {"sendto",        (PyCFunction)PySocketSock_sendto, METH_VARARGS,
  1416.                 sendto_doc},
  1417.     {"setblocking",        (PyCFunction)PySocketSock_setblocking, METH_VARARGS,
  1418.                 setblocking_doc},
  1419.     {"setsockopt",        (PyCFunction)PySocketSock_setsockopt, METH_VARARGS,
  1420.                 setsockopt_doc},
  1421.     {"shutdown",        (PyCFunction)PySocketSock_shutdown, METH_VARARGS,
  1422.                 shutdown_doc},
  1423.     {NULL,            NULL}        /* sentinel */
  1424. };
  1425.  
  1426.  
  1427. /* Deallocate a socket object in response to the last Py_DECREF().
  1428.    First close the file description. */
  1429.  
  1430. static void
  1431. PySocketSock_dealloc(PySocketSockObject *s)
  1432. {
  1433.     if (s->sock_fd != -1)
  1434.         (void) SOCKETCLOSE(s->sock_fd);
  1435.     PyObject_Del(s);
  1436. }
  1437.  
  1438.  
  1439. /* Return a socket object's named attribute. */
  1440.  
  1441. static PyObject *
  1442. PySocketSock_getattr(PySocketSockObject *s, char *name)
  1443. {
  1444.     return Py_FindMethod(PySocketSock_methods, (PyObject *) s, name);
  1445. }
  1446.  
  1447.  
  1448. static PyObject *
  1449. PySocketSock_repr(PySocketSockObject *s)
  1450. {
  1451.     char buf[512];
  1452. #if SIZEOF_SOCKET_T > SIZEOF_LONG
  1453.     if (s->sock_fd > LONG_MAX) {
  1454.         /* this can occur on Win64, and actually there is a special
  1455.            ugly printf formatter for decimal pointer length integer
  1456.            printing, only bother if necessary*/
  1457.         PyErr_SetString(PyExc_OverflowError,
  1458.             "no printf formatter to display the socket descriptor in decimal");
  1459.         return NULL;
  1460.     }
  1461. #endif
  1462.     sprintf(buf, 
  1463.         "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>", 
  1464.         (long)s->sock_fd, s->sock_family, s->sock_type, s->sock_proto);
  1465.     return PyString_FromString(buf);
  1466. }
  1467.  
  1468.  
  1469. /* Type object for socket objects. */
  1470.  
  1471. static PyTypeObject PySocketSock_Type = {
  1472.     PyObject_HEAD_INIT(0)    /* Must fill in type value later */
  1473.     0,
  1474.     "socket",
  1475.     sizeof(PySocketSockObject),
  1476.     0,
  1477.     (destructor)PySocketSock_dealloc, /*tp_dealloc*/
  1478.     0,        /*tp_print*/
  1479.     (getattrfunc)PySocketSock_getattr, /*tp_getattr*/
  1480.     0,        /*tp_setattr*/
  1481.     0,        /*tp_compare*/
  1482.     (reprfunc)PySocketSock_repr, /*tp_repr*/
  1483.     0,        /*tp_as_number*/
  1484.     0,        /*tp_as_sequence*/
  1485.     0,        /*tp_as_mapping*/
  1486. };
  1487.  
  1488.  
  1489. /* Python interface to gethostname(). */
  1490.  
  1491. /*ARGSUSED*/
  1492. static PyObject *
  1493. PySocket_gethostname(PyObject *self, PyObject *args)
  1494. {
  1495.     char buf[1024];
  1496.     int res;
  1497.     if (!PyArg_ParseTuple(args, ":gethostname"))
  1498.         return NULL;
  1499.     Py_BEGIN_ALLOW_THREADS
  1500.     res = gethostname(buf, (int) sizeof buf - 1);
  1501.     Py_END_ALLOW_THREADS
  1502.     if (res < 0)
  1503.         return PySocket_Err();
  1504.     buf[sizeof buf - 1] = '\0';
  1505.     return PyString_FromString(buf);
  1506. }
  1507.  
  1508. static char gethostname_doc[] =
  1509. "gethostname() -> string\n\
  1510. \n\
  1511. Return the current host name.";
  1512.  
  1513.  
  1514. /* Python interface to gethostbyname(name). */
  1515.  
  1516. /*ARGSUSED*/
  1517. static PyObject *
  1518. PySocket_gethostbyname(PyObject *self, PyObject *args)
  1519. {
  1520.     char *name;
  1521.     struct sockaddr_in addrbuf;
  1522.     if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
  1523.         return NULL;
  1524.     if (setipaddr(name, &addrbuf) < 0)
  1525.         return NULL;
  1526.     return makeipaddr(&addrbuf);
  1527. }
  1528.  
  1529. static char gethostbyname_doc[] =
  1530. "gethostbyname(host) -> address\n\
  1531. \n\
  1532. Return the IP address (a string of the form '255.255.255.255') for a host.";
  1533.  
  1534.  
  1535. /* Convenience function common to gethostbyname_ex and gethostbyaddr */
  1536.  
  1537. static PyObject *
  1538. gethost_common(struct hostent *h, struct sockaddr_in *addr)
  1539. {
  1540.     char **pch;
  1541.     PyObject *rtn_tuple = (PyObject *)NULL;
  1542.     PyObject *name_list = (PyObject *)NULL;
  1543.     PyObject *addr_list = (PyObject *)NULL;
  1544.     PyObject *tmp;
  1545.     if (h == NULL) {
  1546. #ifdef HAVE_HSTRERROR
  1547.             /* Let's get real error message to return */
  1548.             extern int h_errno;
  1549.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  1550. #else
  1551.         PyErr_SetString(PySocket_Error, "host not found");
  1552. #endif
  1553.         return NULL;
  1554.     }
  1555.     if ((name_list = PyList_New(0)) == NULL)
  1556.         goto err;
  1557.     if ((addr_list = PyList_New(0)) == NULL)
  1558.         goto err;
  1559.     for (pch = h->h_aliases; *pch != NULL; pch++) {
  1560.         int status;
  1561.         tmp = PyString_FromString(*pch);
  1562.         if (tmp == NULL)
  1563.             goto err;
  1564.         status = PyList_Append(name_list, tmp);
  1565.         Py_DECREF(tmp);
  1566.         if (status)
  1567.             goto err;
  1568.     }
  1569.     for (pch = h->h_addr_list; *pch != NULL; pch++) {
  1570.         int status;
  1571.         memcpy((char *) &addr->sin_addr, *pch, h->h_length);
  1572.         tmp = makeipaddr(addr);
  1573.         if (tmp == NULL)
  1574.             goto err;
  1575.         status = PyList_Append(addr_list, tmp);
  1576.         Py_DECREF(tmp);
  1577.         if (status)
  1578.             goto err;
  1579.     }
  1580.     rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
  1581.  err:
  1582.     Py_XDECREF(name_list);
  1583.     Py_XDECREF(addr_list);
  1584.     return rtn_tuple;
  1585. }
  1586.  
  1587.  
  1588. /* Python interface to gethostbyname_ex(name). */
  1589.  
  1590. /*ARGSUSED*/
  1591. static PyObject *
  1592. PySocket_gethostbyname_ex(PyObject *self, PyObject *args)
  1593. {
  1594.     char *name;
  1595.     struct hostent *h;
  1596.     struct sockaddr_in addr;
  1597.     PyObject *ret;
  1598. #ifdef HAVE_GETHOSTBYNAME_R
  1599.     struct hostent hp_allocated;
  1600. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  1601.     struct hostent_data data;
  1602. #else
  1603.     char buf[16384];
  1604.     int buf_len = (sizeof buf) - 1;
  1605.     int errnop;
  1606. #endif
  1607. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1608.     int result;
  1609. #endif
  1610. #endif /* HAVE_GETHOSTBYNAME_R */
  1611.     if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
  1612.         return NULL;
  1613.     if (setipaddr(name, &addr) < 0)
  1614.         return NULL;
  1615.     Py_BEGIN_ALLOW_THREADS
  1616. #ifdef HAVE_GETHOSTBYNAME_R
  1617. #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1618.     result = gethostbyname_r(name, &hp_allocated, buf, buf_len, &h, &errnop);
  1619. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  1620.     h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  1621. #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
  1622.     memset((void *) &data, '\0', sizeof(data));
  1623.     result = gethostbyname_r(name, &hp_allocated, &data);
  1624.     h = (result != 0) ? NULL : &hp_allocated;
  1625. #endif
  1626. #else /* not HAVE_GETHOSTBYNAME_R */
  1627. #ifdef USE_GETHOSTBYNAME_LOCK
  1628.     PyThread_acquire_lock(gethostbyname_lock, 1);
  1629. #endif
  1630.     h = gethostbyname(name);
  1631. #endif /* HAVE_GETHOSTBYNAME_R */
  1632.     Py_END_ALLOW_THREADS
  1633.     ret = gethost_common(h, &addr);
  1634. #ifdef USE_GETHOSTBYNAME_LOCK
  1635.     PyThread_release_lock(gethostbyname_lock);
  1636. #endif
  1637.     return ret;
  1638. }
  1639.  
  1640. static char ghbn_ex_doc[] =
  1641. "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
  1642. \n\
  1643. Return the true host name, a list of aliases, and a list of IP addresses,\n\
  1644. for a host.  The host argument is a string giving a host name or IP number.";
  1645.  
  1646.  
  1647. /* Python interface to gethostbyaddr(IP). */
  1648.  
  1649. /*ARGSUSED*/
  1650. static PyObject *
  1651. PySocket_gethostbyaddr(PyObject *self, PyObject *args)
  1652. {
  1653.         struct sockaddr_in addr;
  1654.     char *ip_num;
  1655.     struct hostent *h;
  1656.     PyObject *ret;
  1657. #ifdef HAVE_GETHOSTBYNAME_R
  1658.     struct hostent hp_allocated;
  1659. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  1660.     struct hostent_data data;
  1661. #else
  1662.     char buf[16384];
  1663.     int buf_len = (sizeof buf) - 1;
  1664.     int errnop;
  1665. #endif
  1666. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1667.     int result;
  1668. #endif
  1669. #endif /* HAVE_GETHOSTBYNAME_R */
  1670.  
  1671.     if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
  1672.         return NULL;
  1673.     if (setipaddr(ip_num, &addr) < 0)
  1674.         return NULL;
  1675.     Py_BEGIN_ALLOW_THREADS
  1676. #ifdef HAVE_GETHOSTBYNAME_R
  1677. #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1678.     result = gethostbyaddr_r((char *)&addr.sin_addr,
  1679.         sizeof(addr.sin_addr),
  1680.         AF_INET, &hp_allocated, buf, buf_len,
  1681.         &h, &errnop);
  1682. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  1683.     h = gethostbyaddr_r((char *)&addr.sin_addr,
  1684.                 sizeof(addr.sin_addr),
  1685.                 AF_INET, 
  1686.                 &hp_allocated, buf, buf_len, &errnop);
  1687. #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
  1688.     memset((void *) &data, '\0', sizeof(data));
  1689.     result = gethostbyaddr_r((char *)&addr.sin_addr,
  1690.         sizeof(addr.sin_addr),
  1691.         AF_INET, &hp_allocated, &data);
  1692.     h = (result != 0) ? NULL : &hp_allocated;
  1693. #endif
  1694. #else /* not HAVE_GETHOSTBYNAME_R */
  1695. #ifdef USE_GETHOSTBYNAME_LOCK
  1696.     PyThread_acquire_lock(gethostbyname_lock, 1);
  1697. #endif
  1698.     h = gethostbyaddr((char *)&addr.sin_addr,
  1699.               sizeof(addr.sin_addr),
  1700.               AF_INET);
  1701. #endif /* HAVE_GETHOSTBYNAME_R */
  1702.     Py_END_ALLOW_THREADS
  1703.     ret = gethost_common(h, &addr);
  1704. #ifdef USE_GETHOSTBYNAME_LOCK
  1705.     PyThread_release_lock(gethostbyname_lock);
  1706. #endif
  1707.     return ret;
  1708. }
  1709.  
  1710. static char gethostbyaddr_doc[] =
  1711. "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
  1712. \n\
  1713. Return the true host name, a list of aliases, and a list of IP addresses,\n\
  1714. for a host.  The host argument is a string giving a host name or IP number.";
  1715.  
  1716.  
  1717. /* Python interface to getservbyname(name).
  1718.    This only returns the port number, since the other info is already
  1719.    known or not useful (like the list of aliases). */
  1720.  
  1721. /*ARGSUSED*/
  1722. static PyObject *
  1723. PySocket_getservbyname(PyObject *self, PyObject *args)
  1724. {
  1725.     char *name, *proto;
  1726.     struct servent *sp;
  1727.     if (!PyArg_ParseTuple(args, "ss:getservbyname", &name, &proto))
  1728.         return NULL;
  1729.     Py_BEGIN_ALLOW_THREADS
  1730.     sp = getservbyname(name, proto);
  1731.     Py_END_ALLOW_THREADS
  1732.     if (sp == NULL) {
  1733.         PyErr_SetString(PySocket_Error, "service/proto not found");
  1734.         return NULL;
  1735.     }
  1736.     return PyInt_FromLong((long) ntohs(sp->s_port));
  1737. }
  1738.  
  1739. static char getservbyname_doc[] =
  1740. "getservbyname(servicename, protocolname) -> integer\n\
  1741. \n\
  1742. Return a port number from a service name and protocol name.\n\
  1743. The protocol name should be 'tcp' or 'udp'.";
  1744.  
  1745.  
  1746. /* Python interface to getprotobyname(name).
  1747.    This only returns the protocol number, since the other info is
  1748.    already known or not useful (like the list of aliases). */
  1749.  
  1750. /*ARGSUSED*/
  1751. static PyObject *
  1752. PySocket_getprotobyname(PyObject *self, PyObject *args)
  1753. {
  1754.     char *name;
  1755.     struct protoent *sp;
  1756. #ifdef __BEOS__
  1757. /* Not available in BeOS yet. - [cjh] */
  1758.     PyErr_SetString( PySocket_Error, "getprotobyname not supported" );
  1759.     return NULL;
  1760. #else
  1761.     if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
  1762.         return NULL;
  1763.     Py_BEGIN_ALLOW_THREADS
  1764.     sp = getprotobyname(name);
  1765.     Py_END_ALLOW_THREADS
  1766.     if (sp == NULL) {
  1767.         PyErr_SetString(PySocket_Error, "protocol not found");
  1768.         return NULL;
  1769.     }
  1770.     return PyInt_FromLong((long) sp->p_proto);
  1771. #endif
  1772. }
  1773.  
  1774. static char getprotobyname_doc[] =
  1775. "getprotobyname(name) -> integer\n\
  1776. \n\
  1777. Return the protocol number for the named protocol.  (Rarely used.)";
  1778.  
  1779.  
  1780. /* Python interface to socket(family, type, proto).
  1781.    The third (protocol) argument is optional.
  1782.    Return a new socket object. */
  1783.  
  1784. /*ARGSUSED*/
  1785. static PyObject *
  1786. PySocket_socket(PyObject *self, PyObject *args)
  1787. {
  1788.     PySocketSockObject *s;
  1789.     SOCKET_T fd;
  1790.     int family, type, proto = 0;
  1791.     if (!PyArg_ParseTuple(args, "ii|i:socket", &family, &type, &proto))
  1792.         return NULL;
  1793.     Py_BEGIN_ALLOW_THREADS
  1794.     fd = socket(family, type, proto);
  1795.     Py_END_ALLOW_THREADS
  1796. #ifdef MS_WINDOWS
  1797.     if (fd == INVALID_SOCKET)
  1798. #else
  1799.     if (fd < 0)
  1800. #endif
  1801.         return PySocket_Err();
  1802.     s = PySocketSock_New(fd, family, type, proto);
  1803.     /* If the object can't be created, don't forget to close the
  1804.        file descriptor again! */
  1805.     if (s == NULL)
  1806.         (void) SOCKETCLOSE(fd);
  1807.     /* From now on, ignore SIGPIPE and let the error checking
  1808.        do the work. */
  1809. #ifdef SIGPIPE      
  1810.     (void) signal(SIGPIPE, SIG_IGN);
  1811. #endif   
  1812.     return (PyObject *) s;
  1813. }
  1814.  
  1815. static char socket_doc[] =
  1816. "socket(family, type[, proto]) -> socket object\n\
  1817. \n\
  1818. Open a socket of the given type.  The family argument specifies the\n\
  1819. address family; it is normally AF_INET, sometimes AF_UNIX.\n\
  1820. The type argument specifies whether this is a stream (SOCK_STREAM)\n\
  1821. or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,\n\
  1822. specifying the default protocol.";
  1823.  
  1824.  
  1825. #ifndef NO_DUP
  1826. /* Create a socket object from a numeric file description.
  1827.    Useful e.g. if stdin is a socket.
  1828.    Additional arguments as for socket(). */
  1829.  
  1830. /*ARGSUSED*/
  1831. static PyObject *
  1832. PySocket_fromfd(PyObject *self, PyObject *args)
  1833. {
  1834.     PySocketSockObject *s;
  1835.     SOCKET_T fd;
  1836.     int family, type, proto = 0;
  1837.     if (!PyArg_ParseTuple(args, "iii|i:fromfd",
  1838.                   &fd, &family, &type, &proto))
  1839.         return NULL;
  1840.     /* Dup the fd so it and the socket can be closed independently */
  1841.     fd = dup(fd);
  1842.     if (fd < 0)
  1843.         return PySocket_Err();
  1844.     s = PySocketSock_New(fd, family, type, proto);
  1845.     /* From now on, ignore SIGPIPE and let the error checking
  1846.        do the work. */
  1847. #ifdef SIGPIPE      
  1848.     (void) signal(SIGPIPE, SIG_IGN);
  1849. #endif   
  1850.     return (PyObject *) s;
  1851. }
  1852.  
  1853. static char fromfd_doc[] =
  1854. "fromfd(fd, family, type[, proto]) -> socket object\n\
  1855. \n\
  1856. Create a socket object from the given file descriptor.\n\
  1857. The remaining arguments are the same as for socket().";
  1858.  
  1859. #endif /* NO_DUP */
  1860.  
  1861.  
  1862. static PyObject *
  1863. PySocket_ntohs(PyObject *self, PyObject *args)
  1864. {
  1865.     int x1, x2;
  1866.  
  1867.     if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
  1868.         return NULL;
  1869.     }
  1870.     x2 = (int)ntohs((short)x1);
  1871.     return PyInt_FromLong(x2);
  1872. }
  1873.  
  1874. static char ntohs_doc[] =
  1875. "ntohs(integer) -> integer\n\
  1876. \n\
  1877. Convert a 16-bit integer from network to host byte order.";
  1878.  
  1879.  
  1880. static PyObject *
  1881. PySocket_ntohl(PyObject *self, PyObject *args)
  1882. {
  1883.     int x1, x2;
  1884.  
  1885.     if (!PyArg_ParseTuple(args, "i:ntohl", &x1)) {
  1886.         return NULL;
  1887.     }
  1888.     x2 = ntohl(x1);
  1889.     return PyInt_FromLong(x2);
  1890. }
  1891.  
  1892. static char ntohl_doc[] =
  1893. "ntohl(integer) -> integer\n\
  1894. \n\
  1895. Convert a 32-bit integer from network to host byte order.";
  1896.  
  1897.  
  1898. static PyObject *
  1899. PySocket_htons(PyObject *self, PyObject *args)
  1900. {
  1901.     int x1, x2;
  1902.  
  1903.     if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
  1904.         return NULL;
  1905.     }
  1906.     x2 = (int)htons((short)x1);
  1907.     return PyInt_FromLong(x2);
  1908. }
  1909.  
  1910. static char htons_doc[] =
  1911. "htons(integer) -> integer\n\
  1912. \n\
  1913. Convert a 16-bit integer from host to network byte order.";
  1914.  
  1915.  
  1916. static PyObject *
  1917. PySocket_htonl(PyObject *self, PyObject *args)
  1918. {
  1919.     int x1, x2;
  1920.  
  1921.     if (!PyArg_ParseTuple(args, "i:htonl", &x1)) {
  1922.         return NULL;
  1923.     }
  1924.     x2 = htonl(x1);
  1925.     return PyInt_FromLong(x2);
  1926. }
  1927.  
  1928. static char htonl_doc[] =
  1929. "htonl(integer) -> integer\n\
  1930. \n\
  1931. Convert a 32-bit integer from host to network byte order.";
  1932.  
  1933. /*
  1934.  * socket.inet_aton() and socket.inet_ntoa() functions
  1935.  *
  1936.  * written 20 Aug 1999 by Ben Gertzfield <che@debian.org> <- blame him!
  1937.  *
  1938.  */
  1939.  
  1940. static char inet_aton_doc[] = 
  1941. "inet_aton(string) -> packed 32-bit IP representation\n\
  1942. \n\
  1943. Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
  1944. binary format used in low-level network functions.";
  1945.  
  1946. static PyObject*
  1947. PySocket_inet_aton(PyObject *self, PyObject *args)
  1948. {
  1949. #ifndef INADDR_NONE
  1950. #define INADDR_NONE (-1)
  1951. #endif
  1952.  
  1953.     /* Have to use inet_addr() instead */
  1954.     char *ip_addr;
  1955.     long packed_addr;
  1956.  
  1957.     if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) {
  1958.         return NULL;
  1959.     }
  1960. #ifdef USE_GUSI1
  1961.     packed_addr = (long)inet_addr(ip_addr).s_addr;
  1962. #else
  1963.     packed_addr = inet_addr(ip_addr);
  1964. #endif
  1965.  
  1966.     if (packed_addr == INADDR_NONE) {    /* invalid address */
  1967.         PyErr_SetString(PySocket_Error,
  1968.             "illegal IP address string passed to inet_aton");
  1969.         return NULL;
  1970.     }
  1971.  
  1972.     return PyString_FromStringAndSize((char *) &packed_addr,
  1973.                       sizeof(packed_addr));
  1974. }
  1975.  
  1976. static char inet_ntoa_doc[] = 
  1977. "inet_ntoa(packed_ip) -> ip_address_string\n\
  1978. \n\
  1979. Convert an IP address from 32-bit packed binary format to string format";
  1980.  
  1981. static PyObject*
  1982. PySocket_inet_ntoa(PyObject *self, PyObject *args)
  1983. {
  1984.     char *packed_str;
  1985.     int addr_len;
  1986.     struct in_addr packed_addr;
  1987.  
  1988.     if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
  1989.         return NULL;
  1990.     }
  1991.     
  1992.     if (addr_len != sizeof(packed_addr)) {
  1993.         PyErr_SetString(PySocket_Error,
  1994.             "packed IP wrong length for inet_ntoa");
  1995.         return NULL;
  1996.     }
  1997.  
  1998.     memcpy(&packed_addr, packed_str, addr_len);
  1999.  
  2000.     return PyString_FromString(inet_ntoa(packed_addr));
  2001. }
  2002.  
  2003.  
  2004. #ifdef USE_SSL
  2005.  
  2006. /* This is a C function to be called for new object initialization */
  2007. static SSLObject *
  2008. newSSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file)
  2009. {
  2010.     SSLObject *self;
  2011.  
  2012.     self = PyObject_New(SSLObject, &SSL_Type); /* Create new object */
  2013.     if (self == NULL){
  2014.         PyErr_SetObject(SSLErrorObject,
  2015.                 PyString_FromString("newSSLObject error"));
  2016.         return NULL;
  2017.     }
  2018.     memset(self->server, '\0', sizeof(char) * 256);
  2019.     memset(self->issuer, '\0', sizeof(char) * 256);  
  2020.   
  2021.     self->x_attr = PyDict_New();
  2022.     self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
  2023.     if (self->ctx == NULL) {
  2024.         PyErr_SetObject(SSLErrorObject,
  2025.                 PyString_FromString("SSL_CTX_new error"));
  2026.         PyObject_Del(self);
  2027.         return NULL;
  2028.     }
  2029.  
  2030.     if ( (key_file && !cert_file) || (!key_file && cert_file) )
  2031.     {
  2032.         PyErr_SetObject(SSLErrorObject,
  2033.               PyString_FromString(
  2034.             "Both the key & certificate files must be specified"));
  2035.         PyObject_Del(self);
  2036.         return NULL;
  2037.     }
  2038.  
  2039.     if (key_file && cert_file)
  2040.     {
  2041.         if (SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
  2042.                         SSL_FILETYPE_PEM) < 1)
  2043.         {
  2044.             PyErr_SetObject(SSLErrorObject,
  2045.                 PyString_FromString(
  2046.                   "SSL_CTX_use_PrivateKey_file error"));
  2047.             PyObject_Del(self);
  2048.             return NULL;
  2049.         }
  2050.  
  2051.         if (SSL_CTX_use_certificate_chain_file(self->ctx,
  2052.                                cert_file) < 1)
  2053.         {
  2054.             PyErr_SetObject(SSLErrorObject,
  2055.                 PyString_FromString(
  2056.                   "SSL_CTX_use_certificate_chain_file error"));
  2057.             PyObject_Del(self);
  2058.             return NULL;
  2059.         }
  2060.     }
  2061.  
  2062.     SSL_CTX_set_verify(self->ctx,
  2063.                SSL_VERIFY_NONE, NULL); /* set verify lvl */
  2064.     self->ssl = SSL_new(self->ctx); /* New ssl struct */
  2065.     SSL_set_fd(self->ssl, Sock->sock_fd);    /* Set the socket for SSL */
  2066.     SSL_set_connect_state(self->ssl);
  2067.  
  2068.     if ((SSL_connect(self->ssl)) == -1) {
  2069.         /* Actually negotiate SSL connection */
  2070.         PyErr_SetObject(SSLErrorObject,
  2071.                 PyString_FromString("SSL_connect error"));
  2072.         PyObject_Del(self);
  2073.         return NULL;
  2074.     }
  2075.     self->ssl->debug = 1;
  2076.  
  2077.     if ((self->server_cert = SSL_get_peer_certificate(self->ssl))) {
  2078.         X509_NAME_oneline(X509_get_subject_name(self->server_cert),
  2079.                   self->server, 256);
  2080.         X509_NAME_oneline(X509_get_issuer_name(self->server_cert),
  2081.                   self->issuer, 256);
  2082.     }
  2083.     self->x_attr = NULL;
  2084.     self->Socket = Sock;
  2085.     Py_INCREF(self->Socket);
  2086.     return self;
  2087. }
  2088.  
  2089. /* This is the Python function called for new object initialization */
  2090. static PyObject *
  2091. PySocket_ssl(PyObject *self, PyObject *args)
  2092. {
  2093.     SSLObject *rv;
  2094.     PySocketSockObject *Sock;
  2095.     char *key_file;
  2096.     char *cert_file;
  2097.   
  2098.     if (!PyArg_ParseTuple(args, "O!zz:ssl",
  2099.                   &PySocketSock_Type, (PyObject*)&Sock,
  2100.                   &key_file, &cert_file) )
  2101.         return NULL;
  2102.   
  2103.     rv = newSSLObject(Sock, key_file, cert_file);
  2104.     if ( rv == NULL )
  2105.         return NULL;
  2106.     return (PyObject *)rv;
  2107. }
  2108.  
  2109. static char ssl_doc[] =
  2110. "ssl(socket, keyfile, certfile) -> sslobject";
  2111.  
  2112. static PyObject *
  2113. SSL_server(SSLObject *self, PyObject *args)
  2114. {
  2115.     return PyString_FromString(self->server);
  2116. }
  2117.  
  2118. static PyObject *
  2119. SSL_issuer(SSLObject *self, PyObject *args)
  2120. {
  2121.     return PyString_FromString(self->issuer);
  2122. }
  2123.  
  2124.  
  2125. /* SSL object methods */
  2126.  
  2127. static PyMethodDef SSLMethods[] = {
  2128.     { "write", (PyCFunction)SSL_SSLwrite, 1 },
  2129.     { "read", (PyCFunction)SSL_SSLread, 1 },
  2130.     { "server", (PyCFunction)SSL_server, 1 },
  2131.     { "issuer", (PyCFunction)SSL_issuer, 1 },
  2132.     { NULL, NULL}
  2133. };
  2134.  
  2135. static void SSL_dealloc(SSLObject *self)
  2136. {
  2137.     if (self->server_cert)    /* Possible not to have one? */
  2138.         X509_free (self->server_cert);
  2139.     SSL_CTX_free(self->ctx);
  2140.     SSL_free(self->ssl);
  2141.     Py_XDECREF(self->x_attr);
  2142.     Py_XDECREF(self->Socket);
  2143.     PyObject_Del(self);
  2144. }
  2145.  
  2146. static PyObject *SSL_getattr(SSLObject *self, char *name)
  2147. {
  2148.     return Py_FindMethod(SSLMethods, (PyObject *)self, name);
  2149. }
  2150.  
  2151. staticforward PyTypeObject SSL_Type = {
  2152.     PyObject_HEAD_INIT(&PyType_Type)
  2153.     0,                /*ob_size*/
  2154.     "SSL",            /*tp_name*/
  2155.     sizeof(SSLObject),        /*tp_basicsize*/
  2156.     0,                /*tp_itemsize*/
  2157.     /* methods */
  2158.     (destructor)SSL_dealloc,    /*tp_dealloc*/
  2159.     0,                /*tp_print*/
  2160.     (getattrfunc)SSL_getattr,    /*tp_getattr*/
  2161.     0,                /*tp_setattr*/
  2162.     0,                /*tp_compare*/
  2163.     0,                /*tp_repr*/
  2164.     0,                /*tp_as_number*/
  2165.     0,                /*tp_as_sequence*/
  2166.     0,                /*tp_as_mapping*/
  2167.     0,                /*tp_hash*/
  2168. };
  2169.  
  2170.  
  2171.  
  2172. static PyObject *SSL_SSLwrite(SSLObject *self, PyObject *args)
  2173. {
  2174.     char *data;
  2175.     size_t len = 0;
  2176.   
  2177.     if (!PyArg_ParseTuple(args, "s|i:write", &data, &len))
  2178.         return NULL;
  2179.   
  2180.     if (!len)
  2181.         len = strlen(data);
  2182.   
  2183.     len = SSL_write(self->ssl, data, len);
  2184.     return PyInt_FromLong((long)len);
  2185. }
  2186.  
  2187. static PyObject *SSL_SSLread(SSLObject *self, PyObject *args)
  2188. {
  2189.     PyObject *buf;
  2190.     int count = 0;
  2191.     int len = 1024;
  2192.     int res;
  2193.   
  2194.     PyArg_ParseTuple(args, "|i:read", &len);
  2195.   
  2196.     if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
  2197.         return NULL;    /* Error object should already be set */
  2198.   
  2199.     count = SSL_read(self->ssl, PyString_AsString(buf), len);
  2200.     res = SSL_get_error(self->ssl, count);
  2201.  
  2202.     switch (res) {
  2203.     case 0:            /* Good return value! */
  2204.         break;
  2205.     case 6:
  2206.         PyErr_SetString(SSLErrorObject, "EOF");
  2207.         Py_DECREF(buf);
  2208.         return NULL;
  2209.         break;
  2210.     case 5:
  2211.     default:
  2212.         return PyErr_SetFromErrno(SSLErrorObject);
  2213.         break;
  2214.     }
  2215.   
  2216.     fflush(stderr);
  2217.       
  2218.     if (count < 0) {
  2219.         Py_DECREF(buf);
  2220.         return PyErr_SetFromErrno(SSLErrorObject);
  2221.     }
  2222.   
  2223.     if (count != len && _PyString_Resize(&buf, count) < 0)
  2224.         return NULL;
  2225.     return buf;
  2226. }
  2227.  
  2228. #endif /* USE_SSL */
  2229.  
  2230.  
  2231. /* List of functions exported by this module. */
  2232.  
  2233. static PyMethodDef PySocket_methods[] = {
  2234.     {"gethostbyname",    PySocket_gethostbyname, 
  2235.      METH_VARARGS, gethostbyname_doc},
  2236.     {"gethostbyname_ex",    PySocket_gethostbyname_ex, 
  2237.      METH_VARARGS, ghbn_ex_doc},
  2238.     {"gethostbyaddr",    PySocket_gethostbyaddr, 
  2239.      METH_VARARGS, gethostbyaddr_doc},
  2240.     {"gethostname",        PySocket_gethostname, 
  2241.      METH_VARARGS, gethostname_doc},
  2242.     {"getservbyname",    PySocket_getservbyname, 
  2243.      METH_VARARGS, getservbyname_doc},
  2244.     {"getprotobyname",    PySocket_getprotobyname, 
  2245.      METH_VARARGS,getprotobyname_doc},
  2246.     {"socket",        PySocket_socket, 
  2247.      METH_VARARGS, socket_doc},
  2248. #ifndef NO_DUP
  2249.     {"fromfd",        PySocket_fromfd, 
  2250.      METH_VARARGS, fromfd_doc},
  2251. #endif
  2252.     {"ntohs",        PySocket_ntohs, 
  2253.      METH_VARARGS, ntohs_doc},
  2254.     {"ntohl",        PySocket_ntohl, 
  2255.      METH_VARARGS, ntohl_doc},
  2256.     {"htons",        PySocket_htons, 
  2257.      METH_VARARGS, htons_doc},
  2258.     {"htonl",        PySocket_htonl, 
  2259.      METH_VARARGS, htonl_doc},
  2260.     {"inet_aton",        PySocket_inet_aton, 
  2261.      METH_VARARGS, inet_aton_doc},
  2262.     {"inet_ntoa",        PySocket_inet_ntoa, 
  2263.      METH_VARARGS, inet_ntoa_doc},
  2264. #ifdef USE_SSL
  2265.     {"ssl",            PySocket_ssl, 
  2266.      METH_VARARGS, ssl_doc},
  2267. #endif /* USE_SSL */
  2268.     {NULL,            NULL}         /* Sentinel */
  2269. };
  2270.  
  2271.  
  2272. /* Convenience routine to export an integer value.
  2273.  *
  2274.  * Errors are silently ignored, for better or for worse...
  2275.  */
  2276. static void
  2277. insint(PyObject *d, char *name, int value)
  2278. {
  2279.     PyObject *v = PyInt_FromLong((long) value);
  2280.     if (!v || PyDict_SetItemString(d, name, v))
  2281.         PyErr_Clear();
  2282.  
  2283.     Py_XDECREF(v);
  2284. }
  2285.  
  2286.  
  2287. #ifdef MS_WINDOWS
  2288.  
  2289. /* Additional initialization and cleanup for NT/Windows */
  2290.  
  2291. static void
  2292. NTcleanup(void)
  2293. {
  2294.     WSACleanup();
  2295. }
  2296.  
  2297. static int
  2298. NTinit(void)
  2299. {
  2300.     WSADATA WSAData;
  2301.     int ret;
  2302.     char buf[100];
  2303.     ret = WSAStartup(0x0101, &WSAData);
  2304.     switch (ret) {
  2305.     case 0:    /* no error */
  2306.         atexit(NTcleanup);
  2307.         return 1;
  2308.     case WSASYSNOTREADY:
  2309.         PyErr_SetString(PyExc_ImportError,
  2310.                 "WSAStartup failed: network not ready");
  2311.         break;
  2312.     case WSAVERNOTSUPPORTED:
  2313.     case WSAEINVAL:
  2314.         PyErr_SetString(PyExc_ImportError,
  2315.             "WSAStartup failed: requested version not supported");
  2316.         break;
  2317.     default:
  2318.         sprintf(buf, "WSAStartup failed: error code %d", ret);
  2319.         PyErr_SetString(PyExc_ImportError, buf);
  2320.         break;
  2321.     }
  2322.     return 0;
  2323. }
  2324.  
  2325. #endif /* MS_WINDOWS */
  2326.  
  2327. #if defined(PYOS_OS2)
  2328.  
  2329. /* Additional initialization and cleanup for OS/2 */
  2330.  
  2331. static void
  2332. OS2cleanup(void)
  2333. {
  2334.     /* No cleanup is necessary for OS/2 Sockets */
  2335. }
  2336.  
  2337. static int
  2338. OS2init(void)
  2339. {
  2340.     char reason[64];
  2341.     int rc = sock_init();
  2342.  
  2343.     if (rc == 0) {
  2344.         atexit(OS2cleanup);
  2345.         return 1; /* Indicate Success */
  2346.     }
  2347.  
  2348.     sprintf(reason, "OS/2 TCP/IP Error# %d", sock_errno());
  2349.     PyErr_SetString(PyExc_ImportError, reason);
  2350.  
  2351.     return 0;  /* Indicate Failure */
  2352. }
  2353.  
  2354. #endif /* PYOS_OS2 */
  2355.  
  2356. /* Initialize this module.
  2357.  *   This is called when the first 'import socket' is done,
  2358.  *   via a table in config.c, if config.c is compiled with USE_SOCKET
  2359.  *   defined.
  2360.  *
  2361.  *   For MS_WINDOWS (which means any Windows variant), this module
  2362.  *   is actually called "_socket", and there's a wrapper "socket.py"
  2363.  *   which implements some missing functionality (such as makefile(),
  2364.  *   dup() and fromfd()).  The import of "_socket" may fail with an
  2365.  *   ImportError exception if initialization of WINSOCK fails.  When
  2366.  *   WINSOCK is initialized succesfully, a call to WSACleanup() is
  2367.  *   scheduled to be made at exit time.
  2368.  *
  2369.  *   For OS/2, this module is also called "_socket" and uses a wrapper
  2370.  *   "socket.py" which implements that functionality that is missing
  2371.  *   when PC operating systems don't put socket descriptors in the
  2372.  *   operating system's filesystem layer.
  2373.  */
  2374.  
  2375. static char module_doc[] =
  2376. "Implementation module for socket operations.  See the socket module\n\
  2377. for documentation.";
  2378.  
  2379. static char sockettype_doc[] =
  2380. "A socket represents one endpoint of a network connection.\n\
  2381. \n\
  2382. Methods:\n\
  2383. \n\
  2384. accept() -- accept a connection, returning new socket and client address\n\
  2385. bind() -- bind the socket to a local address\n\
  2386. close() -- close the socket\n\
  2387. connect() -- connect the socket to a remote address\n\
  2388. connect_ex() -- connect, return an error code instead of an exception \n\
  2389. dup() -- return a new socket object identical to the current one (*)\n\
  2390. fileno() -- return underlying file descriptor\n\
  2391. getpeername() -- return remote address (*)\n\
  2392. getsockname() -- return local address\n\
  2393. getsockopt() -- get socket options\n\
  2394. listen() -- start listening for incoming connections\n\
  2395. makefile() -- return a file object corresponding tot the socket (*)\n\
  2396. recv() -- receive data\n\
  2397. recvfrom() -- receive data and sender's address\n\
  2398. send() -- send data\n\
  2399. sendto() -- send data to a given address\n\
  2400. setblocking() -- set or clear the blocking I/O flag\n\
  2401. setsockopt() -- set socket options\n\
  2402. shutdown() -- shut down traffic in one or both directions\n\
  2403. \n\
  2404. (*) not available on all platforms!)";
  2405.  
  2406. DL_EXPORT(void)
  2407. init_socket(void)
  2408. {
  2409.     PyObject *m, *d;
  2410. #ifdef MS_WINDOWS
  2411.     if (!NTinit())
  2412.         return;
  2413. #else
  2414. #if defined(__TOS_OS2__)
  2415.     if (!OS2init())
  2416.         return;
  2417. #endif /* __TOS_OS2__ */
  2418. #endif /* MS_WINDOWS */
  2419.     m = Py_InitModule3("_socket", PySocket_methods, module_doc);
  2420.     d = PyModule_GetDict(m);
  2421.     PySocket_Error = PyErr_NewException("socket.error", NULL, NULL);
  2422.     if (PySocket_Error == NULL)
  2423.         return;
  2424. #ifdef USE_SSL
  2425.     SSL_load_error_strings();
  2426.     SSLeay_add_ssl_algorithms();
  2427.     SSLErrorObject = PyErr_NewException("socket.sslerror", NULL, NULL);
  2428.     if (SSLErrorObject == NULL)
  2429.         return;
  2430.     PyDict_SetItemString(d, "sslerror", SSLErrorObject);
  2431.     Py_INCREF(&SSL_Type);
  2432.     if (PyDict_SetItemString(d, "SSLType",
  2433.                  (PyObject *)&SSL_Type) != 0)
  2434.         return;
  2435. #endif /* USE_SSL */
  2436.     PyDict_SetItemString(d, "error", PySocket_Error);
  2437.     PySocketSock_Type.ob_type = &PyType_Type;
  2438.     PySocketSock_Type.tp_doc = sockettype_doc;
  2439.     Py_INCREF(&PySocketSock_Type);
  2440.     if (PyDict_SetItemString(d, "SocketType",
  2441.                  (PyObject *)&PySocketSock_Type) != 0)
  2442.         return;
  2443.  
  2444.     /* Address families (we only support AF_INET and AF_UNIX) */
  2445. #ifdef AF_UNSPEC
  2446.     insint(d, "AF_UNSPEC", AF_UNSPEC);
  2447. #endif
  2448.     insint(d, "AF_INET", AF_INET);
  2449. #ifdef AF_UNIX
  2450.     insint(d, "AF_UNIX", AF_UNIX);
  2451. #endif /* AF_UNIX */
  2452. #ifdef AF_AX25
  2453.     insint(d, "AF_AX25", AF_AX25); /* Amateur Radio AX.25 */
  2454. #endif
  2455. #ifdef AF_IPX
  2456.     insint(d, "AF_IPX", AF_IPX); /* Novell IPX */
  2457. #endif
  2458. #ifdef AF_APPLETALK
  2459.     insint(d, "AF_APPLETALK", AF_APPLETALK); /* Appletalk DDP */
  2460. #endif
  2461. #ifdef AF_NETROM
  2462.     insint(d, "AF_NETROM", AF_NETROM); /* Amateur radio NetROM */
  2463. #endif
  2464. #ifdef AF_BRIDGE
  2465.     insint(d, "AF_BRIDGE", AF_BRIDGE); /* Multiprotocol bridge */
  2466. #endif
  2467. #ifdef AF_AAL5
  2468.     insint(d, "AF_AAL5", AF_AAL5); /* Reserved for Werner's ATM */
  2469. #endif
  2470. #ifdef AF_X25
  2471.     insint(d, "AF_X25", AF_X25); /* Reserved for X.25 project */
  2472. #endif
  2473. #ifdef AF_INET6
  2474.     insint(d, "AF_INET6", AF_INET6); /* IP version 6 */
  2475. #endif
  2476. #ifdef AF_ROSE
  2477.     insint(d, "AF_ROSE", AF_ROSE); /* Amateur Radio X.25 PLP */
  2478. #endif
  2479.  
  2480.     /* Socket types */
  2481.     insint(d, "SOCK_STREAM", SOCK_STREAM);
  2482.     insint(d, "SOCK_DGRAM", SOCK_DGRAM);
  2483. #ifndef __BEOS__
  2484. /* We have incomplete socket support. */
  2485.     insint(d, "SOCK_RAW", SOCK_RAW);
  2486.     insint(d, "SOCK_SEQPACKET", SOCK_SEQPACKET);
  2487.     insint(d, "SOCK_RDM", SOCK_RDM);
  2488. #endif
  2489.  
  2490. #ifdef    SO_DEBUG
  2491.     insint(d, "SO_DEBUG", SO_DEBUG);
  2492. #endif
  2493. #ifdef    SO_ACCEPTCONN
  2494.     insint(d, "SO_ACCEPTCONN", SO_ACCEPTCONN);
  2495. #endif
  2496. #ifdef    SO_REUSEADDR
  2497.     insint(d, "SO_REUSEADDR", SO_REUSEADDR);
  2498. #endif
  2499. #ifdef    SO_KEEPALIVE
  2500.     insint(d, "SO_KEEPALIVE", SO_KEEPALIVE);
  2501. #endif
  2502. #ifdef    SO_DONTROUTE
  2503.     insint(d, "SO_DONTROUTE", SO_DONTROUTE);
  2504. #endif
  2505. #ifdef    SO_BROADCAST
  2506.     insint(d, "SO_BROADCAST", SO_BROADCAST);
  2507. #endif
  2508. #ifdef    SO_USELOOPBACK
  2509.     insint(d, "SO_USELOOPBACK", SO_USELOOPBACK);
  2510. #endif
  2511. #ifdef    SO_LINGER
  2512.     insint(d, "SO_LINGER", SO_LINGER);
  2513. #endif
  2514. #ifdef    SO_OOBINLINE
  2515.     insint(d, "SO_OOBINLINE", SO_OOBINLINE);
  2516. #endif
  2517. #ifdef    SO_REUSEPORT
  2518.     insint(d, "SO_REUSEPORT", SO_REUSEPORT);
  2519. #endif
  2520. #ifdef    SO_SNDBUF
  2521.     insint(d, "SO_SNDBUF", SO_SNDBUF);
  2522. #endif
  2523. #ifdef    SO_RCVBUF
  2524.     insint(d, "SO_RCVBUF", SO_RCVBUF);
  2525. #endif
  2526. #ifdef    SO_SNDLOWAT
  2527.     insint(d, "SO_SNDLOWAT", SO_SNDLOWAT);
  2528. #endif
  2529. #ifdef    SO_RCVLOWAT
  2530.     insint(d, "SO_RCVLOWAT", SO_RCVLOWAT);
  2531. #endif
  2532. #ifdef    SO_SNDTIMEO
  2533.     insint(d, "SO_SNDTIMEO", SO_SNDTIMEO);
  2534. #endif
  2535. #ifdef    SO_RCVTIMEO
  2536.     insint(d, "SO_RCVTIMEO", SO_RCVTIMEO);
  2537. #endif
  2538. #ifdef    SO_ERROR
  2539.     insint(d, "SO_ERROR", SO_ERROR);
  2540. #endif
  2541. #ifdef    SO_TYPE
  2542.     insint(d, "SO_TYPE", SO_TYPE);
  2543. #endif
  2544.  
  2545.     /* Maximum number of connections for "listen" */
  2546. #ifdef    SOMAXCONN
  2547.     insint(d, "SOMAXCONN", SOMAXCONN);
  2548. #else
  2549.     insint(d, "SOMAXCONN", 5);    /* Common value */
  2550. #endif
  2551.  
  2552.     /* Flags for send, recv */
  2553. #ifdef    MSG_OOB
  2554.     insint(d, "MSG_OOB", MSG_OOB);
  2555. #endif
  2556. #ifdef    MSG_PEEK
  2557.     insint(d, "MSG_PEEK", MSG_PEEK);
  2558. #endif
  2559. #ifdef    MSG_DONTROUTE
  2560.     insint(d, "MSG_DONTROUTE", MSG_DONTROUTE);
  2561. #endif
  2562. #ifdef    MSG_DONTWAIT
  2563.     insint(d, "MSG_DONTWAIT", MSG_DONTWAIT);
  2564. #endif
  2565. #ifdef    MSG_EOR
  2566.     insint(d, "MSG_EOR", MSG_EOR);
  2567. #endif
  2568. #ifdef    MSG_TRUNC
  2569.     insint(d, "MSG_TRUNC", MSG_TRUNC);
  2570. #endif
  2571. #ifdef    MSG_CTRUNC
  2572.     insint(d, "MSG_CTRUNC", MSG_CTRUNC);
  2573. #endif
  2574. #ifdef    MSG_WAITALL
  2575.     insint(d, "MSG_WAITALL", MSG_WAITALL);
  2576. #endif
  2577. #ifdef    MSG_BTAG
  2578.     insint(d, "MSG_BTAG", MSG_BTAG);
  2579. #endif
  2580. #ifdef    MSG_ETAG
  2581.     insint(d, "MSG_ETAG", MSG_ETAG);
  2582. #endif
  2583.  
  2584.     /* Protocol level and numbers, usable for [gs]etsockopt */
  2585. #ifdef    SOL_SOCKET
  2586.     insint(d, "SOL_SOCKET", SOL_SOCKET);
  2587. #endif
  2588. #ifdef    SOL_IP
  2589.     insint(d, "SOL_IP", SOL_IP);
  2590. #else
  2591.     insint(d, "SOL_IP", 0);
  2592. #endif
  2593. #ifdef    SOL_IPX
  2594.     insint(d, "SOL_IPX", SOL_IPX);
  2595. #endif
  2596. #ifdef    SOL_AX25
  2597.     insint(d, "SOL_AX25", SOL_AX25);
  2598. #endif
  2599. #ifdef    SOL_ATALK
  2600.     insint(d, "SOL_ATALK", SOL_ATALK);
  2601. #endif
  2602. #ifdef    SOL_NETROM
  2603.     insint(d, "SOL_NETROM", SOL_NETROM);
  2604. #endif
  2605. #ifdef    SOL_ROSE
  2606.     insint(d, "SOL_ROSE", SOL_ROSE);
  2607. #endif
  2608. #ifdef    SOL_TCP
  2609.     insint(d, "SOL_TCP", SOL_TCP);
  2610. #else
  2611.     insint(d, "SOL_TCP", 6);
  2612. #endif
  2613. #ifdef    SOL_UDP
  2614.     insint(d, "SOL_UDP", SOL_UDP);
  2615. #else
  2616.     insint(d, "SOL_UDP", 17);
  2617. #endif
  2618. #ifdef    IPPROTO_IP
  2619.     insint(d, "IPPROTO_IP", IPPROTO_IP);
  2620. #else
  2621.     insint(d, "IPPROTO_IP", 0);
  2622. #endif
  2623. #ifdef    IPPROTO_ICMP
  2624.     insint(d, "IPPROTO_ICMP", IPPROTO_ICMP);
  2625. #else
  2626.     insint(d, "IPPROTO_ICMP", 1);
  2627. #endif
  2628. #ifdef    IPPROTO_IGMP
  2629.     insint(d, "IPPROTO_IGMP", IPPROTO_IGMP);
  2630. #endif
  2631. #ifdef    IPPROTO_GGP
  2632.     insint(d, "IPPROTO_GGP", IPPROTO_GGP);
  2633. #endif
  2634. #ifdef    IPPROTO_TCP
  2635.     insint(d, "IPPROTO_TCP", IPPROTO_TCP);
  2636. #else
  2637.     insint(d, "IPPROTO_TCP", 6);
  2638. #endif
  2639. #ifdef    IPPROTO_EGP
  2640.     insint(d, "IPPROTO_EGP", IPPROTO_EGP);
  2641. #endif
  2642. #ifdef    IPPROTO_PUP
  2643.     insint(d, "IPPROTO_PUP", IPPROTO_PUP);
  2644. #endif
  2645. #ifdef    IPPROTO_UDP
  2646.     insint(d, "IPPROTO_UDP", IPPROTO_UDP);
  2647. #else
  2648.     insint(d, "IPPROTO_UDP", 17);
  2649. #endif
  2650. #ifdef    IPPROTO_IDP
  2651.     insint(d, "IPPROTO_IDP", IPPROTO_IDP);
  2652. #endif
  2653. #ifdef    IPPROTO_HELLO
  2654.     insint(d, "IPPROTO_HELLO", IPPROTO_HELLO);
  2655. #endif
  2656. #ifdef    IPPROTO_ND
  2657.     insint(d, "IPPROTO_ND", IPPROTO_ND);
  2658. #endif
  2659. #ifdef    IPPROTO_TP
  2660.     insint(d, "IPPROTO_TP", IPPROTO_TP);
  2661. #endif
  2662. #ifdef    IPPROTO_XTP
  2663.     insint(d, "IPPROTO_XTP", IPPROTO_XTP);
  2664. #endif
  2665. #ifdef    IPPROTO_EON
  2666.     insint(d, "IPPROTO_EON", IPPROTO_EON);
  2667. #endif
  2668. #ifdef    IPPROTO_BIP
  2669.     insint(d, "IPPROTO_BIP", IPPROTO_BIP);
  2670. #endif
  2671. /**/
  2672. #ifdef    IPPROTO_RAW
  2673.     insint(d, "IPPROTO_RAW", IPPROTO_RAW);
  2674. #else
  2675.     insint(d, "IPPROTO_RAW", 255);
  2676. #endif
  2677. #ifdef    IPPROTO_MAX
  2678.     insint(d, "IPPROTO_MAX", IPPROTO_MAX);
  2679. #endif
  2680.  
  2681.     /* Some port configuration */
  2682. #ifdef    IPPORT_RESERVED
  2683.     insint(d, "IPPORT_RESERVED", IPPORT_RESERVED);
  2684. #else
  2685.     insint(d, "IPPORT_RESERVED", 1024);
  2686. #endif
  2687. #ifdef    IPPORT_USERRESERVED
  2688.     insint(d, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
  2689. #else
  2690.     insint(d, "IPPORT_USERRESERVED", 5000);
  2691. #endif
  2692.  
  2693.     /* Some reserved IP v.4 addresses */
  2694. #ifdef    INADDR_ANY
  2695.     insint(d, "INADDR_ANY", INADDR_ANY);
  2696. #else
  2697.     insint(d, "INADDR_ANY", 0x00000000);
  2698. #endif
  2699. #ifdef    INADDR_BROADCAST
  2700.     insint(d, "INADDR_BROADCAST", INADDR_BROADCAST);
  2701. #else
  2702.     insint(d, "INADDR_BROADCAST", 0xffffffff);
  2703. #endif
  2704. #ifdef    INADDR_LOOPBACK
  2705.     insint(d, "INADDR_LOOPBACK", INADDR_LOOPBACK);
  2706. #else
  2707.     insint(d, "INADDR_LOOPBACK", 0x7F000001);
  2708. #endif
  2709. #ifdef    INADDR_UNSPEC_GROUP
  2710.     insint(d, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
  2711. #else
  2712.     insint(d, "INADDR_UNSPEC_GROUP", 0xe0000000);
  2713. #endif
  2714. #ifdef    INADDR_ALLHOSTS_GROUP
  2715.     insint(d, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP);
  2716. #else
  2717.     insint(d, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
  2718. #endif
  2719. #ifdef    INADDR_MAX_LOCAL_GROUP
  2720.     insint(d, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP);
  2721. #else
  2722.     insint(d, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
  2723. #endif
  2724. #ifdef    INADDR_NONE
  2725.     insint(d, "INADDR_NONE", INADDR_NONE);
  2726. #else
  2727.     insint(d, "INADDR_NONE", 0xffffffff);
  2728. #endif
  2729.  
  2730.     /* IP [gs]etsockopt options */
  2731. #ifdef    IP_OPTIONS
  2732.     insint(d, "IP_OPTIONS", IP_OPTIONS);
  2733. #endif
  2734. #ifdef    IP_HDRINCL
  2735.     insint(d, "IP_HDRINCL", IP_HDRINCL);
  2736. #endif
  2737. #ifdef    IP_TOS
  2738.     insint(d, "IP_TOS", IP_TOS);
  2739. #endif
  2740. #ifdef    IP_TTL
  2741.     insint(d, "IP_TTL", IP_TTL);
  2742. #endif
  2743. #ifdef    IP_RECVOPTS
  2744.     insint(d, "IP_RECVOPTS", IP_RECVOPTS);
  2745. #endif
  2746. #ifdef    IP_RECVRETOPTS
  2747.     insint(d, "IP_RECVRETOPTS", IP_RECVRETOPTS);
  2748. #endif
  2749. #ifdef    IP_RECVDSTADDR
  2750.     insint(d, "IP_RECVDSTADDR", IP_RECVDSTADDR);
  2751. #endif
  2752. #ifdef    IP_RETOPTS
  2753.     insint(d, "IP_RETOPTS", IP_RETOPTS);
  2754. #endif
  2755. #ifdef    IP_MULTICAST_IF
  2756.     insint(d, "IP_MULTICAST_IF", IP_MULTICAST_IF);
  2757. #endif
  2758. #ifdef    IP_MULTICAST_TTL
  2759.     insint(d, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
  2760. #endif
  2761. #ifdef    IP_MULTICAST_LOOP
  2762.     insint(d, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
  2763. #endif
  2764. #ifdef    IP_ADD_MEMBERSHIP
  2765.     insint(d, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
  2766. #endif
  2767. #ifdef    IP_DROP_MEMBERSHIP
  2768.     insint(d, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
  2769. #endif
  2770. #ifdef    IP_DEFAULT_MULTICAST_TTL
  2771.     insint(d, "IP_DEFAULT_MULTICAST_TTL", IP_DEFAULT_MULTICAST_TTL);
  2772. #endif
  2773. #ifdef    IP_DEFAULT_MULTICAST_LOOP
  2774.     insint(d, "IP_DEFAULT_MULTICAST_LOOP", IP_DEFAULT_MULTICAST_LOOP);
  2775. #endif
  2776. #ifdef    IP_MAX_MEMBERSHIPS
  2777.     insint(d, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
  2778. #endif
  2779.  
  2780.     /* TCP options */
  2781. #ifdef    TCP_NODELAY
  2782.     insint(d, "TCP_NODELAY", TCP_NODELAY);
  2783. #endif
  2784. #ifdef    TCP_MAXSEG
  2785.     insint(d, "TCP_MAXSEG", TCP_MAXSEG);
  2786. #endif
  2787.  
  2788.     /* IPX options */
  2789. #ifdef    IPX_TYPE
  2790.     insint(d, "IPX_TYPE", IPX_TYPE);
  2791. #endif
  2792.  
  2793.     /* Initialize gethostbyname lock */
  2794. #ifdef USE_GETHOSTBYNAME_LOCK
  2795.     gethostbyname_lock = PyThread_allocate_lock();
  2796. #endif
  2797. }
  2798.