PageRenderTime 67ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/MOULOpenSourceClientPlugin/Plasma20/SDKs/XPlatform/Cypython-2.3.3/Modules/socketmodule.c

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