socket.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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', 'b', or a combination of
  268. those.
  269. """
  270. # XXX refactor to share code?
  271. if not set(mode) <= {"r", "w", "b"}:
  272. raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))
  273. writing = "w" in mode
  274. reading = "r" in mode or not writing
  275. assert reading or writing
  276. binary = "b" in mode
  277. rawmode = ""
  278. if reading:
  279. rawmode += "r"
  280. if writing:
  281. rawmode += "w"
  282. raw = SocketIO(self, rawmode)
  283. self._io_refs += 1
  284. if buffering is None:
  285. buffering = -1
  286. if buffering < 0:
  287. buffering = io.DEFAULT_BUFFER_SIZE
  288. if buffering == 0:
  289. if not binary:
  290. raise ValueError("unbuffered streams must be binary")
  291. return raw
  292. if reading and writing:
  293. buffer = io.BufferedRWPair(raw, raw, buffering)
  294. elif reading:
  295. buffer = io.BufferedReader(raw, buffering)
  296. else:
  297. assert writing
  298. buffer = io.BufferedWriter(raw, buffering)
  299. if binary:
  300. return buffer
  301. encoding = io.text_encoding(encoding)
  302. text = io.TextIOWrapper(buffer, encoding, errors, newline)
  303. text.mode = mode
  304. return text
  305. if hasattr(os, 'sendfile'):
  306. def _sendfile_use_sendfile(self, file, offset=0, count=None):
  307. self._check_sendfile_params(file, offset, count)
  308. sockno = self.fileno()
  309. try:
  310. fileno = file.fileno()
  311. except (AttributeError, io.UnsupportedOperation) as err:
  312. raise _GiveupOnSendfile(err) # not a regular file
  313. try:
  314. fsize = os.fstat(fileno).st_size
  315. except OSError as err:
  316. raise _GiveupOnSendfile(err) # not a regular file
  317. if not fsize:
  318. return 0 # empty file
  319. # Truncate to 1GiB to avoid OverflowError, see bpo-38319.
  320. blocksize = min(count or fsize, 2 ** 30)
  321. timeout = self.gettimeout()
  322. if timeout == 0:
  323. raise ValueError("non-blocking sockets are not supported")
  324. # poll/select have the advantage of not requiring any
  325. # extra file descriptor, contrarily to epoll/kqueue
  326. # (also, they require a single syscall).
  327. if hasattr(selectors, 'PollSelector'):
  328. selector = selectors.PollSelector()
  329. else:
  330. selector = selectors.SelectSelector()
  331. selector.register(sockno, selectors.EVENT_WRITE)
  332. total_sent = 0
  333. # localize variable access to minimize overhead
  334. selector_select = selector.select
  335. os_sendfile = os.sendfile
  336. try:
  337. while True:
  338. if timeout and not selector_select(timeout):
  339. raise TimeoutError('timed out')
  340. if count:
  341. blocksize = min(count - total_sent, blocksize)
  342. if blocksize <= 0:
  343. break
  344. try:
  345. sent = os_sendfile(sockno, fileno, offset, blocksize)
  346. except BlockingIOError:
  347. if not timeout:
  348. # Block until the socket is ready to send some
  349. # data; avoids hogging CPU resources.
  350. selector_select()
  351. continue
  352. except OSError as err:
  353. if total_sent == 0:
  354. # We can get here for different reasons, the main
  355. # one being 'file' is not a regular mmap(2)-like
  356. # file, in which case we'll fall back on using
  357. # plain send().
  358. raise _GiveupOnSendfile(err)
  359. raise err from None
  360. else:
  361. if sent == 0:
  362. break # EOF
  363. offset += sent
  364. total_sent += sent
  365. return total_sent
  366. finally:
  367. if total_sent > 0 and hasattr(file, 'seek'):
  368. file.seek(offset)
  369. else:
  370. def _sendfile_use_sendfile(self, file, offset=0, count=None):
  371. raise _GiveupOnSendfile(
  372. "os.sendfile() not available on this platform")
  373. def _sendfile_use_send(self, file, offset=0, count=None):
  374. self._check_sendfile_params(file, offset, count)
  375. if self.gettimeout() == 0:
  376. raise ValueError("non-blocking sockets are not supported")
  377. if offset:
  378. file.seek(offset)
  379. blocksize = min(count, 8192) if count else 8192
  380. total_sent = 0
  381. # localize variable access to minimize overhead
  382. file_read = file.read
  383. sock_send = self.send
  384. try:
  385. while True:
  386. if count:
  387. blocksize = min(count - total_sent, blocksize)
  388. if blocksize <= 0:
  389. break
  390. data = memoryview(file_read(blocksize))
  391. if not data:
  392. break # EOF
  393. while True:
  394. try:
  395. sent = sock_send(data)
  396. except BlockingIOError:
  397. continue
  398. else:
  399. total_sent += sent
  400. if sent < len(data):
  401. data = data[sent:]
  402. else:
  403. break
  404. return total_sent
  405. finally:
  406. if total_sent > 0 and hasattr(file, 'seek'):
  407. file.seek(offset + total_sent)
  408. def _check_sendfile_params(self, file, offset, count):
  409. if 'b' not in getattr(file, 'mode', 'b'):
  410. raise ValueError("file should be opened in binary mode")
  411. if not self.type & SOCK_STREAM:
  412. raise ValueError("only SOCK_STREAM type sockets are supported")
  413. if count is not None:
  414. if not isinstance(count, int):
  415. raise TypeError(
  416. "count must be a positive integer (got {!r})".format(count))
  417. if count <= 0:
  418. raise ValueError(
  419. "count must be a positive integer (got {!r})".format(count))
  420. def sendfile(self, file, offset=0, count=None):
  421. """sendfile(file[, offset[, count]]) -> sent
  422. Send a file until EOF is reached by using high-performance
  423. os.sendfile() and return the total number of bytes which
  424. were sent.
  425. *file* must be a regular file object opened in binary mode.
  426. If os.sendfile() is not available (e.g. Windows) or file is
  427. not a regular file socket.send() will be used instead.
  428. *offset* tells from where to start reading the file.
  429. If specified, *count* is the total number of bytes to transmit
  430. as opposed to sending the file until EOF is reached.
  431. File position is updated on return or also in case of error in
  432. which case file.tell() can be used to figure out the number of
  433. bytes which were sent.
  434. The socket must be of SOCK_STREAM type.
  435. Non-blocking sockets are not supported.
  436. """
  437. try:
  438. return self._sendfile_use_sendfile(file, offset, count)
  439. except _GiveupOnSendfile:
  440. return self._sendfile_use_send(file, offset, count)
  441. def _decref_socketios(self):
  442. if self._io_refs > 0:
  443. self._io_refs -= 1
  444. if self._closed:
  445. self.close()
  446. def _real_close(self, _ss=_socket.socket):
  447. # This function should not reference any globals. See issue #808164.
  448. _ss.close(self)
  449. def close(self):
  450. # This function should not reference any globals. See issue #808164.
  451. self._closed = True
  452. if self._io_refs <= 0:
  453. self._real_close()
  454. def detach(self):
  455. """detach() -> file descriptor
  456. Close the socket object without closing the underlying file descriptor.
  457. The object cannot be used after this call, but the file descriptor
  458. can be reused for other purposes. The file descriptor is returned.
  459. """
  460. self._closed = True
  461. return super().detach()
  462. @property
  463. def family(self):
  464. """Read-only access to the address family for this socket.
  465. """
  466. return _intenum_converter(super().family, AddressFamily)
  467. @property
  468. def type(self):
  469. """Read-only access to the socket type.
  470. """
  471. return _intenum_converter(super().type, SocketKind)
  472. if os.name == 'nt':
  473. def get_inheritable(self):
  474. return os.get_handle_inheritable(self.fileno())
  475. def set_inheritable(self, inheritable):
  476. os.set_handle_inheritable(self.fileno(), inheritable)
  477. else:
  478. def get_inheritable(self):
  479. return os.get_inheritable(self.fileno())
  480. def set_inheritable(self, inheritable):
  481. os.set_inheritable(self.fileno(), inheritable)
  482. get_inheritable.__doc__ = "Get the inheritable flag of the socket"
  483. set_inheritable.__doc__ = "Set the inheritable flag of the socket"
  484. def fromfd(fd, family, type, proto=0):
  485. """ fromfd(fd, family, type[, proto]) -> socket object
  486. Create a socket object from a duplicate of the given file
  487. descriptor. The remaining arguments are the same as for socket().
  488. """
  489. nfd = dup(fd)
  490. return socket(family, type, proto, nfd)
  491. if hasattr(_socket.socket, "sendmsg"):
  492. import array
  493. def send_fds(sock, buffers, fds, flags=0, address=None):
  494. """ send_fds(sock, buffers, fds[, flags[, address]]) -> integer
  495. Send the list of file descriptors fds over an AF_UNIX socket.
  496. """
  497. return sock.sendmsg(buffers, [(_socket.SOL_SOCKET,
  498. _socket.SCM_RIGHTS, array.array("i", fds))])
  499. __all__.append("send_fds")
  500. if hasattr(_socket.socket, "recvmsg"):
  501. import array
  502. def recv_fds(sock, bufsize, maxfds, flags=0):
  503. """ recv_fds(sock, bufsize, maxfds[, flags]) -> (data, list of file
  504. descriptors, msg_flags, address)
  505. Receive up to maxfds file descriptors returning the message
  506. data and a list containing the descriptors.
  507. """
  508. # Array of ints
  509. fds = array.array("i")
  510. msg, ancdata, flags, addr = sock.recvmsg(bufsize,
  511. _socket.CMSG_LEN(maxfds * fds.itemsize))
  512. for cmsg_level, cmsg_type, cmsg_data in ancdata:
  513. if (cmsg_level == _socket.SOL_SOCKET and cmsg_type == _socket.SCM_RIGHTS):
  514. fds.frombytes(cmsg_data[:
  515. len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
  516. return msg, list(fds), flags, addr
  517. __all__.append("recv_fds")
  518. if hasattr(_socket.socket, "share"):
  519. def fromshare(info):
  520. """ fromshare(info) -> socket object
  521. Create a socket object from the bytes object returned by
  522. socket.share(pid).
  523. """
  524. return socket(0, 0, 0, info)
  525. __all__.append("fromshare")
  526. # Origin: https://gist.github.com/4325783, by Geert Jansen. Public domain.
  527. # This is used if _socket doesn't natively provide socketpair. It's
  528. # always defined so that it can be patched in for testing purposes.
  529. def _fallback_socketpair(family=AF_INET, type=SOCK_STREAM, proto=0):
  530. if family == AF_INET:
  531. host = _LOCALHOST
  532. elif family == AF_INET6:
  533. host = _LOCALHOST_V6
  534. else:
  535. raise ValueError("Only AF_INET and AF_INET6 socket address families "
  536. "are supported")
  537. if type != SOCK_STREAM:
  538. raise ValueError("Only SOCK_STREAM socket type is supported")
  539. if proto != 0:
  540. raise ValueError("Only protocol zero is supported")
  541. # We create a connected TCP socket. Note the trick with
  542. # setblocking(False) that prevents us from having to create a thread.
  543. lsock = socket(family, type, proto)
  544. try:
  545. lsock.bind((host, 0))
  546. lsock.listen()
  547. # On IPv6, ignore flow_info and scope_id
  548. addr, port = lsock.getsockname()[:2]
  549. csock = socket(family, type, proto)
  550. try:
  551. csock.setblocking(False)
  552. try:
  553. csock.connect((addr, port))
  554. except (BlockingIOError, InterruptedError):
  555. pass
  556. csock.setblocking(True)
  557. ssock, _ = lsock.accept()
  558. except:
  559. csock.close()
  560. raise
  561. finally:
  562. lsock.close()
  563. # Authenticating avoids using a connection from something else
  564. # able to connect to {host}:{port} instead of us.
  565. # We expect only AF_INET and AF_INET6 families.
  566. try:
  567. if (
  568. ssock.getsockname() != csock.getpeername()
  569. or csock.getsockname() != ssock.getpeername()
  570. ):
  571. raise ConnectionError("Unexpected peer connection")
  572. except:
  573. # getsockname() and getpeername() can fail
  574. # if either socket isn't connected.
  575. ssock.close()
  576. csock.close()
  577. raise
  578. return (ssock, csock)
  579. if hasattr(_socket, "socketpair"):
  580. def socketpair(family=None, type=SOCK_STREAM, proto=0):
  581. if family is None:
  582. try:
  583. family = AF_UNIX
  584. except NameError:
  585. family = AF_INET
  586. a, b = _socket.socketpair(family, type, proto)
  587. a = socket(family, type, proto, a.detach())
  588. b = socket(family, type, proto, b.detach())
  589. return a, b
  590. else:
  591. socketpair = _fallback_socketpair
  592. __all__.append("socketpair")
  593. socketpair.__doc__ = """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  594. Create a pair of socket objects from the sockets returned by the platform
  595. socketpair() function.
  596. The arguments are the same as for socket() except the default family is AF_UNIX
  597. if defined on the platform; otherwise, the default is AF_INET.
  598. """
  599. _blocking_errnos = { EAGAIN, EWOULDBLOCK }
  600. class SocketIO(io.RawIOBase):
  601. """Raw I/O implementation for stream sockets.
  602. This class supports the makefile() method on sockets. It provides
  603. the raw I/O interface on top of a socket object.
  604. """
  605. # One might wonder why not let FileIO do the job instead. There are two
  606. # main reasons why FileIO is not adapted:
  607. # - it wouldn't work under Windows (where you can't used read() and
  608. # write() on a socket handle)
  609. # - it wouldn't work with socket timeouts (FileIO would ignore the
  610. # timeout and consider the socket non-blocking)
  611. # XXX More docs
  612. def __init__(self, sock, mode):
  613. if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
  614. raise ValueError("invalid mode: %r" % mode)
  615. io.RawIOBase.__init__(self)
  616. self._sock = sock
  617. if "b" not in mode:
  618. mode += "b"
  619. self._mode = mode
  620. self._reading = "r" in mode
  621. self._writing = "w" in mode
  622. self._timeout_occurred = False
  623. def readinto(self, b):
  624. """Read up to len(b) bytes into the writable buffer *b* and return
  625. the number of bytes read. If the socket is non-blocking and no bytes
  626. are available, None is returned.
  627. If *b* is non-empty, a 0 return value indicates that the connection
  628. was shutdown at the other end.
  629. """
  630. self._checkClosed()
  631. self._checkReadable()
  632. if self._timeout_occurred:
  633. raise OSError("cannot read from timed out object")
  634. while True:
  635. try:
  636. return self._sock.recv_into(b)
  637. except timeout:
  638. self._timeout_occurred = True
  639. raise
  640. except error as e:
  641. if e.errno in _blocking_errnos:
  642. return None
  643. raise
  644. def write(self, b):
  645. """Write the given bytes or bytearray object *b* to the socket
  646. and return the number of bytes written. This can be less than
  647. len(b) if not all data could be written. If the socket is
  648. non-blocking and no bytes could be written None is returned.
  649. """
  650. self._checkClosed()
  651. self._checkWritable()
  652. try:
  653. return self._sock.send(b)
  654. except error as e:
  655. # XXX what about EINTR?
  656. if e.errno in _blocking_errnos:
  657. return None
  658. raise
  659. def readable(self):
  660. """True if the SocketIO is open for reading.
  661. """
  662. if self.closed:
  663. raise ValueError("I/O operation on closed socket.")
  664. return self._reading
  665. def writable(self):
  666. """True if the SocketIO is open for writing.
  667. """
  668. if self.closed:
  669. raise ValueError("I/O operation on closed socket.")
  670. return self._writing
  671. def seekable(self):
  672. """True if the SocketIO is open for seeking.
  673. """
  674. if self.closed:
  675. raise ValueError("I/O operation on closed socket.")
  676. return super().seekable()
  677. def fileno(self):
  678. """Return the file descriptor of the underlying socket.
  679. """
  680. self._checkClosed()
  681. return self._sock.fileno()
  682. @property
  683. def name(self):
  684. if not self.closed:
  685. return self.fileno()
  686. else:
  687. return -1
  688. @property
  689. def mode(self):
  690. return self._mode
  691. def close(self):
  692. """Close the SocketIO object. This doesn't close the underlying
  693. socket, except if all references to it have disappeared.
  694. """
  695. if self.closed:
  696. return
  697. io.RawIOBase.close(self)
  698. self._sock._decref_socketios()
  699. self._sock = None
  700. def getfqdn(name=''):
  701. """Get fully qualified domain name from name.
  702. An empty argument is interpreted as meaning the local host.
  703. First the hostname returned by gethostbyaddr() is checked, then
  704. possibly existing aliases. In case no FQDN is available and `name`
  705. was given, it is returned unchanged. If `name` was empty, '0.0.0.0' or '::',
  706. hostname from gethostname() is returned.
  707. """
  708. name = name.strip()
  709. if not name or name in ('0.0.0.0', '::'):
  710. name = gethostname()
  711. try:
  712. hostname, aliases, ipaddrs = gethostbyaddr(name)
  713. except error:
  714. pass
  715. else:
  716. aliases.insert(0, hostname)
  717. for name in aliases:
  718. if '.' in name:
  719. break
  720. else:
  721. name = hostname
  722. return name
  723. _GLOBAL_DEFAULT_TIMEOUT = object()
  724. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
  725. source_address=None, *, all_errors=False):
  726. """Connect to *address* and return the socket object.
  727. Convenience function. Connect to *address* (a 2-tuple ``(host,
  728. port)``) and return the socket object. Passing the optional
  729. *timeout* parameter will set the timeout on the socket instance
  730. before attempting to connect. If no *timeout* is supplied, the
  731. global default timeout setting returned by :func:`getdefaulttimeout`
  732. is used. If *source_address* is set it must be a tuple of (host, port)
  733. for the socket to bind as a source address before making the connection.
  734. A host of '' or port 0 tells the OS to use the default. When a connection
  735. cannot be created, raises the last error if *all_errors* is False,
  736. and an ExceptionGroup of all errors if *all_errors* is True.
  737. """
  738. host, port = address
  739. exceptions = []
  740. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  741. af, socktype, proto, canonname, sa = res
  742. sock = None
  743. try:
  744. sock = socket(af, socktype, proto)
  745. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  746. sock.settimeout(timeout)
  747. if source_address:
  748. sock.bind(source_address)
  749. sock.connect(sa)
  750. # Break explicitly a reference cycle
  751. exceptions.clear()
  752. return sock
  753. except error as exc:
  754. if not all_errors:
  755. exceptions.clear() # raise only the last error
  756. exceptions.append(exc)
  757. if sock is not None:
  758. sock.close()
  759. if len(exceptions):
  760. try:
  761. if not all_errors:
  762. raise exceptions[0]
  763. raise ExceptionGroup("create_connection failed", exceptions)
  764. finally:
  765. # Break explicitly a reference cycle
  766. exceptions.clear()
  767. else:
  768. raise error("getaddrinfo returns an empty list")
  769. def has_dualstack_ipv6():
  770. """Return True if the platform supports creating a SOCK_STREAM socket
  771. which can handle both AF_INET and AF_INET6 (IPv4 / IPv6) connections.
  772. """
  773. if not has_ipv6 \
  774. or not hasattr(_socket, 'IPPROTO_IPV6') \
  775. or not hasattr(_socket, 'IPV6_V6ONLY'):
  776. return False
  777. try:
  778. with socket(AF_INET6, SOCK_STREAM) as sock:
  779. sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 0)
  780. return True
  781. except error:
  782. return False
  783. def create_server(address, *, family=AF_INET, backlog=None, reuse_port=False,
  784. dualstack_ipv6=False):
  785. """Convenience function which creates a SOCK_STREAM type socket
  786. bound to *address* (a 2-tuple (host, port)) and return the socket
  787. object.
  788. *family* should be either AF_INET or AF_INET6.
  789. *backlog* is the queue size passed to socket.listen().
  790. *reuse_port* dictates whether to use the SO_REUSEPORT socket option.
  791. *dualstack_ipv6*: if true and the platform supports it, it will
  792. create an AF_INET6 socket able to accept both IPv4 or IPv6
  793. connections. When false it will explicitly disable this option on
  794. platforms that enable it by default (e.g. Linux).
  795. >>> with create_server(('', 8000)) as server:
  796. ... while True:
  797. ... conn, addr = server.accept()
  798. ... # handle new connection
  799. """
  800. if reuse_port and not hasattr(_socket, "SO_REUSEPORT"):
  801. raise ValueError("SO_REUSEPORT not supported on this platform")
  802. if dualstack_ipv6:
  803. if not has_dualstack_ipv6():
  804. raise ValueError("dualstack_ipv6 not supported on this platform")
  805. if family != AF_INET6:
  806. raise ValueError("dualstack_ipv6 requires AF_INET6 family")
  807. sock = socket(family, SOCK_STREAM)
  808. try:
  809. # Note about Windows. We don't set SO_REUSEADDR because:
  810. # 1) It's unnecessary: bind() will succeed even in case of a
  811. # previous closed socket on the same address and still in
  812. # TIME_WAIT state.
  813. # 2) If set, another socket is free to bind() on the same
  814. # address, effectively preventing this one from accepting
  815. # connections. Also, it may set the process in a state where
  816. # it'll no longer respond to any signals or graceful kills.
  817. # See: https://learn.microsoft.com/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
  818. if os.name not in ('nt', 'cygwin') and \
  819. hasattr(_socket, 'SO_REUSEADDR'):
  820. try:
  821. sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
  822. except error:
  823. # Fail later on bind(), for platforms which may not
  824. # support this option.
  825. pass
  826. if reuse_port:
  827. sock.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
  828. if has_ipv6 and family == AF_INET6:
  829. if dualstack_ipv6:
  830. sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 0)
  831. elif hasattr(_socket, "IPV6_V6ONLY") and \
  832. hasattr(_socket, "IPPROTO_IPV6"):
  833. sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 1)
  834. try:
  835. sock.bind(address)
  836. except error as err:
  837. msg = '%s (while attempting to bind on address %r)' % \
  838. (err.strerror, address)
  839. raise error(err.errno, msg) from None
  840. if backlog is None:
  841. sock.listen()
  842. else:
  843. sock.listen(backlog)
  844. return sock
  845. except error:
  846. sock.close()
  847. raise
  848. def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
  849. """Resolve host and port into list of address info entries.
  850. Translate the host/port argument into a sequence of 5-tuples that contain
  851. all the necessary arguments for creating a socket connected to that service.
  852. host is a domain name, a string representation of an IPv4/v6 address or
  853. None. port is a string service name such as 'http', a numeric port number or
  854. None. By passing None as the value of host and port, you can pass NULL to
  855. the underlying C API.
  856. The family, type and proto arguments can be optionally specified in order to
  857. narrow the list of addresses returned. Passing zero as a value for each of
  858. these arguments selects the full range of results.
  859. """
  860. # We override this function since we want to translate the numeric family
  861. # and socket type values to enum constants.
  862. addrlist = []
  863. for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
  864. af, socktype, proto, canonname, sa = res
  865. addrlist.append((_intenum_converter(af, AddressFamily),
  866. _intenum_converter(socktype, SocketKind),
  867. proto, canonname, sa))
  868. return addrlist