socket.py 37 KB

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