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