PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/socket.py

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