1 # Wrapper module for _socket, providing some additional facilities
2 # implemented in Python.
3
4 """\
5 This module provides socket operations and some related functions.
6 On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
7 On other systems, it only supports IP. Functions specific for a
8 socket are available as methods of the socket object.
9
10 Functions:
11
12 socket() -- create a new socket object
13 socketpair() -- create a pair of new socket objects [*]
14 fromfd() -- create a socket object from an open file descriptor [*]
15 send_fds() -- Send file descriptor to the socket.
16 recv_fds() -- Receive file descriptors from the socket.
17 fromshare() -- create a socket object from data received from socket.share() [*]
18 gethostname() -- return the current hostname
19 gethostbyname() -- map a hostname to its IP number
20 gethostbyaddr() -- map an IP number or hostname to DNS info
21 getservbyname() -- map a service name and a protocol name to a port number
22 getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
23 ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
24 htons(), htonl() -- convert 16, 32 bit int from host to network byte order
25 inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
26 inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
27 socket.getdefaulttimeout() -- get the default timeout value
28 socket.setdefaulttimeout() -- set the default timeout value
29 create_connection() -- connects to an address, with an optional timeout and
30 optional source address.
31
32 [*] not available on all platforms!
33
34 Special objects:
35
36 SocketType -- type object for socket objects
37 error -- exception raised for I/O errors
38 has_ipv6 -- boolean value indicating if IPv6 is supported
39
40 IntEnum constants:
41
42 AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
43 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
44
45 Integer constants:
46
47 Many other constants may be defined; these may be used in calls to
48 the setsockopt() and getsockopt() methods.
49 """
50
51 import _socket
52 from _socket import *
53
54 import os, sys, io, selectors
55 from enum import IntEnum, IntFlag
56
57 try:
58 import errno
59 except ImportError:
60 errno = None
61 EBADF = getattr(errno, 'EBADF', 9)
62 EAGAIN = getattr(errno, 'EAGAIN', 11)
63 EWOULDBLOCK = 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
75 IntEnum._convert_(
76 'AddressFamily',
77 __name__,
78 lambda C: C.isupper() and C.startswith('AF_'))
79
80 IntEnum._convert_(
81 'SocketKind',
82 __name__,
83 lambda C: C.isupper() and C.startswith('SOCK_'))
84
85 IntFlag._convert_(
86 'MsgFlag',
87 __name__,
88 lambda C: C.isupper() and C.startswith('MSG_'))
89
90 IntFlag._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
99 def _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
111 if 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
211 class ESC[4;38;5;81m_GiveupOnSendfile(ESC[4;38;5;149mException): pass
212
213
214 class ESC[4;38;5;81msocket(ESC[4;38;5;149m_socketESC[4;38;5;149m.ESC[4;38;5;149msocket):
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
540 def 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
549 if 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
561 if 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
583 if 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 if hasattr(_socket, "socketpair"):
594
595 def socketpair(family=None, type=SOCK_STREAM, proto=0):
596 """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
597
598 Create a pair of socket objects from the sockets returned by the platform
599 socketpair() function.
600 The arguments are the same as for socket() except the default family is
601 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
602 """
603 if family is None:
604 try:
605 family = AF_UNIX
606 except NameError:
607 family = AF_INET
608 a, b = _socket.socketpair(family, type, proto)
609 a = socket(family, type, proto, a.detach())
610 b = socket(family, type, proto, b.detach())
611 return a, b
612
613 else:
614
615 # Origin: https://gist.github.com/4325783, by Geert Jansen. Public domain.
616 def socketpair(family=AF_INET, type=SOCK_STREAM, proto=0):
617 if family == AF_INET:
618 host = _LOCALHOST
619 elif family == AF_INET6:
620 host = _LOCALHOST_V6
621 else:
622 raise ValueError("Only AF_INET and AF_INET6 socket address families "
623 "are supported")
624 if type != SOCK_STREAM:
625 raise ValueError("Only SOCK_STREAM socket type is supported")
626 if proto != 0:
627 raise ValueError("Only protocol zero is supported")
628
629 # We create a connected TCP socket. Note the trick with
630 # setblocking(False) that prevents us from having to create a thread.
631 lsock = socket(family, type, proto)
632 try:
633 lsock.bind((host, 0))
634 lsock.listen()
635 # On IPv6, ignore flow_info and scope_id
636 addr, port = lsock.getsockname()[:2]
637 csock = socket(family, type, proto)
638 try:
639 csock.setblocking(False)
640 try:
641 csock.connect((addr, port))
642 except (BlockingIOError, InterruptedError):
643 pass
644 csock.setblocking(True)
645 ssock, _ = lsock.accept()
646 except:
647 csock.close()
648 raise
649 finally:
650 lsock.close()
651 return (ssock, csock)
652 __all__.append("socketpair")
653
654 socketpair.__doc__ = """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
655 Create a pair of socket objects from the sockets returned by the platform
656 socketpair() function.
657 The arguments are the same as for socket() except the default family is AF_UNIX
658 if defined on the platform; otherwise, the default is AF_INET.
659 """
660
661 _blocking_errnos = { EAGAIN, EWOULDBLOCK }
662
663 class ESC[4;38;5;81mSocketIO(ESC[4;38;5;149mioESC[4;38;5;149m.ESC[4;38;5;149mRawIOBase):
664
665 """Raw I/O implementation for stream sockets.
666
667 This class supports the makefile() method on sockets. It provides
668 the raw I/O interface on top of a socket object.
669 """
670
671 # One might wonder why not let FileIO do the job instead. There are two
672 # main reasons why FileIO is not adapted:
673 # - it wouldn't work under Windows (where you can't used read() and
674 # write() on a socket handle)
675 # - it wouldn't work with socket timeouts (FileIO would ignore the
676 # timeout and consider the socket non-blocking)
677
678 # XXX More docs
679
680 def __init__(self, sock, mode):
681 if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
682 raise ValueError("invalid mode: %r" % mode)
683 io.RawIOBase.__init__(self)
684 self._sock = sock
685 if "b" not in mode:
686 mode += "b"
687 self._mode = mode
688 self._reading = "r" in mode
689 self._writing = "w" in mode
690 self._timeout_occurred = False
691
692 def readinto(self, b):
693 """Read up to len(b) bytes into the writable buffer *b* and return
694 the number of bytes read. If the socket is non-blocking and no bytes
695 are available, None is returned.
696
697 If *b* is non-empty, a 0 return value indicates that the connection
698 was shutdown at the other end.
699 """
700 self._checkClosed()
701 self._checkReadable()
702 if self._timeout_occurred:
703 raise OSError("cannot read from timed out object")
704 while True:
705 try:
706 return self._sock.recv_into(b)
707 except timeout:
708 self._timeout_occurred = True
709 raise
710 except error as e:
711 if e.errno in _blocking_errnos:
712 return None
713 raise
714
715 def write(self, b):
716 """Write the given bytes or bytearray object *b* to the socket
717 and return the number of bytes written. This can be less than
718 len(b) if not all data could be written. If the socket is
719 non-blocking and no bytes could be written None is returned.
720 """
721 self._checkClosed()
722 self._checkWritable()
723 try:
724 return self._sock.send(b)
725 except error as e:
726 # XXX what about EINTR?
727 if e.errno in _blocking_errnos:
728 return None
729 raise
730
731 def readable(self):
732 """True if the SocketIO is open for reading.
733 """
734 if self.closed:
735 raise ValueError("I/O operation on closed socket.")
736 return self._reading
737
738 def writable(self):
739 """True if the SocketIO is open for writing.
740 """
741 if self.closed:
742 raise ValueError("I/O operation on closed socket.")
743 return self._writing
744
745 def seekable(self):
746 """True if the SocketIO is open for seeking.
747 """
748 if self.closed:
749 raise ValueError("I/O operation on closed socket.")
750 return super().seekable()
751
752 def fileno(self):
753 """Return the file descriptor of the underlying socket.
754 """
755 self._checkClosed()
756 return self._sock.fileno()
757
758 @property
759 def name(self):
760 if not self.closed:
761 return self.fileno()
762 else:
763 return -1
764
765 @property
766 def mode(self):
767 return self._mode
768
769 def close(self):
770 """Close the SocketIO object. This doesn't close the underlying
771 socket, except if all references to it have disappeared.
772 """
773 if self.closed:
774 return
775 io.RawIOBase.close(self)
776 self._sock._decref_socketios()
777 self._sock = None
778
779
780 def getfqdn(name=''):
781 """Get fully qualified domain name from name.
782
783 An empty argument is interpreted as meaning the local host.
784
785 First the hostname returned by gethostbyaddr() is checked, then
786 possibly existing aliases. In case no FQDN is available and `name`
787 was given, it is returned unchanged. If `name` was empty, '0.0.0.0' or '::',
788 hostname from gethostname() is returned.
789 """
790 name = name.strip()
791 if not name or name in ('0.0.0.0', '::'):
792 name = gethostname()
793 try:
794 hostname, aliases, ipaddrs = gethostbyaddr(name)
795 except error:
796 pass
797 else:
798 aliases.insert(0, hostname)
799 for name in aliases:
800 if '.' in name:
801 break
802 else:
803 name = hostname
804 return name
805
806
807 _GLOBAL_DEFAULT_TIMEOUT = object()
808
809 def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
810 source_address=None, *, all_errors=False):
811 """Connect to *address* and return the socket object.
812
813 Convenience function. Connect to *address* (a 2-tuple ``(host,
814 port)``) and return the socket object. Passing the optional
815 *timeout* parameter will set the timeout on the socket instance
816 before attempting to connect. If no *timeout* is supplied, the
817 global default timeout setting returned by :func:`getdefaulttimeout`
818 is used. If *source_address* is set it must be a tuple of (host, port)
819 for the socket to bind as a source address before making the connection.
820 A host of '' or port 0 tells the OS to use the default. When a connection
821 cannot be created, raises the last error if *all_errors* is False,
822 and an ExceptionGroup of all errors if *all_errors* is True.
823 """
824
825 host, port = address
826 exceptions = []
827 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
828 af, socktype, proto, canonname, sa = res
829 sock = None
830 try:
831 sock = socket(af, socktype, proto)
832 if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
833 sock.settimeout(timeout)
834 if source_address:
835 sock.bind(source_address)
836 sock.connect(sa)
837 # Break explicitly a reference cycle
838 exceptions.clear()
839 return sock
840
841 except error as exc:
842 if not all_errors:
843 exceptions.clear() # raise only the last error
844 exceptions.append(exc)
845 if sock is not None:
846 sock.close()
847
848 if len(exceptions):
849 try:
850 if not all_errors:
851 raise exceptions[0]
852 raise ExceptionGroup("create_connection failed", exceptions)
853 finally:
854 # Break explicitly a reference cycle
855 exceptions.clear()
856 else:
857 raise error("getaddrinfo returns an empty list")
858
859
860 def has_dualstack_ipv6():
861 """Return True if the platform supports creating a SOCK_STREAM socket
862 which can handle both AF_INET and AF_INET6 (IPv4 / IPv6) connections.
863 """
864 if not has_ipv6 \
865 or not hasattr(_socket, 'IPPROTO_IPV6') \
866 or not hasattr(_socket, 'IPV6_V6ONLY'):
867 return False
868 try:
869 with socket(AF_INET6, SOCK_STREAM) as sock:
870 sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 0)
871 return True
872 except error:
873 return False
874
875
876 def create_server(address, *, family=AF_INET, backlog=None, reuse_port=False,
877 dualstack_ipv6=False):
878 """Convenience function which creates a SOCK_STREAM type socket
879 bound to *address* (a 2-tuple (host, port)) and return the socket
880 object.
881
882 *family* should be either AF_INET or AF_INET6.
883 *backlog* is the queue size passed to socket.listen().
884 *reuse_port* dictates whether to use the SO_REUSEPORT socket option.
885 *dualstack_ipv6*: if true and the platform supports it, it will
886 create an AF_INET6 socket able to accept both IPv4 or IPv6
887 connections. When false it will explicitly disable this option on
888 platforms that enable it by default (e.g. Linux).
889
890 >>> with create_server(('', 8000)) as server:
891 ... while True:
892 ... conn, addr = server.accept()
893 ... # handle new connection
894 """
895 if reuse_port and not hasattr(_socket, "SO_REUSEPORT"):
896 raise ValueError("SO_REUSEPORT not supported on this platform")
897 if dualstack_ipv6:
898 if not has_dualstack_ipv6():
899 raise ValueError("dualstack_ipv6 not supported on this platform")
900 if family != AF_INET6:
901 raise ValueError("dualstack_ipv6 requires AF_INET6 family")
902 sock = socket(family, SOCK_STREAM)
903 try:
904 # Note about Windows. We don't set SO_REUSEADDR because:
905 # 1) It's unnecessary: bind() will succeed even in case of a
906 # previous closed socket on the same address and still in
907 # TIME_WAIT state.
908 # 2) If set, another socket is free to bind() on the same
909 # address, effectively preventing this one from accepting
910 # connections. Also, it may set the process in a state where
911 # it'll no longer respond to any signals or graceful kills.
912 # See: https://learn.microsoft.com/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
913 if os.name not in ('nt', 'cygwin') and \
914 hasattr(_socket, 'SO_REUSEADDR'):
915 try:
916 sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
917 except error:
918 # Fail later on bind(), for platforms which may not
919 # support this option.
920 pass
921 if reuse_port:
922 sock.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
923 if has_ipv6 and family == AF_INET6:
924 if dualstack_ipv6:
925 sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 0)
926 elif hasattr(_socket, "IPV6_V6ONLY") and \
927 hasattr(_socket, "IPPROTO_IPV6"):
928 sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 1)
929 try:
930 sock.bind(address)
931 except error as err:
932 msg = '%s (while attempting to bind on address %r)' % \
933 (err.strerror, address)
934 raise error(err.errno, msg) from None
935 if backlog is None:
936 sock.listen()
937 else:
938 sock.listen(backlog)
939 return sock
940 except error:
941 sock.close()
942 raise
943
944
945 def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
946 """Resolve host and port into list of address info entries.
947
948 Translate the host/port argument into a sequence of 5-tuples that contain
949 all the necessary arguments for creating a socket connected to that service.
950 host is a domain name, a string representation of an IPv4/v6 address or
951 None. port is a string service name such as 'http', a numeric port number or
952 None. By passing None as the value of host and port, you can pass NULL to
953 the underlying C API.
954
955 The family, type and proto arguments can be optionally specified in order to
956 narrow the list of addresses returned. Passing zero as a value for each of
957 these arguments selects the full range of results.
958 """
959 # We override this function since we want to translate the numeric family
960 # and socket type values to enum constants.
961 addrlist = []
962 for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
963 af, socktype, proto, canonname, sa = res
964 addrlist.append((_intenum_converter(af, AddressFamily),
965 _intenum_converter(socktype, SocketKind),
966 proto, canonname, sa))
967 return addrlist