Python-2.7.3/Modules/socketmodule.c

Location Tool Test ID Function Issue
/builddir/build/BUILD/Python-2.7.3/Modules/socketmodule.c:2853:9 clang-analyzer Assigned value is garbage or undefined
/builddir/build/BUILD/Python-2.7.3/Modules/socketmodule.c:2853:9 clang-analyzer Assigned value is garbage or undefined
/builddir/build/BUILD/Python-2.7.3/Modules/socketmodule.c:3374:9 gcc unused-but-set-variable socket_gethostbyname_ex variable 'result' set but not used
/builddir/build/BUILD/Python-2.7.3/Modules/socketmodule.c:3374:9 gcc unused-but-set-variable socket_gethostbyname_ex variable 'result' set but not used
/builddir/build/BUILD/Python-2.7.3/Modules/socketmodule.c:3385:5 clang-analyzer Value stored to 'result' is never read
/builddir/build/BUILD/Python-2.7.3/Modules/socketmodule.c:3385:5 clang-analyzer Value stored to 'result' is never read
/builddir/build/BUILD/Python-2.7.3/Modules/socketmodule.c:3450:9 gcc unused-but-set-variable socket_gethostbyaddr variable 'result' set but not used
/builddir/build/BUILD/Python-2.7.3/Modules/socketmodule.c:3450:9 gcc unused-but-set-variable socket_gethostbyaddr variable 'result' set but not used
/builddir/build/BUILD/Python-2.7.3/Modules/socketmodule.c:3482:5 clang-analyzer Value stored to 'result' is never read
/builddir/build/BUILD/Python-2.7.3/Modules/socketmodule.c:3482:5 clang-analyzer Value stored to 'result' is never read
   1 /* Socket module */
   2 
   3 /*
   4 
   5 This module provides an interface to Berkeley socket IPC.
   6 
   7 Limitations:
   8 
   9 - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
  10   portable manner, though AF_PACKET, AF_NETLINK and AF_TIPC are supported
  11   under Linux.
  12 - No read/write operations (use sendall/recv or makefile instead).
  13 - Additional restrictions apply on some non-Unix platforms (compensated
  14   for by socket.py).
  15 
  16 Module interface:
  17 
  18 - socket.error: exception raised for socket specific errors
  19 - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
  20     a subclass of socket.error
  21 - socket.herror: exception raised for gethostby* errors,
  22     a subclass of socket.error
  23 - socket.fromfd(fd, family, type[, proto]) --> new socket object (created
  24     from an existing file descriptor)
  25 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
  26 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
  27 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
  28 - socket.getprotobyname(protocolname) --> protocol number
  29 - socket.getservbyname(servicename[, protocolname]) --> port number
  30 - socket.getservbyport(portnumber[, protocolname]) --> service name
  31 - socket.socket([family[, type [, proto]]]) --> new socket object
  32 - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
  33 - socket.ntohs(16 bit value) --> new int object
  34 - socket.ntohl(32 bit value) --> new int object
  35 - socket.htons(16 bit value) --> new int object
  36 - socket.htonl(32 bit value) --> new int object
  37 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
  38     --> List of (family, socktype, proto, canonname, sockaddr)
  39 - socket.getnameinfo(sockaddr, flags) --> (host, port)
  40 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
  41 - socket.has_ipv6: boolean value indicating if IPv6 is supported
  42 - socket.inet_aton(IP address) -> 32-bit packed IP representation
  43 - socket.inet_ntoa(packed IP) -> IP address string
  44 - socket.getdefaulttimeout() -> None | float
  45 - socket.setdefaulttimeout(None | float)
  46 - an Internet socket address is a pair (hostname, port)
  47   where hostname can be anything recognized by gethostbyname()
  48   (including the dd.dd.dd.dd notation) and port is in host byte order
  49 - where a hostname is returned, the dd.dd.dd.dd notation is used
  50 - a UNIX domain socket address is a string specifying the pathname
  51 - an AF_PACKET socket address is a tuple containing a string
  52   specifying the ethernet interface and an integer specifying
  53   the Ethernet protocol number to be received. For example:
  54   ("eth0",0x1234).  Optional 3rd,4th,5th elements in the tuple
  55   specify packet-type and ha-type/addr.
  56 - an AF_TIPC socket address is expressed as
  57  (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
  58     TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
  59   and scope can be one of:
  60     TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
  61   The meaning of v1, v2 and v3 depends on the value of addr_type:
  62     if addr_type is TIPC_ADDR_NAME:
  63         v1 is the server type
  64         v2 is the port identifier
  65         v3 is ignored
  66     if addr_type is TIPC_ADDR_NAMESEQ:
  67         v1 is the server type
  68         v2 is the lower port number
  69         v3 is the upper port number
  70     if addr_type is TIPC_ADDR_ID:
  71         v1 is the node
  72         v2 is the ref
  73         v3 is ignored
  74 
  75 
  76 Local naming conventions:
  77 
  78 - names starting with sock_ are socket object methods
  79 - names starting with socket_ are module-level functions
  80 - names starting with PySocket are exported through socketmodule.h
  81 
  82 */
  83 
  84 #ifdef __APPLE__
  85   /*
  86    * inet_aton is not available on OSX 10.3, yet we want to use a binary
  87    * that was build on 10.4 or later to work on that release, weak linking
  88    * comes to the rescue.
  89    */
  90 # pragma weak inet_aton
  91 #endif
  92 
  93 #include "Python.h"
  94 #include "structmember.h"
  95 
  96 #undef MAX
  97 #define MAX(x, y) ((x) < (y) ? (y) : (x))
  98 
  99 /* Socket object documentation */
 100 PyDoc_STRVAR(sock_doc,
 101 "socket([family[, type[, proto]]]) -> socket object\n\
 102 \n\
 103 Open a socket of the given type.  The family argument specifies the\n\
 104 address family; it defaults to AF_INET.  The type argument specifies\n\
 105 whether this is a stream (SOCK_STREAM, this is the default)\n\
 106 or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,\n\
 107 specifying the default protocol.  Keyword arguments are accepted.\n\
 108 \n\
 109 A socket object represents one endpoint of a network connection.\n\
 110 \n\
 111 Methods of socket objects (keyword arguments not allowed):\n\
 112 \n\
 113 accept() -- accept a connection, returning new socket and client address\n\
 114 bind(addr) -- bind the socket to a local address\n\
 115 close() -- close the socket\n\
 116 connect(addr) -- connect the socket to a remote address\n\
 117 connect_ex(addr) -- connect, return an error code instead of an exception\n\
 118 dup() -- return a new socket object identical to the current one [*]\n\
 119 fileno() -- return underlying file descriptor\n\
 120 getpeername() -- return remote address [*]\n\
 121 getsockname() -- return local address\n\
 122 getsockopt(level, optname[, buflen]) -- get socket options\n\
 123 gettimeout() -- return timeout or None\n\
 124 listen(n) -- start listening for incoming connections\n\
 125 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
 126 recv(buflen[, flags]) -- receive data\n\
 127 recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
 128 recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
 129 recvfrom_into(buffer[, nbytes, [, flags])\n\
 130   -- receive data and sender\'s address (into a buffer)\n\
 131 sendall(data[, flags]) -- send all data\n\
 132 send(data[, flags]) -- send data, may not send all of it\n\
 133 sendto(data[, flags], addr) -- send data to a given address\n\
 134 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
 135 setsockopt(level, optname, value) -- set socket options\n\
 136 settimeout(None | float) -- set or clear the timeout\n\
 137 shutdown(how) -- shut down traffic in one or both directions\n\
 138 \n\
 139  [*] not available on all platforms!");
 140 
 141 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
 142    I hope some day someone can clean this up please... */
 143 
 144 /* Hacks for gethostbyname_r().  On some non-Linux platforms, the configure
 145    script doesn't get this right, so we hardcode some platform checks below.
 146    On the other hand, not all Linux versions agree, so there the settings
 147    computed by the configure script are needed! */
 148 
 149 #ifndef linux
 150 # undef HAVE_GETHOSTBYNAME_R_3_ARG
 151 # undef HAVE_GETHOSTBYNAME_R_5_ARG
 152 # undef HAVE_GETHOSTBYNAME_R_6_ARG
 153 #endif
 154 
 155 #ifndef WITH_THREAD
 156 # undef HAVE_GETHOSTBYNAME_R
 157 #endif
 158 
 159 #ifdef HAVE_GETHOSTBYNAME_R
 160 # if defined(_AIX) || defined(__osf__)
 161 #  define HAVE_GETHOSTBYNAME_R_3_ARG
 162 # elif defined(__sun) || defined(__sgi)
 163 #  define HAVE_GETHOSTBYNAME_R_5_ARG
 164 # elif defined(linux)
 165 /* Rely on the configure script */
 166 # else
 167 #  undef HAVE_GETHOSTBYNAME_R
 168 # endif
 169 #endif
 170 
 171 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
 172     !defined(MS_WINDOWS)
 173 # define USE_GETHOSTBYNAME_LOCK
 174 #endif
 175 
 176 /* To use __FreeBSD_version */
 177 #ifdef HAVE_SYS_PARAM_H
 178 #include <sys/param.h>
 179 #endif
 180 /* On systems on which getaddrinfo() is believed to not be thread-safe,
 181    (this includes the getaddrinfo emulation) protect access with a lock. */
 182 #if defined(WITH_THREAD) && (defined(__APPLE__) || \
 183     (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
 184     defined(__OpenBSD__) || defined(__NetBSD__) || \
 185     defined(__VMS) || !defined(HAVE_GETADDRINFO))
 186 #define USE_GETADDRINFO_LOCK
 187 #endif
 188 
 189 #ifdef USE_GETADDRINFO_LOCK
 190 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
 191 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
 192 #else
 193 #define ACQUIRE_GETADDRINFO_LOCK
 194 #define RELEASE_GETADDRINFO_LOCK
 195 #endif
 196 
 197 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
 198 # include "pythread.h"
 199 #endif
 200 
 201 #if defined(PYCC_VACPP)
 202 # include <types.h>
 203 # include <io.h>
 204 # include <sys/ioctl.h>
 205 # include <utils.h>
 206 # include <ctype.h>
 207 #endif
 208 
 209 #if defined(__VMS)
 210 #  include <ioctl.h>
 211 #endif
 212 
 213 #if defined(PYOS_OS2)
 214 # define  INCL_DOS
 215 # define  INCL_DOSERRORS
 216 # define  INCL_NOPMAPI
 217 # include <os2.h>
 218 #endif
 219 
 220 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
 221 /* make sure that the reentrant (gethostbyaddr_r etc)
 222    functions are declared correctly if compiling with
 223    MIPSPro 7.x in ANSI C mode (default) */
 224 
 225 /* XXX Using _SGIAPI is the wrong thing,
 226    but I don't know what the right thing is. */
 227 #undef _SGIAPI /* to avoid warning */
 228 #define _SGIAPI 1
 229 
 230 #undef _XOPEN_SOURCE
 231 #include <sys/socket.h>
 232 #include <sys/types.h>
 233 #include <netinet/in.h>
 234 #ifdef _SS_ALIGNSIZE
 235 #define HAVE_GETADDRINFO 1
 236 #define HAVE_GETNAMEINFO 1
 237 #endif
 238 
 239 #define HAVE_INET_PTON
 240 #include <netdb.h>
 241 #endif
 242 
 243 /* Irix 6.5 fails to define this variable at all. This is needed
 244    for both GCC and SGI's compiler. I'd say that the SGI headers
 245    are just busted. Same thing for Solaris. */
 246 #if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
 247 #define INET_ADDRSTRLEN 16
 248 #endif
 249 
 250 /* Generic includes */
 251 #ifdef HAVE_SYS_TYPES_H
 252 #include <sys/types.h>
 253 #endif
 254 
 255 /* Generic socket object definitions and includes */
 256 #define PySocket_BUILDING_SOCKET
 257 #include "socketmodule.h"
 258 
 259 /* Addressing includes */
 260 
 261 #ifndef MS_WINDOWS
 262 
 263 /* Non-MS WINDOWS includes */
 264 # include <netdb.h>
 265 
 266 /* Headers needed for inet_ntoa() and inet_addr() */
 267 # ifdef __BEOS__
 268 #  include <net/netdb.h>
 269 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
 270 #  include <netdb.h>
 271 typedef size_t socklen_t;
 272 # else
 273 #   include <arpa/inet.h>
 274 # endif
 275 
 276 # ifndef RISCOS
 277 #  include <fcntl.h>
 278 # else
 279 #  include <sys/ioctl.h>
 280 #  include <socklib.h>
 281 #  define NO_DUP
 282 int h_errno; /* not used */
 283 #  define INET_ADDRSTRLEN 16
 284 # endif
 285 
 286 #else
 287 
 288 /* MS_WINDOWS includes */
 289 # ifdef HAVE_FCNTL_H
 290 #  include <fcntl.h>
 291 # endif
 292 
 293 #endif
 294 
 295 #include <stddef.h>
 296 
 297 #ifndef offsetof
 298 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
 299 #endif
 300 
 301 #ifndef O_NONBLOCK
 302 # define O_NONBLOCK O_NDELAY
 303 #endif
 304 
 305 /* include Python's addrinfo.h unless it causes trouble */
 306 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
 307   /* Do not include addinfo.h on some newer IRIX versions.
 308    * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
 309    * for example, but not by 6.5.10.
 310    */
 311 #elif defined(_MSC_VER) && _MSC_VER>1201
 312   /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
 313    * EAI_* constants are defined in (the already included) ws2tcpip.h.
 314    */
 315 #else
 316 #  include "addrinfo.h"
 317 #endif
 318 
 319 #ifndef HAVE_INET_PTON
 320 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
 321 int inet_pton(int af, const char *src, void *dst);
 322 const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
 323 #endif
 324 #endif
 325 
 326 #ifdef __APPLE__
 327 /* On OS X, getaddrinfo returns no error indication of lookup
 328    failure, so we must use the emulation instead of the libinfo
 329    implementation. Unfortunately, performing an autoconf test
 330    for this bug would require DNS access for the machine performing
 331    the configuration, which is not acceptable. Therefore, we
 332    determine the bug just by checking for __APPLE__. If this bug
 333    gets ever fixed, perhaps checking for sys/version.h would be
 334    appropriate, which is 10/0 on the system with the bug. */
 335 #ifndef HAVE_GETNAMEINFO
 336 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
 337    Find to check for Jaguar is that it has getnameinfo(), which
 338    older releases don't have */
 339 #undef HAVE_GETADDRINFO
 340 #endif
 341 
 342 #ifdef HAVE_INET_ATON
 343 #define USE_INET_ATON_WEAKLINK
 344 #endif
 345 
 346 #endif
 347 
 348 /* I know this is a bad practice, but it is the easiest... */
 349 #if !defined(HAVE_GETADDRINFO)
 350 /* avoid clashes with the C library definition of the symbol. */
 351 #define getaddrinfo fake_getaddrinfo
 352 #define gai_strerror fake_gai_strerror
 353 #define freeaddrinfo fake_freeaddrinfo
 354 #include "getaddrinfo.c"
 355 #endif
 356 #if !defined(HAVE_GETNAMEINFO)
 357 #define getnameinfo fake_getnameinfo
 358 #include "getnameinfo.c"
 359 #endif
 360 
 361 #if defined(MS_WINDOWS) || defined(__BEOS__)
 362 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
 363 /* seem to be a few differences in the API */
 364 #define SOCKETCLOSE closesocket
 365 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
 366 #endif
 367 
 368 #ifdef MS_WIN32
 369 #define EAFNOSUPPORT WSAEAFNOSUPPORT
 370 #define snprintf _snprintf
 371 #endif
 372 
 373 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
 374 #define SOCKETCLOSE soclose
 375 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
 376 #endif
 377 
 378 #ifndef SOCKETCLOSE
 379 #define SOCKETCLOSE close
 380 #endif
 381 
 382 #if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
 383 #define USE_BLUETOOTH 1
 384 #if defined(__FreeBSD__)
 385 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
 386 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
 387 #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
 388 #define SOL_HCI SOL_HCI_RAW
 389 #define HCI_FILTER SO_HCI_RAW_FILTER
 390 #define sockaddr_l2 sockaddr_l2cap
 391 #define sockaddr_rc sockaddr_rfcomm
 392 #define hci_dev hci_node
 393 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
 394 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
 395 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
 396 #elif defined(__NetBSD__) || defined(__DragonFly__)
 397 #define sockaddr_l2 sockaddr_bt
 398 #define sockaddr_rc sockaddr_bt
 399 #define sockaddr_hci sockaddr_bt
 400 #define sockaddr_sco sockaddr_bt
 401 #define SOL_HCI BTPROTO_HCI
 402 #define HCI_DATA_DIR SO_HCI_DIRECTION
 403 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
 404 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
 405 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
 406 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
 407 #else
 408 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
 409 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
 410 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
 411 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
 412 #endif
 413 #endif
 414 
 415 #ifdef __VMS
 416 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
 417 #define SEGMENT_SIZE (32 * 1024 -1)
 418 #endif
 419 
 420 #define SAS2SA(x)       ((struct sockaddr *)(x))
 421 
 422 /*
 423  * Constants for getnameinfo()
 424  */
 425 #if !defined(NI_MAXHOST)
 426 #define NI_MAXHOST 1025
 427 #endif
 428 #if !defined(NI_MAXSERV)
 429 #define NI_MAXSERV 32
 430 #endif
 431 
 432 /* XXX There's a problem here: *static* functions are not supposed to have
 433    a Py prefix (or use CapitalizedWords).  Later... */
 434 
 435 /* Global variable holding the exception type for errors detected
 436    by this module (but not argument type or memory errors, etc.). */
 437 static PyObject *socket_error;
 438 static PyObject *socket_herror;
 439 static PyObject *socket_gaierror;
 440 static PyObject *socket_timeout;
 441 
 442 #ifdef RISCOS
 443 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
 444 static int taskwindow;
 445 #endif
 446 
 447 /* A forward reference to the socket type object.
 448    The sock_type variable contains pointers to various functions,
 449    some of which call new_sockobject(), which uses sock_type, so
 450    there has to be a circular reference. */
 451 static PyTypeObject sock_type;
 452 
 453 #if defined(HAVE_POLL_H)
 454 #include <poll.h>
 455 #elif defined(HAVE_SYS_POLL_H)
 456 #include <sys/poll.h>
 457 #endif
 458 
 459 #ifdef HAVE_POLL
 460 /* Instead of select(), we'll use poll() since poll() works on any fd. */
 461 #define IS_SELECTABLE(s) 1
 462 /* Can we call select() with this socket without a buffer overrun? */
 463 #else
 464 /* If there's no timeout left, we don't have to call select, so it's a safe,
 465  * little white lie. */
 466 #define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0.0)
 467 #endif
 468 
 469 static PyObject*
 470 select_error(void)
 471 {
 472     PyErr_SetString(socket_error, "unable to select on socket");
 473     return NULL;
 474 }
 475 
 476 /* Convenience function to raise an error according to errno
 477    and return a NULL pointer from a function. */
 478 
 479 static PyObject *
 480 set_error(void)
 481 {
 482 #ifdef MS_WINDOWS
 483     int err_no = WSAGetLastError();
 484     /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
 485        recognizes the error codes used by both GetLastError() and
 486        WSAGetLastError */
 487     if (err_no)
 488         return PyErr_SetExcFromWindowsErr(socket_error, err_no);
 489 #endif
 490 
 491 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
 492     if (sock_errno() != NO_ERROR) {
 493         APIRET rc;
 494         ULONG  msglen;
 495         char outbuf[100];
 496         int myerrorcode = sock_errno();
 497 
 498         /* Retrieve socket-related error message from MPTN.MSG file */
 499         rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
 500                            myerrorcode - SOCBASEERR + 26,
 501                            "mptn.msg",
 502                            &msglen);
 503         if (rc == NO_ERROR) {
 504             PyObject *v;
 505 
 506             /* OS/2 doesn't guarantee a terminator */
 507             outbuf[msglen] = '\0';
 508             if (strlen(outbuf) > 0) {
 509                 /* If non-empty msg, trim CRLF */
 510                 char *lastc = &outbuf[ strlen(outbuf)-1 ];
 511                 while (lastc > outbuf &&
 512                        isspace(Py_CHARMASK(*lastc))) {
 513                     /* Trim trailing whitespace (CRLF) */
 514                     *lastc-- = '\0';
 515                 }
 516             }
 517             v = Py_BuildValue("(is)", myerrorcode, outbuf);
 518             if (v != NULL) {
 519                 PyErr_SetObject(socket_error, v);
 520                 Py_DECREF(v);
 521             }
 522             return NULL;
 523         }
 524     }
 525 #endif
 526 
 527 #if defined(RISCOS)
 528     if (_inet_error.errnum != NULL) {
 529         PyObject *v;
 530         v = Py_BuildValue("(is)", errno, _inet_err());
 531         if (v != NULL) {
 532             PyErr_SetObject(socket_error, v);
 533             Py_DECREF(v);
 534         }
 535         return NULL;
 536     }
 537 #endif
 538 
 539     return PyErr_SetFromErrno(socket_error);
 540 }
 541 
 542 
 543 static PyObject *
 544 set_herror(int h_error)
 545 {
 546     PyObject *v;
 547 
 548 #ifdef HAVE_HSTRERROR
 549     v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
 550 #else
 551     v = Py_BuildValue("(is)", h_error, "host not found");
 552 #endif
 553     if (v != NULL) {
 554         PyErr_SetObject(socket_herror, v);
 555         Py_DECREF(v);
 556     }
 557 
 558     return NULL;
 559 }
 560 
 561 
 562 static PyObject *
 563 set_gaierror(int error)
 564 {
 565     PyObject *v;
 566 
 567 #ifdef EAI_SYSTEM
 568     /* EAI_SYSTEM is not available on Windows XP. */
 569     if (error == EAI_SYSTEM)
 570         return set_error();
 571 #endif
 572 
 573 #ifdef HAVE_GAI_STRERROR
 574     v = Py_BuildValue("(is)", error, gai_strerror(error));
 575 #else
 576     v = Py_BuildValue("(is)", error, "getaddrinfo failed");
 577 #endif
 578     if (v != NULL) {
 579         PyErr_SetObject(socket_gaierror, v);
 580         Py_DECREF(v);
 581     }
 582 
 583     return NULL;
 584 }
 585 
 586 #ifdef __VMS
 587 /* Function to send in segments */
 588 static int
 589 sendsegmented(int sock_fd, char *buf, int len, int flags)
 590 {
 591     int n = 0;
 592     int remaining = len;
 593 
 594     while (remaining > 0) {
 595         unsigned int segment;
 596 
 597         segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
 598         n = send(sock_fd, buf, segment, flags);
 599         if (n < 0) {
 600             return n;
 601         }
 602         remaining -= segment;
 603         buf += segment;
 604     } /* end while */
 605 
 606     return len;
 607 }
 608 #endif
 609 
 610 /* Function to perform the setting of socket blocking mode
 611    internally. block = (1 | 0). */
 612 static int
 613 internal_setblocking(PySocketSockObject *s, int block)
 614 {
 615 #ifndef RISCOS
 616 #ifndef MS_WINDOWS
 617     int delay_flag;
 618 #endif
 619 #endif
 620 
 621     Py_BEGIN_ALLOW_THREADS
 622 #ifdef __BEOS__
 623     block = !block;
 624     setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
 625                (void *)(&block), sizeof(int));
 626 #else
 627 #ifndef RISCOS
 628 #ifndef MS_WINDOWS
 629 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
 630     block = !block;
 631     ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
 632 #elif defined(__VMS)
 633     block = !block;
 634     ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
 635 #else  /* !PYOS_OS2 && !__VMS */
 636     delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
 637     if (block)
 638         delay_flag &= (~O_NONBLOCK);
 639     else
 640         delay_flag |= O_NONBLOCK;
 641     fcntl(s->sock_fd, F_SETFL, delay_flag);
 642 #endif /* !PYOS_OS2 */
 643 #else /* MS_WINDOWS */
 644     block = !block;
 645     ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
 646 #endif /* MS_WINDOWS */
 647 #else /* RISCOS */
 648     block = !block;
 649     socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
 650 #endif /* RISCOS */
 651 #endif /* __BEOS__ */
 652     Py_END_ALLOW_THREADS
 653 
 654     /* Since these don't return anything */
 655     return 1;
 656 }
 657 
 658 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
 659    The argument writing indicates the direction.
 660    This does not raise an exception; we'll let our caller do that
 661    after they've reacquired the interpreter lock.
 662    Returns 1 on timeout, -1 on error, 0 otherwise. */
 663 static int
 664 internal_select(PySocketSockObject *s, int writing)
 665 {
 666     int n;
 667 
 668     /* Nothing to do unless we're in timeout mode (not non-blocking) */
 669     if (s->sock_timeout <= 0.0)
 670         return 0;
 671 
 672     /* Guard against closed socket */
 673     if (s->sock_fd < 0)
 674         return 0;
 675 
 676     /* Prefer poll, if available, since you can poll() any fd
 677      * which can't be done with select(). */
 678 #ifdef HAVE_POLL
 679     {
 680         struct pollfd pollfd;
 681         int timeout;
 682 
 683         pollfd.fd = s->sock_fd;
 684         pollfd.events = writing ? POLLOUT : POLLIN;
 685 
 686         /* s->sock_timeout is in seconds, timeout in ms */
 687         timeout = (int)(s->sock_timeout * 1000 + 0.5);
 688         n = poll(&pollfd, 1, timeout);
 689     }
 690 #else
 691     {
 692         /* Construct the arguments to select */
 693         fd_set fds;
 694         struct timeval tv;
 695         tv.tv_sec = (int)s->sock_timeout;
 696         tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
 697         FD_ZERO(&fds);
 698         FD_SET(s->sock_fd, &fds);
 699 
 700         /* See if the socket is ready */
 701         if (writing)
 702             n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
 703         else
 704             n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
 705     }
 706 #endif
 707 
 708     if (n < 0)
 709         return -1;
 710     if (n == 0)
 711         return 1;
 712     return 0;
 713 }
 714 
 715 /* Initialize a new socket object. */
 716 
 717 static double defaulttimeout = -1.0; /* Default timeout for new sockets */
 718 
 719 PyMODINIT_FUNC
 720 init_sockobject(PySocketSockObject *s,
 721                 SOCKET_T fd, int family, int type, int proto)
 722 {
 723 #ifdef RISCOS
 724     int block = 1;
 725 #endif
 726     s->sock_fd = fd;
 727     s->sock_family = family;
 728     s->sock_type = type;
 729     s->sock_proto = proto;
 730     s->sock_timeout = defaulttimeout;
 731 
 732     s->errorhandler = &set_error;
 733 
 734     if (defaulttimeout >= 0.0)
 735         internal_setblocking(s, 0);
 736 
 737 #ifdef RISCOS
 738     if (taskwindow)
 739         socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
 740 #endif
 741 }
 742 
 743 
 744 /* Create a new socket object.
 745    This just creates the object and initializes it.
 746    If the creation fails, return NULL and set an exception (implicit
 747    in NEWOBJ()). */
 748 
 749 static PySocketSockObject *
 750 new_sockobject(SOCKET_T fd, int family, int type, int proto)
 751 {
 752     PySocketSockObject *s;
 753     s = (PySocketSockObject *)
 754         PyType_GenericNew(&sock_type, NULL, NULL);
 755     if (s != NULL)
 756         init_sockobject(s, fd, family, type, proto);
 757     return s;
 758 }
 759 
 760 
 761 /* Lock to allow python interpreter to continue, but only allow one
 762    thread to be in gethostbyname or getaddrinfo */
 763 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
 764 PyThread_type_lock netdb_lock;
 765 #endif
 766 
 767 
 768 /* Convert a string specifying a host name or one of a few symbolic
 769    names to a numeric IP address.  This usually calls gethostbyname()
 770    to do the work; the names "" and "<broadcast>" are special.
 771    Return the length (IPv4 should be 4 bytes), or negative if
 772    an error occurred; then an exception is raised. */
 773 
 774 static int
 775 setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
 776 {
 777     struct addrinfo hints, *res;
 778     int error;
 779     int d1, d2, d3, d4;
 780     char ch;
 781 
 782     memset((void *) addr_ret, '\0', sizeof(*addr_ret));
 783     if (name[0] == '\0') {
 784         int siz;
 785         memset(&hints, 0, sizeof(hints));
 786         hints.ai_family = af;
 787         hints.ai_socktype = SOCK_DGRAM;         /*dummy*/
 788         hints.ai_flags = AI_PASSIVE;
 789         Py_BEGIN_ALLOW_THREADS
 790         ACQUIRE_GETADDRINFO_LOCK
 791         error = getaddrinfo(NULL, "0", &hints, &res);
 792         Py_END_ALLOW_THREADS
 793         /* We assume that those thread-unsafe getaddrinfo() versions
 794            *are* safe regarding their return value, ie. that a
 795            subsequent call to getaddrinfo() does not destroy the
 796            outcome of the first call. */
 797         RELEASE_GETADDRINFO_LOCK
 798         if (error) {
 799             set_gaierror(error);
 800             return -1;
 801         }
 802         switch (res->ai_family) {
 803         case AF_INET:
 804             siz = 4;
 805             break;
 806 #ifdef ENABLE_IPV6
 807         case AF_INET6:
 808             siz = 16;
 809             break;
 810 #endif
 811         default:
 812             freeaddrinfo(res);
 813             PyErr_SetString(socket_error,
 814                 "unsupported address family");
 815             return -1;
 816         }
 817         if (res->ai_next) {
 818             freeaddrinfo(res);
 819             PyErr_SetString(socket_error,
 820                 "wildcard resolved to multiple address");
 821             return -1;
 822         }
 823         if (res->ai_addrlen < addr_ret_size)
 824             addr_ret_size = res->ai_addrlen;
 825         memcpy(addr_ret, res->ai_addr, addr_ret_size);
 826         freeaddrinfo(res);
 827         return siz;
 828     }
 829     if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
 830         struct sockaddr_in *sin;
 831         if (af != AF_INET && af != AF_UNSPEC) {
 832             PyErr_SetString(socket_error,
 833                 "address family mismatched");
 834             return -1;
 835         }
 836         sin = (struct sockaddr_in *)addr_ret;
 837         memset((void *) sin, '\0', sizeof(*sin));
 838         sin->sin_family = AF_INET;
 839 #ifdef HAVE_SOCKADDR_SA_LEN
 840         sin->sin_len = sizeof(*sin);
 841 #endif
 842         sin->sin_addr.s_addr = INADDR_BROADCAST;
 843         return sizeof(sin->sin_addr);
 844     }
 845     if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
 846         0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
 847         0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
 848         struct sockaddr_in *sin;
 849         sin = (struct sockaddr_in *)addr_ret;
 850         sin->sin_addr.s_addr = htonl(
 851             ((long) d1 << 24) | ((long) d2 << 16) |
 852             ((long) d3 << 8) | ((long) d4 << 0));
 853         sin->sin_family = AF_INET;
 854 #ifdef HAVE_SOCKADDR_SA_LEN
 855         sin->sin_len = sizeof(*sin);
 856 #endif
 857         return 4;
 858     }
 859     memset(&hints, 0, sizeof(hints));
 860     hints.ai_family = af;
 861     Py_BEGIN_ALLOW_THREADS
 862     ACQUIRE_GETADDRINFO_LOCK
 863     error = getaddrinfo(name, NULL, &hints, &res);
 864 #if defined(__digital__) && defined(__unix__)
 865     if (error == EAI_NONAME && af == AF_UNSPEC) {
 866         /* On Tru64 V5.1, numeric-to-addr conversion fails
 867            if no address family is given. Assume IPv4 for now.*/
 868         hints.ai_family = AF_INET;
 869         error = getaddrinfo(name, NULL, &hints, &res);
 870     }
 871 #endif
 872     Py_END_ALLOW_THREADS
 873     RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
 874     if (error) {
 875         set_gaierror(error);
 876         return -1;
 877     }
 878     if (res->ai_addrlen < addr_ret_size)
 879         addr_ret_size = res->ai_addrlen;
 880     memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
 881     freeaddrinfo(res);
 882     switch (addr_ret->sa_family) {
 883     case AF_INET:
 884         return 4;
 885 #ifdef ENABLE_IPV6
 886     case AF_INET6:
 887         return 16;
 888 #endif
 889     default:
 890         PyErr_SetString(socket_error, "unknown address family");
 891         return -1;
 892     }
 893 }
 894 
 895 
 896 /* Create a string object representing an IP address.
 897    This is always a string of the form 'dd.dd.dd.dd' (with variable
 898    size numbers). */
 899 
 900 static PyObject *
 901 makeipaddr(struct sockaddr *addr, int addrlen)
 902 {
 903     char buf[NI_MAXHOST];
 904     int error;
 905 
 906     error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
 907         NI_NUMERICHOST);
 908     if (error) {
 909         set_gaierror(error);
 910         return NULL;
 911     }
 912     return PyString_FromString(buf);
 913 }
 914 
 915 
 916 #ifdef USE_BLUETOOTH
 917 /* Convert a string representation of a Bluetooth address into a numeric
 918    address.  Returns the length (6), or raises an exception and returns -1 if
 919    an error occurred. */
 920 
 921 static int
 922 setbdaddr(char *name, bdaddr_t *bdaddr)
 923 {
 924     unsigned int b0, b1, b2, b3, b4, b5;
 925     char ch;
 926     int n;
 927 
 928     n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
 929                &b5, &b4, &b3, &b2, &b1, &b0, &ch);
 930     if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
 931         bdaddr->b[0] = b0;
 932         bdaddr->b[1] = b1;
 933         bdaddr->b[2] = b2;
 934         bdaddr->b[3] = b3;
 935         bdaddr->b[4] = b4;
 936         bdaddr->b[5] = b5;
 937         return 6;
 938     } else {
 939         PyErr_SetString(socket_error, "bad bluetooth address");
 940         return -1;
 941     }
 942 }
 943 
 944 /* Create a string representation of the Bluetooth address.  This is always a
 945    string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
 946    value (zero padded if necessary). */
 947 
 948 static PyObject *
 949 makebdaddr(bdaddr_t *bdaddr)
 950 {
 951     char buf[(6 * 2) + 5 + 1];
 952 
 953     sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
 954         bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
 955         bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
 956     return PyString_FromString(buf);
 957 }
 958 #endif
 959 
 960 
 961 /* Create an object representing the given socket address,
 962    suitable for passing it back to bind(), connect() etc.
 963    The family field of the sockaddr structure is inspected
 964    to determine what kind of address it really is. */
 965 
 966 /*ARGSUSED*/
 967 static PyObject *
 968 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
 969 {
 970     if (addrlen == 0) {
 971         /* No address -- may be recvfrom() from known socket */
 972         Py_INCREF(Py_None);
 973         return Py_None;
 974     }
 975 
 976 #ifdef __BEOS__
 977     /* XXX: BeOS version of accept() doesn't set family correctly */
 978     addr->sa_family = AF_INET;
 979 #endif
 980 
 981     switch (addr->sa_family) {
 982 
 983     case AF_INET:
 984     {
 985         struct sockaddr_in *a;
 986         PyObject *addrobj = makeipaddr(addr, sizeof(*a));
 987         PyObject *ret = NULL;
 988         if (addrobj) {
 989             a = (struct sockaddr_in *)addr;
 990             ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
 991             Py_DECREF(addrobj);
 992         }
 993         return ret;
 994     }
 995 
 996 #if defined(AF_UNIX)
 997     case AF_UNIX:
 998     {
 999         struct sockaddr_un *a = (struct sockaddr_un *) addr;
1000 #ifdef linux
1001         if (a->sun_path[0] == 0) {  /* Linux abstract namespace */
1002             addrlen -= offsetof(struct sockaddr_un, sun_path);
1003             return PyString_FromStringAndSize(a->sun_path,
1004                                               addrlen);
1005         }
1006         else
1007 #endif /* linux */
1008         {
1009             /* regular NULL-terminated string */
1010             return PyString_FromString(a->sun_path);
1011         }
1012     }
1013 #endif /* AF_UNIX */
1014 
1015 #if defined(AF_NETLINK)
1016        case AF_NETLINK:
1017        {
1018            struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
1019            return Py_BuildValue("II", a->nl_pid, a->nl_groups);
1020        }
1021 #endif /* AF_NETLINK */
1022 
1023 #ifdef ENABLE_IPV6
1024     case AF_INET6:
1025     {
1026         struct sockaddr_in6 *a;
1027         PyObject *addrobj = makeipaddr(addr, sizeof(*a));
1028         PyObject *ret = NULL;
1029         if (addrobj) {
1030             a = (struct sockaddr_in6 *)addr;
1031             ret = Py_BuildValue("OiII",
1032                                 addrobj,
1033                                 ntohs(a->sin6_port),
1034                                 ntohl(a->sin6_flowinfo),
1035                                 a->sin6_scope_id);
1036             Py_DECREF(addrobj);
1037         }
1038         return ret;
1039     }
1040 #endif
1041 
1042 #ifdef USE_BLUETOOTH
1043     case AF_BLUETOOTH:
1044         switch (proto) {
1045 
1046         case BTPROTO_L2CAP:
1047         {
1048             struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
1049             PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
1050             PyObject *ret = NULL;
1051             if (addrobj) {
1052                 ret = Py_BuildValue("Oi",
1053                                     addrobj,
1054                                     _BT_L2_MEMB(a, psm));
1055                 Py_DECREF(addrobj);
1056             }
1057             return ret;
1058         }
1059 
1060         case BTPROTO_RFCOMM:
1061         {
1062             struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
1063             PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
1064             PyObject *ret = NULL;
1065             if (addrobj) {
1066                 ret = Py_BuildValue("Oi",
1067                                     addrobj,
1068                                     _BT_RC_MEMB(a, channel));
1069                 Py_DECREF(addrobj);
1070             }
1071             return ret;
1072         }
1073 
1074         case BTPROTO_HCI:
1075         {
1076             struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
1077 #if defined(__NetBSD__) || defined(__DragonFly__)
1078             return makebdaddr(&_BT_HCI_MEMB(a, bdaddr));
1079 #else
1080             PyObject *ret = NULL;
1081             ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
1082             return ret;
1083 #endif
1084         }
1085 
1086 #if !defined(__FreeBSD__)
1087         case BTPROTO_SCO:
1088         {
1089             struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1090             return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1091         }
1092 #endif
1093 
1094         default:
1095             PyErr_SetString(PyExc_ValueError,
1096                             "Unknown Bluetooth protocol");
1097             return NULL;
1098         }
1099 #endif
1100 
1101 #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFNAME)
1102     case AF_PACKET:
1103     {
1104         struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1105         char *ifname = "";
1106         struct ifreq ifr;
1107         /* need to look up interface name give index */
1108         if (a->sll_ifindex) {
1109             ifr.ifr_ifindex = a->sll_ifindex;
1110             if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1111                 ifname = ifr.ifr_name;
1112         }
1113         return Py_BuildValue("shbhs#",
1114                              ifname,
1115                              ntohs(a->sll_protocol),
1116                              a->sll_pkttype,
1117                              a->sll_hatype,
1118                              a->sll_addr,
1119                              a->sll_halen);
1120     }
1121 #endif
1122 
1123 #ifdef HAVE_LINUX_TIPC_H
1124     case AF_TIPC:
1125     {
1126         struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
1127         if (a->addrtype == TIPC_ADDR_NAMESEQ) {
1128             return Py_BuildValue("IIIII",
1129                             a->addrtype,
1130                             a->addr.nameseq.type,
1131                             a->addr.nameseq.lower,
1132                             a->addr.nameseq.upper,
1133                             a->scope);
1134         } else if (a->addrtype == TIPC_ADDR_NAME) {
1135             return Py_BuildValue("IIIII",
1136                             a->addrtype,
1137                             a->addr.name.name.type,
1138                             a->addr.name.name.instance,
1139                             a->addr.name.name.instance,
1140                             a->scope);
1141         } else if (a->addrtype == TIPC_ADDR_ID) {
1142             return Py_BuildValue("IIIII",
1143                             a->addrtype,
1144                             a->addr.id.node,
1145                             a->addr.id.ref,
1146                             0,
1147                             a->scope);
1148         } else {
1149             PyErr_SetString(PyExc_ValueError,
1150                             "Invalid address type");
1151             return NULL;
1152         }
1153     }
1154 #endif
1155 
1156     /* More cases here... */
1157 
1158     default:
1159         /* If we don't know the address family, don't raise an
1160            exception -- return it as a tuple. */
1161         return Py_BuildValue("is#",
1162                              addr->sa_family,
1163                              addr->sa_data,
1164                              sizeof(addr->sa_data));
1165 
1166     }
1167 }
1168 
1169 
1170 /* Parse a socket address argument according to the socket object's
1171    address family.  Return 1 if the address was in the proper format,
1172    0 of not.  The address is returned through addr_ret, its length
1173    through len_ret. */
1174 
1175 static int
1176 getsockaddrarg(PySocketSockObject *s, PyObject *args,
1177                struct sockaddr *addr_ret, int *len_ret)
1178 {
1179     switch (s->sock_family) {
1180 
1181 #if defined(AF_UNIX)
1182     case AF_UNIX:
1183     {
1184         struct sockaddr_un* addr;
1185         char *path;
1186         int len;
1187         if (!PyArg_Parse(args, "t#", &path, &len))
1188             return 0;
1189 
1190         addr = (struct sockaddr_un*)addr_ret;
1191 #ifdef linux
1192         if (len > 0 && path[0] == 0) {
1193             /* Linux abstract namespace extension */
1194             if (len > sizeof addr->sun_path) {
1195                 PyErr_SetString(socket_error,
1196                                 "AF_UNIX path too long");
1197                 return 0;
1198             }
1199         }
1200         else
1201 #endif /* linux */
1202         {
1203             /* regular NULL-terminated string */
1204             if (len >= sizeof addr->sun_path) {
1205                 PyErr_SetString(socket_error,
1206                                 "AF_UNIX path too long");
1207                 return 0;
1208             }
1209             addr->sun_path[len] = 0;
1210         }
1211         addr->sun_family = s->sock_family;
1212         memcpy(addr->sun_path, path, len);
1213 #if defined(PYOS_OS2)
1214         *len_ret = sizeof(*addr);
1215 #else
1216         *len_ret = len + offsetof(struct sockaddr_un, sun_path);
1217 #endif
1218         return 1;
1219     }
1220 #endif /* AF_UNIX */
1221 
1222 #if defined(AF_NETLINK)
1223     case AF_NETLINK:
1224     {
1225         struct sockaddr_nl* addr;
1226         int pid, groups;
1227         addr = (struct sockaddr_nl *)addr_ret;
1228         if (!PyTuple_Check(args)) {
1229             PyErr_Format(
1230                 PyExc_TypeError,
1231                 "getsockaddrarg: "
1232                 "AF_NETLINK address must be tuple, not %.500s",
1233                 Py_TYPE(args)->tp_name);
1234             return 0;
1235         }
1236         if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
1237             return 0;
1238         addr->nl_family = AF_NETLINK;
1239         addr->nl_pid = pid;
1240         addr->nl_groups = groups;
1241         *len_ret = sizeof(*addr);
1242         return 1;
1243     }
1244 #endif
1245 
1246     case AF_INET:
1247     {
1248         struct sockaddr_in* addr;
1249         char *host;
1250         int port, result;
1251         if (!PyTuple_Check(args)) {
1252             PyErr_Format(
1253                 PyExc_TypeError,
1254                 "getsockaddrarg: "
1255                 "AF_INET address must be tuple, not %.500s",
1256                 Py_TYPE(args)->tp_name);
1257             return 0;
1258         }
1259         if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
1260                               "idna", &host, &port))
1261             return 0;
1262         addr=(struct sockaddr_in*)addr_ret;
1263         result = setipaddr(host, (struct sockaddr *)addr,
1264                            sizeof(*addr),  AF_INET);
1265         PyMem_Free(host);
1266         if (result < 0)
1267             return 0;
1268         if (port < 0 || port > 0xffff) {
1269             PyErr_SetString(
1270                 PyExc_OverflowError,
1271                 "getsockaddrarg: port must be 0-65535.");
1272             return 0;
1273         }
1274         addr->sin_family = AF_INET;
1275         addr->sin_port = htons((short)port);
1276         *len_ret = sizeof *addr;
1277         return 1;
1278     }
1279 
1280 #ifdef ENABLE_IPV6
1281     case AF_INET6:
1282     {
1283         struct sockaddr_in6* addr;
1284         char *host;
1285         int port, result;
1286         unsigned int flowinfo, scope_id;
1287         flowinfo = scope_id = 0;
1288         if (!PyTuple_Check(args)) {
1289             PyErr_Format(
1290                 PyExc_TypeError,
1291                 "getsockaddrarg: "
1292                 "AF_INET6 address must be tuple, not %.500s",
1293                 Py_TYPE(args)->tp_name);
1294             return 0;
1295         }
1296         if (!PyArg_ParseTuple(args, "eti|II",
1297                               "idna", &host, &port, &flowinfo,
1298                               &scope_id)) {
1299             return 0;
1300         }
1301         addr = (struct sockaddr_in6*)addr_ret;
1302         result = setipaddr(host, (struct sockaddr *)addr,
1303                            sizeof(*addr), AF_INET6);
1304         PyMem_Free(host);
1305         if (result < 0)
1306             return 0;
1307         if (port < 0 || port > 0xffff) {
1308             PyErr_SetString(
1309                 PyExc_OverflowError,
1310                 "getsockaddrarg: port must be 0-65535.");
1311             return 0;
1312         }
1313         if (flowinfo < 0 || flowinfo > 0xfffff) {
1314             PyErr_SetString(
1315                 PyExc_OverflowError,
1316                 "getsockaddrarg: flowinfo must be 0-1048575.");
1317             return 0;
1318         }
1319         addr->sin6_family = s->sock_family;
1320         addr->sin6_port = htons((short)port);
1321         addr->sin6_flowinfo = htonl(flowinfo);
1322         addr->sin6_scope_id = scope_id;
1323         *len_ret = sizeof *addr;
1324         return 1;
1325     }
1326 #endif
1327 
1328 #ifdef USE_BLUETOOTH
1329     case AF_BLUETOOTH:
1330     {
1331         switch (s->sock_proto) {
1332         case BTPROTO_L2CAP:
1333         {
1334             struct sockaddr_l2 *addr;
1335             char *straddr;
1336 
1337             addr = (struct sockaddr_l2 *)addr_ret;
1338             memset(addr, 0, sizeof(struct sockaddr_l2));
1339             _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1340             if (!PyArg_ParseTuple(args, "si", &straddr,
1341                                   &_BT_L2_MEMB(addr, psm))) {
1342                 PyErr_SetString(socket_error, "getsockaddrarg: "
1343                                 "wrong format");
1344                 return 0;
1345             }
1346             if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1347                 return 0;
1348 
1349             *len_ret = sizeof *addr;
1350             return 1;
1351         }
1352         case BTPROTO_RFCOMM:
1353         {
1354             struct sockaddr_rc *addr;
1355             char *straddr;
1356 
1357             addr = (struct sockaddr_rc *)addr_ret;
1358             _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1359             if (!PyArg_ParseTuple(args, "si", &straddr,
1360                                   &_BT_RC_MEMB(addr, channel))) {
1361                 PyErr_SetString(socket_error, "getsockaddrarg: "
1362                                 "wrong format");
1363                 return 0;
1364             }
1365             if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
1366                 return 0;
1367 
1368             *len_ret = sizeof *addr;
1369             return 1;
1370         }
1371         case BTPROTO_HCI:
1372         {
1373             struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
1374 #if defined(__NetBSD__) || defined(__DragonFly__)
1375 			char *straddr = PyBytes_AS_STRING(args);
1376 
1377 			_BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
1378             if (straddr == NULL) {
1379                 PyErr_SetString(socket_error, "getsockaddrarg: "
1380                     "wrong format");
1381                 return 0;
1382             }
1383             if (setbdaddr(straddr, &_BT_HCI_MEMB(addr, bdaddr)) < 0)
1384                 return 0;
1385 #else
1386             _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
1387             if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
1388                 PyErr_SetString(socket_error, "getsockaddrarg: "
1389                                 "wrong format");
1390                 return 0;
1391             }
1392 #endif
1393             *len_ret = sizeof *addr;
1394             return 1;
1395         }
1396 #if !defined(__FreeBSD__)
1397         case BTPROTO_SCO:
1398         {
1399             struct sockaddr_sco *addr;
1400             char *straddr;
1401 
1402             addr = (struct sockaddr_sco *)addr_ret;
1403             _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
1404             straddr = PyString_AsString(args);
1405             if (straddr == NULL) {
1406                 PyErr_SetString(socket_error, "getsockaddrarg: "
1407                                 "wrong format");
1408                 return 0;
1409             }
1410             if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
1411                 return 0;
1412 
1413             *len_ret = sizeof *addr;
1414             return 1;
1415         }
1416 #endif
1417         default:
1418             PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
1419             return 0;
1420         }
1421     }
1422 #endif
1423 
1424 #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFINDEX)
1425     case AF_PACKET:
1426     {
1427         struct sockaddr_ll* addr;
1428         struct ifreq ifr;
1429         char *interfaceName;
1430         int protoNumber;
1431         int hatype = 0;
1432         int pkttype = 0;
1433         char *haddr = NULL;
1434         unsigned int halen = 0;
1435 
1436         if (!PyTuple_Check(args)) {
1437             PyErr_Format(
1438                 PyExc_TypeError,
1439                 "getsockaddrarg: "
1440                 "AF_PACKET address must be tuple, not %.500s",
1441                 Py_TYPE(args)->tp_name);
1442             return 0;
1443         }
1444         if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
1445                               &protoNumber, &pkttype, &hatype,
1446                               &haddr, &halen))
1447             return 0;
1448         strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1449         ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1450         if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1451             s->errorhandler();
1452             return 0;
1453         }
1454         if (halen > 8) {
1455           PyErr_SetString(PyExc_ValueError,
1456                           "Hardware address must be 8 bytes or less");
1457           return 0;
1458         }
1459         if (protoNumber < 0 || protoNumber > 0xffff) {
1460             PyErr_SetString(
1461                 PyExc_OverflowError,
1462                 "getsockaddrarg: protoNumber must be 0-65535.");
1463             return 0;
1464         }
1465         addr = (struct sockaddr_ll*)addr_ret;
1466         addr->sll_family = AF_PACKET;
1467         addr->sll_protocol = htons((short)protoNumber);
1468         addr->sll_ifindex = ifr.ifr_ifindex;
1469         addr->sll_pkttype = pkttype;
1470         addr->sll_hatype = hatype;
1471         if (halen != 0) {
1472           memcpy(&addr->sll_addr, haddr, halen);
1473         }
1474         addr->sll_halen = halen;
1475         *len_ret = sizeof *addr;
1476         return 1;
1477     }
1478 #endif
1479 
1480 #ifdef HAVE_LINUX_TIPC_H
1481     case AF_TIPC:
1482     {
1483         unsigned int atype, v1, v2, v3;
1484         unsigned int scope = TIPC_CLUSTER_SCOPE;
1485         struct sockaddr_tipc *addr;
1486 
1487         if (!PyTuple_Check(args)) {
1488             PyErr_Format(
1489                 PyExc_TypeError,
1490                 "getsockaddrarg: "
1491                 "AF_TIPC address must be tuple, not %.500s",
1492                 Py_TYPE(args)->tp_name);
1493             return 0;
1494         }
1495 
1496         if (!PyArg_ParseTuple(args,
1497                                 "IIII|I;Invalid TIPC address format",
1498                                 &atype, &v1, &v2, &v3, &scope))
1499             return 0;
1500 
1501         addr = (struct sockaddr_tipc *) addr_ret;
1502         memset(addr, 0, sizeof(struct sockaddr_tipc));
1503 
1504         addr->family = AF_TIPC;
1505         addr->scope = scope;
1506         addr->addrtype = atype;
1507 
1508         if (atype == TIPC_ADDR_NAMESEQ) {
1509             addr->addr.nameseq.type = v1;
1510             addr->addr.nameseq.lower = v2;
1511             addr->addr.nameseq.upper = v3;
1512         } else if (atype == TIPC_ADDR_NAME) {
1513             addr->addr.name.name.type = v1;
1514             addr->addr.name.name.instance = v2;
1515         } else if (atype == TIPC_ADDR_ID) {
1516             addr->addr.id.node = v1;
1517             addr->addr.id.ref = v2;
1518         } else {
1519             /* Shouldn't happen */
1520             PyErr_SetString(PyExc_TypeError, "Invalid address type");
1521             return 0;
1522         }
1523 
1524         *len_ret = sizeof(*addr);
1525 
1526         return 1;
1527     }
1528 #endif
1529 
1530     /* More cases here... */
1531 
1532     default:
1533         PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1534         return 0;
1535 
1536     }
1537 }
1538 
1539 
1540 /* Get the address length according to the socket object's address family.
1541    Return 1 if the family is known, 0 otherwise.  The length is returned
1542    through len_ret. */
1543 
1544 static int
1545 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1546 {
1547     switch (s->sock_family) {
1548 
1549 #if defined(AF_UNIX)
1550     case AF_UNIX:
1551     {
1552         *len_ret = sizeof (struct sockaddr_un);
1553         return 1;
1554     }
1555 #endif /* AF_UNIX */
1556 #if defined(AF_NETLINK)
1557        case AF_NETLINK:
1558        {
1559            *len_ret = sizeof (struct sockaddr_nl);
1560            return 1;
1561        }
1562 #endif
1563 
1564     case AF_INET:
1565     {
1566         *len_ret = sizeof (struct sockaddr_in);
1567         return 1;
1568     }
1569 
1570 #ifdef ENABLE_IPV6
1571     case AF_INET6:
1572     {
1573         *len_ret = sizeof (struct sockaddr_in6);
1574         return 1;
1575     }
1576 #endif
1577 
1578 #ifdef USE_BLUETOOTH
1579     case AF_BLUETOOTH:
1580     {
1581         switch(s->sock_proto)
1582         {
1583 
1584         case BTPROTO_L2CAP:
1585             *len_ret = sizeof (struct sockaddr_l2);
1586             return 1;
1587         case BTPROTO_RFCOMM:
1588             *len_ret = sizeof (struct sockaddr_rc);
1589             return 1;
1590         case BTPROTO_HCI:
1591             *len_ret = sizeof (struct sockaddr_hci);
1592             return 1;
1593 #if !defined(__FreeBSD__)
1594         case BTPROTO_SCO:
1595             *len_ret = sizeof (struct sockaddr_sco);
1596             return 1;
1597 #endif
1598         default:
1599             PyErr_SetString(socket_error, "getsockaddrlen: "
1600                             "unknown BT protocol");
1601             return 0;
1602 
1603         }
1604     }
1605 #endif
1606 
1607 #ifdef HAVE_NETPACKET_PACKET_H
1608     case AF_PACKET:
1609     {
1610         *len_ret = sizeof (struct sockaddr_ll);
1611         return 1;
1612     }
1613 #endif
1614 
1615 #ifdef HAVE_LINUX_TIPC_H
1616     case AF_TIPC:
1617     {
1618         *len_ret = sizeof (struct sockaddr_tipc);
1619         return 1;
1620     }
1621 #endif
1622 
1623     /* More cases here... */
1624 
1625     default:
1626         PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1627         return 0;
1628 
1629     }
1630 }
1631 
1632 
1633 /* s.accept() method */
1634 
1635 static PyObject *
1636 sock_accept(PySocketSockObject *s)
1637 {
1638     sock_addr_t addrbuf;
1639     SOCKET_T newfd;
1640     socklen_t addrlen;
1641     PyObject *sock = NULL;
1642     PyObject *addr = NULL;
1643     PyObject *res = NULL;
1644     int timeout;
1645 
1646     if (!getsockaddrlen(s, &addrlen))
1647         return NULL;
1648     memset(&addrbuf, 0, addrlen);
1649 
1650 #ifdef MS_WINDOWS
1651     newfd = INVALID_SOCKET;
1652 #else
1653     newfd = -1;
1654 #endif
1655 
1656     if (!IS_SELECTABLE(s))
1657         return select_error();
1658 
1659     Py_BEGIN_ALLOW_THREADS
1660     timeout = internal_select(s, 0);
1661     if (!timeout)
1662         newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
1663     Py_END_ALLOW_THREADS
1664 
1665     if (timeout == 1) {
1666         PyErr_SetString(socket_timeout, "timed out");
1667         return NULL;
1668     }
1669 
1670 #ifdef MS_WINDOWS
1671     if (newfd == INVALID_SOCKET)
1672 #else
1673     if (newfd < 0)
1674 #endif
1675         return s->errorhandler();
1676 
1677     /* Create the new object with unspecified family,
1678        to avoid calls to bind() etc. on it. */
1679     sock = (PyObject *) new_sockobject(newfd,
1680                                        s->sock_family,
1681                                        s->sock_type,
1682                                        s->sock_proto);
1683 
1684     if (sock == NULL) {
1685         SOCKETCLOSE(newfd);
1686         goto finally;
1687     }
1688     addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
1689                         addrlen, s->sock_proto);
1690     if (addr == NULL)
1691         goto finally;
1692 
1693     res = PyTuple_Pack(2, sock, addr);
1694 
1695 finally:
1696     Py_XDECREF(sock);
1697     Py_XDECREF(addr);
1698     return res;
1699 }
1700 
1701 PyDoc_STRVAR(accept_doc,
1702 "accept() -> (socket object, address info)\n\
1703 \n\
1704 Wait for an incoming connection.  Return a new socket representing the\n\
1705 connection, and the address of the client.  For IP sockets, the address\n\
1706 info is a pair (hostaddr, port).");
1707 
1708 /* s.setblocking(flag) method.  Argument:
1709    False -- non-blocking mode; same as settimeout(0)
1710    True -- blocking mode; same as settimeout(None)
1711 */
1712 
1713 static PyObject *
1714 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1715 {
1716     int block;
1717 
1718     block = PyInt_AsLong(arg);
1719     if (block == -1 && PyErr_Occurred())
1720         return NULL;
1721 
1722     s->sock_timeout = block ? -1.0 : 0.0;
1723     internal_setblocking(s, block);
1724 
1725     Py_INCREF(Py_None);
1726     return Py_None;
1727 }
1728 
1729 PyDoc_STRVAR(setblocking_doc,
1730 "setblocking(flag)\n\
1731 \n\
1732 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1733 setblocking(True) is equivalent to settimeout(None);\n\
1734 setblocking(False) is equivalent to settimeout(0.0).");
1735 
1736 /* s.settimeout(timeout) method.  Argument:
1737    None -- no timeout, blocking mode; same as setblocking(True)
1738    0.0  -- non-blocking mode; same as setblocking(False)
1739    > 0  -- timeout mode; operations time out after timeout seconds
1740    < 0  -- illegal; raises an exception
1741 */
1742 static PyObject *
1743 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1744 {
1745     double timeout;
1746 
1747     if (arg == Py_None)
1748         timeout = -1.0;
1749     else {
1750         timeout = PyFloat_AsDouble(arg);
1751         if (timeout < 0.0) {
1752             if (!PyErr_Occurred())
1753                 PyErr_SetString(PyExc_ValueError,
1754                                 "Timeout value out of range");
1755             return NULL;
1756         }
1757     }
1758 
1759     s->sock_timeout = timeout;
1760     internal_setblocking(s, timeout < 0.0);
1761 
1762     Py_INCREF(Py_None);
1763     return Py_None;
1764 }
1765 
1766 PyDoc_STRVAR(settimeout_doc,
1767 "settimeout(timeout)\n\
1768 \n\
1769 Set a timeout on socket operations.  'timeout' can be a float,\n\
1770 giving in seconds, or None.  Setting a timeout of None disables\n\
1771 the timeout feature and is equivalent to setblocking(1).\n\
1772 Setting a timeout of zero is the same as setblocking(0).");
1773 
1774 /* s.gettimeout() method.
1775    Returns the timeout associated with a socket. */
1776 static PyObject *
1777 sock_gettimeout(PySocketSockObject *s)
1778 {
1779     if (s->sock_timeout < 0.0) {
1780         Py_INCREF(Py_None);
1781         return Py_None;
1782     }
1783     else
1784         return PyFloat_FromDouble(s->sock_timeout);
1785 }
1786 
1787 PyDoc_STRVAR(gettimeout_doc,
1788 "gettimeout() -> timeout\n\
1789 \n\
1790 Returns the timeout in seconds (float) associated with socket \n\
1791 operations. A timeout of None indicates that timeouts on socket \n\
1792 operations are disabled.");
1793 
1794 #ifdef RISCOS
1795 /* s.sleeptaskw(1 | 0) method */
1796 
1797 static PyObject *
1798 sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1799 {
1800     int block;
1801     block = PyInt_AsLong(arg);
1802     if (block == -1 && PyErr_Occurred())
1803         return NULL;
1804     Py_BEGIN_ALLOW_THREADS
1805     socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1806     Py_END_ALLOW_THREADS
1807 
1808     Py_INCREF(Py_None);
1809     return Py_None;
1810 }
1811 PyDoc_STRVAR(sleeptaskw_doc,
1812 "sleeptaskw(flag)\n\
1813 \n\
1814 Allow sleeps in taskwindows.");
1815 #endif
1816 
1817 
1818 /* s.setsockopt() method.
1819    With an integer third argument, sets an integer option.
1820    With a string third argument, sets an option from a buffer;
1821    use optional built-in module 'struct' to encode the string. */
1822 
1823 static PyObject *
1824 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1825 {
1826     int level;
1827     int optname;
1828     int res;
1829     char *buf;
1830     int buflen;
1831     int flag;
1832 
1833     if (PyArg_ParseTuple(args, "iii:setsockopt",
1834                          &level, &optname, &flag)) {
1835         buf = (char *) &flag;
1836         buflen = sizeof flag;
1837     }
1838     else {
1839         PyErr_Clear();
1840         if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1841                               &level, &optname, &buf, &buflen))
1842             return NULL;
1843     }
1844     res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1845     if (res < 0)
1846         return s->errorhandler();
1847     Py_INCREF(Py_None);
1848     return Py_None;
1849 }
1850 
1851 PyDoc_STRVAR(setsockopt_doc,
1852 "setsockopt(level, option, value)\n\
1853 \n\
1854 Set a socket option.  See the Unix manual for level and option.\n\
1855 The value argument can either be an integer or a string.");
1856 
1857 
1858 /* s.getsockopt() method.
1859    With two arguments, retrieves an integer option.
1860    With a third integer argument, retrieves a string buffer of that size;
1861    use optional built-in module 'struct' to decode the string. */
1862 
1863 static PyObject *
1864 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1865 {
1866     int level;
1867     int optname;
1868     int res;
1869     PyObject *buf;
1870     socklen_t buflen = 0;
1871 
1872 #ifdef __BEOS__
1873     /* We have incomplete socket support. */
1874     PyErr_SetString(socket_error, "getsockopt not supported");
1875     return NULL;
1876 #else
1877 
1878     if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1879                           &level, &optname, &buflen))
1880         return NULL;
1881 
1882     if (buflen == 0) {
1883         int flag = 0;
1884         socklen_t flagsize = sizeof flag;
1885         res = getsockopt(s->sock_fd, level, optname,
1886                          (void *)&flag, &flagsize);
1887         if (res < 0)
1888             return s->errorhandler();
1889         return PyInt_FromLong(flag);
1890     }
1891 #ifdef __VMS
1892     /* socklen_t is unsigned so no negative test is needed,
1893        test buflen == 0 is previously done */
1894     if (buflen > 1024) {
1895 #else
1896     if (buflen <= 0 || buflen > 1024) {
1897 #endif
1898         PyErr_SetString(socket_error,
1899                         "getsockopt buflen out of range");
1900         return NULL;
1901     }
1902     buf = PyString_FromStringAndSize((char *)NULL, buflen);
1903     if (buf == NULL)
1904         return NULL;
1905     res = getsockopt(s->sock_fd, level, optname,
1906                      (void *)PyString_AS_STRING(buf), &buflen);
1907     if (res < 0) {
1908         Py_DECREF(buf);
1909         return s->errorhandler();
1910     }
1911     _PyString_Resize(&buf, buflen);
1912     return buf;
1913 #endif /* __BEOS__ */
1914 }
1915 
1916 PyDoc_STRVAR(getsockopt_doc,
1917 "getsockopt(level, option[, buffersize]) -> value\n\
1918 \n\
1919 Get a socket option.  See the Unix manual for level and option.\n\
1920 If a nonzero buffersize argument is given, the return value is a\n\
1921 string of that length; otherwise it is an integer.");
1922 
1923 
1924 /* s.bind(sockaddr) method */
1925 
1926 static PyObject *
1927 sock_bind(PySocketSockObject *s, PyObject *addro)
1928 {
1929     sock_addr_t addrbuf;
1930     int addrlen;
1931     int res;
1932 
1933     if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1934         return NULL;
1935     Py_BEGIN_ALLOW_THREADS
1936     res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
1937     Py_END_ALLOW_THREADS
1938     if (res < 0)
1939         return s->errorhandler();
1940     Py_INCREF(Py_None);
1941     return Py_None;
1942 }
1943 
1944 PyDoc_STRVAR(bind_doc,
1945 "bind(address)\n\
1946 \n\
1947 Bind the socket to a local address.  For IP sockets, the address is a\n\
1948 pair (host, port); the host must refer to the local host. For raw packet\n\
1949 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1950 
1951 
1952 /* s.close() method.
1953    Set the file descriptor to -1 so operations tried subsequently
1954    will surely fail. */
1955 
1956 static PyObject *
1957 sock_close(PySocketSockObject *s)
1958 {
1959     SOCKET_T fd;
1960 
1961     if ((fd = s->sock_fd) != -1) {
1962         s->sock_fd = -1;
1963         Py_BEGIN_ALLOW_THREADS
1964         (void) SOCKETCLOSE(fd);
1965         Py_END_ALLOW_THREADS
1966     }
1967     Py_INCREF(Py_None);
1968     return Py_None;
1969 }
1970 
1971 PyDoc_STRVAR(close_doc,
1972 "close()\n\
1973 \n\
1974 Close the socket.  It cannot be used after this call.");
1975 
1976 static int
1977 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
1978                  int *timeoutp)
1979 {
1980     int res, timeout;
1981 
1982     timeout = 0;
1983     res = connect(s->sock_fd, addr, addrlen);
1984 
1985 #ifdef MS_WINDOWS
1986 
1987     if (s->sock_timeout > 0.0) {
1988         if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
1989             IS_SELECTABLE(s)) {
1990             /* This is a mess.  Best solution: trust select */
1991             fd_set fds;
1992             fd_set fds_exc;
1993             struct timeval tv;
1994             tv.tv_sec = (int)s->sock_timeout;
1995             tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1996             FD_ZERO(&fds);
1997             FD_SET(s->sock_fd, &fds);
1998             FD_ZERO(&fds_exc);
1999             FD_SET(s->sock_fd, &fds_exc);
2000             res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
2001             if (res == 0) {
2002                 res = WSAEWOULDBLOCK;
2003                 timeout = 1;
2004             } else if (res > 0) {
2005                 if (FD_ISSET(s->sock_fd, &fds))
2006                     /* The socket is in the writeable set - this
2007                        means connected */
2008                     res = 0;
2009                 else {
2010                     /* As per MS docs, we need to call getsockopt()
2011                        to get the underlying error */
2012                     int res_size = sizeof res;
2013                     /* It must be in the exception set */
2014                     assert(FD_ISSET(s->sock_fd, &fds_exc));
2015                     if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
2016                                         (char *)&res, &res_size))
2017                         /* getsockopt also clears WSAGetLastError,
2018                            so reset it back. */
2019                         WSASetLastError(res);
2020                     else
2021                         res = WSAGetLastError();
2022                 }
2023             }
2024             /* else if (res < 0) an error occurred */
2025         }
2026     }
2027 
2028     if (res < 0)
2029         res = WSAGetLastError();
2030 
2031 #else
2032 
2033     if (s->sock_timeout > 0.0) {
2034         if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
2035             timeout = internal_select(s, 1);
2036             if (timeout == 0) {
2037                 /* Bug #1019808: in case of an EINPROGRESS,
2038                    use getsockopt(SO_ERROR) to get the real
2039                    error. */
2040                 socklen_t res_size = sizeof res;
2041                 (void)getsockopt(s->sock_fd, SOL_SOCKET,
2042                                  SO_ERROR, &res, &res_size);
2043                 if (res == EISCONN)
2044                     res = 0;
2045                 errno = res;
2046             }
2047             else if (timeout == -1) {
2048                 res = errno;            /* had error */
2049             }
2050             else
2051                 res = EWOULDBLOCK;                      /* timed out */
2052         }
2053     }
2054 
2055     if (res < 0)
2056         res = errno;
2057 
2058 #endif
2059     *timeoutp = timeout;
2060 
2061     return res;
2062 }
2063 
2064 /* s.connect(sockaddr) method */
2065 
2066 static PyObject *
2067 sock_connect(PySocketSockObject *s, PyObject *addro)
2068 {
2069     sock_addr_t addrbuf;
2070     int addrlen;
2071     int res;
2072     int timeout;
2073 
2074     if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2075         return NULL;
2076 
2077     Py_BEGIN_ALLOW_THREADS
2078     res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2079     Py_END_ALLOW_THREADS
2080 
2081     if (timeout == 1) {
2082         PyErr_SetString(socket_timeout, "timed out");
2083         return NULL;
2084     }
2085     if (res != 0)
2086         return s->errorhandler();
2087     Py_INCREF(Py_None);
2088     return Py_None;
2089 }
2090 
2091 PyDoc_STRVAR(connect_doc,
2092 "connect(address)\n\
2093 \n\
2094 Connect the socket to a remote address.  For IP sockets, the address\n\
2095 is a pair (host, port).");
2096 
2097 
2098 /* s.connect_ex(sockaddr) method */
2099 
2100 static PyObject *
2101 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
2102 {
2103     sock_addr_t addrbuf;
2104     int addrlen;
2105     int res;
2106     int timeout;
2107 
2108     if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2109         return NULL;
2110 
2111     Py_BEGIN_ALLOW_THREADS
2112     res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2113     Py_END_ALLOW_THREADS
2114 
2115     /* Signals are not errors (though they may raise exceptions).  Adapted
2116        from PyErr_SetFromErrnoWithFilenameObject(). */
2117 #ifdef EINTR
2118     if (res == EINTR && PyErr_CheckSignals())
2119         return NULL;
2120 #endif
2121 
2122     return PyInt_FromLong((long) res);
2123 }
2124 
2125 PyDoc_STRVAR(connect_ex_doc,
2126 "connect_ex(address) -> errno\n\
2127 \n\
2128 This is like connect(address), but returns an error code (the errno value)\n\
2129 instead of raising an exception when an error occurs.");
2130 
2131 
2132 /* s.fileno() method */
2133 
2134 static PyObject *
2135 sock_fileno(PySocketSockObject *s)
2136 {
2137 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2138     return PyInt_FromLong((long) s->sock_fd);
2139 #else
2140     return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
2141 #endif
2142 }
2143 
2144 PyDoc_STRVAR(fileno_doc,
2145 "fileno() -> integer\n\
2146 \n\
2147 Return the integer file descriptor of the socket.");
2148 
2149 
2150 #ifndef NO_DUP
2151 /* s.dup() method */
2152 
2153 static PyObject *
2154 sock_dup(PySocketSockObject *s)
2155 {
2156     SOCKET_T newfd;
2157     PyObject *sock;
2158 
2159     newfd = dup(s->sock_fd);
2160     if (newfd < 0)
2161         return s->errorhandler();
2162     sock = (PyObject *) new_sockobject(newfd,
2163                                        s->sock_family,
2164                                        s->sock_type,
2165                                        s->sock_proto);
2166     if (sock == NULL)
2167         SOCKETCLOSE(newfd);
2168     return sock;
2169 }
2170 
2171 PyDoc_STRVAR(dup_doc,
2172 "dup() -> socket object\n\
2173 \n\
2174 Return a new socket object connected to the same system resource.");
2175 
2176 #endif
2177 
2178 
2179 /* s.getsockname() method */
2180 
2181 static PyObject *
2182 sock_getsockname(PySocketSockObject *s)
2183 {
2184     sock_addr_t addrbuf;
2185     int res;
2186     socklen_t addrlen;
2187 
2188     if (!getsockaddrlen(s, &addrlen))
2189         return NULL;
2190     memset(&addrbuf, 0, addrlen);
2191     Py_BEGIN_ALLOW_THREADS
2192     res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2193     Py_END_ALLOW_THREADS
2194     if (res < 0)
2195         return s->errorhandler();
2196     return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2197                         s->sock_proto);
2198 }
2199 
2200 PyDoc_STRVAR(getsockname_doc,
2201 "getsockname() -> address info\n\
2202 \n\
2203 Return the address of the local endpoint.  For IP sockets, the address\n\
2204 info is a pair (hostaddr, port).");
2205 
2206 
2207 #ifdef HAVE_GETPEERNAME         /* Cray APP doesn't have this :-( */
2208 /* s.getpeername() method */
2209 
2210 static PyObject *
2211 sock_getpeername(PySocketSockObject *s)
2212 {
2213     sock_addr_t addrbuf;
2214     int res;
2215     socklen_t addrlen;
2216 
2217     if (!getsockaddrlen(s, &addrlen))
2218         return NULL;
2219     memset(&addrbuf, 0, addrlen);
2220     Py_BEGIN_ALLOW_THREADS
2221     res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2222     Py_END_ALLOW_THREADS
2223     if (res < 0)
2224         return s->errorhandler();
2225     return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2226                         s->sock_proto);
2227 }
2228 
2229 PyDoc_STRVAR(getpeername_doc,
2230 "getpeername() -> address info\n\
2231 \n\
2232 Return the address of the remote endpoint.  For IP sockets, the address\n\
2233 info is a pair (hostaddr, port).");
2234 
2235 #endif /* HAVE_GETPEERNAME */
2236 
2237 
2238 /* s.listen(n) method */
2239 
2240 static PyObject *
2241 sock_listen(PySocketSockObject *s, PyObject *arg)
2242 {
2243     int backlog;
2244     int res;
2245 
2246     backlog = PyInt_AsLong(arg);
2247     if (backlog == -1 && PyErr_Occurred())
2248         return NULL;
2249     Py_BEGIN_ALLOW_THREADS
2250     /* To avoid problems on systems that don't allow a negative backlog
2251      * (which doesn't make sense anyway) we force a minimum value of 0. */
2252     if (backlog < 0)
2253         backlog = 0;
2254     res = listen(s->sock_fd, backlog);
2255     Py_END_ALLOW_THREADS
2256     if (res < 0)
2257         return s->errorhandler();
2258     Py_INCREF(Py_None);
2259     return Py_None;
2260 }
2261 
2262 PyDoc_STRVAR(listen_doc,
2263 "listen(backlog)\n\
2264 \n\
2265 Enable a server to accept connections.  The backlog argument must be at\n\
2266 least 0 (if it is lower, it is set to 0); it specifies the number of\n\
2267 unaccepted connections that the system will allow before refusing new\n\
2268 connections.");
2269 
2270 
2271 #ifndef NO_DUP
2272 /* s.makefile(mode) method.
2273    Create a new open file object referring to a dupped version of
2274    the socket's file descriptor.  (The dup() call is necessary so
2275    that the open file and socket objects may be closed independent
2276    of each other.)
2277    The mode argument specifies 'r' or 'w' passed to fdopen(). */
2278 
2279 static PyObject *
2280 sock_makefile(PySocketSockObject *s, PyObject *args)
2281 {
2282     extern int fclose(FILE *);
2283     char *mode = "r";
2284     int bufsize = -1;
2285 #ifdef MS_WIN32
2286     Py_intptr_t fd;
2287 #else
2288     int fd;
2289 #endif
2290     FILE *fp;
2291     PyObject *f;
2292 #ifdef __VMS
2293     char *mode_r = "r";
2294     char *mode_w = "w";
2295 #endif
2296 
2297     if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
2298         return NULL;
2299 #ifdef __VMS
2300     if (strcmp(mode,"rb") == 0) {
2301         mode = mode_r;
2302     }
2303     else {
2304         if (strcmp(mode,"wb") == 0) {
2305             mode = mode_w;
2306         }
2307     }
2308 #endif
2309 #ifdef MS_WIN32
2310     if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
2311         ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
2312 #else
2313     if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
2314 #endif
2315     {
2316         if (fd >= 0)
2317             SOCKETCLOSE(fd);
2318         return s->errorhandler();
2319     }
2320     f = PyFile_FromFile(fp, "<socket>", mode, fclose);
2321     if (f != NULL)
2322         PyFile_SetBufSize(f, bufsize);
2323     return f;
2324 }
2325 
2326 PyDoc_STRVAR(makefile_doc,
2327 "makefile([mode[, buffersize]]) -> file object\n\
2328 \n\
2329 Return a regular file object corresponding to the socket.\n\
2330 The mode and buffersize arguments are as for the built-in open() function.");
2331 
2332 #endif /* NO_DUP */
2333 
2334 /*
2335  * This is the guts of the recv() and recv_into() methods, which reads into a
2336  * char buffer.  If you have any inc/dec ref to do to the objects that contain
2337  * the buffer, do it in the caller.  This function returns the number of bytes
2338  * successfully read.  If there was an error, it returns -1.  Note that it is
2339  * also possible that we return a number of bytes smaller than the request
2340  * bytes.
2341  */
2342 static ssize_t
2343 sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
2344 {
2345     ssize_t outlen = -1;
2346     int timeout;
2347 #ifdef __VMS
2348     int remaining;
2349     char *read_buf;
2350 #endif
2351 
2352     if (!IS_SELECTABLE(s)) {
2353         select_error();
2354         return -1;
2355     }
2356 
2357 #ifndef __VMS
2358     Py_BEGIN_ALLOW_THREADS
2359     timeout = internal_select(s, 0);
2360     if (!timeout)
2361         outlen = recv(s->sock_fd, cbuf, len, flags);
2362     Py_END_ALLOW_THREADS
2363 
2364     if (timeout == 1) {
2365         PyErr_SetString(socket_timeout, "timed out");
2366         return -1;
2367     }
2368     if (outlen < 0) {
2369         /* Note: the call to errorhandler() ALWAYS indirectly returned
2370            NULL, so ignore its return value */
2371         s->errorhandler();
2372         return -1;
2373     }
2374 #else
2375     read_buf = cbuf;
2376     remaining = len;
2377     while (remaining != 0) {
2378         unsigned int segment;
2379         int nread = -1;
2380 
2381         segment = remaining /SEGMENT_SIZE;
2382         if (segment != 0) {
2383             segment = SEGMENT_SIZE;
2384         }
2385         else {
2386             segment = remaining;
2387         }
2388 
2389         Py_BEGIN_ALLOW_THREADS
2390         timeout = internal_select(s, 0);
2391         if (!timeout)
2392             nread = recv(s->sock_fd, read_buf, segment, flags);
2393         Py_END_ALLOW_THREADS
2394 
2395         if (timeout == 1) {
2396             PyErr_SetString(socket_timeout, "timed out");
2397             return -1;
2398         }
2399         if (nread < 0) {
2400             s->errorhandler();
2401             return -1;
2402         }
2403         if (nread != remaining) {
2404             read_buf += nread;
2405             break;
2406         }
2407 
2408         remaining -= segment;
2409         read_buf += segment;
2410     }
2411     outlen = read_buf - cbuf;
2412 #endif /* !__VMS */
2413 
2414     return outlen;
2415 }
2416 
2417 
2418 /* s.recv(nbytes [,flags]) method */
2419 
2420 static PyObject *
2421 sock_recv(PySocketSockObject *s, PyObject *args)
2422 {
2423     int recvlen, flags = 0;
2424     ssize_t outlen;
2425     PyObject *buf;
2426 
2427     if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
2428         return NULL;
2429 
2430     if (recvlen < 0) {
2431         PyErr_SetString(PyExc_ValueError,
2432                         "negative buffersize in recv");
2433         return NULL;
2434     }
2435 
2436     /* Allocate a new string. */
2437     buf = PyString_FromStringAndSize((char *) 0, recvlen);
2438     if (buf == NULL)
2439         return NULL;
2440 
2441     /* Call the guts */
2442     outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
2443     if (outlen < 0) {
2444         /* An error occurred, release the string and return an
2445            error. */
2446         Py_DECREF(buf);
2447         return NULL;
2448     }
2449     if (outlen != recvlen) {
2450         /* We did not read as many bytes as we anticipated, resize the
2451            string if possible and be successful. */
2452         if (_PyString_Resize(&buf, outlen) < 0)
2453             /* Oopsy, not so successful after all. */
2454             return NULL;
2455     }
2456 
2457     return buf;
2458 }
2459 
2460 PyDoc_STRVAR(recv_doc,
2461 "recv(buffersize[, flags]) -> data\n\
2462 \n\
2463 Receive up to buffersize bytes from the socket.  For the optional flags\n\
2464 argument, see the Unix manual.  When no data is available, block until\n\
2465 at least one byte is available or until the remote end is closed.  When\n\
2466 the remote end is closed and all data is read, return the empty string.");
2467 
2468 
2469 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2470 
2471 static PyObject*
2472 sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
2473 {
2474     static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2475 
2476     int recvlen = 0, flags = 0;
2477     ssize_t readlen;
2478     Py_buffer buf;
2479     Py_ssize_t buflen;
2480 
2481     /* Get the buffer's memory */
2482     if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist,
2483                                      &buf, &recvlen, &flags))
2484         return NULL;
2485     buflen = buf.len;
2486     assert(buf.buf != 0 && buflen > 0);
2487 
2488     if (recvlen < 0) {
2489         PyErr_SetString(PyExc_ValueError,
2490                         "negative buffersize in recv_into");
2491         goto error;
2492     }
2493     if (recvlen == 0) {
2494         /* If nbytes was not specified, use the buffer's length */
2495         recvlen = buflen;
2496     }
2497 
2498     /* Check if the buffer is large enough */
2499     if (buflen < recvlen) {
2500         PyErr_SetString(PyExc_ValueError,
2501                         "buffer too small for requested bytes");
2502         goto error;
2503     }
2504 
2505     /* Call the guts */
2506     readlen = sock_recv_guts(s, buf.buf, recvlen, flags);
2507     if (readlen < 0) {
2508         /* Return an error. */
2509         goto error;
2510     }
2511 
2512     PyBuffer_Release(&buf);
2513     /* Return the number of bytes read.  Note that we do not do anything
2514        special here in the case that readlen < recvlen. */
2515     return PyInt_FromSsize_t(readlen);
2516 
2517 error:
2518     PyBuffer_Release(&buf);
2519     return NULL;
2520 }
2521 
2522 PyDoc_STRVAR(recv_into_doc,
2523 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2524 \n\
2525 A version of recv() that stores its data into a buffer rather than creating \n\
2526 a new string.  Receive up to buffersize bytes from the socket.  If buffersize \n\
2527 is not specified (or 0), receive up to the size available in the given buffer.\n\
2528 \n\
2529 See recv() for documentation about the flags.");
2530 
2531 
2532 /*
2533  * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
2534  * into a char buffer.  If you have any inc/def ref to do to the objects that
2535  * contain the buffer, do it in the caller.  This function returns the number
2536  * of bytes successfully read.  If there was an error, it returns -1.  Note
2537  * that it is also possible that we return a number of bytes smaller than the
2538  * request bytes.
2539  *
2540  * 'addr' is a return value for the address object.  Note that you must decref
2541  * it yourself.
2542  */
2543 static ssize_t
2544 sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
2545                    PyObject** addr)
2546 {
2547     sock_addr_t addrbuf;
2548     int timeout;
2549     ssize_t n = -1;
2550     socklen_t addrlen;
2551 
2552     *addr = NULL;
2553 
2554     if (!getsockaddrlen(s, &addrlen))
2555         return -1;
2556 
2557     if (!IS_SELECTABLE(s)) {
2558         select_error();
2559         return -1;
2560     }
2561 
2562     Py_BEGIN_ALLOW_THREADS
2563     memset(&addrbuf, 0, addrlen);
2564     timeout = internal_select(s, 0);
2565     if (!timeout) {
2566 #ifndef MS_WINDOWS
2567 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2568         n = recvfrom(s->sock_fd, cbuf, len, flags,
2569                      SAS2SA(&addrbuf), &addrlen);
2570 #else
2571         n = recvfrom(s->sock_fd, cbuf, len, flags,
2572                      (void *) &addrbuf, &addrlen);
2573 #endif
2574 #else
2575         n = recvfrom(s->sock_fd, cbuf, len, flags,
2576                      SAS2SA(&addrbuf), &addrlen);
2577 #endif
2578     }
2579     Py_END_ALLOW_THREADS
2580 
2581     if (timeout == 1) {
2582         PyErr_SetString(socket_timeout, "timed out");
2583         return -1;
2584     }
2585     if (n < 0) {
2586         s->errorhandler();
2587         return -1;
2588     }
2589 
2590     if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
2591                                addrlen, s->sock_proto)))
2592         return -1;
2593 
2594     return n;
2595 }
2596 
2597 /* s.recvfrom(nbytes [,flags]) method */
2598 
2599 static PyObject *
2600 sock_recvfrom(PySocketSockObject *s, PyObject *args)
2601 {
2602     PyObject *buf = NULL;
2603     PyObject *addr = NULL;
2604     PyObject *ret = NULL;
2605     int recvlen, flags = 0;
2606     ssize_t outlen;
2607 
2608     if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
2609         return NULL;
2610 
2611     if (recvlen < 0) {
2612         PyErr_SetString(PyExc_ValueError,
2613                         "negative buffersize in recvfrom");
2614         return NULL;
2615     }
2616 
2617     buf = PyString_FromStringAndSize((char *) 0, recvlen);
2618     if (buf == NULL)
2619         return NULL;
2620 
2621     outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
2622                                 recvlen, flags, &addr);
2623     if (outlen < 0) {
2624         goto finally;
2625     }
2626 
2627     if (outlen != recvlen) {
2628         /* We did not read as many bytes as we anticipated, resize the
2629            string if possible and be successful. */
2630         if (_PyString_Resize(&buf, outlen) < 0)
2631             /* Oopsy, not so successful after all. */
2632             goto finally;
2633     }
2634 
2635     ret = PyTuple_Pack(2, buf, addr);
2636 
2637 finally:
2638     Py_XDECREF(buf);
2639     Py_XDECREF(addr);
2640     return ret;
2641 }
2642 
2643 PyDoc_STRVAR(recvfrom_doc,
2644 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2645 \n\
2646 Like recv(buffersize, flags) but also return the sender's address info.");
2647 
2648 
2649 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2650 
2651 static PyObject *
2652 sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
2653 {
2654     static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2655 
2656     int recvlen = 0, flags = 0;
2657     ssize_t readlen;
2658     Py_buffer buf;
2659     int buflen;
2660 
2661     PyObject *addr = NULL;
2662 
2663     if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into",
2664                                      kwlist, &buf,
2665                                      &recvlen, &flags))
2666         return NULL;
2667     buflen = buf.len;
2668     assert(buf.buf != 0 && buflen > 0);
2669 
2670     if (recvlen < 0) {
2671         PyErr_SetString(PyExc_ValueError,
2672                         "negative buffersize in recvfrom_into");
2673         goto error;
2674     }
2675     if (recvlen == 0) {
2676         /* If nbytes was not specified, use the buffer's length */
2677         recvlen = buflen;
2678     }
2679 
2680     readlen = sock_recvfrom_guts(s, buf.buf, recvlen, flags, &addr);
2681     if (readlen < 0) {
2682         /* Return an error */
2683         goto error;
2684     }
2685 
2686     PyBuffer_Release(&buf);
2687     /* Return the number of bytes read and the address.  Note that we do
2688        not do anything special here in the case that readlen < recvlen. */
2689     return Py_BuildValue("lN", readlen, addr);
2690 
2691 error:
2692     Py_XDECREF(addr);
2693     PyBuffer_Release(&buf);
2694     return NULL;
2695 }
2696 
2697 PyDoc_STRVAR(recvfrom_into_doc,
2698 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2699 \n\
2700 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2701 
2702 
2703 /* s.send(data [,flags]) method */
2704 
2705 static PyObject *
2706 sock_send(PySocketSockObject *s, PyObject *args)
2707 {
2708     char *buf;
2709     int len, n = -1, flags = 0, timeout;
2710     Py_buffer pbuf;
2711 
2712     if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
2713         return NULL;
2714 
2715     if (!IS_SELECTABLE(s)) {
2716         PyBuffer_Release(&pbuf);
2717         return select_error();
2718     }
2719     buf = pbuf.buf;
2720     len = pbuf.len;
2721 
2722     Py_BEGIN_ALLOW_THREADS
2723     timeout = internal_select(s, 1);
2724     if (!timeout)
2725 #ifdef __VMS
2726         n = sendsegmented(s->sock_fd, buf, len, flags);
2727 #else
2728         n = send(s->sock_fd, buf, len, flags);
2729 #endif
2730     Py_END_ALLOW_THREADS
2731 
2732     PyBuffer_Release(&pbuf);
2733 
2734     if (timeout == 1) {
2735         PyErr_SetString(socket_timeout, "timed out");
2736         return NULL;
2737     }
2738     if (n < 0)
2739         return s->errorhandler();
2740     return PyInt_FromLong((long)n);
2741 }
2742 
2743 PyDoc_STRVAR(send_doc,
2744 "send(data[, flags]) -> count\n\
2745 \n\
2746 Send a data string to the socket.  For the optional flags\n\
2747 argument, see the Unix manual.  Return the number of bytes\n\
2748 sent; this may be less than len(data) if the network is busy.");
2749 
2750 
2751 /* s.sendall(data [,flags]) method */
2752 
2753 static PyObject *
2754 sock_sendall(PySocketSockObject *s, PyObject *args)
2755 {
2756     char *buf;
2757     int len, n = -1, flags = 0, timeout, saved_errno;
2758     Py_buffer pbuf;
2759 
2760     if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
2761         return NULL;
2762     buf = pbuf.buf;
2763     len = pbuf.len;
2764 
2765     if (!IS_SELECTABLE(s)) {
2766         PyBuffer_Release(&pbuf);
2767         return select_error();
2768     }
2769 
2770     do {
2771         Py_BEGIN_ALLOW_THREADS
2772         timeout = internal_select(s, 1);
2773         n = -1;
2774         if (!timeout) {
2775 #ifdef __VMS
2776             n = sendsegmented(s->sock_fd, buf, len, flags);
2777 #else
2778             n = send(s->sock_fd, buf, len, flags);
2779 #endif
2780         }
2781         Py_END_ALLOW_THREADS
2782         if (timeout == 1) {
2783             PyBuffer_Release(&pbuf);
2784             PyErr_SetString(socket_timeout, "timed out");
2785             return NULL;
2786         }
2787         /* PyErr_CheckSignals() might change errno */
2788         saved_errno = errno;
2789         /* We must run our signal handlers before looping again.
2790            send() can return a successful partial write when it is
2791            interrupted, so we can't restrict ourselves to EINTR. */
2792         if (PyErr_CheckSignals()) {
2793             PyBuffer_Release(&pbuf);
2794             return NULL;
2795         }
2796         if (n < 0) {
2797             /* If interrupted, try again */
2798             if (saved_errno == EINTR)
2799                 continue;
2800             else
2801                 break;
2802         }
2803         buf += n;
2804         len -= n;
2805     } while (len > 0);
2806     PyBuffer_Release(&pbuf);
2807 
2808     if (n < 0)
2809         return s->errorhandler();
2810 
2811     Py_INCREF(Py_None);
2812     return Py_None;
2813 }
2814 
2815 PyDoc_STRVAR(sendall_doc,
2816 "sendall(data[, flags])\n\
2817 \n\
2818 Send a data string to the socket.  For the optional flags\n\
2819 argument, see the Unix manual.  This calls send() repeatedly\n\
2820 until all data is sent.  If an error occurs, it's impossible\n\
2821 to tell how much data has been sent.");
2822 
2823 
2824 /* s.sendto(data, [flags,] sockaddr) method */
2825 
2826 static PyObject *
2827 sock_sendto(PySocketSockObject *s, PyObject *args)
2828 {
2829     Py_buffer pbuf;
2830     PyObject *addro;
2831     char *buf;
2832     Py_ssize_t len;
2833     sock_addr_t addrbuf;
2834     int addrlen, n = -1, flags, timeout;
2835     int arglen;
2836 
2837     flags = 0;
2838     arglen = PyTuple_Size(args);
2839     switch(arglen) {
2840         case 2:
2841             PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro);
2842             break;
2843         case 3:
2844             PyArg_ParseTuple(args, "s*iO:sendto", &pbuf, &flags, &addro);
2845             break;
2846         default:
2847             PyErr_Format(PyExc_TypeError, "sendto() takes 2 or 3"
2848                          " arguments (%d given)", arglen);
2849     }
2850     if (PyErr_Occurred())
2851         return NULL;
2852 
2853     buf = pbuf.buf;
Assigned value is garbage or undefined
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Assigned value is garbage or undefined
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

2854 len = pbuf.len; 2855 2856 if (!IS_SELECTABLE(s)) { 2857 PyBuffer_Release(&pbuf); 2858 return select_error(); 2859 } 2860 2861 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) { 2862 PyBuffer_Release(&pbuf); 2863 return NULL; 2864 } 2865 2866 Py_BEGIN_ALLOW_THREADS 2867 timeout = internal_select(s, 1); 2868 if (!timeout) 2869 n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen); 2870 Py_END_ALLOW_THREADS 2871 2872 PyBuffer_Release(&pbuf); 2873 if (timeout == 1) { 2874 PyErr_SetString(socket_timeout, "timed out"); 2875 return NULL; 2876 } 2877 if (n < 0) 2878 return s->errorhandler(); 2879 return PyInt_FromLong((long)n); 2880 } 2881 2882 PyDoc_STRVAR(sendto_doc, 2883 "sendto(data[, flags], address) -> count\n\ 2884 \n\ 2885 Like send(data, flags) but allows specifying the destination address.\n\ 2886 For IP sockets, the address is a pair (hostaddr, port)."); 2887 2888 2889 /* s.shutdown(how) method */ 2890 2891 static PyObject * 2892 sock_shutdown(PySocketSockObject *s, PyObject *arg) 2893 { 2894 int how; 2895 int res; 2896 2897 how = PyInt_AsLong(arg); 2898 if (how == -1 && PyErr_Occurred()) 2899 return NULL; 2900 Py_BEGIN_ALLOW_THREADS 2901 res = shutdown(s->sock_fd, how); 2902 Py_END_ALLOW_THREADS 2903 if (res < 0) 2904 return s->errorhandler(); 2905 Py_INCREF(Py_None); 2906 return Py_None; 2907 } 2908 2909 PyDoc_STRVAR(shutdown_doc, 2910 "shutdown(flag)\n\ 2911 \n\ 2912 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\ 2913 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR)."); 2914 2915 #if defined(MS_WINDOWS) && defined(SIO_RCVALL) 2916 static PyObject* 2917 sock_ioctl(PySocketSockObject *s, PyObject *arg) 2918 { 2919 unsigned long cmd = SIO_RCVALL; 2920 PyObject *argO; 2921 DWORD recv; 2922 2923 if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO)) 2924 return NULL; 2925 2926 switch (cmd) { 2927 case SIO_RCVALL: { 2928 unsigned int option = RCVALL_ON; 2929 if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option)) 2930 return NULL; 2931 if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option), 2932 NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) { 2933 return set_error(); 2934 } 2935 return PyLong_FromUnsignedLong(recv); } 2936 case SIO_KEEPALIVE_VALS: { 2937 struct tcp_keepalive ka; 2938 if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd, 2939 &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval)) 2940 return NULL; 2941 if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka), 2942 NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) { 2943 return set_error(); 2944 } 2945 return PyLong_FromUnsignedLong(recv); } 2946 default: 2947 PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd); 2948 return NULL; 2949 } 2950 } 2951 PyDoc_STRVAR(sock_ioctl_doc, 2952 "ioctl(cmd, option) -> long\n\ 2953 \n\ 2954 Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\ 2955 SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.\n\ 2956 SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval)."); 2957 2958 #endif 2959 2960 /* List of methods for socket objects */ 2961 2962 static PyMethodDef sock_methods[] = { 2963 {"accept", (PyCFunction)sock_accept, METH_NOARGS, 2964 accept_doc}, 2965 {"bind", (PyCFunction)sock_bind, METH_O, 2966 bind_doc}, 2967 {"close", (PyCFunction)sock_close, METH_NOARGS, 2968 close_doc}, 2969 {"connect", (PyCFunction)sock_connect, METH_O, 2970 connect_doc}, 2971 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O, 2972 connect_ex_doc}, 2973 #ifndef NO_DUP 2974 {"dup", (PyCFunction)sock_dup, METH_NOARGS, 2975 dup_doc}, 2976 #endif 2977 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS, 2978 fileno_doc}, 2979 #ifdef HAVE_GETPEERNAME 2980 {"getpeername", (PyCFunction)sock_getpeername, 2981 METH_NOARGS, getpeername_doc}, 2982 #endif 2983 {"getsockname", (PyCFunction)sock_getsockname, 2984 METH_NOARGS, getsockname_doc}, 2985 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS, 2986 getsockopt_doc}, 2987 #if defined(MS_WINDOWS) && defined(SIO_RCVALL) 2988 {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS, 2989 sock_ioctl_doc}, 2990 #endif 2991 {"listen", (PyCFunction)sock_listen, METH_O, 2992 listen_doc}, 2993 #ifndef NO_DUP 2994 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS, 2995 makefile_doc}, 2996 #endif 2997 {"recv", (PyCFunction)sock_recv, METH_VARARGS, 2998 recv_doc}, 2999 {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS, 3000 recv_into_doc}, 3001 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS, 3002 recvfrom_doc}, 3003 {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS, 3004 recvfrom_into_doc}, 3005 {"send", (PyCFunction)sock_send, METH_VARARGS, 3006 send_doc}, 3007 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS, 3008 sendall_doc}, 3009 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS, 3010 sendto_doc}, 3011 {"setblocking", (PyCFunction)sock_setblocking, METH_O, 3012 setblocking_doc}, 3013 {"settimeout", (PyCFunction)sock_settimeout, METH_O, 3014 settimeout_doc}, 3015 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS, 3016 gettimeout_doc}, 3017 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS, 3018 setsockopt_doc}, 3019 {"shutdown", (PyCFunction)sock_shutdown, METH_O, 3020 shutdown_doc}, 3021 #ifdef RISCOS 3022 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O, 3023 sleeptaskw_doc}, 3024 #endif 3025 {NULL, NULL} /* sentinel */ 3026 }; 3027 3028 /* SockObject members */ 3029 static PyMemberDef sock_memberlist[] = { 3030 {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"}, 3031 {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"}, 3032 {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"}, 3033 {"timeout", T_DOUBLE, offsetof(PySocketSockObject, sock_timeout), READONLY, "the socket timeout"}, 3034 {0}, 3035 }; 3036 3037 /* Deallocate a socket object in response to the last Py_DECREF(). 3038 First close the file description. */ 3039 3040 static void 3041 sock_dealloc(PySocketSockObject *s) 3042 { 3043 if (s->sock_fd != -1) 3044 (void) SOCKETCLOSE(s->sock_fd); 3045 Py_TYPE(s)->tp_free((PyObject *)s); 3046 } 3047 3048 3049 static PyObject * 3050 sock_repr(PySocketSockObject *s) 3051 { 3052 char buf[512]; 3053 #if SIZEOF_SOCKET_T > SIZEOF_LONG 3054 if (s->sock_fd > LONG_MAX) { 3055 /* this can occur on Win64, and actually there is a special 3056 ugly printf formatter for decimal pointer length integer 3057 printing, only bother if necessary*/ 3058 PyErr_SetString(PyExc_OverflowError, 3059 "no printf formatter to display " 3060 "the socket descriptor in decimal"); 3061 return NULL; 3062 } 3063 #endif 3064 PyOS_snprintf( 3065 buf, sizeof(buf), 3066 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>", 3067 (long)s->sock_fd, s->sock_family, 3068 s->sock_type, 3069 s->sock_proto); 3070 return PyString_FromString(buf); 3071 } 3072 3073 3074 /* Create a new, uninitialized socket object. */ 3075 3076 static PyObject * 3077 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) 3078 { 3079 PyObject *new; 3080 3081 new = type->tp_alloc(type, 0); 3082 if (new != NULL) { 3083 ((PySocketSockObject *)new)->sock_fd = -1; 3084 ((PySocketSockObject *)new)->sock_timeout = -1.0; 3085 ((PySocketSockObject *)new)->errorhandler = &set_error; 3086 } 3087 return new; 3088 } 3089 3090 3091 /* Initialize a new socket object. */ 3092 3093 /*ARGSUSED*/ 3094 static int 3095 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds) 3096 { 3097 PySocketSockObject *s = (PySocketSockObject *)self; 3098 SOCKET_T fd; 3099 int family = AF_INET, type = SOCK_STREAM, proto = 0; 3100 static char *keywords[] = {"family", "type", "proto", 0}; 3101 3102 if (!PyArg_ParseTupleAndKeywords(args, kwds, 3103 "|iii:socket", keywords, 3104 &family, &type, &proto)) 3105 return -1; 3106 3107 Py_BEGIN_ALLOW_THREADS 3108 fd = socket(family, type, proto); 3109 Py_END_ALLOW_THREADS 3110 3111 #ifdef MS_WINDOWS 3112 if (fd == INVALID_SOCKET) 3113 #else 3114 if (fd < 0) 3115 #endif 3116 { 3117 set_error(); 3118 return -1; 3119 } 3120 init_sockobject(s, fd, family, type, proto); 3121 3122 return 0; 3123 3124 } 3125 3126 3127 /* Type object for socket objects. */ 3128 3129 static PyTypeObject sock_type = { 3130 PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ 3131 "_socket.socket", /* tp_name */ 3132 sizeof(PySocketSockObject), /* tp_basicsize */ 3133 0, /* tp_itemsize */ 3134 (destructor)sock_dealloc, /* tp_dealloc */ 3135 0, /* tp_print */ 3136 0, /* tp_getattr */ 3137 0, /* tp_setattr */ 3138 0, /* tp_compare */ 3139 (reprfunc)sock_repr, /* tp_repr */ 3140 0, /* tp_as_number */ 3141 0, /* tp_as_sequence */ 3142 0, /* tp_as_mapping */ 3143 0, /* tp_hash */ 3144 0, /* tp_call */ 3145 0, /* tp_str */ 3146 PyObject_GenericGetAttr, /* tp_getattro */ 3147 0, /* tp_setattro */ 3148 0, /* tp_as_buffer */ 3149 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ 3150 sock_doc, /* tp_doc */ 3151 0, /* tp_traverse */ 3152 0, /* tp_clear */ 3153 0, /* tp_richcompare */ 3154 0, /* tp_weaklistoffset */ 3155 0, /* tp_iter */ 3156 0, /* tp_iternext */ 3157 sock_methods, /* tp_methods */ 3158 sock_memberlist, /* tp_members */ 3159 0, /* tp_getset */ 3160 0, /* tp_base */ 3161 0, /* tp_dict */ 3162 0, /* tp_descr_get */ 3163 0, /* tp_descr_set */ 3164 0, /* tp_dictoffset */ 3165 sock_initobj, /* tp_init */ 3166 PyType_GenericAlloc, /* tp_alloc */ 3167 sock_new, /* tp_new */ 3168 PyObject_Del, /* tp_free */ 3169 }; 3170 3171 3172 /* Python interface to gethostname(). */ 3173 3174 /*ARGSUSED*/ 3175 static PyObject * 3176 socket_gethostname(PyObject *self, PyObject *unused) 3177 { 3178 char buf[1024]; 3179 int res; 3180 Py_BEGIN_ALLOW_THREADS 3181 res = gethostname(buf, (int) sizeof buf - 1); 3182 Py_END_ALLOW_THREADS 3183 if (res < 0) 3184 return set_error(); 3185 buf[sizeof buf - 1] = '\0'; 3186 return PyString_FromString(buf); 3187 } 3188 3189 PyDoc_STRVAR(gethostname_doc, 3190 "gethostname() -> string\n\ 3191 \n\ 3192 Return the current host name."); 3193 3194 3195 /* Python interface to gethostbyname(name). */ 3196 3197 /*ARGSUSED*/ 3198 static PyObject * 3199 socket_gethostbyname(PyObject *self, PyObject *args) 3200 { 3201 char *name; 3202 sock_addr_t addrbuf; 3203 3204 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name)) 3205 return NULL; 3206 if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0) 3207 return NULL; 3208 return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in)); 3209 } 3210 3211 PyDoc_STRVAR(gethostbyname_doc, 3212 "gethostbyname(host) -> address\n\ 3213 \n\ 3214 Return the IP address (a string of the form '255.255.255.255') for a host."); 3215 3216 3217 /* Convenience function common to gethostbyname_ex and gethostbyaddr */ 3218 3219 static PyObject * 3220 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af) 3221 { 3222 char **pch; 3223 PyObject *rtn_tuple = (PyObject *)NULL; 3224 PyObject *name_list = (PyObject *)NULL; 3225 PyObject *addr_list = (PyObject *)NULL; 3226 PyObject *tmp; 3227 3228 if (h == NULL) { 3229 /* Let's get real error message to return */ 3230 #ifndef RISCOS 3231 set_herror(h_errno); 3232 #else 3233 PyErr_SetString(socket_error, "host not found"); 3234 #endif 3235 return NULL; 3236 } 3237 3238 if (h->h_addrtype != af) { 3239 /* Let's get real error message to return */ 3240 PyErr_SetString(socket_error, 3241 (char *)strerror(EAFNOSUPPORT)); 3242 3243 return NULL; 3244 } 3245 3246 switch (af) { 3247 3248 case AF_INET: 3249 if (alen < sizeof(struct sockaddr_in)) 3250 return NULL; 3251 break; 3252 3253 #ifdef ENABLE_IPV6 3254 case AF_INET6: 3255 if (alen < sizeof(struct sockaddr_in6)) 3256 return NULL; 3257 break; 3258 #endif 3259 3260 } 3261 3262 if ((name_list = PyList_New(0)) == NULL) 3263 goto err; 3264 3265 if ((addr_list = PyList_New(0)) == NULL) 3266 goto err; 3267 3268 /* SF #1511317: h_aliases can be NULL */ 3269 if (h->h_aliases) { 3270 for (pch = h->h_aliases; *pch != NULL; pch++) { 3271 int status; 3272 tmp = PyString_FromString(*pch); 3273 if (tmp == NULL) 3274 goto err; 3275 3276 status = PyList_Append(name_list, tmp); 3277 Py_DECREF(tmp); 3278 3279 if (status) 3280 goto err; 3281 } 3282 } 3283 3284 for (pch = h->h_addr_list; *pch != NULL; pch++) { 3285 int status; 3286 3287 switch (af) { 3288 3289 case AF_INET: 3290 { 3291 struct sockaddr_in sin; 3292 memset(&sin, 0, sizeof(sin)); 3293 sin.sin_family = af; 3294 #ifdef HAVE_SOCKADDR_SA_LEN 3295 sin.sin_len = sizeof(sin); 3296 #endif 3297 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr)); 3298 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin)); 3299 3300 if (pch == h->h_addr_list && alen >= sizeof(sin)) 3301 memcpy((char *) addr, &sin, sizeof(sin)); 3302 break; 3303 } 3304 3305 #ifdef ENABLE_IPV6 3306 case AF_INET6: 3307 { 3308 struct sockaddr_in6 sin6; 3309 memset(&sin6, 0, sizeof(sin6)); 3310 sin6.sin6_family = af; 3311 #ifdef HAVE_SOCKADDR_SA_LEN 3312 sin6.sin6_len = sizeof(sin6); 3313 #endif 3314 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr)); 3315 tmp = makeipaddr((struct sockaddr *)&sin6, 3316 sizeof(sin6)); 3317 3318 if (pch == h->h_addr_list && alen >= sizeof(sin6)) 3319 memcpy((char *) addr, &sin6, sizeof(sin6)); 3320 break; 3321 } 3322 #endif 3323 3324 default: /* can't happen */ 3325 PyErr_SetString(socket_error, 3326 "unsupported address family"); 3327 return NULL; 3328 } 3329 3330 if (tmp == NULL) 3331 goto err; 3332 3333 status = PyList_Append(addr_list, tmp); 3334 Py_DECREF(tmp); 3335 3336 if (status) 3337 goto err; 3338 } 3339 3340 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list); 3341 3342 err: 3343 Py_XDECREF(name_list); 3344 Py_XDECREF(addr_list); 3345 return rtn_tuple; 3346 } 3347 3348 3349 /* Python interface to gethostbyname_ex(name). */ 3350 3351 /*ARGSUSED*/ 3352 static PyObject * 3353 socket_gethostbyname_ex(PyObject *self, PyObject *args) 3354 { 3355 char *name; 3356 struct hostent *h; 3357 #ifdef ENABLE_IPV6 3358 struct sockaddr_storage addr; 3359 #else 3360 struct sockaddr_in addr; 3361 #endif 3362 struct sockaddr *sa; 3363 PyObject *ret; 3364 #ifdef HAVE_GETHOSTBYNAME_R 3365 struct hostent hp_allocated; 3366 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG 3367 struct hostent_data data; 3368 #else 3369 char buf[16384]; 3370 int buf_len = (sizeof buf) - 1; 3371 int errnop; 3372 #endif 3373 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG) 3374 int result;
variable 'result' set but not used
(emitted by gcc)
variable 'result' set but not used
(emitted by gcc)
3375 #endif 3376 #endif /* HAVE_GETHOSTBYNAME_R */ 3377 3378 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name)) 3379 return NULL; 3380 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0) 3381 return NULL; 3382 Py_BEGIN_ALLOW_THREADS 3383 #ifdef HAVE_GETHOSTBYNAME_R 3384 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG) 3385 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
Value stored to 'result' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'result' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

