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