logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

socket.py (36733B)


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