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