3386 &h, &errnop); 3387 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG) 3388 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop); 3389 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */ 3390 memset((void *) &data, '\0', sizeof(data)); 3391 result = gethostbyname_r(name, &hp_allocated, &data); 3392 h = (result != 0) ? NULL : &hp_allocated; 3393 #endif 3394 #else /* not HAVE_GETHOSTBYNAME_R */ 3395 #ifdef USE_GETHOSTBYNAME_LOCK 3396 PyThread_acquire_lock(netdb_lock, 1); 3397 #endif 3398 h = gethostbyname(name); 3399 #endif /* HAVE_GETHOSTBYNAME_R */ 3400 Py_END_ALLOW_THREADS 3401 /* Some C libraries would require addr.__ss_family instead of 3402 addr.ss_family. 3403 Therefore, we cast the sockaddr_storage into sockaddr to 3404 access sa_family. */ 3405 sa = (struct sockaddr*)&addr; 3406 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), 3407 sa->sa_family); 3408 #ifdef USE_GETHOSTBYNAME_LOCK 3409 PyThread_release_lock(netdb_lock); 3410 #endif 3411 return ret; 3412 } 3413 3414 PyDoc_STRVAR(ghbn_ex_doc, 3415 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\ 3416 \n\ 3417 Return the true host name, a list of aliases, and a list of IP addresses,\n\ 3418 for a host. The host argument is a string giving a host name or IP number."); 3419 3420 3421 /* Python interface to gethostbyaddr(IP). */ 3422 3423 /*ARGSUSED*/ 3424 static PyObject * 3425 socket_gethostbyaddr(PyObject *self, PyObject *args) 3426 { 3427 #ifdef ENABLE_IPV6 3428 struct sockaddr_storage addr; 3429 #else 3430 struct sockaddr_in addr; 3431 #endif 3432 struct sockaddr *sa = (struct sockaddr *)&addr; 3433 char *ip_num; 3434 struct hostent *h; 3435 PyObject *ret; 3436 #ifdef HAVE_GETHOSTBYNAME_R 3437 struct hostent hp_allocated; 3438 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG 3439 struct hostent_data data; 3440 #else 3441 /* glibcs up to 2.10 assume that the buf argument to 3442 gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc 3443 does not ensure. The attribute below instructs the compiler 3444 to maintain this alignment. */ 3445 char buf[16384] Py_ALIGNED(8); 3446 int buf_len = (sizeof buf) - 1; 3447 int errnop; 3448 #endif 3449 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG) 3450 int result;
variable 'result' set but not used
(emitted by gcc)
variable 'result' set but not used
(emitted by gcc)
3451 #endif 3452 #endif /* HAVE_GETHOSTBYNAME_R */ 3453 char *ap; 3454 int al; 3455 int af; 3456 3457 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num)) 3458 return NULL; 3459 af = AF_UNSPEC; 3460 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0) 3461 return NULL; 3462 af = sa->sa_family; 3463 ap = NULL; 3464 switch (af) { 3465 case AF_INET: 3466 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr; 3467 al = sizeof(((struct sockaddr_in *)sa)->sin_addr); 3468 break; 3469 #ifdef ENABLE_IPV6 3470 case AF_INET6: 3471 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr; 3472 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr); 3473 break; 3474 #endif 3475 default: 3476 PyErr_SetString(socket_error, "unsupported address family"); 3477 return NULL; 3478 } 3479 Py_BEGIN_ALLOW_THREADS 3480 #ifdef HAVE_GETHOSTBYNAME_R 3481 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG) 3482 result = gethostbyaddr_r(ap, al, af,
Value stored to 'result' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Value stored to 'result' is never read
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

