socket.py 36 KB

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