PageRenderTime 59ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/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

Large files files are truncated, but you can click here to view the full file

  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. f

Large files files are truncated, but you can click here to view the full file