PageRenderTime 72ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/Modules/socketmodule.c

https://bitbucket.org/mirror/python-release25-maint
C | 5096 lines | 4071 code | 586 blank | 439 comment | 540 complexity | 631d9354adf7b82818fcf7948b11813e MD5 | raw file
Possible License(s): 0BSD

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 and AF_NETLINK are supported under Linux.
  7. - No read/write operations (use sendall/recv or makefile instead).
  8. - Additional restrictions apply on some non-Unix platforms (compensated
  9. for by socket.py).
  10. Module interface:
  11. - socket.error: exception raised for socket specific errors
  12. - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
  13. a subclass of socket.error
  14. - socket.herror: exception raised for gethostby* errors,
  15. a subclass of socket.error
  16. - socket.fromfd(fd, family, type[, proto]) --> new socket object (created
  17. from an existing file descriptor)
  18. - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
  19. - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
  20. - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
  21. - socket.getprotobyname(protocolname) --> protocol number
  22. - socket.getservbyname(servicename[, protocolname]) --> port number
  23. - socket.getservbyport(portnumber[, protocolname]) --> service name
  24. - socket.socket([family[, type [, proto]]]) --> new socket object
  25. - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
  26. - socket.ntohs(16 bit value) --> new int object
  27. - socket.ntohl(32 bit value) --> new int object
  28. - socket.htons(16 bit value) --> new int object
  29. - socket.htonl(32 bit value) --> new int object
  30. - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
  31. --> List of (family, socktype, proto, canonname, sockaddr)
  32. - socket.getnameinfo(sockaddr, flags) --> (host, port)
  33. - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
  34. - socket.has_ipv6: boolean value indicating if IPv6 is supported
  35. - socket.inet_aton(IP address) -> 32-bit packed IP representation
  36. - socket.inet_ntoa(packed IP) -> IP address string
  37. - socket.getdefaulttimeout() -> None | float
  38. - socket.setdefaulttimeout(None | float)
  39. - an Internet socket address is a pair (hostname, port)
  40. where hostname can be anything recognized by gethostbyname()
  41. (including the dd.dd.dd.dd notation) and port is in host byte order
  42. - where a hostname is returned, the dd.dd.dd.dd notation is used
  43. - a UNIX domain socket address is a string specifying the pathname
  44. - an AF_PACKET socket address is a tuple containing a string
  45. specifying the ethernet interface and an integer specifying
  46. the Ethernet protocol number to be received. For example:
  47. ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
  48. specify packet-type and ha-type/addr.
  49. Local naming conventions:
  50. - names starting with sock_ are socket object methods
  51. - names starting with socket_ are module-level functions
  52. - names starting with PySocket are exported through socketmodule.h
  53. */
  54. #ifdef __APPLE__
  55. /*
  56. * inet_aton is not available on OSX 10.3, yet we want to use a binary
  57. * that was build on 10.4 or later to work on that release, weak linking
  58. * comes to the rescue.
  59. */
  60. # pragma weak inet_aton
  61. #endif
  62. #include "Python.h"
  63. #include "structmember.h"
  64. #undef MAX
  65. #define MAX(x, y) ((x) < (y) ? (y) : (x))
  66. /* Socket object documentation */
  67. PyDoc_STRVAR(sock_doc,
  68. "socket([family[, type[, proto]]]) -> socket object\n\
  69. \n\
  70. Open a socket of the given type. The family argument specifies the\n\
  71. address family; it defaults to AF_INET. The type argument specifies\n\
  72. whether this is a stream (SOCK_STREAM, this is the default)\n\
  73. or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
  74. specifying the default protocol. Keyword arguments are accepted.\n\
  75. \n\
  76. A socket object represents one endpoint of a network connection.\n\
  77. \n\
  78. Methods of socket objects (keyword arguments not allowed):\n\
  79. \n\
  80. accept() -- accept a connection, returning new socket and client address\n\
  81. bind(addr) -- bind the socket to a local address\n\
  82. close() -- close the socket\n\
  83. connect(addr) -- connect the socket to a remote address\n\
  84. connect_ex(addr) -- connect, return an error code instead of an exception\n\
  85. dup() -- return a new socket object identical to the current one [*]\n\
  86. fileno() -- return underlying file descriptor\n\
  87. getpeername() -- return remote address [*]\n\
  88. getsockname() -- return local address\n\
  89. getsockopt(level, optname[, buflen]) -- get socket options\n\
  90. gettimeout() -- return timeout or None\n\
  91. listen(n) -- start listening for incoming connections\n\
  92. makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
  93. recv(buflen[, flags]) -- receive data\n\
  94. recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
  95. recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
  96. recvfrom_into(buffer[, nbytes, [, flags])\n\
  97. -- receive data and sender\'s address (into a buffer)\n\
  98. sendall(data[, flags]) -- send all data\n\
  99. send(data[, flags]) -- send data, may not send all of it\n\
  100. sendto(data[, flags], addr) -- send data to a given address\n\
  101. setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
  102. setsockopt(level, optname, value) -- set socket options\n\
  103. settimeout(None | float) -- set or clear the timeout\n\
  104. shutdown(how) -- shut down traffic in one or both directions\n\
  105. \n\
  106. [*] not available on all platforms!");
  107. /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
  108. I hope some day someone can clean this up please... */
  109. /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
  110. script doesn't get this right, so we hardcode some platform checks below.
  111. On the other hand, not all Linux versions agree, so there the settings
  112. computed by the configure script are needed! */
  113. #ifndef linux
  114. # undef HAVE_GETHOSTBYNAME_R_3_ARG
  115. # undef HAVE_GETHOSTBYNAME_R_5_ARG
  116. # undef HAVE_GETHOSTBYNAME_R_6_ARG
  117. #endif
  118. #ifndef WITH_THREAD
  119. # undef HAVE_GETHOSTBYNAME_R
  120. #endif
  121. #ifdef HAVE_GETHOSTBYNAME_R
  122. # if defined(_AIX) || defined(__osf__)
  123. # define HAVE_GETHOSTBYNAME_R_3_ARG
  124. # elif defined(__sun) || defined(__sgi)
  125. # define HAVE_GETHOSTBYNAME_R_5_ARG
  126. # elif defined(linux)
  127. /* Rely on the configure script */
  128. # else
  129. # undef HAVE_GETHOSTBYNAME_R
  130. # endif
  131. #endif
  132. #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
  133. !defined(MS_WINDOWS)
  134. # define USE_GETHOSTBYNAME_LOCK
  135. #endif
  136. /* To use __FreeBSD_version */
  137. #ifdef HAVE_SYS_PARAM_H
  138. #include <sys/param.h>
  139. #endif
  140. /* On systems on which getaddrinfo() is believed to not be thread-safe,
  141. (this includes the getaddrinfo emulation) protect access with a lock. */
  142. #if defined(WITH_THREAD) && (defined(__APPLE__) || \
  143. (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
  144. defined(__OpenBSD__) || defined(__NetBSD__) || \
  145. defined(__VMS) || !defined(HAVE_GETADDRINFO))
  146. #define USE_GETADDRINFO_LOCK
  147. #endif
  148. #ifdef USE_GETADDRINFO_LOCK
  149. #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
  150. #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
  151. #else
  152. #define ACQUIRE_GETADDRINFO_LOCK
  153. #define RELEASE_GETADDRINFO_LOCK
  154. #endif
  155. #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
  156. # include "pythread.h"
  157. #endif
  158. #if defined(PYCC_VACPP)
  159. # include <types.h>
  160. # include <io.h>
  161. # include <sys/ioctl.h>
  162. # include <utils.h>
  163. # include <ctype.h>
  164. #endif
  165. #if defined(__VMS)
  166. # include <ioctl.h>
  167. #endif
  168. #if defined(PYOS_OS2)
  169. # define INCL_DOS
  170. # define INCL_DOSERRORS
  171. # define INCL_NOPMAPI
  172. # include <os2.h>
  173. #endif
  174. #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
  175. /* make sure that the reentrant (gethostbyaddr_r etc)
  176. functions are declared correctly if compiling with
  177. MIPSPro 7.x in ANSI C mode (default) */
  178. /* XXX Using _SGIAPI is the wrong thing,
  179. but I don't know what the right thing is. */
  180. #undef _SGIAPI /* to avoid warning */
  181. #define _SGIAPI 1
  182. #undef _XOPEN_SOURCE
  183. #include <sys/socket.h>
  184. #include <sys/types.h>
  185. #include <netinet/in.h>
  186. #ifdef _SS_ALIGNSIZE
  187. #define HAVE_GETADDRINFO 1
  188. #define HAVE_GETNAMEINFO 1
  189. #endif
  190. #define HAVE_INET_PTON
  191. #include <netdb.h>
  192. #endif
  193. /* Irix 6.5 fails to define this variable at all. This is needed
  194. for both GCC and SGI's compiler. I'd say that the SGI headers
  195. are just busted. Same thing for Solaris. */
  196. #if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
  197. #define INET_ADDRSTRLEN 16
  198. #endif
  199. /* Generic includes */
  200. #ifdef HAVE_SYS_TYPES_H
  201. #include <sys/types.h>
  202. #endif
  203. /* Generic socket object definitions and includes */
  204. #define PySocket_BUILDING_SOCKET
  205. #include "socketmodule.h"
  206. /* Addressing includes */
  207. #ifndef MS_WINDOWS
  208. /* Non-MS WINDOWS includes */
  209. # include <netdb.h>
  210. /* Headers needed for inet_ntoa() and inet_addr() */
  211. # ifdef __BEOS__
  212. # include <net/netdb.h>
  213. # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
  214. # include <netdb.h>
  215. typedef size_t socklen_t;
  216. # else
  217. # include <arpa/inet.h>
  218. # endif
  219. # ifndef RISCOS
  220. # include <fcntl.h>
  221. # else
  222. # include <sys/ioctl.h>
  223. # include <socklib.h>
  224. # define NO_DUP
  225. int h_errno; /* not used */
  226. # define INET_ADDRSTRLEN 16
  227. # endif
  228. #else
  229. /* MS_WINDOWS includes */
  230. # ifdef HAVE_FCNTL_H
  231. # include <fcntl.h>
  232. # endif
  233. #endif
  234. #include <stddef.h>
  235. #ifndef offsetof
  236. # define offsetof(type, member) ((size_t)(&((type *)0)->member))
  237. #endif
  238. #ifndef O_NONBLOCK
  239. # define O_NONBLOCK O_NDELAY
  240. #endif
  241. /* include Python's addrinfo.h unless it causes trouble */
  242. #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
  243. /* Do not include addinfo.h on some newer IRIX versions.
  244. * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
  245. * for example, but not by 6.5.10.
  246. */
  247. #elif defined(_MSC_VER) && _MSC_VER>1201
  248. /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
  249. * EAI_* constants are defined in (the already included) ws2tcpip.h.
  250. */
  251. #else
  252. # include "addrinfo.h"
  253. #endif
  254. #ifndef HAVE_INET_PTON
  255. int inet_pton(int af, const char *src, void *dst);
  256. const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
  257. #endif
  258. #ifdef __APPLE__
  259. /* On OS X, getaddrinfo returns no error indication of lookup
  260. failure, so we must use the emulation instead of the libinfo
  261. implementation. Unfortunately, performing an autoconf test
  262. for this bug would require DNS access for the machine performing
  263. the configuration, which is not acceptable. Therefore, we
  264. determine the bug just by checking for __APPLE__. If this bug
  265. gets ever fixed, perhaps checking for sys/version.h would be
  266. appropriate, which is 10/0 on the system with the bug. */
  267. #ifndef HAVE_GETNAMEINFO
  268. /* This bug seems to be fixed in Jaguar. Ths easiest way I could
  269. Find to check for Jaguar is that it has getnameinfo(), which
  270. older releases don't have */
  271. #undef HAVE_GETADDRINFO
  272. #endif
  273. #ifdef HAVE_INET_ATON
  274. #define USE_INET_ATON_WEAKLINK
  275. #endif
  276. #endif
  277. /* I know this is a bad practice, but it is the easiest... */
  278. #if !defined(HAVE_GETADDRINFO)
  279. /* avoid clashes with the C library definition of the symbol. */
  280. #define getaddrinfo fake_getaddrinfo
  281. #define gai_strerror fake_gai_strerror
  282. #define freeaddrinfo fake_freeaddrinfo
  283. #include "getaddrinfo.c"
  284. #endif
  285. #if !defined(HAVE_GETNAMEINFO)
  286. #define getnameinfo fake_getnameinfo
  287. #include "getnameinfo.c"
  288. #endif
  289. #if defined(MS_WINDOWS) || defined(__BEOS__)
  290. /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
  291. /* seem to be a few differences in the API */
  292. #define SOCKETCLOSE closesocket
  293. #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
  294. #endif
  295. #ifdef MS_WIN32
  296. #define EAFNOSUPPORT WSAEAFNOSUPPORT
  297. #define snprintf _snprintf
  298. #endif
  299. #if defined(PYOS_OS2) && !defined(PYCC_GCC)
  300. #define SOCKETCLOSE soclose
  301. #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
  302. #endif
  303. #ifndef SOCKETCLOSE
  304. #define SOCKETCLOSE close
  305. #endif
  306. #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)
  307. #define USE_BLUETOOTH 1
  308. #if defined(__FreeBSD__)
  309. #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
  310. #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
  311. #define sockaddr_l2 sockaddr_l2cap
  312. #define sockaddr_rc sockaddr_rfcomm
  313. #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
  314. #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
  315. #elif defined(__NetBSD__)
  316. #define sockaddr_l2 sockaddr_bt
  317. #define sockaddr_rc sockaddr_bt
  318. #define sockaddr_sco sockaddr_bt
  319. #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
  320. #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
  321. #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
  322. #else
  323. #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
  324. #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
  325. #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
  326. #endif
  327. #endif
  328. #ifdef __VMS
  329. /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
  330. #define SEGMENT_SIZE (32 * 1024 -1)
  331. #endif
  332. #define SAS2SA(x) ((struct sockaddr *)(x))
  333. /*
  334. * Constants for getnameinfo()
  335. */
  336. #if !defined(NI_MAXHOST)
  337. #define NI_MAXHOST 1025
  338. #endif
  339. #if !defined(NI_MAXSERV)
  340. #define NI_MAXSERV 32
  341. #endif
  342. /* XXX There's a problem here: *static* functions are not supposed to have
  343. a Py prefix (or use CapitalizedWords). Later... */
  344. /* Global variable holding the exception type for errors detected
  345. by this module (but not argument type or memory errors, etc.). */
  346. static PyObject *socket_error;
  347. static PyObject *socket_herror;
  348. static PyObject *socket_gaierror;
  349. static PyObject *socket_timeout;
  350. #ifdef RISCOS
  351. /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
  352. static int taskwindow;
  353. #endif
  354. /* A forward reference to the socket type object.
  355. The sock_type variable contains pointers to various functions,
  356. some of which call new_sockobject(), which uses sock_type, so
  357. there has to be a circular reference. */
  358. static PyTypeObject sock_type;
  359. #if defined(HAVE_POLL_H)
  360. #include <poll.h>
  361. #elif defined(HAVE_SYS_POLL_H)
  362. #include <sys/poll.h>
  363. #endif
  364. #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
  365. /* Platform can select file descriptors beyond FD_SETSIZE */
  366. #define IS_SELECTABLE(s) 1
  367. #elif defined(HAVE_POLL)
  368. /* Instead of select(), we'll use poll() since poll() works on any fd. */
  369. #define IS_SELECTABLE(s) 1
  370. /* Can we call select() with this socket without a buffer overrun? */
  371. #else
  372. /* POSIX says selecting file descriptors beyond FD_SETSIZE
  373. has undefined behaviour. If there's no timeout left, we don't have to
  374. call select, so it's a safe, little white lie. */
  375. #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
  376. #endif
  377. static PyObject*
  378. select_error(void)
  379. {
  380. PyErr_SetString(socket_error, "unable to select on socket");
  381. return NULL;
  382. }
  383. /* Convenience function to raise an error according to errno
  384. and return a NULL pointer from a function. */
  385. static PyObject *
  386. set_error(void)
  387. {
  388. #ifdef MS_WINDOWS
  389. int err_no = WSAGetLastError();
  390. static struct {
  391. int no;
  392. const char *msg;
  393. } *msgp, msgs[] = {
  394. {WSAEINTR, "Interrupted system call"},
  395. {WSAEBADF, "Bad file descriptor"},
  396. {WSAEACCES, "Permission denied"},
  397. {WSAEFAULT, "Bad address"},
  398. {WSAEINVAL, "Invalid argument"},
  399. {WSAEMFILE, "Too many open files"},
  400. {WSAEWOULDBLOCK,
  401. "The socket operation could not complete "
  402. "without blocking"},
  403. {WSAEINPROGRESS, "Operation now in progress"},
  404. {WSAEALREADY, "Operation already in progress"},
  405. {WSAENOTSOCK, "Socket operation on non-socket"},
  406. {WSAEDESTADDRREQ, "Destination address required"},
  407. {WSAEMSGSIZE, "Message too long"},
  408. {WSAEPROTOTYPE, "Protocol wrong type for socket"},
  409. {WSAENOPROTOOPT, "Protocol not available"},
  410. {WSAEPROTONOSUPPORT, "Protocol not supported"},
  411. {WSAESOCKTNOSUPPORT, "Socket type not supported"},
  412. {WSAEOPNOTSUPP, "Operation not supported"},
  413. {WSAEPFNOSUPPORT, "Protocol family not supported"},
  414. {WSAEAFNOSUPPORT, "Address family not supported"},
  415. {WSAEADDRINUSE, "Address already in use"},
  416. {WSAEADDRNOTAVAIL, "Can't assign requested address"},
  417. {WSAENETDOWN, "Network is down"},
  418. {WSAENETUNREACH, "Network is unreachable"},
  419. {WSAENETRESET, "Network dropped connection on reset"},
  420. {WSAECONNABORTED, "Software caused connection abort"},
  421. {WSAECONNRESET, "Connection reset by peer"},
  422. {WSAENOBUFS, "No buffer space available"},
  423. {WSAEISCONN, "Socket is already connected"},
  424. {WSAENOTCONN, "Socket is not connected"},
  425. {WSAESHUTDOWN, "Can't send after socket shutdown"},
  426. {WSAETOOMANYREFS, "Too many references: can't splice"},
  427. {WSAETIMEDOUT, "Operation timed out"},
  428. {WSAECONNREFUSED, "Connection refused"},
  429. {WSAELOOP, "Too many levels of symbolic links"},
  430. {WSAENAMETOOLONG, "File name too long"},
  431. {WSAEHOSTDOWN, "Host is down"},
  432. {WSAEHOSTUNREACH, "No route to host"},
  433. {WSAENOTEMPTY, "Directory not empty"},
  434. {WSAEPROCLIM, "Too many processes"},
  435. {WSAEUSERS, "Too many users"},
  436. {WSAEDQUOT, "Disc quota exceeded"},
  437. {WSAESTALE, "Stale NFS file handle"},
  438. {WSAEREMOTE, "Too many levels of remote in path"},
  439. {WSASYSNOTREADY, "Network subsystem is unvailable"},
  440. {WSAVERNOTSUPPORTED, "WinSock version is not supported"},
  441. {WSANOTINITIALISED,
  442. "Successful WSAStartup() not yet performed"},
  443. {WSAEDISCON, "Graceful shutdown in progress"},
  444. /* Resolver errors */
  445. {WSAHOST_NOT_FOUND, "No such host is known"},
  446. {WSATRY_AGAIN, "Host not found, or server failed"},
  447. {WSANO_RECOVERY, "Unexpected server error encountered"},
  448. {WSANO_DATA, "Valid name without requested data"},
  449. {WSANO_ADDRESS, "No address, look for MX record"},
  450. {0, NULL}
  451. };
  452. if (err_no) {
  453. PyObject *v;
  454. const char *msg = "winsock error";
  455. for (msgp = msgs; msgp->msg; msgp++) {
  456. if (err_no == msgp->no) {
  457. msg = msgp->msg;
  458. break;
  459. }
  460. }
  461. v = Py_BuildValue("(is)", err_no, msg);
  462. if (v != NULL) {
  463. PyErr_SetObject(socket_error, v);
  464. Py_DECREF(v);
  465. }
  466. return NULL;
  467. }
  468. else
  469. #endif
  470. #if defined(PYOS_OS2) && !defined(PYCC_GCC)
  471. if (sock_errno() != NO_ERROR) {
  472. APIRET rc;
  473. ULONG msglen;
  474. char outbuf[100];
  475. int myerrorcode = sock_errno();
  476. /* Retrieve socket-related error message from MPTN.MSG file */
  477. rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
  478. myerrorcode - SOCBASEERR + 26,
  479. "mptn.msg",
  480. &msglen);
  481. if (rc == NO_ERROR) {
  482. PyObject *v;
  483. /* OS/2 doesn't guarantee a terminator */
  484. outbuf[msglen] = '\0';
  485. if (strlen(outbuf) > 0) {
  486. /* If non-empty msg, trim CRLF */
  487. char *lastc = &outbuf[ strlen(outbuf)-1 ];
  488. while (lastc > outbuf &&
  489. isspace(Py_CHARMASK(*lastc))) {
  490. /* Trim trailing whitespace (CRLF) */
  491. *lastc-- = '\0';
  492. }
  493. }
  494. v = Py_BuildValue("(is)", myerrorcode, outbuf);
  495. if (v != NULL) {
  496. PyErr_SetObject(socket_error, v);
  497. Py_DECREF(v);
  498. }
  499. return NULL;
  500. }
  501. }
  502. #endif
  503. #if defined(RISCOS)
  504. if (_inet_error.errnum != NULL) {
  505. PyObject *v;
  506. v = Py_BuildValue("(is)", errno, _inet_err());
  507. if (v != NULL) {
  508. PyErr_SetObject(socket_error, v);
  509. Py_DECREF(v);
  510. }
  511. return NULL;
  512. }
  513. #endif
  514. return PyErr_SetFromErrno(socket_error);
  515. }
  516. static PyObject *
  517. set_herror(int h_error)
  518. {
  519. PyObject *v;
  520. #ifdef HAVE_HSTRERROR
  521. v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
  522. #else
  523. v = Py_BuildValue("(is)", h_error, "host not found");
  524. #endif
  525. if (v != NULL) {
  526. PyErr_SetObject(socket_herror, v);
  527. Py_DECREF(v);
  528. }
  529. return NULL;
  530. }
  531. static PyObject *
  532. set_gaierror(int error)
  533. {
  534. PyObject *v;
  535. #ifdef EAI_SYSTEM
  536. /* EAI_SYSTEM is not available on Windows XP. */
  537. if (error == EAI_SYSTEM)
  538. return set_error();
  539. #endif
  540. #ifdef HAVE_GAI_STRERROR
  541. v = Py_BuildValue("(is)", error, gai_strerror(error));
  542. #else
  543. v = Py_BuildValue("(is)", error, "getaddrinfo failed");
  544. #endif
  545. if (v != NULL) {
  546. PyErr_SetObject(socket_gaierror, v);
  547. Py_DECREF(v);
  548. }
  549. return NULL;
  550. }
  551. #ifdef __VMS
  552. /* Function to send in segments */
  553. static int
  554. sendsegmented(int sock_fd, char *buf, int len, int flags)
  555. {
  556. int n = 0;
  557. int remaining = len;
  558. while (remaining > 0) {
  559. unsigned int segment;
  560. segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
  561. n = send(sock_fd, buf, segment, flags);
  562. if (n < 0) {
  563. return n;
  564. }
  565. remaining -= segment;
  566. buf += segment;
  567. } /* end while */
  568. return len;
  569. }
  570. #endif
  571. /* Function to perform the setting of socket blocking mode
  572. internally. block = (1 | 0). */
  573. static int
  574. internal_setblocking(PySocketSockObject *s, int block)
  575. {
  576. #ifndef RISCOS
  577. #ifndef MS_WINDOWS
  578. int delay_flag;
  579. #endif
  580. #endif
  581. Py_BEGIN_ALLOW_THREADS
  582. #ifdef __BEOS__
  583. block = !block;
  584. setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
  585. (void *)(&block), sizeof(int));
  586. #else
  587. #ifndef RISCOS
  588. #ifndef MS_WINDOWS
  589. #if defined(PYOS_OS2) && !defined(PYCC_GCC)
  590. block = !block;
  591. ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
  592. #elif defined(__VMS)
  593. block = !block;
  594. ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
  595. #else /* !PYOS_OS2 && !__VMS */
  596. delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
  597. if (block)
  598. delay_flag &= (~O_NONBLOCK);
  599. else
  600. delay_flag |= O_NONBLOCK;
  601. fcntl(s->sock_fd, F_SETFL, delay_flag);
  602. #endif /* !PYOS_OS2 */
  603. #else /* MS_WINDOWS */
  604. block = !block;
  605. ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
  606. #endif /* MS_WINDOWS */
  607. #else /* RISCOS */
  608. block = !block;
  609. socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
  610. #endif /* RISCOS */
  611. #endif /* __BEOS__ */
  612. Py_END_ALLOW_THREADS
  613. /* Since these don't return anything */
  614. return 1;
  615. }
  616. /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
  617. The argument writing indicates the direction.
  618. This does not raise an exception; we'll let our caller do that
  619. after they've reacquired the interpreter lock.
  620. Returns 1 on timeout, -1 on error, 0 otherwise. */
  621. static int
  622. internal_select(PySocketSockObject *s, int writing)
  623. {
  624. int n;
  625. /* Nothing to do unless we're in timeout mode (not non-blocking) */
  626. if (s->sock_timeout <= 0.0)
  627. return 0;
  628. /* Guard against closed socket */
  629. if (s->sock_fd < 0)
  630. return 0;
  631. /* Prefer poll, if available, since you can poll() any fd
  632. * which can't be done with select(). */
  633. #ifdef HAVE_POLL
  634. {
  635. struct pollfd pollfd;
  636. int timeout;
  637. pollfd.fd = s->sock_fd;
  638. pollfd.events = writing ? POLLOUT : POLLIN;
  639. /* s->sock_timeout is in seconds, timeout in ms */
  640. timeout = (int)(s->sock_timeout * 1000 + 0.5);
  641. n = poll(&pollfd, 1, timeout);
  642. }
  643. #else
  644. {
  645. /* Construct the arguments to select */
  646. fd_set fds;
  647. struct timeval tv;
  648. tv.tv_sec = (int)s->sock_timeout;
  649. tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
  650. FD_ZERO(&fds);
  651. FD_SET(s->sock_fd, &fds);
  652. /* See if the socket is ready */
  653. if (writing)
  654. n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
  655. else
  656. n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
  657. }
  658. #endif
  659. if (n < 0)
  660. return -1;
  661. if (n == 0)
  662. return 1;
  663. return 0;
  664. }
  665. /* Initialize a new socket object. */
  666. static double defaulttimeout = -1.0; /* Default timeout for new sockets */
  667. PyMODINIT_FUNC
  668. init_sockobject(PySocketSockObject *s,
  669. SOCKET_T fd, int family, int type, int proto)
  670. {
  671. #ifdef RISCOS
  672. int block = 1;
  673. #endif
  674. s->sock_fd = fd;
  675. s->sock_family = family;
  676. s->sock_type = type;
  677. s->sock_proto = proto;
  678. s->sock_timeout = defaulttimeout;
  679. s->errorhandler = &set_error;
  680. if (defaulttimeout >= 0.0)
  681. internal_setblocking(s, 0);
  682. #ifdef RISCOS
  683. if (taskwindow)
  684. socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
  685. #endif
  686. }
  687. /* Create a new socket object.
  688. This just creates the object and initializes it.
  689. If the creation fails, return NULL and set an exception (implicit
  690. in NEWOBJ()). */
  691. static PySocketSockObject *
  692. new_sockobject(SOCKET_T fd, int family, int type, int proto)
  693. {
  694. PySocketSockObject *s;
  695. s = (PySocketSockObject *)
  696. PyType_GenericNew(&sock_type, NULL, NULL);
  697. if (s != NULL)
  698. init_sockobject(s, fd, family, type, proto);
  699. return s;
  700. }
  701. /* Lock to allow python interpreter to continue, but only allow one
  702. thread to be in gethostbyname or getaddrinfo */
  703. #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
  704. PyThread_type_lock netdb_lock;
  705. #endif
  706. /* Convert a string specifying a host name or one of a few symbolic
  707. names to a numeric IP address. This usually calls gethostbyname()
  708. to do the work; the names "" and "<broadcast>" are special.
  709. Return the length (IPv4 should be 4 bytes), or negative if
  710. an error occurred; then an exception is raised. */
  711. static int
  712. setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
  713. {
  714. struct addrinfo hints, *res;
  715. int error;
  716. int d1, d2, d3, d4;
  717. char ch;
  718. memset((void *) addr_ret, '\0', sizeof(*addr_ret));
  719. if (name[0] == '\0') {
  720. int siz;
  721. memset(&hints, 0, sizeof(hints));
  722. hints.ai_family = af;
  723. hints.ai_socktype = SOCK_DGRAM; /*dummy*/
  724. hints.ai_flags = AI_PASSIVE;
  725. Py_BEGIN_ALLOW_THREADS
  726. ACQUIRE_GETADDRINFO_LOCK
  727. error = getaddrinfo(NULL, "0", &hints, &res);
  728. Py_END_ALLOW_THREADS
  729. /* We assume that those thread-unsafe getaddrinfo() versions
  730. *are* safe regarding their return value, ie. that a
  731. subsequent call to getaddrinfo() does not destroy the
  732. outcome of the first call. */
  733. RELEASE_GETADDRINFO_LOCK
  734. if (error) {
  735. set_gaierror(error);
  736. return -1;
  737. }
  738. switch (res->ai_family) {
  739. case AF_INET:
  740. siz = 4;
  741. break;
  742. #ifdef ENABLE_IPV6
  743. case AF_INET6:
  744. siz = 16;
  745. break;
  746. #endif
  747. default:
  748. freeaddrinfo(res);
  749. PyErr_SetString(socket_error,
  750. "unsupported address family");
  751. return -1;
  752. }
  753. if (res->ai_next) {
  754. freeaddrinfo(res);
  755. PyErr_SetString(socket_error,
  756. "wildcard resolved to multiple address");
  757. return -1;
  758. }
  759. if (res->ai_addrlen < addr_ret_size)
  760. addr_ret_size = res->ai_addrlen;
  761. memcpy(addr_ret, res->ai_addr, addr_ret_size);
  762. freeaddrinfo(res);
  763. return siz;
  764. }
  765. if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
  766. struct sockaddr_in *sin;
  767. if (af != AF_INET && af != AF_UNSPEC) {
  768. PyErr_SetString(socket_error,
  769. "address family mismatched");
  770. return -1;
  771. }
  772. sin = (struct sockaddr_in *)addr_ret;
  773. memset((void *) sin, '\0', sizeof(*sin));
  774. sin->sin_family = AF_INET;
  775. #ifdef HAVE_SOCKADDR_SA_LEN
  776. sin->sin_len = sizeof(*sin);
  777. #endif
  778. sin->sin_addr.s_addr = INADDR_BROADCAST;
  779. return sizeof(sin->sin_addr);
  780. }
  781. if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
  782. 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
  783. 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
  784. struct sockaddr_in *sin;
  785. sin = (struct sockaddr_in *)addr_ret;
  786. sin->sin_addr.s_addr = htonl(
  787. ((long) d1 << 24) | ((long) d2 << 16) |
  788. ((long) d3 << 8) | ((long) d4 << 0));
  789. sin->sin_family = AF_INET;
  790. #ifdef HAVE_SOCKADDR_SA_LEN
  791. sin->sin_len = sizeof(*sin);
  792. #endif
  793. return 4;
  794. }
  795. memset(&hints, 0, sizeof(hints));
  796. hints.ai_family = af;
  797. Py_BEGIN_ALLOW_THREADS
  798. ACQUIRE_GETADDRINFO_LOCK
  799. error = getaddrinfo(name, NULL, &hints, &res);
  800. #if defined(__digital__) && defined(__unix__)
  801. if (error == EAI_NONAME && af == AF_UNSPEC) {
  802. /* On Tru64 V5.1, numeric-to-addr conversion fails
  803. if no address family is given. Assume IPv4 for now.*/
  804. hints.ai_family = AF_INET;
  805. error = getaddrinfo(name, NULL, &hints, &res);
  806. }
  807. #endif
  808. Py_END_ALLOW_THREADS
  809. RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
  810. if (error) {
  811. set_gaierror(error);
  812. return -1;
  813. }
  814. if (res->ai_addrlen < addr_ret_size)
  815. addr_ret_size = res->ai_addrlen;
  816. memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
  817. freeaddrinfo(res);
  818. switch (addr_ret->sa_family) {
  819. case AF_INET:
  820. return 4;
  821. #ifdef ENABLE_IPV6
  822. case AF_INET6:
  823. return 16;
  824. #endif
  825. default:
  826. PyErr_SetString(socket_error, "unknown address family");
  827. return -1;
  828. }
  829. }
  830. /* Create a string object representing an IP address.
  831. This is always a string of the form 'dd.dd.dd.dd' (with variable
  832. size numbers). */
  833. static PyObject *
  834. makeipaddr(struct sockaddr *addr, int addrlen)
  835. {
  836. char buf[NI_MAXHOST];
  837. int error;
  838. error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
  839. NI_NUMERICHOST);
  840. if (error) {
  841. set_gaierror(error);
  842. return NULL;
  843. }
  844. return PyString_FromString(buf);
  845. }
  846. #ifdef USE_BLUETOOTH
  847. /* Convert a string representation of a Bluetooth address into a numeric
  848. address. Returns the length (6), or raises an exception and returns -1 if
  849. an error occurred. */
  850. static int
  851. setbdaddr(char *name, bdaddr_t *bdaddr)
  852. {
  853. unsigned int b0, b1, b2, b3, b4, b5;
  854. char ch;
  855. int n;
  856. n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
  857. &b5, &b4, &b3, &b2, &b1, &b0, &ch);
  858. if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
  859. bdaddr->b[0] = b0;
  860. bdaddr->b[1] = b1;
  861. bdaddr->b[2] = b2;
  862. bdaddr->b[3] = b3;
  863. bdaddr->b[4] = b4;
  864. bdaddr->b[5] = b5;
  865. return 6;
  866. } else {
  867. PyErr_SetString(socket_error, "bad bluetooth address");
  868. return -1;
  869. }
  870. }
  871. /* Create a string representation of the Bluetooth address. This is always a
  872. string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
  873. value (zero padded if necessary). */
  874. static PyObject *
  875. makebdaddr(bdaddr_t *bdaddr)
  876. {
  877. char buf[(6 * 2) + 5 + 1];
  878. sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
  879. bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
  880. bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
  881. return PyString_FromString(buf);
  882. }
  883. #endif
  884. /* Create an object representing the given socket address,
  885. suitable for passing it back to bind(), connect() etc.
  886. The family field of the sockaddr structure is inspected
  887. to determine what kind of address it really is. */
  888. /*ARGSUSED*/
  889. static PyObject *
  890. makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
  891. {
  892. if (addrlen == 0) {
  893. /* No address -- may be recvfrom() from known socket */
  894. Py_INCREF(Py_None);
  895. return Py_None;
  896. }
  897. #ifdef __BEOS__
  898. /* XXX: BeOS version of accept() doesn't set family correctly */
  899. addr->sa_family = AF_INET;
  900. #endif
  901. switch (addr->sa_family) {
  902. case AF_INET:
  903. {
  904. struct sockaddr_in *a;
  905. PyObject *addrobj = makeipaddr(addr, sizeof(*a));
  906. PyObject *ret = NULL;
  907. if (addrobj) {
  908. a = (struct sockaddr_in *)addr;
  909. ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
  910. Py_DECREF(addrobj);
  911. }
  912. return ret;
  913. }
  914. #if defined(AF_UNIX)
  915. case AF_UNIX:
  916. {
  917. struct sockaddr_un *a = (struct sockaddr_un *) addr;
  918. #ifdef linux
  919. if (a->sun_path[0] == 0) { /* Linux abstract namespace */
  920. addrlen -= (sizeof(*a) - sizeof(a->sun_path));
  921. return PyString_FromStringAndSize(a->sun_path,
  922. addrlen);
  923. }
  924. else
  925. #endif /* linux */
  926. {
  927. /* regular NULL-terminated string */
  928. return PyString_FromString(a->sun_path);
  929. }
  930. }
  931. #endif /* AF_UNIX */
  932. #if defined(AF_NETLINK)
  933. case AF_NETLINK:
  934. {
  935. struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
  936. return Py_BuildValue("II", a->nl_pid, a->nl_groups);
  937. }
  938. #endif /* AF_NETLINK */
  939. #ifdef ENABLE_IPV6
  940. case AF_INET6:
  941. {
  942. struct sockaddr_in6 *a;
  943. PyObject *addrobj = makeipaddr(addr, sizeof(*a));
  944. PyObject *ret = NULL;
  945. if (addrobj) {
  946. a = (struct sockaddr_in6 *)addr;
  947. ret = Py_BuildValue("Oiii",
  948. addrobj,
  949. ntohs(a->sin6_port),
  950. a->sin6_flowinfo,
  951. a->sin6_scope_id);
  952. Py_DECREF(addrobj);
  953. }
  954. return ret;
  955. }
  956. #endif
  957. #ifdef USE_BLUETOOTH
  958. case AF_BLUETOOTH:
  959. switch (proto) {
  960. case BTPROTO_L2CAP:
  961. {
  962. struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
  963. PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
  964. PyObject *ret = NULL;
  965. if (addrobj) {
  966. ret = Py_BuildValue("Oi",
  967. addrobj,
  968. _BT_L2_MEMB(a, psm));
  969. Py_DECREF(addrobj);
  970. }
  971. return ret;
  972. }
  973. case BTPROTO_RFCOMM:
  974. {
  975. struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
  976. PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
  977. PyObject *ret = NULL;
  978. if (addrobj) {
  979. ret = Py_BuildValue("Oi",
  980. addrobj,
  981. _BT_RC_MEMB(a, channel));
  982. Py_DECREF(addrobj);
  983. }
  984. return ret;
  985. }
  986. #if !defined(__FreeBSD__)
  987. case BTPROTO_SCO:
  988. {
  989. struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
  990. return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
  991. }
  992. #endif
  993. }
  994. #endif
  995. #ifdef HAVE_NETPACKET_PACKET_H
  996. case AF_PACKET:
  997. {
  998. struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
  999. char *ifname = "";
  1000. struct ifreq ifr;
  1001. /* need to look up interface name give index */
  1002. if (a->sll_ifindex) {
  1003. ifr.ifr_ifindex = a->sll_ifindex;
  1004. if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
  1005. ifname = ifr.ifr_name;
  1006. }
  1007. return Py_BuildValue("shbhs#",
  1008. ifname,
  1009. ntohs(a->sll_protocol),
  1010. a->sll_pkttype,
  1011. a->sll_hatype,
  1012. a->sll_addr,
  1013. a->sll_halen);
  1014. }
  1015. #endif
  1016. /* More cases here... */
  1017. default:
  1018. /* If we don't know the address family, don't raise an
  1019. exception -- return it as a tuple. */
  1020. return Py_BuildValue("is#",
  1021. addr->sa_family,
  1022. addr->sa_data,
  1023. sizeof(addr->sa_data));
  1024. }
  1025. }
  1026. /* Parse a socket address argument according to the socket object's
  1027. address family. Return 1 if the address was in the proper format,
  1028. 0 of not. The address is returned through addr_ret, its length
  1029. through len_ret. */
  1030. static int
  1031. getsockaddrarg(PySocketSockObject *s, PyObject *args,
  1032. struct sockaddr *addr_ret, int *len_ret)
  1033. {
  1034. switch (s->sock_family) {
  1035. #if defined(AF_UNIX)
  1036. case AF_UNIX:
  1037. {
  1038. struct sockaddr_un* addr;
  1039. char *path;
  1040. int len;
  1041. if (!PyArg_Parse(args, "t#", &path, &len))
  1042. return 0;
  1043. addr = (struct sockaddr_un*)addr_ret;
  1044. #ifdef linux
  1045. if (len > 0 && path[0] == 0) {
  1046. /* Linux abstract namespace extension */
  1047. if (len > sizeof addr->sun_path) {
  1048. PyErr_SetString(socket_error,
  1049. "AF_UNIX path too long");
  1050. return 0;
  1051. }
  1052. }
  1053. else
  1054. #endif /* linux */
  1055. {
  1056. /* regular NULL-terminated string */
  1057. if (len >= sizeof addr->sun_path) {
  1058. PyErr_SetString(socket_error,
  1059. "AF_UNIX path too long");
  1060. return 0;
  1061. }
  1062. addr->sun_path[len] = 0;
  1063. }
  1064. addr->sun_family = s->sock_family;
  1065. memcpy(addr->sun_path, path, len);
  1066. #if defined(PYOS_OS2)
  1067. *len_ret = sizeof(*addr);
  1068. #else
  1069. *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
  1070. #endif
  1071. return 1;
  1072. }
  1073. #endif /* AF_UNIX */
  1074. #if defined(AF_NETLINK)
  1075. case AF_NETLINK:
  1076. {
  1077. struct sockaddr_nl* addr;
  1078. int pid, groups;
  1079. addr = (struct sockaddr_nl *)addr_ret;
  1080. if (!PyTuple_Check(args)) {
  1081. PyErr_Format(
  1082. PyExc_TypeError,
  1083. "getsockaddrarg: "
  1084. "AF_NETLINK address must be tuple, not %.500s",
  1085. args->ob_type->tp_name);
  1086. return 0;
  1087. }
  1088. if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
  1089. return 0;
  1090. addr->nl_family = AF_NETLINK;
  1091. addr->nl_pid = pid;
  1092. addr->nl_groups = groups;
  1093. *len_ret = sizeof(*addr);
  1094. return 1;
  1095. }
  1096. #endif
  1097. case AF_INET:
  1098. {
  1099. struct sockaddr_in* addr;
  1100. char *host;
  1101. int port, result;
  1102. if (!PyTuple_Check(args)) {
  1103. PyErr_Format(
  1104. PyExc_TypeError,
  1105. "getsockaddrarg: "
  1106. "AF_INET address must be tuple, not %.500s",
  1107. args->ob_type->tp_name);
  1108. return 0;
  1109. }
  1110. if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
  1111. "idna", &host, &port))
  1112. return 0;
  1113. addr=(struct sockaddr_in*)addr_ret;
  1114. result = setipaddr(host, (struct sockaddr *)addr,
  1115. sizeof(*addr), AF_INET);
  1116. PyMem_Free(host);
  1117. if (result < 0)
  1118. return 0;
  1119. addr->sin_family = AF_INET;
  1120. addr->sin_port = htons((short)port);
  1121. *len_ret = sizeof *addr;
  1122. return 1;
  1123. }
  1124. #ifdef ENABLE_IPV6
  1125. case AF_INET6:
  1126. {
  1127. struct sockaddr_in6* addr;
  1128. char *host;
  1129. int port, flowinfo, scope_id, result;
  1130. flowinfo = scope_id = 0;
  1131. if (!PyTuple_Check(args)) {
  1132. PyErr_Format(
  1133. PyExc_TypeError,
  1134. "getsockaddrarg: "
  1135. "AF_INET6 address must be tuple, not %.500s",
  1136. args->ob_type->tp_name);
  1137. return 0;
  1138. }
  1139. if (!PyArg_ParseTuple(args, "eti|ii",
  1140. "idna", &host, &port, &flowinfo,
  1141. &scope_id)) {
  1142. return 0;
  1143. }
  1144. addr = (struct sockaddr_in6*)addr_ret;
  1145. result = setipaddr(host, (struct sockaddr *)addr,
  1146. sizeof(*addr), AF_INET6);
  1147. PyMem_Free(host);
  1148. if (result < 0)
  1149. return 0;
  1150. addr->sin6_family = s->sock_family;
  1151. addr->sin6_port = htons((short)port);
  1152. addr->sin6_flowinfo = flowinfo;
  1153. addr->sin6_scope_id = scope_id;
  1154. *len_ret = sizeof *addr;
  1155. return 1;
  1156. }
  1157. #endif
  1158. #ifdef USE_BLUETOOTH
  1159. case AF_BLUETOOTH:
  1160. {
  1161. switch (s->sock_proto) {
  1162. case BTPROTO_L2CAP:
  1163. {
  1164. struct sockaddr_l2 *addr;
  1165. char *straddr;
  1166. addr = (struct sockaddr_l2 *)addr_ret;
  1167. _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
  1168. if (!PyArg_ParseTuple(args, "si", &straddr,
  1169. &_BT_L2_MEMB(addr, psm))) {
  1170. PyErr_SetString(socket_error, "getsockaddrarg: "
  1171. "wrong format");
  1172. return 0;
  1173. }
  1174. if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
  1175. return 0;
  1176. *len_ret = sizeof *addr;
  1177. return 1;
  1178. }
  1179. case BTPROTO_RFCOMM:
  1180. {
  1181. struct sockaddr_rc *addr;
  1182. char *straddr;
  1183. addr = (struct sockaddr_rc *)addr_ret;
  1184. _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
  1185. if (!PyArg_ParseTuple(args, "si", &straddr,
  1186. &_BT_RC_MEMB(addr, channel))) {
  1187. PyErr_SetString(socket_error, "getsockaddrarg: "
  1188. "wrong format");
  1189. return 0;
  1190. }
  1191. if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
  1192. return 0;
  1193. *len_ret = sizeof *addr;
  1194. return 1;
  1195. }
  1196. #if !defined(__FreeBSD__)
  1197. case BTPROTO_SCO:
  1198. {
  1199. struct sockaddr_sco *addr;
  1200. char *straddr;
  1201. addr = (struct sockaddr_sco *)addr_ret;
  1202. _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
  1203. straddr = PyString_AsString(args);
  1204. if (straddr == NULL) {
  1205. PyErr_SetString(socket_error, "getsockaddrarg: "
  1206. "wrong format");
  1207. return 0;
  1208. }
  1209. if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
  1210. return 0;
  1211. *len_ret = sizeof *addr;
  1212. return 1;
  1213. }
  1214. #endif
  1215. default:
  1216. PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
  1217. return 0;
  1218. }
  1219. }
  1220. #endif
  1221. #ifdef HAVE_NETPACKET_PACKET_H
  1222. case AF_PACKET:
  1223. {
  1224. struct sockaddr_ll* addr;
  1225. struct ifreq ifr;
  1226. char *interfaceName;
  1227. int protoNumber;
  1228. int hatype = 0;
  1229. int pkttype = 0;
  1230. char *haddr = NULL;
  1231. unsigned int halen = 0;
  1232. if (!PyTuple_Check(args)) {
  1233. PyErr_Format(
  1234. PyExc_TypeError,
  1235. "getsockaddrarg: "
  1236. "AF_PACKET address must be tuple, not %.500s",
  1237. args->ob_type->tp_name);
  1238. return 0;
  1239. }
  1240. if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
  1241. &protoNumber, &pkttype, &hatype,
  1242. &haddr, &halen))
  1243. return 0;
  1244. strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
  1245. ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
  1246. if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
  1247. s->errorhandler();
  1248. return 0;
  1249. }
  1250. if (halen > 8) {
  1251. PyErr_SetString(PyExc_ValueError,
  1252. "Hardware address must be 8 bytes or less");
  1253. return 0;
  1254. }
  1255. addr = (struct sockaddr_ll*)addr_ret;
  1256. addr->sll_family = AF_PACKET;
  1257. addr->sll_protocol = htons((short)protoNumber);
  1258. addr->sll_ifindex = ifr.ifr_ifindex;
  1259. addr->sll_pkttype = pkttype;
  1260. addr->sll_hatype = hatype;
  1261. if (halen != 0) {
  1262. memcpy(&addr->sll_addr, haddr, halen);
  1263. }
  1264. addr->sll_halen = halen;
  1265. *len_ret = sizeof *addr;
  1266. return 1;
  1267. }
  1268. #endif
  1269. /* More cases here... */
  1270. default:
  1271. PyErr_SetString(socket_error, "getsockaddrarg: bad family");
  1272. return 0;
  1273. }
  1274. }
  1275. /* Get the address length according to the socket object's address family.
  1276. Return 1 if the family is known, 0 otherwise. The length is returned
  1277. through len_ret. */
  1278. static int
  1279. getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
  1280. {
  1281. switch (s->sock_family) {
  1282. #if defined(AF_UNIX)
  1283. case AF_UNIX:
  1284. {
  1285. *len_ret = sizeof (struct sockaddr_un);
  1286. return 1;
  1287. }
  1288. #endif /* AF_UNIX */
  1289. #if defined(AF_NETLINK)
  1290. case AF_NETLINK:
  1291. {
  1292. *len_ret = sizeof (struct sockaddr_nl);
  1293. return 1;
  1294. }
  1295. #endif
  1296. case AF_INET:
  1297. {
  1298. *len_ret = sizeof (struct sockaddr_in);
  1299. return 1;
  1300. }
  1301. #ifdef ENABLE_IPV6
  1302. case AF_INET6:
  1303. {
  1304. *len_ret = sizeof (struct sockaddr_in6);
  1305. return 1;
  1306. }
  1307. #endif
  1308. #ifdef USE_BLUETOOTH
  1309. case AF_BLUETOOTH:
  1310. {
  1311. switch(s->sock_proto)
  1312. {
  1313. case BTPROTO_L2CAP:
  1314. *len_ret = sizeof (struct sockaddr_l2);
  1315. return 1;
  1316. case BTPROTO_RFCOMM:
  1317. *len_ret = sizeof (struct sockaddr_rc);
  1318. return 1;
  1319. #if !defined(__FreeBSD__)
  1320. case BTPROTO_SCO:
  1321. *len_ret = sizeof (struct sockaddr_sco);
  1322. return 1;
  1323. #endif
  1324. default:
  1325. PyErr_SetString(socket_error, "getsockaddrlen: "
  1326. "unknown BT protocol");
  1327. return 0;
  1328. }
  1329. }
  1330. #endif
  1331. #ifdef HAVE_NETPACKET_PACKET_H
  1332. case AF_PACKET:
  1333. {
  1334. *len_ret = sizeof (struct sockaddr_ll);
  1335. return 1;
  1336. }
  1337. #endif
  1338. /* More cases here... */
  1339. default:
  1340. PyErr_SetString(socket_error, "getsockaddrlen: bad family");
  1341. return 0;
  1342. }
  1343. }
  1344. /* s.accept() method */
  1345. static PyObject *
  1346. sock_accept(PySocketSockObject *s)
  1347. {
  1348. sock_addr_t addrbuf;
  1349. SOCKET_T newfd;
  1350. socklen_t addrlen;
  1351. PyObject *sock = NULL;
  1352. PyObject *addr = NULL;
  1353. PyObject *res = NULL;
  1354. int timeout;
  1355. if (!getsockaddrlen(s, &addrlen))
  1356. return NULL;
  1357. memset(&addrbuf, 0, addrlen);
  1358. #ifdef MS_WINDOWS
  1359. newfd = INVALID_SOCKET;
  1360. #else
  1361. newfd = -1;
  1362. #endif
  1363. if (!IS_SELECTABLE(s))
  1364. return select_error();
  1365. Py_BEGIN_ALLOW_THREADS
  1366. timeout = internal_select(s, 0);
  1367. if (!timeout)
  1368. newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
  1369. Py_END_ALLOW_THREADS
  1370. if (timeout == 1) {
  1371. PyErr_SetString(socket_timeout, "timed out");
  1372. return NULL;
  1373. }
  1374. #ifdef MS_WINDOWS
  1375. if (newfd == INVALID_SOCKET)
  1376. #else
  1377. if (newfd < 0)
  1378. #endif
  1379. return s->errorhandler();
  1380. /* Create the new object with unspecified family,
  1381. to avoid calls to bind() etc. on it. */
  1382. sock = (PyObject *) new_sockobject(newfd,
  1383. s->sock_family,
  1384. s->sock_type,
  1385. s->sock_proto);
  1386. if (sock == NULL) {
  1387. SOCKETCLOSE(newfd);
  1388. goto finally;
  1389. }
  1390. addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
  1391. addrlen, s->sock_proto);
  1392. if (addr == NULL)
  1393. goto finally;
  1394. res = PyTuple_Pack(2, sock, addr);
  1395. finally:
  1396. Py_XDECREF(sock);
  1397. Py_XDECREF(addr);
  1398. return res;
  1399. }
  1400. PyDoc_STRVAR(accept_doc,
  1401. "accept() -> (socket object, address info)\n\
  1402. \n\
  1403. Wait for an incoming connection. Return a new socket representing the\n\
  1404. connection, and the address of the client. For IP sockets, the address\n\
  1405. info is a pair (hostaddr, port).");
  1406. /* s.setblocking(flag) method. Argument:
  1407. False -- non-blocking mode; same as settimeout(0)
  1408. True -- blocking mode; same as settimeout(None)
  1409. */
  1410. static PyObject *
  1411. sock_setblocking(PySocketSockObject *s, PyObject *arg)
  1412. {
  1413. int block;
  1414. block = PyInt_AsLong(arg);
  1415. if (block == -1 && PyErr_Occurred())
  1416. return NULL;
  1417. s->sock_timeout = block ? -1.0 : 0.0;
  1418. internal_setblocking(s, block);
  1419. Py_INCREF(Py_None);
  1420. return Py_None;
  1421. }
  1422. PyDoc_STRVAR(setblocking_doc,
  1423. "setblocking(flag)\n\
  1424. \n\
  1425. Set the socket to blocking (flag is true) or non-blocking (false).\n\
  1426. setblocking(True) is equivalent to settimeout(None);\n\
  1427. setblocking(False) is equivalent to settimeout(0.0).");
  1428. /* s.settimeout(timeout) method. Argument:
  1429. None -- no timeout, blocking mode; same as setblocking(True)
  1430. 0.0 -- non-blocking mode; same as setblocking(False)
  1431. > 0 -- timeout mode; operations time out after timeout seconds
  1432. < 0 -- illegal; raises an exception
  1433. */
  1434. static PyObject *
  1435. sock_settimeout(PySocketSockObject *s, PyObject *arg)
  1436. {
  1437. double timeout;
  1438. if (arg == Py_None)
  1439. timeout = -1.0;
  1440. else {
  1441. timeout = PyFloat_AsDouble(arg);
  1442. if (timeout < 0.0) {
  1443. if (!PyErr_Occurred())
  1444. PyErr_SetString(PyExc_ValueError,
  1445. "Timeout value out of range");
  1446. return NULL;
  1447. }
  1448. }
  1449. s->sock_timeout = timeout;
  1450. internal_setblocking(s, timeout < 0.0);
  1451. Py_INCREF(Py_None);
  1452. return Py_None;
  1453. }
  1454. PyDoc_STRVAR(settimeout_doc,
  1455. "settimeout(timeout)\n\
  1456. \n\
  1457. Set a timeout on socket operations. 'timeout' can be a float,\n\
  1458. giving in seconds, or None. Setting a timeout of None disables\n\
  1459. the timeout feature and is equivalent to setblocking(1).\n\
  1460. Setting a timeout of zero is the same as setblocking(0).");
  1461. /* s.gettimeout() method.
  1462. Returns the timeout associated with a socket. */
  1463. static PyObject *
  1464. sock_gettimeout(PySocketSockObject *s)
  1465. {
  1466. if (s->sock_timeout < 0.0) {
  1467. Py_INCREF(Py_None);
  1468. return Py_None;
  1469. }
  1470. else
  1471. return PyFloat_FromDouble(s->sock_timeout);
  1472. }
  1473. PyDoc_STRVAR(gettimeout_doc,
  1474. "gettimeout() -> timeout\n\
  1475. \n\
  1476. Returns the timeout in floating seconds associated with socket \n\
  1477. operations. A timeout of None indicates that timeouts on socket \n\
  1478. operations are disabled.");
  1479. #ifdef RISCOS
  1480. /* s.sleeptaskw(1 | 0) method */
  1481. static PyObject *
  1482. sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
  1483. {
  1484. int block;
  1485. block = PyInt_AsLong(arg);
  1486. if (block == -1 && PyErr_Occurred())
  1487. return NULL;
  1488. Py_BEGIN_ALLOW_THREADS
  1489. socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
  1490. Py_END_ALLOW_THREADS
  1491. Py_INCREF(Py_None);
  1492. return Py_None;
  1493. }
  1494. PyDoc_STRVAR(sleeptaskw_doc,
  1495. "sleeptaskw(flag)\n\
  1496. \n\
  1497. Allow sleeps in taskwindows.");
  1498. #endif
  1499. /* s.setsockopt() method.
  1500. With an integer third argument, sets an integer option.
  1501. With a string third argument, sets an option from a buffer;
  1502. use optional built-in module 'struct' to encode the string. */
  1503. static PyObject *
  1504. sock_setsockopt(PySocketSockObject *s, PyObject *args)
  1505. {
  1506. int level;
  1507. int optname;
  1508. int res;
  1509. char *buf;
  1510. int buflen;
  1511. int flag;
  1512. if (PyArg_ParseTuple(args, "iii:setsockopt",
  1513. &level, &optname, &flag)) {
  1514. buf = (char *) &flag;
  1515. buflen = sizeof flag;
  1516. }
  1517. else {
  1518. PyErr_Clear();
  1519. if (!PyArg_ParseTuple(args, "iis#:setsockopt",
  1520. &level, &optname, &buf, &buflen))
  1521. return NULL;
  1522. }
  1523. res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
  1524. if (res < 0)
  1525. return s->errorhandler();
  1526. Py_INCREF(Py_None);
  1527. return Py_None;
  1528. }
  1529. PyDoc_STRVAR(setsockopt_doc,
  1530. "setsockopt(level, option, value)\n\
  1531. \n\
  1532. Set a socket option. See the Unix manual for level and option.\n\
  1533. The value argument can either be an integer or a string.");
  1534. /* s.getsockopt() method.
  1535. With two arguments, retrieves an integer option.
  1536. With a third integer argument, retrieves a string buffer of that size;
  1537. use optional built-in module 'struct' to decode the string. */
  1538. static PyObject *
  1539. sock_getsockopt(PySocketSockObject *s, PyObject *args)
  1540. {
  1541. int level;
  1542. int optname;
  1543. int res;
  1544. PyObject *buf;
  1545. socklen_t buflen = 0;
  1546. #ifdef __BEOS__
  1547. /* We have incomplete socket support. */
  1548. PyErr_SetString(socket_error, "getsockopt not supported");
  1549. return NULL;
  1550. #else
  1551. if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
  1552. &level, &optname, &buflen))
  1553. return NULL;
  1554. if (buflen == 0) {
  1555. int flag = 0;
  1556. socklen_t flagsize = sizeof flag;
  1557. res = getsockopt(s->sock_fd, level, optname,
  1558. (void *)&flag, &flagsize);
  1559. if (res < 0)
  1560. return s->errorhandler();
  1561. return PyInt_FromLong(flag);
  1562. }
  1563. #ifdef __VMS
  1564. /* socklen_t is unsigned so no negative test is needed,
  1565. test buflen == 0 is previously done */
  1566. if (buflen > 1024) {
  1567. #else
  1568. if (buflen <= 0 || buflen > 1024) {
  1569. #endif
  1570. PyErr_SetString(socket_error,
  1571. "getsockopt buflen out of range");
  1572. return NULL;
  1573. }
  1574. buf = PyString_FromStringAndSize((char *)NULL, buflen);
  1575. if (buf == NULL)
  1576. return NULL;
  1577. res = getsockopt(s->sock_fd, level, optname,
  1578. (void *)PyString_AS_STRING(buf), &buflen);
  1579. if (res < 0) {
  1580. Py_DECREF(buf);
  1581. return s->errorhandler();
  1582. }
  1583. _PyString_Resize(&buf, buflen);
  1584. return buf;
  1585. #endif /* __BEOS__ */
  1586. }
  1587. PyDoc_STRVAR(getsockopt_doc,
  1588. "getsockopt(level, option[, buffersize]) -> value\n\
  1589. \n\
  1590. Get a socket option. See the Unix manual for level and option.\n\
  1591. If a nonzero buffersize argument is given, the return value is a\n\
  1592. string of that length; otherwise it is an integer.");
  1593. /* s.bind(sockaddr) method */
  1594. static PyObject *
  1595. sock_bind(PySocketSockObject *s, PyObject *addro)
  1596. {
  1597. sock_addr_t addrbuf;
  1598. int addrlen;
  1599. int res;
  1600. if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
  1601. return NULL;
  1602. Py_BEGIN_ALLOW_THREADS
  1603. res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
  1604. Py_END_ALLOW_THREADS
  1605. if (res < 0)
  1606. return s->errorhandler();
  1607. Py_INCREF(Py_None);
  1608. return Py_None;
  1609. }
  1610. PyDoc_STRVAR(bind_doc,
  1611. "bind(address)\n\
  1612. \n\
  1613. Bind the socket to a local address. For IP sockets, the address is a\n\
  1614. pair (host, port); the host must refer to the local host. For raw packet\n\
  1615. sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
  1616. /* s.close() method.
  1617. Set the file descriptor to -1 so operations tried subsequently
  1618. will surely fail. */
  1619. static PyObject *
  1620. sock_close(PySocketSockObject *s)
  1621. {
  1622. SOCKET_T fd;
  1623. if ((fd = s->sock_fd) != -1) {
  1624. s->sock_fd = -1;
  1625. Py_BEGIN_ALLOW_THREADS
  1626. (void) SOCKETCLOSE(fd);
  1627. Py_END_ALLOW_THREADS
  1628. }
  1629. Py_INCREF(Py_None);
  1630. return Py_None;
  1631. }
  1632. PyDoc_STRVAR(close_doc,
  1633. "close()\n\
  1634. \n\
  1635. Close the socket. It cannot be used after this call.");
  1636. static int
  1637. internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
  1638. int *timeoutp)
  1639. {
  1640. int res, timeout;
  1641. timeout = 0;
  1642. res = connect(s->sock_fd, addr, addrlen);
  1643. #ifdef MS_WINDOWS
  1644. if (s->sock_timeout > 0.0) {
  1645. if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
  1646. IS_SELECTABLE(s)) {
  1647. /* This is a mess. Best solution: trust select */
  1648. fd_set fds;
  1649. fd_set fds_exc;
  1650. struct timeval tv;
  1651. tv.tv_sec = (int)s->sock_timeout;
  1652. tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
  1653. FD_ZERO(&fds);
  1654. FD_SET(s->sock_fd, &fds);
  1655. FD_ZERO(&fds_exc);
  1656. FD_SET(s->sock_fd, &fds_exc);
  1657. res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
  1658. if (res == 0) {
  1659. res = WSAEWOULDBLOCK;
  1660. timeout = 1;
  1661. } else if (res > 0) {
  1662. if (FD_ISSET(s->sock_fd, &fds))
  1663. /* The socket is in the writeable set - this
  1664. means connected */
  1665. res = 0;
  1666. else {
  1667. /* As per MS docs, we need to call getsockopt()
  1668. to get the underlying error */
  1669. int res_size = sizeof res;
  1670. /* It must be in the exception set */
  1671. assert(FD_ISSET(s->sock_fd, &fds_exc));
  1672. if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
  1673. (char *)&res, &res_size))
  1674. /* getsockopt also clears WSAGetLastError,
  1675. so reset it back. */
  1676. WSASetLastError(res);
  1677. else
  1678. res = WSAGetLastError();
  1679. }
  1680. }
  1681. /* else if (res < 0) an error occurred */
  1682. }
  1683. }
  1684. if (res < 0)
  1685. res = WSAGetLastError();
  1686. #else
  1687. if (s->sock_timeout > 0.0) {
  1688. if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
  1689. timeout = internal_select(s, 1);
  1690. if (timeout == 0) {
  1691. res = connect(s->sock_fd, addr, addrlen);
  1692. if (res < 0 && errno == EISCONN)
  1693. res = 0;
  1694. }
  1695. else if (timeout == -1)
  1696. res = errno; /* had error */
  1697. else
  1698. res = EWOULDBLOCK; /* timed out */
  1699. }
  1700. }
  1701. if (r

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