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