5100 lines · 126.2 KB · C
RawDownload
/* Socket module */ /* This module provides an interface to Berkeley socket IPC. Limitations: - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a  portable manner, though AF_PACKET and AF_NETLINK are supported under Linux.- No read/write operations (use sendall/recv or makefile instead).- Additional restrictions apply on some non-Unix platforms (compensated  for by socket.py). Module interface: - socket.error: exception raised for socket specific errors- socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,	a subclass of socket.error- socket.herror: exception raised for gethostby* errors,	a subclass of socket.error- socket.fromfd(fd, family, type[, proto]) --> new socket object (created        from an existing file descriptor)- socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')- socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])- socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')- socket.getprotobyname(protocolname) --> protocol number- socket.getservbyname(servicename[, protocolname]) --> port number- socket.getservbyport(portnumber[, protocolname]) --> service name- socket.socket([family[, type [, proto]]]) --> new socket object- socket.socketpair([family[, type [, proto]]]) --> (socket, socket)- socket.ntohs(16 bit value) --> new int object- socket.ntohl(32 bit value) --> new int object- socket.htons(16 bit value) --> new int object- socket.htonl(32 bit value) --> new int object- socket.getaddrinfo(host, port [, family, socktype, proto, flags])	--> List of (family, socktype, proto, canonname, sockaddr)- socket.getnameinfo(sockaddr, flags) --> (host, port)- socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>- socket.has_ipv6: boolean value indicating if IPv6 is supported- socket.inet_aton(IP address) -> 32-bit packed IP representation- socket.inet_ntoa(packed IP) -> IP address string- socket.getdefaulttimeout() -> None | float- socket.setdefaulttimeout(None | float)- an Internet socket address is a pair (hostname, port)  where hostname can be anything recognized by gethostbyname()  (including the dd.dd.dd.dd notation) and port is in host byte order- where a hostname is returned, the dd.dd.dd.dd notation is used- a UNIX domain socket address is a string specifying the pathname- an AF_PACKET socket address is a tuple containing a string  specifying the ethernet interface and an integer specifying  the Ethernet protocol number to be received. For example:  ("eth0",0x1234).  Optional 3rd,4th,5th elements in the tuple  specify packet-type and ha-type/addr. Local naming conventions: - names starting with sock_ are socket object methods- names starting with socket_ are module-level functions- names starting with PySocket are exported through socketmodule.h */ #ifdef __APPLE__  /*   * inet_aton is not available on OSX 10.3, yet we want to use a binary   * that was build on 10.4 or later to work on that release, weak linking   * comes to the rescue.   */# pragma weak inet_aton#endif #include "Python.h"#include "structmember.h" #undef MAX#define MAX(x, y) ((x) < (y) ? (y) : (x)) /* Socket object documentation */PyDoc_STRVAR(sock_doc,"socket([family[, type[, proto]]]) -> socket object\n\\n\Open a socket of the given type.  The family argument specifies the\n\address family; it defaults to AF_INET.  The type argument specifies\n\whether this is a stream (SOCK_STREAM, this is the default)\n\or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,\n\specifying the default protocol.  Keyword arguments are accepted.\n\\n\A socket object represents one endpoint of a network connection.\n\\n\Methods of socket objects (keyword arguments not allowed):\n\\n\accept() -- accept a connection, returning new socket and client address\n\bind(addr) -- bind the socket to a local address\n\close() -- close the socket\n\connect(addr) -- connect the socket to a remote address\n\connect_ex(addr) -- connect, return an error code instead of an exception\n\dup() -- return a new socket object identical to the current one [*]\n\fileno() -- return underlying file descriptor\n\getpeername() -- return remote address [*]\n\getsockname() -- return local address\n\getsockopt(level, optname[, buflen]) -- get socket options\n\gettimeout() -- return timeout or None\n\listen(n) -- start listening for incoming connections\n\makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\recv(buflen[, flags]) -- receive data\n\recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\recvfrom_into(buffer[, nbytes, [, flags])\n\  -- receive data and sender\'s address (into a buffer)\n\sendall(data[, flags]) -- send all data\n\send(data[, flags]) -- send data, may not send all of it\n\sendto(data[, flags], addr) -- send data to a given address\n\setblocking(0 | 1) -- set or clear the blocking I/O flag\n\setsockopt(level, optname, value) -- set socket options\n\settimeout(None | float) -- set or clear the timeout\n\shutdown(how) -- shut down traffic in one or both directions\n\\n\ [*] not available on all platforms!"); /* XXX This is a terrible mess of platform-dependent preprocessor hacks.   I hope some day someone can clean this up please... */ /* Hacks for gethostbyname_r().  On some non-Linux platforms, the configure   script doesn't get this right, so we hardcode some platform checks below.   On the other hand, not all Linux versions agree, so there the settings   computed by the configure script are needed! */ #ifndef linux# undef HAVE_GETHOSTBYNAME_R_3_ARG# undef HAVE_GETHOSTBYNAME_R_5_ARG# undef HAVE_GETHOSTBYNAME_R_6_ARG#endif #ifndef WITH_THREAD# undef HAVE_GETHOSTBYNAME_R#endif #ifdef HAVE_GETHOSTBYNAME_R# if defined(_AIX) || defined(__osf__)#  define HAVE_GETHOSTBYNAME_R_3_ARG# elif defined(__sun) || defined(__sgi)#  define HAVE_GETHOSTBYNAME_R_5_ARG# elif defined(linux)/* Rely on the configure script */# else#  undef HAVE_GETHOSTBYNAME_R# endif#endif #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \    !defined(MS_WINDOWS)# define USE_GETHOSTBYNAME_LOCK#endif /* To use __FreeBSD_version */#ifdef HAVE_SYS_PARAM_H#include <sys/param.h>#endif/* On systems on which getaddrinfo() is believed to not be thread-safe,   (this includes the getaddrinfo emulation) protect access with a lock. */#if defined(WITH_THREAD) && (defined(__APPLE__) || \    (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \    defined(__OpenBSD__) || defined(__NetBSD__) || \    defined(__VMS) || !defined(HAVE_GETADDRINFO))#define USE_GETADDRINFO_LOCK#endif #ifdef USE_GETADDRINFO_LOCK#define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);#define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);#else#define ACQUIRE_GETADDRINFO_LOCK#define RELEASE_GETADDRINFO_LOCK#endif #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)# include "pythread.h"#endif #if defined(PYCC_VACPP)# include <types.h># include <io.h># include <sys/ioctl.h># include <utils.h># include <ctype.h>#endif #if defined(__VMS)#  include <ioctl.h>#endif #if defined(PYOS_OS2)# define  INCL_DOS# define  INCL_DOSERRORS# define  INCL_NOPMAPI# include <os2.h>#endif #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI/* make sure that the reentrant (gethostbyaddr_r etc)   functions are declared correctly if compiling with   MIPSPro 7.x in ANSI C mode (default) */ /* XXX Using _SGIAPI is the wrong thing,   but I don't know what the right thing is. */#undef _SGIAPI /* to avoid warning */#define _SGIAPI 1 #undef _XOPEN_SOURCE#include <sys/socket.h>#include <sys/types.h>#include <netinet/in.h>#ifdef _SS_ALIGNSIZE#define HAVE_GETADDRINFO 1#define HAVE_GETNAMEINFO 1#endif #define HAVE_INET_PTON#include <netdb.h>#endif /* Irix 6.5 fails to define this variable at all. This is needed   for both GCC and SGI's compiler. I'd say that the SGI headers   are just busted. Same thing for Solaris. */#if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)#define INET_ADDRSTRLEN 16#endif /* Generic includes */#ifdef HAVE_SYS_TYPES_H#include <sys/types.h>#endif /* Generic socket object definitions and includes */#define PySocket_BUILDING_SOCKET#include "socketmodule.h" /* Addressing includes */ #ifndef MS_WINDOWS /* Non-MS WINDOWS includes */# include <netdb.h> /* Headers needed for inet_ntoa() and inet_addr() */# ifdef __BEOS__#  include <net/netdb.h># elif defined(PYOS_OS2) && defined(PYCC_VACPP)#  include <netdb.h>typedef size_t socklen_t;# else#   include <arpa/inet.h># endif # ifndef RISCOS#  include <fcntl.h># else#  include <sys/ioctl.h>#  include <socklib.h>#  define NO_DUPint h_errno; /* not used */#  define INET_ADDRSTRLEN 16# endif #else /* MS_WINDOWS includes */# ifdef HAVE_FCNTL_H#  include <fcntl.h># endif #endif #include <stddef.h> #ifndef offsetof# define offsetof(type, member)	((size_t)(&((type *)0)->member))#endif #ifndef O_NONBLOCK# define O_NONBLOCK O_NDELAY#endif /* include Python's addrinfo.h unless it causes trouble */#if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)  /* Do not include addinfo.h on some newer IRIX versions.   * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,   * for example, but not by 6.5.10.   */#elif defined(_MSC_VER) && _MSC_VER>1201  /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and   * EAI_* constants are defined in (the already included) ws2tcpip.h.   */#else#  include "addrinfo.h"#endif #ifndef HAVE_INET_PTONint inet_pton(int af, const char *src, void *dst);const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);#endif #ifdef __APPLE__/* On OS X, getaddrinfo returns no error indication of lookup   failure, so we must use the emulation instead of the libinfo   implementation. Unfortunately, performing an autoconf test   for this bug would require DNS access for the machine performing   the configuration, which is not acceptable. Therefore, we   determine the bug just by checking for __APPLE__. If this bug   gets ever fixed, perhaps checking for sys/version.h would be   appropriate, which is 10/0 on the system with the bug. */#ifndef HAVE_GETNAMEINFO/* This bug seems to be fixed in Jaguar. Ths easiest way I could   Find to check for Jaguar is that it has getnameinfo(), which   older releases don't have */#undef HAVE_GETADDRINFO#endif #ifdef HAVE_INET_ATON#define USE_INET_ATON_WEAKLINK#endif #endif /* I know this is a bad practice, but it is the easiest... */#if !defined(HAVE_GETADDRINFO)/* avoid clashes with the C library definition of the symbol. */#define getaddrinfo fake_getaddrinfo#define gai_strerror fake_gai_strerror#define freeaddrinfo fake_freeaddrinfo#include "getaddrinfo.c"#endif#if !defined(HAVE_GETNAMEINFO)#define getnameinfo fake_getnameinfo#include "getnameinfo.c"#endif #if defined(MS_WINDOWS) || defined(__BEOS__)/* BeOS suffers from the same socket dichotomy as Win32... - [cjh] *//* seem to be a few differences in the API */#define SOCKETCLOSE closesocket#define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */#endif #ifdef MS_WIN32#define EAFNOSUPPORT WSAEAFNOSUPPORT#define snprintf _snprintf#endif #if defined(PYOS_OS2) && !defined(PYCC_GCC)#define SOCKETCLOSE soclose#define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */#endif #ifndef SOCKETCLOSE#define SOCKETCLOSE close#endif #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)#define USE_BLUETOOTH 1#if defined(__FreeBSD__)#define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP#define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM#define sockaddr_l2 sockaddr_l2cap#define sockaddr_rc sockaddr_rfcomm#define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)#define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)#elif defined(__NetBSD__)#define sockaddr_l2 sockaddr_bt#define sockaddr_rc sockaddr_bt#define sockaddr_sco sockaddr_bt#define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)#define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)#define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)#else#define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)#define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)#define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)#endif#endif #ifdef __VMS/* TCP/IP Services for VMS uses a maximum send/recv buffer length */#define SEGMENT_SIZE (32 * 1024 -1)#endif #define	SAS2SA(x)	((struct sockaddr *)(x)) /* * Constants for getnameinfo() */#if !defined(NI_MAXHOST)#define NI_MAXHOST 1025#endif#if !defined(NI_MAXSERV)#define NI_MAXSERV 32#endif /* XXX There's a problem here: *static* functions are not supposed to have   a Py prefix (or use CapitalizedWords).  Later... */ /* Global variable holding the exception type for errors detected   by this module (but not argument type or memory errors, etc.). */static PyObject *socket_error;static PyObject *socket_herror;static PyObject *socket_gaierror;static PyObject *socket_timeout; #ifdef RISCOS/* Global variable which is !=0 if Python is running in a RISC OS taskwindow */static int taskwindow;#endif /* A forward reference to the socket type object.   The sock_type variable contains pointers to various functions,   some of which call new_sockobject(), which uses sock_type, so   there has to be a circular reference. */static PyTypeObject sock_type; #if defined(HAVE_POLL_H)#include <poll.h>#elif defined(HAVE_SYS_POLL_H)#include <sys/poll.h>#endif #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE/* Platform can select file descriptors beyond FD_SETSIZE */#define IS_SELECTABLE(s) 1#elif defined(HAVE_POLL)/* Instead of select(), we'll use poll() since poll() works on any fd. */#define IS_SELECTABLE(s) 1/* Can we call select() with this socket without a buffer overrun? */#else/* POSIX says selecting file descriptors beyond FD_SETSIZE   has undefined behaviour.  If there's no timeout left, we don't have to   call select, so it's a safe, little white lie. */#define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)#endif static PyObject*select_error(void){	PyErr_SetString(socket_error, "unable to select on socket");	return NULL;} /* Convenience function to raise an error according to errno   and return a NULL pointer from a function. */ static PyObject *set_error(void){#ifdef MS_WINDOWS	int err_no = WSAGetLastError();	static struct {		int no;		const char *msg;	} *msgp, msgs[] = {		{WSAEINTR, "Interrupted system call"},		{WSAEBADF, "Bad file descriptor"},		{WSAEACCES, "Permission denied"},		{WSAEFAULT, "Bad address"},		{WSAEINVAL, "Invalid argument"},		{WSAEMFILE, "Too many open files"},		{WSAEWOULDBLOCK,		  "The socket operation could not complete "		  "without blocking"},		{WSAEINPROGRESS, "Operation now in progress"},		{WSAEALREADY, "Operation already in progress"},		{WSAENOTSOCK, "Socket operation on non-socket"},		{WSAEDESTADDRREQ, "Destination address required"},		{WSAEMSGSIZE, "Message too long"},		{WSAEPROTOTYPE, "Protocol wrong type for socket"},		{WSAENOPROTOOPT, "Protocol not available"},		{WSAEPROTONOSUPPORT, "Protocol not supported"},		{WSAESOCKTNOSUPPORT, "Socket type not supported"},		{WSAEOPNOTSUPP, "Operation not supported"},		{WSAEPFNOSUPPORT, "Protocol family not supported"},		{WSAEAFNOSUPPORT, "Address family not supported"},		{WSAEADDRINUSE, "Address already in use"},		{WSAEADDRNOTAVAIL, "Can't assign requested address"},		{WSAENETDOWN, "Network is down"},		{WSAENETUNREACH, "Network is unreachable"},		{WSAENETRESET, "Network dropped connection on reset"},		{WSAECONNABORTED, "Software caused connection abort"},		{WSAECONNRESET, "Connection reset by peer"},		{WSAENOBUFS, "No buffer space available"},		{WSAEISCONN, "Socket is already connected"},		{WSAENOTCONN, "Socket is not connected"},		{WSAESHUTDOWN, "Can't send after socket shutdown"},		{WSAETOOMANYREFS, "Too many references: can't splice"},		{WSAETIMEDOUT, "Operation timed out"},		{WSAECONNREFUSED, "Connection refused"},		{WSAELOOP, "Too many levels of symbolic links"},		{WSAENAMETOOLONG, "File name too long"},		{WSAEHOSTDOWN, "Host is down"},		{WSAEHOSTUNREACH, "No route to host"},		{WSAENOTEMPTY, "Directory not empty"},		{WSAEPROCLIM, "Too many processes"},

Lines 1–500 of 5100.