PageRenderTime 95ms CodeModel.GetById 6ms app.highlight 71ms RepoModel.GetById 2ms app.codeStats 1ms

/Modules/socketmodule.c

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

Large files files are truncated, but you can click here to view the full 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 (r

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