PageRenderTime 109ms CodeModel.GetById 4ms app.highlight 90ms RepoModel.GetById 1ms app.codeStats 1ms

/MOULOpenSourceClientPlugin/Plasma20/SDKs/XPlatform/Cypython-2.3.3/Modules/socketmodule.c

https://bitbucket.org/cwalther/cwe-ou-nobink
C | 4151 lines | 3336 code | 486 blank | 329 comment | 445 complexity | 2f0c83c48857c1e4f744b8ba347759d8 MD5 | raw file

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

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