PageRenderTime 23ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/socket.py

https://bitbucket.org/jaraco/cpython-issue13540
Python | 681 lines | 653 code | 1 blank | 27 comment | 0 complexity | 864a879fcc77307396935fb517d241a8 MD5 | raw file
Possible License(s): BSD-3-Clause, 0BSD
  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. fromshare() -- create a socket object from data received from socket.share() [*]
  13. gethostname() -- return the current hostname
  14. gethostbyname() -- map a hostname to its IP number
  15. gethostbyaddr() -- map an IP number or hostname to DNS info
  16. getservbyname() -- map a service name and a protocol name to a port number
  17. getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
  18. ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
  19. htons(), htonl() -- convert 16, 32 bit int from host to network byte order
  20. inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
  21. inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
  22. socket.getdefaulttimeout() -- get the default timeout value
  23. socket.setdefaulttimeout() -- set the default timeout value
  24. create_connection() -- connects to an address, with an optional timeout and
  25. optional source address.
  26. [*] not available on all platforms!
  27. Special objects:
  28. SocketType -- type object for socket objects
  29. error -- exception raised for I/O errors
  30. has_ipv6 -- boolean value indicating if IPv6 is supported
  31. Integer constants:
  32. AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
  33. SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
  34. Many other constants may be defined; these may be used in calls to
  35. the setsockopt() and getsockopt() methods.
  36. """
  37. import _socket
  38. from _socket import *
  39. import os, sys, io, selectors
  40. from enum import IntEnum
  41. try:
  42. import errno
  43. except ImportError:
  44. errno = None
  45. EBADF = getattr(errno, 'EBADF', 9)
  46. EAGAIN = getattr(errno, 'EAGAIN', 11)
  47. EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11)
  48. __all__ = ["getfqdn", "create_connection"]
  49. __all__.extend(os._get_exports_list(_socket))
  50. # Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for
  51. # nicer string representations.
  52. # Note that _socket only knows about the integer values. The public interface
  53. # in this module understands the enums and translates them back from integers
  54. # where needed (e.g. .family property of a socket object).
  55. AddressFamily = IntEnum('AddressFamily',
  56. {name: value for name, value in globals().items()
  57. if name.isupper() and name.startswith('AF_')})
  58. globals().update(AddressFamily.__members__)
  59. SocketType = IntEnum('SocketType',
  60. {name: value for name, value in globals().items()
  61. if name.isupper() and name.startswith('SOCK_')})
  62. globals().update(SocketType.__members__)
  63. def _intenum_converter(value, enum_klass):
  64. """Convert a numeric family value to an IntEnum member.
  65. If it's not a known member, return the numeric value itself.
  66. """
  67. try:
  68. return enum_klass(value)
  69. except ValueError:
  70. return value
  71. _realsocket = socket
  72. # WSA error codes
  73. if sys.platform.lower().startswith("win"):
  74. errorTab = {}
  75. errorTab[10004] = "The operation was interrupted."
  76. errorTab[10009] = "A bad file handle was passed."
  77. errorTab[10013] = "Permission denied."
  78. errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
  79. errorTab[10022] = "An invalid operation was attempted."
  80. errorTab[10035] = "The socket operation would block"
  81. errorTab[10036] = "A blocking operation is already in progress."
  82. errorTab[10048] = "The network address is in use."
  83. errorTab[10054] = "The connection has been reset."
  84. errorTab[10058] = "The network has been shut down."
  85. errorTab[10060] = "The operation timed out."
  86. errorTab[10061] = "Connection refused."
  87. errorTab[10063] = "The name is too long."
  88. errorTab[10064] = "The host is down."
  89. errorTab[10065] = "The host is unreachable."
  90. __all__.append("errorTab")
  91. class _GiveupOnSendfile(Exception): pass
  92. class socket(_socket.socket):
  93. """A subclass of _socket.socket adding the makefile() method."""
  94. __slots__ = ["__weakref__", "_io_refs", "_closed"]
  95. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
  96. # For user code address family and type values are IntEnum members, but
  97. # for the underlying _socket.socket they're just integers. The
  98. # constructor of _socket.socket converts the given argument to an
  99. # integer automatically.
  100. _socket.socket.__init__(self, family, type, proto, fileno)
  101. self._io_refs = 0
  102. self._closed = False
  103. def __enter__(self):
  104. return self
  105. def __exit__(self, *args):
  106. if not self._closed:
  107. self.close()
  108. def __repr__(self):
  109. """Wrap __repr__() to reveal the real class name and socket
  110. address(es).
  111. """
  112. closed = getattr(self, '_closed', False)
  113. s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \
  114. % (self.__class__.__module__,
  115. self.__class__.__qualname__,
  116. " [closed]" if closed else "",
  117. self.fileno(),
  118. self.family,
  119. self.type,
  120. self.proto)
  121. if not closed:
  122. try:
  123. laddr = self.getsockname()
  124. if laddr:
  125. s += ", laddr=%s" % str(laddr)
  126. except error:
  127. pass
  128. try:
  129. raddr = self.getpeername()
  130. if raddr:
  131. s += ", raddr=%s" % str(raddr)
  132. except error:
  133. pass
  134. s += '>'
  135. return s
  136. def __getstate__(self):
  137. raise TypeError("Cannot serialize socket object")
  138. def dup(self):
  139. """dup() -> socket object
  140. Duplicate the socket. Return a new socket object connected to the same
  141. system resource. The new socket is non-inheritable.
  142. """
  143. fd = dup(self.fileno())
  144. sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
  145. sock.settimeout(self.gettimeout())
  146. return sock
  147. def accept(self):
  148. """accept() -> (socket object, address info)
  149. Wait for an incoming connection. Return a new socket
  150. representing the connection, and the address of the client.
  151. For IP sockets, the address info is a pair (hostaddr, port).
  152. """
  153. fd, addr = self._accept()
  154. sock = socket(self.family, self.type, self.proto, fileno=fd)
  155. # Issue #7995: if no default timeout is set and the listening
  156. # socket had a (non-zero) timeout, force the new socket in blocking
  157. # mode to override platform-specific socket flags inheritance.
  158. if getdefaulttimeout() is None and self.gettimeout():
  159. sock.setblocking(True)
  160. return sock, addr
  161. def makefile(self, mode="r", buffering=None, *,
  162. encoding=None, errors=None, newline=None):
  163. """makefile(...) -> an I/O stream connected to the socket
  164. The arguments are as for io.open() after the filename,
  165. except the only mode characters supported are 'r', 'w' and 'b'.
  166. The semantics are similar too. (XXX refactor to share code?)
  167. """
  168. for c in mode:
  169. if c not in {"r", "w", "b"}:
  170. raise ValueError("invalid mode %r (only r, w, b allowed)")
  171. writing = "w" in mode
  172. reading = "r" in mode or not writing
  173. assert reading or writing
  174. binary = "b" in mode
  175. rawmode = ""
  176. if reading:
  177. rawmode += "r"
  178. if writing:
  179. rawmode += "w"
  180. raw = SocketIO(self, rawmode)
  181. self._io_refs += 1
  182. if buffering is None:
  183. buffering = -1
  184. if buffering < 0:
  185. buffering = io.DEFAULT_BUFFER_SIZE
  186. if buffering == 0:
  187. if not binary:
  188. raise ValueError("unbuffered streams must be binary")
  189. return raw
  190. if reading and writing:
  191. buffer = io.BufferedRWPair(raw, raw, buffering)
  192. elif reading:
  193. buffer = io.BufferedReader(raw, buffering)
  194. else:
  195. assert writing
  196. buffer = io.BufferedWriter(raw, buffering)
  197. if binary:
  198. return buffer
  199. text = io.TextIOWrapper(buffer, encoding, errors, newline)
  200. text.mode = mode
  201. return text
  202. if hasattr(os, 'sendfile'):
  203. def _sendfile_use_sendfile(self, file, offset=0, count=None):
  204. self._check_sendfile_params(file, offset, count)
  205. sockno = self.fileno()
  206. try:
  207. fileno = file.fileno()
  208. except (AttributeError, io.UnsupportedOperation) as err:
  209. raise _GiveupOnSendfile(err) # not a regular file
  210. try:
  211. fsize = os.fstat(fileno).st_size
  212. except OSError:
  213. raise _GiveupOnSendfile(err) # not a regular file
  214. if not fsize:
  215. return 0 # empty file
  216. blocksize = fsize if not count else count
  217. timeout = self.gettimeout()
  218. if timeout == 0:
  219. raise ValueError("non-blocking sockets are not supported")
  220. # poll/select have the advantage of not requiring any
  221. # extra file descriptor, contrarily to epoll/kqueue
  222. # (also, they require a single syscall).
  223. if hasattr(selectors, 'PollSelector'):
  224. selector = selectors.PollSelector()
  225. else:
  226. selector = selectors.SelectSelector()
  227. selector.register(sockno, selectors.EVENT_WRITE)
  228. total_sent = 0
  229. # localize variable access to minimize overhead
  230. selector_select = selector.select
  231. os_sendfile = os.sendfile
  232. try:
  233. while True:
  234. if timeout and not selector_select(timeout):
  235. raise _socket.timeout('timed out')
  236. if count:
  237. blocksize = count - total_sent
  238. if blocksize <= 0:
  239. break
  240. try:
  241. sent = os_sendfile(sockno, fileno, offset, blocksize)
  242. except BlockingIOError:
  243. if not timeout:
  244. # Block until the socket is ready to send some
  245. # data; avoids hogging CPU resources.
  246. selector_select()
  247. continue
  248. except OSError as err:
  249. if total_sent == 0:
  250. # We can get here for different reasons, the main
  251. # one being 'file' is not a regular mmap(2)-like
  252. # file, in which case we'll fall back on using
  253. # plain send().
  254. raise _GiveupOnSendfile(err)
  255. raise err from None
  256. else:
  257. if sent == 0:
  258. break # EOF
  259. offset += sent
  260. total_sent += sent
  261. return total_sent
  262. finally:
  263. if total_sent > 0 and hasattr(file, 'seek'):
  264. file.seek(offset)
  265. else:
  266. def _sendfile_use_sendfile(self, file, offset=0, count=None):
  267. raise _GiveupOnSendfile(
  268. "os.sendfile() not available on this platform")
  269. def _sendfile_use_send(self, file, offset=0, count=None):
  270. self._check_sendfile_params(file, offset, count)
  271. if self.gettimeout() == 0:
  272. raise ValueError("non-blocking sockets are not supported")
  273. if offset:
  274. file.seek(offset)
  275. blocksize = min(count, 8192) if count else 8192
  276. total_sent = 0
  277. # localize variable access to minimize overhead
  278. file_read = file.read
  279. sock_send = self.send
  280. try:
  281. while True:
  282. if count:
  283. blocksize = min(count - total_sent, blocksize)
  284. if blocksize <= 0:
  285. break
  286. data = memoryview(file_read(blocksize))
  287. if not data:
  288. break # EOF
  289. while True:
  290. try:
  291. sent = sock_send(data)
  292. except BlockingIOError:
  293. continue
  294. else:
  295. total_sent += sent
  296. if sent < len(data):
  297. data = data[sent:]
  298. else:
  299. break
  300. return total_sent
  301. finally:
  302. if total_sent > 0 and hasattr(file, 'seek'):
  303. file.seek(offset + total_sent)
  304. def _check_sendfile_params(self, file, offset, count):
  305. if 'b' not in getattr(file, 'mode', 'b'):
  306. raise ValueError("file should be opened in binary mode")
  307. if not self.type & SOCK_STREAM:
  308. raise ValueError("only SOCK_STREAM type sockets are supported")
  309. if count is not None:
  310. if not isinstance(count, int):
  311. raise TypeError(
  312. "count must be a positive integer (got {!r})".format(count))
  313. if count <= 0:
  314. raise ValueError(
  315. "count must be a positive integer (got {!r})".format(count))
  316. def sendfile(self, file, offset=0, count=None):
  317. """sendfile(file[, offset[, count]]) -> sent
  318. Send a file until EOF is reached by using high-performance
  319. os.sendfile() and return the total number of bytes which
  320. were sent.
  321. *file* must be a regular file object opened in binary mode.
  322. If os.sendfile() is not available (e.g. Windows) or file is
  323. not a regular file socket.send() will be used instead.
  324. *offset* tells from where to start reading the file.
  325. If specified, *count* is the total number of bytes to transmit
  326. as opposed to sending the file until EOF is reached.
  327. File position is updated on return or also in case of error in
  328. which case file.tell() can be used to figure out the number of
  329. bytes which were sent.
  330. The socket must be of SOCK_STREAM type.
  331. Non-blocking sockets are not supported.
  332. """
  333. try:
  334. return self._sendfile_use_sendfile(file, offset, count)
  335. except _GiveupOnSendfile:
  336. return self._sendfile_use_send(file, offset, count)
  337. def _decref_socketios(self):
  338. if self._io_refs > 0:
  339. self._io_refs -= 1
  340. if self._closed:
  341. self.close()
  342. def _real_close(self, _ss=_socket.socket):
  343. # This function should not reference any globals. See issue #808164.
  344. _ss.close(self)
  345. def close(self):
  346. # This function should not reference any globals. See issue #808164.
  347. self._closed = True
  348. if self._io_refs <= 0:
  349. self._real_close()
  350. def detach(self):
  351. """detach() -> file descriptor
  352. Close the socket object without closing the underlying file descriptor.
  353. The object cannot be used after this call, but the file descriptor
  354. can be reused for other purposes. The file descriptor is returned.
  355. """
  356. self._closed = True
  357. return super().detach()
  358. @property
  359. def family(self):
  360. """Read-only access to the address family for this socket.
  361. """
  362. return _intenum_converter(super().family, AddressFamily)
  363. @property
  364. def type(self):
  365. """Read-only access to the socket type.
  366. """
  367. return _intenum_converter(super().type, SocketType)
  368. if os.name == 'nt':
  369. def get_inheritable(self):
  370. return os.get_handle_inheritable(self.fileno())
  371. def set_inheritable(self, inheritable):
  372. os.set_handle_inheritable(self.fileno(), inheritable)
  373. else:
  374. def get_inheritable(self):
  375. return os.get_inheritable(self.fileno())
  376. def set_inheritable(self, inheritable):
  377. os.set_inheritable(self.fileno(), inheritable)
  378. get_inheritable.__doc__ = "Get the inheritable flag of the socket"
  379. set_inheritable.__doc__ = "Set the inheritable flag of the socket"
  380. def fromfd(fd, family, type, proto=0):
  381. """ fromfd(fd, family, type[, proto]) -> socket object
  382. Create a socket object from a duplicate of the given file
  383. descriptor. The remaining arguments are the same as for socket().
  384. """
  385. nfd = dup(fd)
  386. return socket(family, type, proto, nfd)
  387. if hasattr(_socket.socket, "share"):
  388. def fromshare(info):
  389. """ fromshare(info) -> socket object
  390. Create a socket object from a the bytes object returned by
  391. socket.share(pid).
  392. """
  393. return socket(0, 0, 0, info)
  394. if hasattr(_socket, "socketpair"):
  395. def socketpair(family=None, type=SOCK_STREAM, proto=0):
  396. """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  397. Create a pair of socket objects from the sockets returned by the platform
  398. socketpair() function.
  399. The arguments are the same as for socket() except the default family is
  400. AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
  401. """
  402. if family is None:
  403. try:
  404. family = AF_UNIX
  405. except NameError:
  406. family = AF_INET
  407. a, b = _socket.socketpair(family, type, proto)
  408. a = socket(family, type, proto, a.detach())
  409. b = socket(family, type, proto, b.detach())
  410. return a, b
  411. _blocking_errnos = { EAGAIN, EWOULDBLOCK }
  412. class SocketIO(io.RawIOBase):
  413. """Raw I/O implementation for stream sockets.
  414. This class supports the makefile() method on sockets. It provides
  415. the raw I/O interface on top of a socket object.
  416. """
  417. # One might wonder why not let FileIO do the job instead. There are two
  418. # main reasons why FileIO is not adapted:
  419. # - it wouldn't work under Windows (where you can't used read() and
  420. # write() on a socket handle)
  421. # - it wouldn't work with socket timeouts (FileIO would ignore the
  422. # timeout and consider the socket non-blocking)
  423. # XXX More docs
  424. def __init__(self, sock, mode):
  425. if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
  426. raise ValueError("invalid mode: %r" % mode)
  427. io.RawIOBase.__init__(self)
  428. self._sock = sock
  429. if "b" not in mode:
  430. mode += "b"
  431. self._mode = mode
  432. self._reading = "r" in mode
  433. self._writing = "w" in mode
  434. self._timeout_occurred = False
  435. def readinto(self, b):
  436. """Read up to len(b) bytes into the writable buffer *b* and return
  437. the number of bytes read. If the socket is non-blocking and no bytes
  438. are available, None is returned.
  439. If *b* is non-empty, a 0 return value indicates that the connection
  440. was shutdown at the other end.
  441. """
  442. self._checkClosed()
  443. self._checkReadable()
  444. if self._timeout_occurred:
  445. raise OSError("cannot read from timed out object")
  446. while True:
  447. try:
  448. return self._sock.recv_into(b)
  449. except timeout:
  450. self._timeout_occurred = True
  451. raise
  452. except InterruptedError:
  453. continue
  454. except error as e:
  455. if e.args[0] in _blocking_errnos:
  456. return None
  457. raise
  458. def write(self, b):
  459. """Write the given bytes or bytearray object *b* to the socket
  460. and return the number of bytes written. This can be less than
  461. len(b) if not all data could be written. If the socket is
  462. non-blocking and no bytes could be written None is returned.
  463. """
  464. self._checkClosed()
  465. self._checkWritable()
  466. try:
  467. return self._sock.send(b)
  468. except error as e:
  469. # XXX what about EINTR?
  470. if e.args[0] in _blocking_errnos:
  471. return None
  472. raise
  473. def readable(self):
  474. """True if the SocketIO is open for reading.
  475. """
  476. if self.closed:
  477. raise ValueError("I/O operation on closed socket.")
  478. return self._reading
  479. def writable(self):
  480. """True if the SocketIO is open for writing.
  481. """
  482. if self.closed:
  483. raise ValueError("I/O operation on closed socket.")
  484. return self._writing
  485. def seekable(self):
  486. """True if the SocketIO is open for seeking.
  487. """
  488. if self.closed:
  489. raise ValueError("I/O operation on closed socket.")
  490. return super().seekable()
  491. def fileno(self):
  492. """Return the file descriptor of the underlying socket.
  493. """
  494. self._checkClosed()
  495. return self._sock.fileno()
  496. @property
  497. def name(self):
  498. if not self.closed:
  499. return self.fileno()
  500. else:
  501. return -1
  502. @property
  503. def mode(self):
  504. return self._mode
  505. def close(self):
  506. """Close the SocketIO object. This doesn't close the underlying
  507. socket, except if all references to it have disappeared.
  508. """
  509. if self.closed:
  510. return
  511. io.RawIOBase.close(self)
  512. self._sock._decref_socketios()
  513. self._sock = None
  514. def getfqdn(name=''):
  515. """Get fully qualified domain name from name.
  516. An empty argument is interpreted as meaning the local host.
  517. First the hostname returned by gethostbyaddr() is checked, then
  518. possibly existing aliases. In case no FQDN is available, hostname
  519. from gethostname() is returned.
  520. """
  521. name = name.strip()
  522. if not name or name == '0.0.0.0':
  523. name = gethostname()
  524. try:
  525. hostname, aliases, ipaddrs = gethostbyaddr(name)
  526. except error:
  527. pass
  528. else:
  529. aliases.insert(0, hostname)
  530. for name in aliases:
  531. if '.' in name:
  532. break
  533. else:
  534. name = hostname
  535. return name
  536. _GLOBAL_DEFAULT_TIMEOUT = object()
  537. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
  538. source_address=None):
  539. """Connect to *address* and return the socket object.
  540. Convenience function. Connect to *address* (a 2-tuple ``(host,
  541. port)``) and return the socket object. Passing the optional
  542. *timeout* parameter will set the timeout on the socket instance
  543. before attempting to connect. If no *timeout* is supplied, the
  544. global default timeout setting returned by :func:`getdefaulttimeout`
  545. is used. If *source_address* is set it must be a tuple of (host, port)
  546. for the socket to bind as a source address before making the connection.
  547. An host of '' or port 0 tells the OS to use the default.
  548. """
  549. host, port = address
  550. err = None
  551. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  552. af, socktype, proto, canonname, sa = res
  553. sock = None
  554. try:
  555. sock = socket(af, socktype, proto)
  556. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  557. sock.settimeout(timeout)
  558. if source_address:
  559. sock.bind(source_address)
  560. sock.connect(sa)
  561. return sock
  562. except error as _:
  563. err = _
  564. if sock is not None:
  565. sock.close()
  566. if err is not None:
  567. raise err
  568. else:
  569. raise error("getaddrinfo returns an empty list")
  570. def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
  571. """Resolve host and port into list of address info entries.
  572. Translate the host/port argument into a sequence of 5-tuples that contain
  573. all the necessary arguments for creating a socket connected to that service.
  574. host is a domain name, a string representation of an IPv4/v6 address or
  575. None. port is a string service name such as 'http', a numeric port number or
  576. None. By passing None as the value of host and port, you can pass NULL to
  577. the underlying C API.
  578. The family, type and proto arguments can be optionally specified in order to
  579. narrow the list of addresses returned. Passing zero as a value for each of
  580. these arguments selects the full range of results.
  581. """
  582. # We override this function since we want to translate the numeric family
  583. # and socket type values to enum constants.
  584. addrlist = []
  585. for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
  586. af, socktype, proto, canonname, sa = res
  587. addrlist.append((_intenum_converter(af, AddressFamily),
  588. _intenum_converter(socktype, SocketType),
  589. proto, canonname, sa))
  590. return addrlist