PageRenderTime 70ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/Modules/socketmodule.c

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