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