socket.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. from __future__ import unicode_literals
  38. from __future__ import print_function
  39. from __future__ import division
  40. from __future__ import absolute_import
  41. from future.builtins import super
  42. import _socket
  43. from _socket import *
  44. import os, sys, io
  45. try:
  46. import errno
  47. except ImportError:
  48. errno = None
  49. EBADF = getattr(errno, 'EBADF', 9)
  50. EAGAIN = getattr(errno, 'EAGAIN', 11)
  51. EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11)
  52. __all__ = ["getfqdn", "create_connection"]
  53. __all__.extend(os._get_exports_list(_socket))
  54. _realsocket = socket
  55. # WSA error codes
  56. if sys.platform.lower().startswith("win"):
  57. errorTab = {}
  58. errorTab[10004] = "The operation was interrupted."
  59. errorTab[10009] = "A bad file handle was passed."
  60. errorTab[10013] = "Permission denied."
  61. errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
  62. errorTab[10022] = "An invalid operation was attempted."
  63. errorTab[10035] = "The socket operation would block"
  64. errorTab[10036] = "A blocking operation is already in progress."
  65. errorTab[10048] = "The network address is in use."
  66. errorTab[10054] = "The connection has been reset."
  67. errorTab[10058] = "The network has been shut down."
  68. errorTab[10060] = "The operation timed out."
  69. errorTab[10061] = "Connection refused."
  70. errorTab[10063] = "The name is too long."
  71. errorTab[10064] = "The host is down."
  72. errorTab[10065] = "The host is unreachable."
  73. __all__.append("errorTab")
  74. class socket(_socket.socket):
  75. """A subclass of _socket.socket adding the makefile() method."""
  76. __slots__ = ["__weakref__", "_io_refs", "_closed"]
  77. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
  78. if fileno is None:
  79. _socket.socket.__init__(self, family, type, proto)
  80. else:
  81. _socket.socket.__init__(self, family, type, proto, fileno)
  82. self._io_refs = 0
  83. self._closed = False
  84. def __enter__(self):
  85. return self
  86. def __exit__(self, *args):
  87. if not self._closed:
  88. self.close()
  89. def __repr__(self):
  90. """Wrap __repr__() to reveal the real class name."""
  91. s = _socket.socket.__repr__(self)
  92. if s.startswith("<socket object"):
  93. s = "<%s.%s%s%s" % (self.__class__.__module__,
  94. self.__class__.__name__,
  95. getattr(self, '_closed', False) and " [closed] " or "",
  96. s[7:])
  97. return s
  98. def __getstate__(self):
  99. raise TypeError("Cannot serialize socket object")
  100. def dup(self):
  101. """dup() -> socket object
  102. Return a new socket object connected to the same system resource.
  103. """
  104. fd = dup(self.fileno())
  105. sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
  106. sock.settimeout(self.gettimeout())
  107. return sock
  108. def accept(self):
  109. """accept() -> (socket object, address info)
  110. Wait for an incoming connection. Return a new socket
  111. representing the connection, and the address of the client.
  112. For IP sockets, the address info is a pair (hostaddr, port).
  113. """
  114. fd, addr = self._accept()
  115. sock = socket(self.family, self.type, self.proto, fileno=fd)
  116. # Issue #7995: if no default timeout is set and the listening
  117. # socket had a (non-zero) timeout, force the new socket in blocking
  118. # mode to override platform-specific socket flags inheritance.
  119. if getdefaulttimeout() is None and self.gettimeout():
  120. sock.setblocking(True)
  121. return sock, addr
  122. def makefile(self, mode="r", buffering=None, **_3to2kwargs):
  123. """makefile(...) -> an I/O stream connected to the socket
  124. The arguments are as for io.open() after the filename,
  125. except the only mode characters supported are 'r', 'w' and 'b'.
  126. The semantics are similar too. (XXX refactor to share code?)
  127. """
  128. if 'newline' in _3to2kwargs: newline = _3to2kwargs['newline']; del _3to2kwargs['newline']
  129. else: newline = None
  130. if 'errors' in _3to2kwargs: errors = _3to2kwargs['errors']; del _3to2kwargs['errors']
  131. else: errors = None
  132. if 'encoding' in _3to2kwargs: encoding = _3to2kwargs['encoding']; del _3to2kwargs['encoding']
  133. else: encoding = None
  134. for c in mode:
  135. if c not in ("r", "w", "b"):
  136. raise ValueError("invalid mode %r (only r, w, b allowed)")
  137. writing = "w" in mode
  138. reading = "r" in mode or not writing
  139. assert reading or writing
  140. binary = "b" in mode
  141. rawmode = ""
  142. if reading:
  143. rawmode += "r"
  144. if writing:
  145. rawmode += "w"
  146. raw = SocketIO(self, rawmode)
  147. self._io_refs += 1
  148. if buffering is None:
  149. buffering = -1
  150. if buffering < 0:
  151. buffering = io.DEFAULT_BUFFER_SIZE
  152. if buffering == 0:
  153. if not binary:
  154. raise ValueError("unbuffered streams must be binary")
  155. return raw
  156. if reading and writing:
  157. buffer = io.BufferedRWPair(raw, raw, buffering)
  158. elif reading:
  159. buffer = io.BufferedReader(raw, buffering)
  160. else:
  161. assert writing
  162. buffer = io.BufferedWriter(raw, buffering)
  163. if binary:
  164. return buffer
  165. text = io.TextIOWrapper(buffer, encoding, errors, newline)
  166. text.mode = mode
  167. return text
  168. def _decref_socketios(self):
  169. if self._io_refs > 0:
  170. self._io_refs -= 1
  171. if self._closed:
  172. self.close()
  173. def _real_close(self, _ss=_socket.socket):
  174. # This function should not reference any globals. See issue #808164.
  175. _ss.close(self)
  176. def close(self):
  177. # This function should not reference any globals. See issue #808164.
  178. self._closed = True
  179. if self._io_refs <= 0:
  180. self._real_close()
  181. def detach(self):
  182. """detach() -> file descriptor
  183. Close the socket object without closing the underlying file descriptor.
  184. The object cannot be used after this call, but the file descriptor
  185. can be reused for other purposes. The file descriptor is returned.
  186. """
  187. self._closed = True
  188. return super().detach()
  189. def fromfd(fd, family, type, proto=0):
  190. """ fromfd(fd, family, type[, proto]) -> socket object
  191. Create a socket object from a duplicate of the given file
  192. descriptor. The remaining arguments are the same as for socket().
  193. """
  194. nfd = dup(fd)
  195. return socket(family, type, proto, nfd)
  196. if hasattr(_socket.socket, "share"):
  197. def fromshare(info):
  198. """ fromshare(info) -> socket object
  199. Create a socket object from a the bytes object returned by
  200. socket.share(pid).
  201. """
  202. return socket(0, 0, 0, info)
  203. if hasattr(_socket, "socketpair"):
  204. def socketpair(family=None, type=SOCK_STREAM, proto=0):
  205. """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  206. Create a pair of socket objects from the sockets returned by the platform
  207. socketpair() function.
  208. The arguments are the same as for socket() except the default family is
  209. AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
  210. """
  211. if family is None:
  212. try:
  213. family = AF_UNIX
  214. except NameError:
  215. family = AF_INET
  216. a, b = _socket.socketpair(family, type, proto)
  217. a = socket(family, type, proto, a.detach())
  218. b = socket(family, type, proto, b.detach())
  219. return a, b
  220. _blocking_errnos = set([EAGAIN, EWOULDBLOCK])
  221. class SocketIO(io.RawIOBase):
  222. """Raw I/O implementation for stream sockets.
  223. This class supports the makefile() method on sockets. It provides
  224. the raw I/O interface on top of a socket object.
  225. """
  226. # One might wonder why not let FileIO do the job instead. There are two
  227. # main reasons why FileIO is not adapted:
  228. # - it wouldn't work under Windows (where you can't used read() and
  229. # write() on a socket handle)
  230. # - it wouldn't work with socket timeouts (FileIO would ignore the
  231. # timeout and consider the socket non-blocking)
  232. # XXX More docs
  233. def __init__(self, sock, mode):
  234. if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
  235. raise ValueError("invalid mode: %r" % mode)
  236. io.RawIOBase.__init__(self)
  237. self._sock = sock
  238. if "b" not in mode:
  239. mode += "b"
  240. self._mode = mode
  241. self._reading = "r" in mode
  242. self._writing = "w" in mode
  243. self._timeout_occurred = False
  244. def readinto(self, b):
  245. """Read up to len(b) bytes into the writable buffer *b* and return
  246. the number of bytes read. If the socket is non-blocking and no bytes
  247. are available, None is returned.
  248. If *b* is non-empty, a 0 return value indicates that the connection
  249. was shutdown at the other end.
  250. """
  251. self._checkClosed()
  252. self._checkReadable()
  253. if self._timeout_occurred:
  254. raise IOError("cannot read from timed out object")
  255. while True:
  256. try:
  257. return self._sock.recv_into(b)
  258. except timeout:
  259. self._timeout_occurred = True
  260. raise
  261. # except InterruptedError:
  262. # continue
  263. except error as e:
  264. if e.args[0] in _blocking_errnos:
  265. return None
  266. raise
  267. def write(self, b):
  268. """Write the given bytes or bytearray object *b* to the socket
  269. and return the number of bytes written. This can be less than
  270. len(b) if not all data could be written. If the socket is
  271. non-blocking and no bytes could be written None is returned.
  272. """
  273. self._checkClosed()
  274. self._checkWritable()
  275. try:
  276. return self._sock.send(b)
  277. except error as e:
  278. # XXX what about EINTR?
  279. if e.args[0] in _blocking_errnos:
  280. return None
  281. raise
  282. def readable(self):
  283. """True if the SocketIO is open for reading.
  284. """
  285. if self.closed:
  286. raise ValueError("I/O operation on closed socket.")
  287. return self._reading
  288. def writable(self):
  289. """True if the SocketIO is open for writing.
  290. """
  291. if self.closed:
  292. raise ValueError("I/O operation on closed socket.")
  293. return self._writing
  294. def seekable(self):
  295. """True if the SocketIO is open for seeking.
  296. """
  297. if self.closed:
  298. raise ValueError("I/O operation on closed socket.")
  299. return super().seekable()
  300. def fileno(self):
  301. """Return the file descriptor of the underlying socket.
  302. """
  303. self._checkClosed()
  304. return self._sock.fileno()
  305. @property
  306. def name(self):
  307. if not self.closed:
  308. return self.fileno()
  309. else:
  310. return -1
  311. @property
  312. def mode(self):
  313. return self._mode
  314. def close(self):
  315. """Close the SocketIO object. This doesn't close the underlying
  316. socket, except if all references to it have disappeared.
  317. """
  318. if self.closed:
  319. return
  320. io.RawIOBase.close(self)
  321. self._sock._decref_socketios()
  322. self._sock = None
  323. def getfqdn(name=''):
  324. """Get fully qualified domain name from name.
  325. An empty argument is interpreted as meaning the local host.
  326. First the hostname returned by gethostbyaddr() is checked, then
  327. possibly existing aliases. In case no FQDN is available, hostname
  328. from gethostname() is returned.
  329. """
  330. name = name.strip()
  331. if not name or name == '0.0.0.0':
  332. name = gethostname()
  333. try:
  334. hostname, aliases, ipaddrs = gethostbyaddr(name)
  335. except error:
  336. pass
  337. else:
  338. aliases.insert(0, hostname)
  339. for name in aliases:
  340. if '.' in name:
  341. break
  342. else:
  343. name = hostname
  344. return name
  345. # Re-use the same sentinel as in the Python stdlib socket module:
  346. from socket import _GLOBAL_DEFAULT_TIMEOUT
  347. # Was: _GLOBAL_DEFAULT_TIMEOUT = object()
  348. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
  349. source_address=None):
  350. """Connect to *address* and return the socket object.
  351. Convenience function. Connect to *address* (a 2-tuple ``(host,
  352. port)``) and return the socket object. Passing the optional
  353. *timeout* parameter will set the timeout on the socket instance
  354. before attempting to connect. If no *timeout* is supplied, the
  355. global default timeout setting returned by :func:`getdefaulttimeout`
  356. is used. If *source_address* is set it must be a tuple of (host, port)
  357. for the socket to bind as a source address before making the connection.
  358. An host of '' or port 0 tells the OS to use the default.
  359. """
  360. host, port = address
  361. err = None
  362. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  363. af, socktype, proto, canonname, sa = res
  364. sock = None
  365. try:
  366. sock = socket(af, socktype, proto)
  367. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  368. sock.settimeout(timeout)
  369. if source_address:
  370. sock.bind(source_address)
  371. sock.connect(sa)
  372. return sock
  373. except error as _:
  374. err = _
  375. if sock is not None:
  376. sock.close()
  377. if err is not None:
  378. raise err
  379. else:
  380. raise error("getaddrinfo returns an empty list")