PageRenderTime 53ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/socket.py

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