3483 &hp_allocated, buf, buf_len, 3484 &h, &errnop); 3485 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG) 3486 h = gethostbyaddr_r(ap, al, af, 3487 &hp_allocated, buf, buf_len, &errnop); 3488 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */ 3489 memset((void *) &data, '\0', sizeof(data)); 3490 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data); 3491 h = (result != 0) ? NULL : &hp_allocated; 3492 #endif 3493 #else /* not HAVE_GETHOSTBYNAME_R */ 3494 #ifdef USE_GETHOSTBYNAME_LOCK 3495 PyThread_acquire_lock(netdb_lock, 1); 3496 #endif 3497 h = gethostbyaddr(ap, al, af); 3498 #endif /* HAVE_GETHOSTBYNAME_R */ 3499 Py_END_ALLOW_THREADS 3500 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af); 3501 #ifdef USE_GETHOSTBYNAME_LOCK 3502 PyThread_release_lock(netdb_lock); 3503 #endif 3504 return ret; 3505 } 3506 3507 PyDoc_STRVAR(gethostbyaddr_doc, 3508 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\ 3509 \n\ 3510 Return the true host name, a list of aliases, and a list of IP addresses,\n\ 3511 for a host. The host argument is a string giving a host name or IP number."); 3512 3513 3514 /* Python interface to getservbyname(name). 3515 This only returns the port number, since the other info is already 3516 known or not useful (like the list of aliases). */ 3517 3518 /*ARGSUSED*/ 3519 static PyObject * 3520 socket_getservbyname(PyObject *self, PyObject *args) 3521 { 3522 char *name, *proto=NULL; 3523 struct servent *sp; 3524 if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto)) 3525 return NULL; 3526 Py_BEGIN_ALLOW_THREADS 3527 sp = getservbyname(name, proto); 3528 Py_END_ALLOW_THREADS 3529 if (sp == NULL) { 3530 PyErr_SetString(socket_error, "service/proto not found"); 3531 return NULL; 3532 } 3533 return PyInt_FromLong((long) ntohs(sp->s_port)); 3534 } 3535 3536 PyDoc_STRVAR(getservbyname_doc, 3537 "getservbyname(servicename[, protocolname]) -> integer\n\ 3538 \n\ 3539 Return a port number from a service name and protocol name.\n\ 3540 The optional protocol name, if given, should be 'tcp' or 'udp',\n\ 3541 otherwise any protocol will match."); 3542 3543 3544 /* Python interface to getservbyport(port). 3545 This only returns the service name, since the other info is already 3546 known or not useful (like the list of aliases). */ 3547 3548 /*ARGSUSED*/ 3549 static PyObject * 3550 socket_getservbyport(PyObject *self, PyObject *args) 3551 { 3552 int port; 3553 char *proto=NULL; 3554 struct servent *sp; 3555 if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto)) 3556 return NULL; 3557 if (port < 0 || port > 0xffff) { 3558 PyErr_SetString( 3559 PyExc_OverflowError, 3560 "getservbyport: port must be 0-65535."); 3561 return NULL; 3562 } 3563 Py_BEGIN_ALLOW_THREADS 3564 sp = getservbyport(htons((short)port), proto); 3565 Py_END_ALLOW_THREADS 3566 if (sp == NULL) { 3567 PyErr_SetString(socket_error, "port/proto not found"); 3568 return NULL; 3569 } 3570 return PyString_FromString(sp->s_name); 3571 } 3572 3573 PyDoc_STRVAR(getservbyport_doc, 3574 "getservbyport(port[, protocolname]) -> string\n\ 3575 \n\ 3576 Return the service name from a port number and protocol name.\n\ 3577 The optional protocol name, if given, should be 'tcp' or 'udp',\n\ 3578 otherwise any protocol will match."); 3579 3580 /* Python interface to getprotobyname(name). 3581 This only returns the protocol number, since the other info is 3582 already known or not useful (like the list of aliases). */ 3583 3584 /*ARGSUSED*/ 3585 static PyObject * 3586 socket_getprotobyname(PyObject *self, PyObject *args) 3587 { 3588 char *name; 3589 struct protoent *sp; 3590 #ifdef __BEOS__ 3591 /* Not available in BeOS yet. - [cjh] */ 3592 PyErr_SetString(socket_error, "getprotobyname not supported"); 3593 return NULL; 3594 #else 3595 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name)) 3596 return NULL; 3597 Py_BEGIN_ALLOW_THREADS 3598 sp = getprotobyname(name); 3599 Py_END_ALLOW_THREADS 3600 if (sp == NULL) { 3601 PyErr_SetString(socket_error, "protocol not found"); 3602 return NULL; 3603 } 3604 return PyInt_FromLong((long) sp->p_proto); 3605 #endif 3606 } 3607 3608 PyDoc_STRVAR(getprotobyname_doc, 3609 "getprotobyname(name) -> integer\n\ 3610 \n\ 3611 Return the protocol number for the named protocol. (Rarely used.)"); 3612 3613 3614 #ifdef HAVE_SOCKETPAIR 3615 /* Create a pair of sockets using the socketpair() function. 3616 Arguments as for socket() except the default family is AF_UNIX if 3617 defined on the platform; otherwise, the default is AF_INET. */ 3618 3619 /*ARGSUSED*/ 3620 static PyObject * 3621 socket_socketpair(PyObject *self, PyObject *args) 3622 { 3623 PySocketSockObject *s0 = NULL, *s1 = NULL; 3624 SOCKET_T sv[2]; 3625 int family, type = SOCK_STREAM, proto = 0; 3626 PyObject *res = NULL; 3627 3628 #if defined(AF_UNIX) 3629 family = AF_UNIX; 3630 #else 3631 family = AF_INET; 3632 #endif 3633 if (!PyArg_ParseTuple(args, "|iii:socketpair", 3634 &family, &type, &proto)) 3635 return NULL; 3636 /* Create a pair of socket fds */ 3637 if (socketpair(family, type, proto, sv) < 0) 3638 return set_error(); 3639 s0 = new_sockobject(sv[0], family, type, proto); 3640 if (s0 == NULL) 3641 goto finally; 3642 s1 = new_sockobject(sv[1], family, type, proto); 3643 if (s1 == NULL) 3644 goto finally; 3645 res = PyTuple_Pack(2, s0, s1); 3646 3647 finally: 3648 if (res == NULL) { 3649 if (s0 == NULL) 3650 SOCKETCLOSE(sv[0]); 3651 if (s1 == NULL) 3652 SOCKETCLOSE(sv[1]); 3653 } 3654 Py_XDECREF(s0); 3655 Py_XDECREF(s1); 3656 return res; 3657 } 3658 3659 PyDoc_STRVAR(socketpair_doc, 3660 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\ 3661 \n\ 3662 Create a pair of socket objects from the sockets returned by the platform\n\ 3663 socketpair() function.\n\ 3664 The arguments are the same as for socket() except the default family is\n\ 3665 AF_UNIX if defined on the platform; otherwise, the default is AF_INET."); 3666 3667 #endif /* HAVE_SOCKETPAIR */ 3668 3669 3670 #ifndef NO_DUP 3671 /* Create a socket object from a numeric file description. 3672 Useful e.g. if stdin is a socket. 3673 Additional arguments as for socket(). */ 3674 3675 /*ARGSUSED*/ 3676 static PyObject * 3677 socket_fromfd(PyObject *self, PyObject *args) 3678 { 3679 PySocketSockObject *s; 3680 SOCKET_T fd; 3681 int family, type, proto = 0; 3682 if (!PyArg_ParseTuple(args, "iii|i:fromfd", 3683 &fd, &family, &type, &proto)) 3684 return NULL; 3685 /* Dup the fd so it and the socket can be closed independently */ 3686 fd = dup(fd); 3687 if (fd < 0) 3688 return set_error(); 3689 s = new_sockobject(fd, family, type, proto); 3690 return (PyObject *) s; 3691 } 3692 3693 PyDoc_STRVAR(fromfd_doc, 3694 "fromfd(fd, family, type[, proto]) -> socket object\n\ 3695 \n\ 3696 Create a socket object from a duplicate of the given\n\ 3697 file descriptor.\n\ 3698 The remaining arguments are the same as for socket()."); 3699 3700 #endif /* NO_DUP */ 3701 3702 3703 static PyObject * 3704 socket_ntohs(PyObject *self, PyObject *args) 3705 { 3706 int x1, x2; 3707 3708 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) { 3709 return NULL; 3710 } 3711 if (x1 < 0) { 3712 PyErr_SetString(PyExc_OverflowError, 3713 "can't convert negative number to unsigned long"); 3714 return NULL; 3715 } 3716 x2 = (unsigned int)ntohs((unsigned short)x1); 3717 return PyInt_FromLong(x2); 3718 } 3719 3720 PyDoc_STRVAR(ntohs_doc, 3721 "ntohs(integer) -> integer\n\ 3722 \n\ 3723 Convert a 16-bit integer from network to host byte order."); 3724 3725 3726 static PyObject * 3727 socket_ntohl(PyObject *self, PyObject *arg) 3728 { 3729 unsigned long x; 3730 3731 if (PyInt_Check(arg)) { 3732 x = PyInt_AS_LONG(arg); 3733 if (x == (unsigned long) -1 && PyErr_Occurred()) 3734 return NULL; 3735 if ((long)x < 0) { 3736 PyErr_SetString(PyExc_OverflowError, 3737 "can't convert negative number to unsigned long"); 3738 return NULL; 3739 } 3740 } 3741 else if (PyLong_Check(arg)) { 3742 x = PyLong_AsUnsignedLong(arg); 3743 if (x == (unsigned long) -1 && PyErr_Occurred()) 3744 return NULL; 3745 #if SIZEOF_LONG > 4 3746 { 3747 unsigned long y; 3748 /* only want the trailing 32 bits */ 3749 y = x & 0xFFFFFFFFUL; 3750 if (y ^ x) 3751 return PyErr_Format(PyExc_OverflowError, 3752 "long int larger than 32 bits"); 3753 x = y; 3754 } 3755 #endif 3756 } 3757 else 3758 return PyErr_Format(PyExc_TypeError, 3759 "expected int/long, %s found", 3760 Py_TYPE(arg)->tp_name); 3761 if (x == (unsigned long) -1 && PyErr_Occurred()) 3762 return NULL; 3763 return PyLong_FromUnsignedLong(ntohl(x)); 3764 } 3765 3766 PyDoc_STRVAR(ntohl_doc, 3767 "ntohl(integer) -> integer\n\ 3768 \n\ 3769 Convert a 32-bit integer from network to host byte order."); 3770 3771 3772 static PyObject * 3773 socket_htons(PyObject *self, PyObject *args) 3774 { 3775 int x1, x2; 3776 3777 if (!PyArg_ParseTuple(args, "i:htons", &x1)) { 3778 return NULL; 3779 } 3780 if (x1 < 0) { 3781 PyErr_SetString(PyExc_OverflowError, 3782 "can't convert negative number to unsigned long"); 3783 return NULL; 3784 } 3785 x2 = (unsigned int)htons((unsigned short)x1); 3786 return PyInt_FromLong(x2); 3787 } 3788 3789 PyDoc_STRVAR(htons_doc, 3790 "htons(integer) -> integer\n\ 3791 \n\ 3792 Convert a 16-bit integer from host to network byte order."); 3793 3794 3795 static PyObject * 3796 socket_htonl(PyObject *self, PyObject *arg) 3797 { 3798 unsigned long x; 3799 3800 if (PyInt_Check(arg)) { 3801 x = PyInt_AS_LONG(arg); 3802 if (x == (unsigned long) -1 && PyErr_Occurred()) 3803 return NULL; 3804 if ((long)x < 0) { 3805 PyErr_SetString(PyExc_OverflowError, 3806 "can't convert negative number to unsigned long"); 3807 return NULL; 3808 } 3809 } 3810 else if (PyLong_Check(arg)) { 3811 x = PyLong_AsUnsignedLong(arg); 3812 if (x == (unsigned long) -1 && PyErr_Occurred()) 3813 return NULL; 3814 #if SIZEOF_LONG > 4 3815 { 3816 unsigned long y; 3817 /* only want the trailing 32 bits */ 3818 y = x & 0xFFFFFFFFUL; 3819 if (y ^ x) 3820 return PyErr_Format(PyExc_OverflowError, 3821 "long int larger than 32 bits"); 3822 x = y; 3823 } 3824 #endif 3825 } 3826 else 3827 return PyErr_Format(PyExc_TypeError, 3828 "expected int/long, %s found", 3829 Py_TYPE(arg)->tp_name); 3830 return PyLong_FromUnsignedLong(htonl((unsigned long)x)); 3831 } 3832 3833 PyDoc_STRVAR(htonl_doc, 3834 "htonl(integer) -> integer\n\ 3835 \n\ 3836 Convert a 32-bit integer from host to network byte order."); 3837 3838 /* socket.inet_aton() and socket.inet_ntoa() functions. */ 3839 3840 PyDoc_STRVAR(inet_aton_doc, 3841 "inet_aton(string) -> packed 32-bit IP representation\n\ 3842 \n\ 3843 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\ 3844 binary format used in low-level network functions."); 3845 3846 static PyObject* 3847 socket_inet_aton(PyObject *self, PyObject *args) 3848 { 3849 #ifndef INADDR_NONE 3850 #define INADDR_NONE (-1) 3851 #endif 3852 #ifdef HAVE_INET_ATON 3853 struct in_addr buf; 3854 #endif 3855 3856 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK) 3857 #if (SIZEOF_INT != 4) 3858 #error "Not sure if in_addr_t exists and int is not 32-bits." 3859 #endif 3860 /* Have to use inet_addr() instead */ 3861 unsigned int packed_addr; 3862 #endif 3863 char *ip_addr; 3864 3865 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) 3866 return NULL; 3867 3868 3869 #ifdef HAVE_INET_ATON 3870 3871 #ifdef USE_INET_ATON_WEAKLINK 3872 if (inet_aton != NULL) { 3873 #endif 3874 if (inet_aton(ip_addr, &buf)) 3875 return PyString_FromStringAndSize((char *)(&buf), 3876 sizeof(buf)); 3877 3878 PyErr_SetString(socket_error, 3879 "illegal IP address string passed to inet_aton"); 3880 return NULL; 3881 3882 #ifdef USE_INET_ATON_WEAKLINK 3883 } else { 3884 #endif 3885 3886 #endif 3887 3888 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK) 3889 3890 /* special-case this address as inet_addr might return INADDR_NONE 3891 * for this */ 3892 if (strcmp(ip_addr, "255.255.255.255") == 0) { 3893 packed_addr = 0xFFFFFFFF; 3894 } else { 3895 3896 packed_addr = inet_addr(ip_addr); 3897 3898 if (packed_addr == INADDR_NONE) { /* invalid address */ 3899 PyErr_SetString(socket_error, 3900 "illegal IP address string passed to inet_aton"); 3901 return NULL; 3902 } 3903 } 3904 return PyString_FromStringAndSize((char *) &packed_addr, 3905 sizeof(packed_addr)); 3906 3907 #ifdef USE_INET_ATON_WEAKLINK 3908 } 3909 #endif 3910 3911 #endif 3912 } 3913 3914 PyDoc_STRVAR(inet_ntoa_doc, 3915 "inet_ntoa(packed_ip) -> ip_address_string\n\ 3916 \n\ 3917 Convert an IP address from 32-bit packed binary format to string format"); 3918 3919 static PyObject* 3920 socket_inet_ntoa(PyObject *self, PyObject *args) 3921 { 3922 char *packed_str; 3923 int addr_len; 3924 struct in_addr packed_addr; 3925 3926 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) { 3927 return NULL; 3928 } 3929 3930 if (addr_len != sizeof(packed_addr)) { 3931 PyErr_SetString(socket_error, 3932 "packed IP wrong length for inet_ntoa"); 3933 return NULL; 3934 } 3935 3936 memcpy(&packed_addr, packed_str, addr_len); 3937 3938 return PyString_FromString(inet_ntoa(packed_addr)); 3939 } 3940 3941 #ifdef HAVE_INET_PTON 3942 3943 PyDoc_STRVAR(inet_pton_doc, 3944 "inet_pton(af, ip) -> packed IP address string\n\ 3945 \n\ 3946 Convert an IP address from string format to a packed string suitable\n\ 3947 for use with low-level network functions."); 3948 3949 static PyObject * 3950 socket_inet_pton(PyObject *self, PyObject *args) 3951 { 3952 int af; 3953 char* ip; 3954 int retval; 3955 #ifdef ENABLE_IPV6 3956 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))]; 3957 #else 3958 char packed[sizeof(struct in_addr)]; 3959 #endif 3960 if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) { 3961 return NULL; 3962 } 3963 3964 #if !defined(ENABLE_IPV6) && defined(AF_INET6) 3965 if(af == AF_INET6) { 3966 PyErr_SetString(socket_error, 3967 "can't use AF_INET6, IPv6 is disabled"); 3968 return NULL; 3969 } 3970 #endif 3971 3972 retval = inet_pton(af, ip, packed); 3973 if (retval < 0) { 3974 PyErr_SetFromErrno(socket_error); 3975 return NULL; 3976 } else if (retval == 0) { 3977 PyErr_SetString(socket_error, 3978 "illegal IP address string passed to inet_pton"); 3979 return NULL; 3980 } else if (af == AF_INET) { 3981 return PyString_FromStringAndSize(packed, 3982 sizeof(struct in_addr)); 3983 #ifdef ENABLE_IPV6 3984 } else if (af == AF_INET6) { 3985 return PyString_FromStringAndSize(packed, 3986 sizeof(struct in6_addr)); 3987 #endif 3988 } else { 3989 PyErr_SetString(socket_error, "unknown address family"); 3990 return NULL; 3991 } 3992 } 3993 3994 PyDoc_STRVAR(inet_ntop_doc, 3995 "inet_ntop(af, packed_ip) -> string formatted IP address\n\ 3996 \n\ 3997 Convert a packed IP address of the given family to string format."); 3998 3999 static PyObject * 4000 socket_inet_ntop(PyObject *self, PyObject *args) 4001 { 4002 int af; 4003 char* packed; 4004 int len; 4005 const char* retval; 4006 #ifdef ENABLE_IPV6 4007 char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1]; 4008 #else 4009 char ip[INET_ADDRSTRLEN + 1]; 4010 #endif 4011 4012 /* Guarantee NUL-termination for PyString_FromString() below */ 4013 memset((void *) &ip[0], '\0', sizeof(ip)); 4014 4015 if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) { 4016 return NULL; 4017 } 4018 4019 if (af == AF_INET) { 4020 if (len != sizeof(struct in_addr)) { 4021 PyErr_SetString(PyExc_ValueError, 4022 "invalid length of packed IP address string"); 4023 return NULL; 4024 } 4025 #ifdef ENABLE_IPV6 4026 } else if (af == AF_INET6) { 4027 if (len != sizeof(struct in6_addr)) { 4028 PyErr_SetString(PyExc_ValueError, 4029 "invalid length of packed IP address string"); 4030 return NULL; 4031 } 4032 #endif 4033 } else { 4034 PyErr_Format(PyExc_ValueError, 4035 "unknown address family %d", af); 4036 return NULL; 4037 } 4038 4039 retval = inet_ntop(af, packed, ip, sizeof(ip)); 4040 if (!retval) { 4041 PyErr_SetFromErrno(socket_error); 4042 return NULL; 4043 } else { 4044 return PyString_FromString(retval); 4045 } 4046 4047 /* NOTREACHED */ 4048 PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop"); 4049 return NULL; 4050 } 4051 4052 #endif /* HAVE_INET_PTON */ 4053 4054 /* Python interface to getaddrinfo(host, port). */ 4055 4056 /*ARGSUSED*/ 4057 static PyObject * 4058 socket_getaddrinfo(PyObject *self, PyObject *args) 4059 { 4060 struct addrinfo hints, *res; 4061 struct addrinfo *res0 = NULL; 4062 PyObject *hobj = NULL; 4063 PyObject *pobj = (PyObject *)NULL; 4064 char pbuf[30]; 4065 char *hptr, *pptr; 4066 int family, socktype, protocol, flags; 4067 int error; 4068 PyObject *all = (PyObject *)NULL; 4069 PyObject *single = (PyObject *)NULL; 4070 PyObject *idna = NULL; 4071 4072 family = socktype = protocol = flags = 0; 4073 family = AF_UNSPEC; 4074 if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo", 4075 &hobj, &pobj, &family, &socktype, 4076 &protocol, &flags)) { 4077 return NULL; 4078 } 4079 if (hobj == Py_None) { 4080 hptr = NULL; 4081 } else if (PyUnicode_Check(hobj)) { 4082 idna = PyObject_CallMethod(hobj, "encode", "s", "idna"); 4083 if (!idna) 4084 return NULL; 4085 hptr = PyString_AsString(idna); 4086 } else if (PyString_Check(hobj)) { 4087 hptr = PyString_AsString(hobj); 4088 } else { 4089 PyErr_SetString(PyExc_TypeError, 4090 "getaddrinfo() argument 1 must be string or None"); 4091 return NULL; 4092 } 4093 if (PyInt_Check(pobj)) { 4094 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj)); 4095 pptr = pbuf; 4096 } else if (PyString_Check(pobj)) { 4097 pptr = PyString_AsString(pobj); 4098 } else if (pobj == Py_None) { 4099 pptr = (char *)NULL; 4100 } else { 4101 PyErr_SetString(socket_error, "Int or String expected"); 4102 goto err; 4103 } 4104 memset(&hints, 0, sizeof(hints)); 4105 hints.ai_family = family; 4106 hints.ai_socktype = socktype; 4107 hints.ai_protocol = protocol; 4108 hints.ai_flags = flags; 4109 Py_BEGIN_ALLOW_THREADS 4110 ACQUIRE_GETADDRINFO_LOCK 4111 error = getaddrinfo(hptr, pptr, &hints, &res0); 4112 Py_END_ALLOW_THREADS 4113 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ 4114 if (error) { 4115 set_gaierror(error); 4116 goto err; 4117 } 4118 4119 if ((all = PyList_New(0)) == NULL) 4120 goto err; 4121 for (res = res0; res; res = res->ai_next) { 4122 PyObject *addr = 4123 makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol); 4124 if (addr == NULL) 4125 goto err; 4126 single = Py_BuildValue("iiisO", res->ai_family, 4127 res->ai_socktype, res->ai_protocol, 4128 res->ai_canonname ? res->ai_canonname : "", 4129 addr); 4130 Py_DECREF(addr); 4131 if (single == NULL) 4132 goto err; 4133 4134 if (PyList_Append(all, single)) 4135 goto err; 4136 Py_XDECREF(single); 4137 } 4138 Py_XDECREF(idna); 4139 if (res0) 4140 freeaddrinfo(res0); 4141 return all; 4142 err: 4143 Py_XDECREF(single); 4144 Py_XDECREF(all); 4145 Py_XDECREF(idna); 4146 if (res0) 4147 freeaddrinfo(res0); 4148 return (PyObject *)NULL; 4149 } 4150 4151 PyDoc_STRVAR(getaddrinfo_doc, 4152 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\ 4153 -> list of (family, socktype, proto, canonname, sockaddr)\n\ 4154 \n\ 4155 Resolve host and port into addrinfo struct."); 4156 4157 /* Python interface to getnameinfo(sa, flags). */ 4158 4159 /*ARGSUSED*/ 4160 static PyObject * 4161 socket_getnameinfo(PyObject *self, PyObject *args) 4162 { 4163 PyObject *sa = (PyObject *)NULL; 4164 int flags; 4165 char *hostp; 4166 int port; 4167 unsigned int flowinfo, scope_id; 4168 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV]; 4169 struct addrinfo hints, *res = NULL; 4170 int error; 4171 PyObject *ret = (PyObject *)NULL; 4172 4173 flags = flowinfo = scope_id = 0; 4174 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags)) 4175 return NULL; 4176 if (!PyTuple_Check(sa)) { 4177 PyErr_SetString(PyExc_TypeError, 4178 "getnameinfo() argument 1 must be a tuple"); 4179 return NULL; 4180 } 4181 if (!PyArg_ParseTuple(sa, "si|II", 4182 &hostp, &port, &flowinfo, &scope_id)) 4183 return NULL; 4184 if (flowinfo < 0 || flowinfo > 0xfffff) { 4185 PyErr_SetString(PyExc_OverflowError, 4186 "getsockaddrarg: flowinfo must be 0-1048575."); 4187 return NULL; 4188 } 4189 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port); 4190 memset(&hints, 0, sizeof(hints)); 4191 hints.ai_family = AF_UNSPEC; 4192 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */ 4193 Py_BEGIN_ALLOW_THREADS 4194 ACQUIRE_GETADDRINFO_LOCK 4195 error = getaddrinfo(hostp, pbuf, &hints, &res); 4196 Py_END_ALLOW_THREADS 4197 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ 4198 if (error) { 4199 set_gaierror(error); 4200 goto fail; 4201 } 4202 if (res->ai_next) { 4203 PyErr_SetString(socket_error, 4204 "sockaddr resolved to multiple addresses"); 4205 goto fail; 4206 } 4207 switch (res->ai_family) { 4208 case AF_INET: 4209 { 4210 if (PyTuple_GET_SIZE(sa) != 2) { 4211 PyErr_SetString(socket_error, 4212 "IPv4 sockaddr must be 2 tuple"); 4213 goto fail; 4214 } 4215 break; 4216 } 4217 #ifdef ENABLE_IPV6 4218 case AF_INET6: 4219 { 4220 struct sockaddr_in6 *sin6; 4221 sin6 = (struct sockaddr_in6 *)res->ai_addr; 4222 sin6->sin6_flowinfo = htonl(flowinfo); 4223 sin6->sin6_scope_id = scope_id; 4224 break; 4225 } 4226 #endif 4227 } 4228 error = getnameinfo(res->ai_addr, res->ai_addrlen, 4229 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags); 4230 if (error) { 4231 set_gaierror(error); 4232 goto fail; 4233 } 4234 ret = Py_BuildValue("ss", hbuf, pbuf); 4235 4236 fail: 4237 if (res) 4238 freeaddrinfo(res); 4239 return ret; 4240 } 4241 4242 PyDoc_STRVAR(getnameinfo_doc, 4243 "getnameinfo(sockaddr, flags) --> (host, port)\n\ 4244 \n\ 4245 Get host and port for a sockaddr."); 4246 4247 4248 /* Python API to getting and setting the default timeout value. */ 4249 4250 static PyObject * 4251 socket_getdefaulttimeout(PyObject *self) 4252 { 4253 if (defaulttimeout < 0.0) { 4254 Py_INCREF(Py_None); 4255 return Py_None; 4256 } 4257 else 4258 return PyFloat_FromDouble(defaulttimeout); 4259 } 4260 4261 PyDoc_STRVAR(getdefaulttimeout_doc, 4262 "getdefaulttimeout() -> timeout\n\ 4263 \n\ 4264 Returns the default timeout in seconds (float) for new socket objects.\n\ 4265 A value of None indicates that new socket objects have no timeout.\n\ 4266 When the socket module is first imported, the default is None."); 4267 4268 static PyObject * 4269 socket_setdefaulttimeout(PyObject *self, PyObject *arg) 4270 { 4271 double timeout; 4272 4273 if (arg == Py_None) 4274 timeout = -1.0; 4275 else { 4276 timeout = PyFloat_AsDouble(arg); 4277 if (timeout < 0.0) { 4278 if (!PyErr_Occurred()) 4279 PyErr_SetString(PyExc_ValueError, 4280 "Timeout value out of range"); 4281 return NULL; 4282 } 4283 } 4284 4285 defaulttimeout = timeout; 4286 4287 Py_INCREF(Py_None); 4288 return Py_None; 4289 } 4290 4291 PyDoc_STRVAR(setdefaulttimeout_doc, 4292 "setdefaulttimeout(timeout)\n\ 4293 \n\ 4294 Set the default timeout in seconds (float) for new socket objects.\n\ 4295 A value of None indicates that new socket objects have no timeout.\n\ 4296 When the socket module is first imported, the default is None."); 4297 4298 4299 /* List of functions exported by this module. */ 4300 4301 static PyMethodDef socket_methods[] = { 4302 {"gethostbyname", socket_gethostbyname, 4303 METH_VARARGS, gethostbyname_doc}, 4304 {"gethostbyname_ex", socket_gethostbyname_ex, 4305 METH_VARARGS, ghbn_ex_doc}, 4306 {"gethostbyaddr", socket_gethostbyaddr, 4307 METH_VARARGS, gethostbyaddr_doc}, 4308 {"gethostname", socket_gethostname, 4309 METH_NOARGS, gethostname_doc}, 4310 {"getservbyname", socket_getservbyname, 4311 METH_VARARGS, getservbyname_doc}, 4312 {"getservbyport", socket_getservbyport, 4313 METH_VARARGS, getservbyport_doc}, 4314 {"getprotobyname", socket_getprotobyname, 4315 METH_VARARGS, getprotobyname_doc}, 4316 #ifndef NO_DUP 4317 {"fromfd", socket_fromfd, 4318 METH_VARARGS, fromfd_doc}, 4319 #endif 4320 #ifdef HAVE_SOCKETPAIR 4321 {"socketpair", socket_socketpair, 4322 METH_VARARGS, socketpair_doc}, 4323 #endif 4324 {"ntohs", socket_ntohs, 4325 METH_VARARGS, ntohs_doc}, 4326 {"ntohl", socket_ntohl, 4327 METH_O, ntohl_doc}, 4328 {"htons", socket_htons, 4329 METH_VARARGS, htons_doc}, 4330 {"htonl", socket_htonl, 4331 METH_O, htonl_doc}, 4332 {"inet_aton", socket_inet_aton, 4333 METH_VARARGS, inet_aton_doc}, 4334 {"inet_ntoa", socket_inet_ntoa, 4335 METH_VARARGS, inet_ntoa_doc}, 4336 #ifdef HAVE_INET_PTON 4337 {"inet_pton", socket_inet_pton, 4338 METH_VARARGS, inet_pton_doc}, 4339 {"inet_ntop", socket_inet_ntop, 4340 METH_VARARGS, inet_ntop_doc}, 4341 #endif 4342 {"getaddrinfo", socket_getaddrinfo, 4343 METH_VARARGS, getaddrinfo_doc}, 4344 {"getnameinfo", socket_getnameinfo, 4345 METH_VARARGS, getnameinfo_doc}, 4346 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout, 4347 METH_NOARGS, getdefaulttimeout_doc}, 4348 {"setdefaulttimeout", socket_setdefaulttimeout, 4349 METH_O, setdefaulttimeout_doc}, 4350 {NULL, NULL} /* Sentinel */ 4351 }; 4352 4353 4354 #ifdef RISCOS 4355 #define OS_INIT_DEFINED 4356 4357 static int 4358 os_init(void) 4359 { 4360 _kernel_swi_regs r; 4361 4362 r.r[0] = 0; 4363 _kernel_swi(0x43380, &r, &r); 4364 taskwindow = r.r[0]; 4365 4366 return 1; 4367 } 4368 4369 #endif /* RISCOS */ 4370 4371 4372 #ifdef MS_WINDOWS 4373 #define OS_INIT_DEFINED 4374 4375 /* Additional initialization and cleanup for Windows */ 4376 4377 static void 4378 os_cleanup(void) 4379 { 4380 WSACleanup(); 4381 } 4382 4383 static int 4384 os_init(void) 4385 { 4386 WSADATA WSAData; 4387 int ret; 4388 char buf[100]; 4389 ret = WSAStartup(0x0101, &WSAData); 4390 switch (ret) { 4391 case 0: /* No error */ 4392 Py_AtExit(os_cleanup); 4393 return 1; /* Success */ 4394 case WSASYSNOTREADY: 4395 PyErr_SetString(PyExc_ImportError, 4396 "WSAStartup failed: network not ready"); 4397 break; 4398 case WSAVERNOTSUPPORTED: 4399 case WSAEINVAL: 4400 PyErr_SetString( 4401 PyExc_ImportError, 4402 "WSAStartup failed: requested version not supported"); 4403 break; 4404 default: 4405 PyOS_snprintf(buf, sizeof(buf), 4406 "WSAStartup failed: error code %d", ret); 4407 PyErr_SetString(PyExc_ImportError, buf); 4408 break; 4409 } 4410 return 0; /* Failure */ 4411 } 4412 4413 #endif /* MS_WINDOWS */ 4414 4415 4416 #ifdef PYOS_OS2 4417 #define OS_INIT_DEFINED 4418 4419 /* Additional initialization for OS/2 */ 4420 4421 static int 4422 os_init(void) 4423 { 4424 #ifndef PYCC_GCC 4425 char reason[64]; 4426 int rc = sock_init(); 4427 4428 if (rc == 0) { 4429 return 1; /* Success */ 4430 } 4431 4432 PyOS_snprintf(reason, sizeof(reason), 4433 "OS/2 TCP/IP Error# %d", sock_errno()); 4434 PyErr_SetString(PyExc_ImportError, reason); 4435 4436 return 0; /* Failure */ 4437 #else 4438 /* No need to initialize sockets with GCC/EMX */ 4439 return 1; /* Success */ 4440 #endif 4441 } 4442