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