1# Wrapper module for _socket, providing some additional facilities 2# implemented in Python. 3 4"""\ 5This module provides socket operations and some related functions. 6On Unix, it supports IP (Internet Protocol) and Unix domain sockets. 7On other systems, it only supports IP. Functions specific for a 8socket are available as methods of the socket object. 9 10Functions: 11 12socket() -- create a new socket object 13socketpair() -- create a pair of new socket objects [*] 14fromfd() -- create a socket object from an open file descriptor [*] 15send_fds() -- Send file descriptor to the socket. 16recv_fds() -- Receive file descriptors from the socket. 17fromshare() -- create a socket object from data received from socket.share() [*] 18gethostname() -- return the current hostname 19gethostbyname() -- map a hostname to its IP number 20gethostbyaddr() -- map an IP number or hostname to DNS info 21getservbyname() -- map a service name and a protocol name to a port number 22getprotobyname() -- map a protocol name (e.g. 'tcp') to a number 23ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order 24htons(), htonl() -- convert 16, 32 bit int from host to network byte order 25inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format 26inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) 27socket.getdefaulttimeout() -- get the default timeout value 28socket.setdefaulttimeout() -- set the default timeout value 29create_connection() -- connects to an address, with an optional timeout and 30 optional source address. 31 32 [*] not available on all platforms! 33 34Special objects: 35 36SocketType -- type object for socket objects 37error -- exception raised for I/O errors 38has_ipv6 -- boolean value indicating if IPv6 is supported 39 40IntEnum constants: 41 42AF_INET, AF_UNIX -- socket domains (first argument to socket() call) 43SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) 44 45Integer constants: 46 47Many other constants may be defined; these may be used in calls to 48the setsockopt() and getsockopt() methods. 49""" 50 51import _socket 52from _socket import * 53 54import os, sys, io, selectors 55from enum import IntEnum, IntFlag 56 57try: 58 import errno 59except ImportError: 60 errno = None 61EBADF = getattr(errno, 'EBADF', 9) 62EAGAIN = getattr(errno, 'EAGAIN', 11) 63EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11) 64 65__all__ = ["fromfd", "getfqdn", "create_connection", "create_server", 66 "has_dualstack_ipv6", "AddressFamily", "SocketKind"] 67__all__.extend(os._get_exports_list(_socket)) 68 69# Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for 70# nicer string representations. 71# Note that _socket only knows about the integer values. The public interface 72# in this module understands the enums and translates them back from integers 73# where needed (e.g. .family property of a socket object). 74 75IntEnum._convert_( 76 'AddressFamily', 77 __name__, 78 lambda C: C.isupper() and C.startswith('AF_')) 79 80IntEnum._convert_( 81 'SocketKind', 82 __name__, 83 lambda C: C.isupper() and C.startswith('SOCK_')) 84 85IntFlag._convert_( 86 'MsgFlag', 87 __name__, 88 lambda C: C.isupper() and C.startswith('MSG_')) 89 90IntFlag._convert_( 91 'AddressInfo', 92 __name__, 93 lambda C: C.isupper() and C.startswith('AI_')) 94 95_LOCALHOST = '127.0.0.1' 96_LOCALHOST_V6 = '::1' 97 98 99def _intenum_converter(value, enum_klass): 100 """Convert a numeric family value to an IntEnum member. 101 102 If it's not a known member, return the numeric value itself. 103 """ 104 try: 105 return enum_klass(value) 106 except ValueError: 107 return value 108 109 110# WSA error codes 111if sys.platform.lower().startswith("win"): 112 errorTab = {} 113 errorTab[6] = "Specified event object handle is invalid." 114 errorTab[8] = "Insufficient memory available." 115 errorTab[87] = "One or more parameters are invalid." 116 errorTab[995] = "Overlapped operation aborted." 117 errorTab[996] = "Overlapped I/O event object not in signaled state." 118 errorTab[997] = "Overlapped operation will complete later." 119 errorTab[10004] = "The operation was interrupted." 120 errorTab[10009] = "A bad file handle was passed." 121 errorTab[10013] = "Permission denied." 122 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT 123 errorTab[10022] = "An invalid operation was attempted." 124 errorTab[10024] = "Too many open files." 125 errorTab[10035] = "The socket operation would block." 126 errorTab[10036] = "A blocking operation is already in progress." 127 errorTab[10037] = "Operation already in progress." 128 errorTab[10038] = "Socket operation on nonsocket." 129 errorTab[10039] = "Destination address required." 130 errorTab[10040] = "Message too long." 131 errorTab[10041] = "Protocol wrong type for socket." 132 errorTab[10042] = "Bad protocol option." 133 errorTab[10043] = "Protocol not supported." 134 errorTab[10044] = "Socket type not supported." 135 errorTab[10045] = "Operation not supported." 136 errorTab[10046] = "Protocol family not supported." 137 errorTab[10047] = "Address family not supported by protocol family." 138 errorTab[10048] = "The network address is in use." 139 errorTab[10049] = "Cannot assign requested address." 140 errorTab[10050] = "Network is down." 141 errorTab[10051] = "Network is unreachable." 142 errorTab[10052] = "Network dropped connection on reset." 143 errorTab[10053] = "Software caused connection abort." 144 errorTab[10054] = "The connection has been reset." 145 errorTab[10055] = "No buffer space available." 146 errorTab[10056] = "Socket is already connected." 147 errorTab[10057] = "Socket is not connected." 148 errorTab[10058] = "The network has been shut down." 149 errorTab[10059] = "Too many references." 150 errorTab[10060] = "The operation timed out." 151 errorTab[10061] = "Connection refused." 152 errorTab[10062] = "Cannot translate name." 153 errorTab[10063] = "The name is too long." 154 errorTab[10064] = "The host is down." 155 errorTab[10065] = "The host is unreachable." 156 errorTab[10066] = "Directory not empty." 157 errorTab[10067] = "Too many processes." 158 errorTab[10068] = "User quota exceeded." 159 errorTab[10069] = "Disk quota exceeded." 160 errorTab[10070] = "Stale file handle reference." 161 errorTab[10071] = "Item is remote." 162 errorTab[10091] = "Network subsystem is unavailable." 163 errorTab[10092] = "Winsock.dll version out of range." 164 errorTab[10093] = "Successful WSAStartup not yet performed." 165 errorTab[10101] = "Graceful shutdown in progress." 166 errorTab[10102] = "No more results from WSALookupServiceNext." 167 errorTab[10103] = "Call has been canceled." 168 errorTab[10104] = "Procedure call table is invalid." 169 errorTab[10105] = "Service provider is invalid." 170 errorTab[10106] = "Service provider failed to initialize." 171 errorTab[10107] = "System call failure." 172 errorTab[10108] = "Service not found." 173 errorTab[10109] = "Class type not found." 174 errorTab[10110] = "No more results from WSALookupServiceNext." 175 errorTab[10111] = "Call was canceled." 176 errorTab[10112] = "Database query was refused." 177 errorTab[11001] = "Host not found." 178 errorTab[11002] = "Nonauthoritative host not found." 179 errorTab[11003] = "This is a nonrecoverable error." 180 errorTab[11004] = "Valid name, no data record requested type." 181 errorTab[11005] = "QoS receivers." 182 errorTab[11006] = "QoS senders." 183 errorTab[11007] = "No QoS senders." 184 errorTab[11008] = "QoS no receivers." 185 errorTab[11009] = "QoS request confirmed." 186 errorTab[11010] = "QoS admission error." 187 errorTab[11011] = "QoS policy failure." 188 errorTab[11012] = "QoS bad style." 189 errorTab[11013] = "QoS bad object." 190 errorTab[11014] = "QoS traffic control error." 191 errorTab[11015] = "QoS generic error." 192 errorTab[11016] = "QoS service type error." 193 errorTab[11017] = "QoS flowspec error." 194 errorTab[11018] = "Invalid QoS provider buffer." 195 errorTab[11019] = "Invalid QoS filter style." 196 errorTab[11020] = "Invalid QoS filter style." 197 errorTab[11021] = "Incorrect QoS filter count." 198 errorTab[11022] = "Invalid QoS object length." 199 errorTab[11023] = "Incorrect QoS flow count." 200 errorTab[11024] = "Unrecognized QoS object." 201 errorTab[11025] = "Invalid QoS policy object." 202 errorTab[11026] = "Invalid QoS flow descriptor." 203 errorTab[11027] = "Invalid QoS provider-specific flowspec." 204 errorTab[11028] = "Invalid QoS provider-specific filterspec." 205 errorTab[11029] = "Invalid QoS shape discard mode object." 206 errorTab[11030] = "Invalid QoS shaping rate object." 207 errorTab[11031] = "Reserved policy QoS element type." 208 __all__.append("errorTab") 209 210 211class _GiveupOnSendfile(Exception): pass 212 213 214class socket(_socket.socket): 215 216 """A subclass of _socket.socket adding the makefile() method.""" 217 218 __slots__ = ["__weakref__", "_io_refs", "_closed"] 219 220 def __init__(self, family=-1, type=-1, proto=-1, fileno=None): 221 # For user code address family and type values are IntEnum members, but 222 # for the underlying _socket.socket they're just integers. The 223 # constructor of _socket.socket converts the given argument to an 224 # integer automatically. 225 if fileno is None: 226 if family == -1: 227 family = AF_INET 228 if type == -1: 229 type = SOCK_STREAM 230 if proto == -1: 231 proto = 0 232 _socket.socket.__init__(self, family, type, proto, fileno) 233 self._io_refs = 0 234 self._closed = False 235 236 def __enter__(self): 237 return self 238 239 def __exit__(self, *args): 240 if not self._closed: 241 self.close() 242 243 def __repr__(self): 244 """Wrap __repr__() to reveal the real class name and socket 245 address(es). 246 """ 247 closed = getattr(self, '_closed', False) 248 s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \ 249 % (self.__class__.__module__, 250 self.__class__.__qualname__, 251 " [closed]" if closed else "", 252 self.fileno(), 253 self.family, 254 self.type, 255 self.proto) 256 if not closed: 257 # getsockname and getpeername may not be available on WASI. 258 try: 259 laddr = self.getsockname() 260 if laddr: 261 s += ", laddr=%s" % str(laddr) 262 except (error, AttributeError): 263 pass 264 try: 265 raddr = self.getpeername() 266 if raddr: 267 s += ", raddr=%s" % str(raddr) 268 except (error, AttributeError): 269 pass 270 s += '>' 271 return s 272 273 def __getstate__(self): 274 raise TypeError(f"cannot pickle {self.__class__.__name__!r} object") 275 276 def dup(self): 277 """dup() -> socket object 278 279 Duplicate the socket. Return a new socket object connected to the same 280 system resource. The new socket is non-inheritable. 281 """ 282 fd = dup(self.fileno()) 283 sock = self.__class__(self.family, self.type, self.proto, fileno=fd) 284 sock.settimeout(self.gettimeout()) 285 return sock 286 287 def accept(self): 288 """accept() -> (socket object, address info) 289 290 Wait for an incoming connection. Return a new socket 291 representing the connection, and the address of the client. 292 For IP sockets, the address info is a pair (hostaddr, port). 293 """ 294 fd, addr = self._accept() 295 sock = socket(self.family, self.type, self.proto, fileno=fd) 296 # Issue #7995: if no default timeout is set and the listening 297 # socket had a (non-zero) timeout, force the new socket in blocking 298 # mode to override platform-specific socket flags inheritance. 299 if getdefaulttimeout() is None and self.gettimeout(): 300 sock.setblocking(True) 301 return sock, addr 302 303 def makefile(self, mode="r", buffering=None, *, 304 encoding=None, errors=None, newline=None): 305 """makefile(...) -> an I/O stream connected to the socket 306 307 The arguments are as for io.open() after the filename, except the only 308 supported mode values are 'r' (default), 'w' and 'b'. 309 """ 310 # XXX refactor to share code? 311 if not set(mode) <= {"r", "w", "b"}: 312 raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,)) 313 writing = "w" in mode 314 reading = "r" in mode or not writing 315 assert reading or writing 316 binary = "b" in mode 317 rawmode = "" 318 if reading: 319 rawmode += "r" 320 if writing: 321 rawmode += "w" 322 raw = SocketIO(self, rawmode) 323 self._io_refs += 1 324 if buffering is None: 325 buffering = -1 326 if buffering < 0: 327 buffering = io.DEFAULT_BUFFER_SIZE 328 if buffering == 0: 329 if not binary: 330 raise ValueError("unbuffered streams must be binary") 331 return raw 332 if reading and writing: 333 buffer = io.BufferedRWPair(raw, raw, buffering) 334 elif reading: 335 buffer = io.BufferedReader(raw, buffering) 336 else: 337 assert writing 338 buffer = io.BufferedWriter(raw, buffering) 339 if binary: 340 return buffer 341 encoding = io.text_encoding(encoding) 342 text = io.TextIOWrapper(buffer, encoding, errors, newline) 343 text.mode = mode 344 return text 345 346 if hasattr(os, 'sendfile'): 347 348 def _sendfile_use_sendfile(self, file, offset=0, count=None): 349 self._check_sendfile_params(file, offset, count) 350 sockno = self.fileno() 351 try: 352 fileno = file.fileno() 353 except (AttributeError, io.UnsupportedOperation) as err: 354 raise _GiveupOnSendfile(err) # not a regular file 355 try: 356 fsize = os.fstat(fileno).st_size 357 except OSError as err: 358 raise _GiveupOnSendfile(err) # not a regular file 359 if not fsize: 360 return 0 # empty file 361 # Truncate to 1GiB to avoid OverflowError, see bpo-38319. 362 blocksize = min(count or fsize, 2 ** 30) 363 timeout = self.gettimeout() 364 if timeout == 0: 365 raise ValueError("non-blocking sockets are not supported") 366 # poll/select have the advantage of not requiring any 367 # extra file descriptor, contrarily to epoll/kqueue 368 # (also, they require a single syscall). 369 if hasattr(selectors, 'PollSelector'): 370 selector = selectors.PollSelector() 371 else: 372 selector = selectors.SelectSelector() 373 selector.register(sockno, selectors.EVENT_WRITE) 374 375 total_sent = 0 376 # localize variable access to minimize overhead 377 selector_select = selector.select 378 os_sendfile = os.sendfile 379 try: 380 while True: 381 if timeout and not selector_select(timeout): 382 raise TimeoutError('timed out') 383 if count: 384 blocksize = count - total_sent 385 if blocksize <= 0: 386 break 387 try: 388 sent = os_sendfile(sockno, fileno, offset, blocksize) 389 except BlockingIOError: 390 if not timeout: 391 # Block until the socket is ready to send some 392 # data; avoids hogging CPU resources. 393 selector_select() 394 continue 395 except OSError as err: 396 if total_sent == 0: 397 # We can get here for different reasons, the main 398 # one being 'file' is not a regular mmap(2)-like 399 # file, in which case we'll fall back on using 400 # plain send(). 401 raise _GiveupOnSendfile(err) 402 raise err from None 403 else: 404 if sent == 0: 405 break # EOF 406 offset += sent 407 total_sent += sent 408 return total_sent 409 finally: 410 if total_sent > 0 and hasattr(file, 'seek'): 411 file.seek(offset) 412 else: 413 def _sendfile_use_sendfile(self, file, offset=0, count=None): 414 raise _GiveupOnSendfile( 415 "os.sendfile() not available on this platform") 416 417 def _sendfile_use_send(self, file, offset=0, count=None): 418 self._check_sendfile_params(file, offset, count) 419 if self.gettimeout() == 0: 420 raise ValueError("non-blocking sockets are not supported") 421 if offset: 422 file.seek(offset) 423 blocksize = min(count, 8192) if count else 8192 424 total_sent = 0 425 # localize variable access to minimize overhead 426 file_read = file.read 427 sock_send = self.send 428 try: 429 while True: 430 if count: 431 blocksize = min(count - total_sent, blocksize) 432 if blocksize <= 0: 433 break 434 data = memoryview(file_read(blocksize)) 435 if not data: 436 break # EOF 437 while True: 438 try: 439 sent = sock_send(data) 440 except BlockingIOError: 441 continue 442 else: 443 total_sent += sent 444 if sent < len(data): 445 data = data[sent:] 446 else: 447 break 448 return total_sent 449 finally: 450 if total_sent > 0 and hasattr(file, 'seek'): 451 file.seek(offset + total_sent) 452 453 def _check_sendfile_params(self, file, offset, count): 454 if 'b' not in getattr(file, 'mode', 'b'): 455 raise ValueError("file should be opened in binary mode") 456 if not self.type & SOCK_STREAM: 457 raise ValueError("only SOCK_STREAM type sockets are supported") 458 if count is not None: 459 if not isinstance(count, int): 460 raise TypeError( 461 "count must be a positive integer (got {!r})".format(count)) 462 if count <= 0: 463 raise ValueError( 464 "count must be a positive integer (got {!r})".format(count)) 465 466 def sendfile(self, file, offset=0, count=None): 467 """sendfile(file[, offset[, count]]) -> sent 468 469 Send a file until EOF is reached by using high-performance 470 os.sendfile() and return the total number of bytes which 471 were sent. 472 *file* must be a regular file object opened in binary mode. 473 If os.sendfile() is not available (e.g. Windows) or file is 474 not a regular file socket.send() will be used instead. 475 *offset* tells from where to start reading the file. 476 If specified, *count* is the total number of bytes to transmit 477 as opposed to sending the file until EOF is reached. 478 File position is updated on return or also in case of error in 479 which case file.tell() can be used to figure out the number of 480 bytes which were sent. 481 The socket must be of SOCK_STREAM type. 482 Non-blocking sockets are not supported. 483 """ 484 try: 485 return self._sendfile_use_sendfile(file, offset, count) 486 except _GiveupOnSendfile: 487 return self._sendfile_use_send(file, offset, count) 488 489 def _decref_socketios(self): 490 if self._io_refs > 0: 491 self._io_refs -= 1 492 if self._closed: 493 self.close() 494 495 def _real_close(self, _ss=_socket.socket): 496 # This function should not reference any globals. See issue #808164. 497 _ss.close(self) 498 499 def close(self): 500 # This function should not reference any globals. See issue #808164. 501 self._closed = True 502 if self._io_refs <= 0: 503 self._real_close() 504 505 def detach(self): 506 """detach() -> file descriptor 507 508 Close the socket object without closing the underlying file descriptor. 509 The object cannot be used after this call, but the file descriptor 510 can be reused for other purposes. The file descriptor is returned. 511 """ 512 self._closed = True 513 return super().detach() 514 515 @property 516 def family(self): 517 """Read-only access to the address family for this socket. 518 """ 519 return _intenum_converter(super().family, AddressFamily) 520 521 @property 522 def type(self): 523 """Read-only access to the socket type. 524 """ 525 return _intenum_converter(super().type, SocketKind) 526 527 if os.name == 'nt': 528 def get_inheritable(self): 529 return os.get_handle_inheritable(self.fileno()) 530 def set_inheritable(self, inheritable): 531 os.set_handle_inheritable(self.fileno(), inheritable) 532 else: 533 def get_inheritable(self): 534 return os.get_inheritable(self.fileno()) 535 def set_inheritable(self, inheritable): 536 os.set_inheritable(self.fileno(), inheritable) 537 get_inheritable.__doc__ = "Get the inheritable flag of the socket" 538 set_inheritable.__doc__ = "Set the inheritable flag of the socket" 539 540def fromfd(fd, family, type, proto=0): 541 """ fromfd(fd, family, type[, proto]) -> socket object 542 543 Create a socket object from a duplicate of the given file 544 descriptor. The remaining arguments are the same as for socket(). 545 """ 546 nfd = dup(fd) 547 return socket(family, type, proto, nfd) 548 549if hasattr(_socket.socket, "sendmsg"): 550 import array 551 552 def send_fds(sock, buffers, fds, flags=0, address=None): 553 """ send_fds(sock, buffers, fds[, flags[, address]]) -> integer 554 555 Send the list of file descriptors fds over an AF_UNIX socket. 556 """ 557 return sock.sendmsg(buffers, [(_socket.SOL_SOCKET, 558 _socket.SCM_RIGHTS, array.array("i", fds))]) 559 __all__.append("send_fds") 560 561if hasattr(_socket.socket, "recvmsg"): 562 import array 563 564 def recv_fds(sock, bufsize, maxfds, flags=0): 565 """ recv_fds(sock, bufsize, maxfds[, flags]) -> (data, list of file 566 descriptors, msg_flags, address) 567 568 Receive up to maxfds file descriptors returning the message 569 data and a list containing the descriptors. 570 """ 571 # Array of ints 572 fds = array.array("i") 573 msg, ancdata, flags, addr = sock.recvmsg(bufsize, 574 _socket.CMSG_LEN(maxfds * fds.itemsize)) 575 for cmsg_level, cmsg_type, cmsg_data in ancdata: 576 if (cmsg_level == _socket.SOL_SOCKET and cmsg_type == _socket.SCM_RIGHTS): 577 fds.frombytes(cmsg_data[: 578 len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) 579 580 return msg, list(fds), flags, addr 581 __all__.append("recv_fds") 582 583if hasattr(_socket.socket, "share"): 584 def fromshare(info): 585 """ fromshare(info) -> socket object 586 587 Create a socket object from the bytes object returned by 588 socket.share(pid). 589 """ 590 return socket(0, 0, 0, info) 591 __all__.append("fromshare") 592 593# Origin: https://gist.github.com/4325783, by Geert Jansen. Public domain. 594# This is used if _socket doesn't natively provide socketpair. It's 595# always defined so that it can be patched in for testing purposes. 596def _fallback_socketpair(family=AF_INET, type=SOCK_STREAM, proto=0): 597 if family == AF_INET: 598 host = _LOCALHOST 599 elif family == AF_INET6: 600 host = _LOCALHOST_V6 601 else: 602 raise ValueError("Only AF_INET and AF_INET6 socket address families " 603 "are supported") 604 if type != SOCK_STREAM: 605 raise ValueError("Only SOCK_STREAM socket type is supported") 606 if proto != 0: 607 raise ValueError("Only protocol zero is supported") 608 609 # We create a connected TCP socket. Note the trick with 610 # setblocking(False) that prevents us from having to create a thread. 611 lsock = socket(family, type, proto) 612 try: 613 lsock.bind((host, 0)) 614 lsock.listen() 615 # On IPv6, ignore flow_info and scope_id 616 addr, port = lsock.getsockname()[:2] 617 csock = socket(family, type, proto) 618 try: 619 csock.setblocking(False) 620 try: 621 csock.connect((addr, port)) 622 except (BlockingIOError, InterruptedError): 623 pass 624 csock.setblocking(True) 625 ssock, _ = lsock.accept() 626 except: 627 csock.close() 628 raise 629 finally: 630 lsock.close() 631 632 # Authenticating avoids using a connection from something else 633 # able to connect to {host}:{port} instead of us. 634 # We expect only AF_INET and AF_INET6 families. 635 try: 636 if ( 637 ssock.getsockname() != csock.getpeername() 638 or csock.getsockname() != ssock.getpeername() 639 ): 640 raise ConnectionError("Unexpected peer connection") 641 except: 642 # getsockname() and getpeername() can fail 643 # if either socket isn't connected. 644 ssock.close() 645 csock.close() 646 raise 647 return (ssock, csock) 648 649if hasattr(_socket, "socketpair"): 650 def socketpair(family=None, type=SOCK_STREAM, proto=0): 651 if family is None: 652 try: 653 family = AF_UNIX 654 except NameError: 655 family = AF_INET 656 a, b = _socket.socketpair(family, type, proto) 657 a = socket(family, type, proto, a.detach()) 658 b = socket(family, type, proto, b.detach()) 659 return a, b 660 661else: 662 socketpair = _fallback_socketpair 663 __all__.append("socketpair") 664 665socketpair.__doc__ = """socketpair([family[, type[, proto]]]) -> (socket object, socket object) 666Create a pair of socket objects from the sockets returned by the platform 667socketpair() function. 668The arguments are the same as for socket() except the default family is AF_UNIX 669if defined on the platform; otherwise, the default is AF_INET. 670""" 671 672_blocking_errnos = { EAGAIN, EWOULDBLOCK } 673 674class SocketIO(io.RawIOBase): 675 676 """Raw I/O implementation for stream sockets. 677 678 This class supports the makefile() method on sockets. It provides 679 the raw I/O interface on top of a socket object. 680 """ 681 682 # One might wonder why not let FileIO do the job instead. There are two 683 # main reasons why FileIO is not adapted: 684 # - it wouldn't work under Windows (where you can't used read() and 685 # write() on a socket handle) 686 # - it wouldn't work with socket timeouts (FileIO would ignore the 687 # timeout and consider the socket non-blocking) 688 689 # XXX More docs 690 691 def __init__(self, sock, mode): 692 if mode not in ("r", "w", "rw", "rb", "wb", "rwb"): 693 raise ValueError("invalid mode: %r" % mode) 694 io.RawIOBase.__init__(self) 695 self._sock = sock 696 if "b" not in mode: 697 mode += "b" 698 self._mode = mode 699 self._reading = "r" in mode 700 self._writing = "w" in mode 701 self._timeout_occurred = False 702 703 def readinto(self, b): 704 """Read up to len(b) bytes into the writable buffer *b* and return 705 the number of bytes read. If the socket is non-blocking and no bytes 706 are available, None is returned. 707 708 If *b* is non-empty, a 0 return value indicates that the connection 709 was shutdown at the other end. 710 """ 711 self._checkClosed() 712 self._checkReadable() 713 if self._timeout_occurred: 714 raise OSError("cannot read from timed out object") 715 while True: 716 try: 717 return self._sock.recv_into(b) 718 except timeout: 719 self._timeout_occurred = True 720 raise 721 except error as e: 722 if e.errno in _blocking_errnos: 723 return None 724 raise 725 726 def write(self, b): 727 """Write the given bytes or bytearray object *b* to the socket 728 and return the number of bytes written. This can be less than 729 len(b) if not all data could be written. If the socket is 730 non-blocking and no bytes could be written None is returned. 731 """ 732 self._checkClosed() 733 self._checkWritable() 734 try: 735 return self._sock.send(b) 736 except error as e: 737 # XXX what about EINTR? 738 if e.errno in _blocking_errnos: 739 return None 740 raise 741 742 def readable(self): 743 """True if the SocketIO is open for reading. 744 """ 745 if self.closed: 746 raise ValueError("I/O operation on closed socket.") 747 return self._reading 748 749 def writable(self): 750 """True if the SocketIO is open for writing. 751 """ 752 if self.closed: 753 raise ValueError("I/O operation on closed socket.") 754 return self._writing 755 756 def seekable(self): 757 """True if the SocketIO is open for seeking. 758 """ 759 if self.closed: 760 raise ValueError("I/O operation on closed socket.") 761 return super().seekable() 762 763 def fileno(self): 764 """Return the file descriptor of the underlying socket. 765 """ 766 self._checkClosed() 767 return self._sock.fileno() 768 769 @property 770 def name(self): 771 if not self.closed: 772 return self.fileno() 773 else: 774 return -1 775 776 @property 777 def mode(self): 778 return self._mode 779 780 def close(self): 781 """Close the SocketIO object. This doesn't close the underlying 782 socket, except if all references to it have disappeared. 783 """ 784 if self.closed: 785 return 786 io.RawIOBase.close(self) 787 self._sock._decref_socketios() 788 self._sock = None 789 790 791def getfqdn(name=''): 792 """Get fully qualified domain name from name. 793 794 An empty argument is interpreted as meaning the local host. 795 796 First the hostname returned by gethostbyaddr() is checked, then 797 possibly existing aliases. In case no FQDN is available and `name` 798 was given, it is returned unchanged. If `name` was empty, '0.0.0.0' or '::', 799 hostname from gethostname() is returned. 800 """ 801 name = name.strip() 802 if not name or name in ('0.0.0.0', '::'): 803 name = gethostname() 804 try: 805 hostname, aliases, ipaddrs = gethostbyaddr(name) 806 except error: 807 pass 808 else: 809 aliases.insert(0, hostname) 810 for name in aliases: 811 if '.' in name: 812 break 813 else: 814 name = hostname 815 return name 816 817 818_GLOBAL_DEFAULT_TIMEOUT = object() 819 820def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, 821 source_address=None, *, all_errors=False): 822 """Connect to *address* and return the socket object. 823 824 Convenience function. Connect to *address* (a 2-tuple ``(host, 825 port)``) and return the socket object. Passing the optional 826 *timeout* parameter will set the timeout on the socket instance 827 before attempting to connect. If no *timeout* is supplied, the 828 global default timeout setting returned by :func:`getdefaulttimeout` 829 is used. If *source_address* is set it must be a tuple of (host, port) 830 for the socket to bind as a source address before making the connection. 831 A host of '' or port 0 tells the OS to use the default. When a connection 832 cannot be created, raises the last error if *all_errors* is False, 833 and an ExceptionGroup of all errors if *all_errors* is True. 834 """ 835 836 host, port = address 837 exceptions = [] 838 for res in getaddrinfo(host, port, 0, SOCK_STREAM): 839 af, socktype, proto, canonname, sa = res 840 sock = None 841 try: 842 sock = socket(af, socktype, proto) 843 if timeout is not _GLOBAL_DEFAULT_TIMEOUT: 844 sock.settimeout(timeout) 845 if source_address: 846 sock.bind(source_address) 847 sock.connect(sa) 848 # Break explicitly a reference cycle 849 exceptions.clear() 850 return sock 851 852 except error as exc: 853 if not all_errors: 854 exceptions.clear() # raise only the last error 855 exceptions.append(exc) 856 if sock is not None: 857 sock.close() 858 859 if len(exceptions): 860 try: 861 if not all_errors: 862 raise exceptions[0] 863 raise ExceptionGroup("create_connection failed", exceptions) 864 finally: 865 # Break explicitly a reference cycle 866 exceptions.clear() 867 else: 868 raise error("getaddrinfo returns an empty list") 869 870 871def has_dualstack_ipv6(): 872 """Return True if the platform supports creating a SOCK_STREAM socket 873 which can handle both AF_INET and AF_INET6 (IPv4 / IPv6) connections. 874 """ 875 if not has_ipv6 \ 876 or not hasattr(_socket, 'IPPROTO_IPV6') \ 877 or not hasattr(_socket, 'IPV6_V6ONLY'): 878 return False 879 try: 880 with socket(AF_INET6, SOCK_STREAM) as sock: 881 sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 0) 882 return True 883 except error: 884 return False 885 886 887def create_server(address, *, family=AF_INET, backlog=None, reuse_port=False, 888 dualstack_ipv6=False): 889 """Convenience function which creates a SOCK_STREAM type socket 890 bound to *address* (a 2-tuple (host, port)) and return the socket 891 object. 892 893 *family* should be either AF_INET or AF_INET6. 894 *backlog* is the queue size passed to socket.listen(). 895 *reuse_port* dictates whether to use the SO_REUSEPORT socket option. 896 *dualstack_ipv6*: if true and the platform supports it, it will 897 create an AF_INET6 socket able to accept both IPv4 or IPv6 898 connections. When false it will explicitly disable this option on 899 platforms that enable it by default (e.g. Linux). 900 901 >>> with create_server(('', 8000)) as server: 902 ... while True: 903 ... conn, addr = server.accept() 904 ... # handle new connection 905 """ 906 if reuse_port and not hasattr(_socket, "SO_REUSEPORT"): 907 raise ValueError("SO_REUSEPORT not supported on this platform") 908 if dualstack_ipv6: 909 if not has_dualstack_ipv6(): 910 raise ValueError("dualstack_ipv6 not supported on this platform") 911 if family != AF_INET6: 912 raise ValueError("dualstack_ipv6 requires AF_INET6 family") 913 sock = socket(family, SOCK_STREAM) 914 try: 915 # Note about Windows. We don't set SO_REUSEADDR because: 916 # 1) It's unnecessary: bind() will succeed even in case of a 917 # previous closed socket on the same address and still in 918 # TIME_WAIT state. 919 # 2) If set, another socket is free to bind() on the same 920 # address, effectively preventing this one from accepting 921 # connections. Also, it may set the process in a state where 922 # it'll no longer respond to any signals or graceful kills. 923 # See: https://learn.microsoft.com/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse 924 if os.name not in ('nt', 'cygwin') and \ 925 hasattr(_socket, 'SO_REUSEADDR'): 926 try: 927 sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 928 except error: 929 # Fail later on bind(), for platforms which may not 930 # support this option. 931 pass 932 if reuse_port: 933 sock.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1) 934 if has_ipv6 and family == AF_INET6: 935 if dualstack_ipv6: 936 sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 0) 937 elif hasattr(_socket, "IPV6_V6ONLY") and \ 938 hasattr(_socket, "IPPROTO_IPV6"): 939 sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 1) 940 try: 941 sock.bind(address) 942 except error as err: 943 msg = '%s (while attempting to bind on address %r)' % \ 944 (err.strerror, address) 945 raise error(err.errno, msg) from None 946 if backlog is None: 947 sock.listen() 948 else: 949 sock.listen(backlog) 950 return sock 951 except error: 952 sock.close() 953 raise 954 955 956def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0): 957 """Resolve host and port into list of address info entries. 958 959 Translate the host/port argument into a sequence of 5-tuples that contain 960 all the necessary arguments for creating a socket connected to that service. 961 host is a domain name, a string representation of an IPv4/v6 address or 962 None. port is a string service name such as 'http', a numeric port number or 963 None. By passing None as the value of host and port, you can pass NULL to 964 the underlying C API. 965 966 The family, type and proto arguments can be optionally specified in order to 967 narrow the list of addresses returned. Passing zero as a value for each of 968 these arguments selects the full range of results. 969 """ 970 # We override this function since we want to translate the numeric family 971 # and socket type values to enum constants. 972 addrlist = [] 973 for res in _socket.getaddrinfo(host, port, family, type, proto, flags): 974 af, socktype, proto, canonname, sa = res 975 addrlist.append((_intenum_converter(af, AddressFamily), 976 _intenum_converter(socktype, SocketKind), 977 proto, canonname, sa)) 978 return addrlist 979