PageRenderTime 54ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/socket.py

https://bitbucket.org/atsuoishimoto/cpython
Python | 535 lines | 507 code | 1 blank | 27 comment | 0 complexity | 6837ab88895443c67247da301e7b2e0d 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. 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 socket(_socket.socket):
  92. """A subclass of _socket.socket adding the makefile() method."""
  93. __slots__ = ["__weakref__", "_io_refs", "_closed"]
  94. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
  95. # For user code address family and type values are IntEnum members, but
  96. # for the underlying _socket.socket they're just integers. The
  97. # constructor of _socket.socket converts the given argument to an
  98. # integer automatically.
  99. _socket.socket.__init__(self, family, type, proto, fileno)
  100. self._io_refs = 0
  101. self._closed = False
  102. def __enter__(self):
  103. return self
  104. def __exit__(self, *args):
  105. if not self._closed:
  106. self.close()
  107. def __repr__(self):
  108. """Wrap __repr__() to reveal the real class name and socket
  109. address(es).
  110. """
  111. closed = getattr(self, '_closed', False)
  112. s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \
  113. % (self.__class__.__module__,
  114. self.__class__.__name__,
  115. " [closed]" if closed else "",
  116. self.fileno(),
  117. self.family,
  118. self.type,
  119. self.proto)
  120. if not closed:
  121. try:
  122. laddr = self.getsockname()
  123. if laddr:
  124. s += ", laddr=%s" % str(laddr)
  125. except error:
  126. pass
  127. try:
  128. raddr = self.getpeername()
  129. if raddr:
  130. s += ", raddr=%s" % str(raddr)
  131. except error:
  132. pass
  133. s += '>'
  134. return s
  135. def __getstate__(self):
  136. raise TypeError("Cannot serialize socket object")
  137. def dup(self):
  138. """dup() -> socket object
  139. Duplicate the socket. Return a new socket object connected to the same
  140. system resource. The new socket is non-inheritable.
  141. """
  142. fd = dup(self.fileno())
  143. sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
  144. sock.settimeout(self.gettimeout())
  145. return sock
  146. def accept(self):
  147. """accept() -> (socket object, address info)
  148. Wait for an incoming connection. Return a new socket
  149. representing the connection, and the address of the client.
  150. For IP sockets, the address info is a pair (hostaddr, port).
  151. """
  152. fd, addr = self._accept()
  153. sock = socket(self.family, self.type, self.proto, fileno=fd)
  154. # Issue #7995: if no default timeout is set and the listening
  155. # socket had a (non-zero) timeout, force the new socket in blocking
  156. # mode to override platform-specific socket flags inheritance.
  157. if getdefaulttimeout() is None and self.gettimeout():
  158. sock.setblocking(True)
  159. return sock, addr
  160. def makefile(self, mode="r", buffering=None, *,
  161. encoding=None, errors=None, newline=None):
  162. """makefile(...) -> an I/O stream connected to the socket
  163. The arguments are as for io.open() after the filename,
  164. except the only mode characters supported are 'r', 'w' and 'b'.
  165. The semantics are similar too. (XXX refactor to share code?)
  166. """
  167. for c in mode:
  168. if c not in {"r", "w", "b"}:
  169. raise ValueError("invalid mode %r (only r, w, b allowed)")
  170. writing = "w" in mode
  171. reading = "r" in mode or not writing
  172. assert reading or writing
  173. binary = "b" in mode
  174. rawmode = ""
  175. if reading:
  176. rawmode += "r"
  177. if writing:
  178. rawmode += "w"
  179. raw = SocketIO(self, rawmode)
  180. self._io_refs += 1
  181. if buffering is None:
  182. buffering = -1
  183. if buffering < 0:
  184. buffering = io.DEFAULT_BUFFER_SIZE
  185. if buffering == 0:
  186. if not binary:
  187. raise ValueError("unbuffered streams must be binary")
  188. return raw
  189. if reading and writing:
  190. buffer = io.BufferedRWPair(raw, raw, buffering)
  191. elif reading:
  192. buffer = io.BufferedReader(raw, buffering)
  193. else:
  194. assert writing
  195. buffer = io.BufferedWriter(raw, buffering)
  196. if binary:
  197. return buffer
  198. text = io.TextIOWrapper(buffer, encoding, errors, newline)
  199. text.mode = mode
  200. return text
  201. def _decref_socketios(self):
  202. if self._io_refs > 0:
  203. self._io_refs -= 1
  204. if self._closed:
  205. self.close()
  206. def _real_close(self, _ss=_socket.socket):
  207. # This function should not reference any globals. See issue #808164.
  208. _ss.close(self)
  209. def close(self):
  210. # This function should not reference any globals. See issue #808164.
  211. self._closed = True
  212. if self._io_refs <= 0:
  213. self._real_close()
  214. def detach(self):
  215. """detach() -> file descriptor
  216. Close the socket object without closing the underlying file descriptor.
  217. The object cannot be used after this call, but the file descriptor
  218. can be reused for other purposes. The file descriptor is returned.
  219. """
  220. self._closed = True
  221. return super().detach()
  222. @property
  223. def family(self):
  224. """Read-only access to the address family for this socket.
  225. """
  226. return _intenum_converter(super().family, AddressFamily)
  227. @property
  228. def type(self):
  229. """Read-only access to the socket type.
  230. """
  231. return _intenum_converter(super().type, SocketType)
  232. if os.name == 'nt':
  233. def get_inheritable(self):
  234. return os.get_handle_inheritable(self.fileno())
  235. def set_inheritable(self, inheritable):
  236. os.set_handle_inheritable(self.fileno(), inheritable)
  237. else:
  238. def get_inheritable(self):
  239. return os.get_inheritable(self.fileno())
  240. def set_inheritable(self, inheritable):
  241. os.set_inheritable(self.fileno(), inheritable)
  242. get_inheritable.__doc__ = "Get the inheritable flag of the socket"
  243. set_inheritable.__doc__ = "Set the inheritable flag of the socket"
  244. def fromfd(fd, family, type, proto=0):
  245. """ fromfd(fd, family, type[, proto]) -> socket object
  246. Create a socket object from a duplicate of the given file
  247. descriptor. The remaining arguments are the same as for socket().
  248. """
  249. nfd = dup(fd)
  250. return socket(family, type, proto, nfd)
  251. if hasattr(_socket.socket, "share"):
  252. def fromshare(info):
  253. """ fromshare(info) -> socket object
  254. Create a socket object from a the bytes object returned by
  255. socket.share(pid).
  256. """
  257. return socket(0, 0, 0, info)
  258. if hasattr(_socket, "socketpair"):
  259. def socketpair(family=None, type=SOCK_STREAM, proto=0):
  260. """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  261. Create a pair of socket objects from the sockets returned by the platform
  262. socketpair() function.
  263. The arguments are the same as for socket() except the default family is
  264. AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
  265. """
  266. if family is None:
  267. try:
  268. family = AF_UNIX
  269. except NameError:
  270. family = AF_INET
  271. a, b = _socket.socketpair(family, type, proto)
  272. a = socket(family, type, proto, a.detach())
  273. b = socket(family, type, proto, b.detach())
  274. return a, b
  275. _blocking_errnos = { EAGAIN, EWOULDBLOCK }
  276. class SocketIO(io.RawIOBase):
  277. """Raw I/O implementation for stream sockets.
  278. This class supports the makefile() method on sockets. It provides
  279. the raw I/O interface on top of a socket object.
  280. """
  281. # One might wonder why not let FileIO do the job instead. There are two
  282. # main reasons why FileIO is not adapted:
  283. # - it wouldn't work under Windows (where you can't used read() and
  284. # write() on a socket handle)
  285. # - it wouldn't work with socket timeouts (FileIO would ignore the
  286. # timeout and consider the socket non-blocking)
  287. # XXX More docs
  288. def __init__(self, sock, mode):
  289. if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
  290. raise ValueError("invalid mode: %r" % mode)
  291. io.RawIOBase.__init__(self)
  292. self._sock = sock
  293. if "b" not in mode:
  294. mode += "b"
  295. self._mode = mode
  296. self._reading = "r" in mode
  297. self._writing = "w" in mode
  298. self._timeout_occurred = False
  299. def readinto(self, b):
  300. """Read up to len(b) bytes into the writable buffer *b* and return
  301. the number of bytes read. If the socket is non-blocking and no bytes
  302. are available, None is returned.
  303. If *b* is non-empty, a 0 return value indicates that the connection
  304. was shutdown at the other end.
  305. """
  306. self._checkClosed()
  307. self._checkReadable()
  308. if self._timeout_occurred:
  309. raise OSError("cannot read from timed out object")
  310. while True:
  311. try:
  312. return self._sock.recv_into(b)
  313. except timeout:
  314. self._timeout_occurred = True
  315. raise
  316. except InterruptedError:
  317. continue
  318. except error as e:
  319. if e.args[0] in _blocking_errnos:
  320. return None
  321. raise
  322. def write(self, b):
  323. """Write the given bytes or bytearray object *b* to the socket
  324. and return the number of bytes written. This can be less than
  325. len(b) if not all data could be written. If the socket is
  326. non-blocking and no bytes could be written None is returned.
  327. """
  328. self._checkClosed()
  329. self._checkWritable()
  330. try:
  331. return self._sock.send(b)
  332. except error as e:
  333. # XXX what about EINTR?
  334. if e.args[0] in _blocking_errnos:
  335. return None
  336. raise
  337. def readable(self):
  338. """True if the SocketIO is open for reading.
  339. """
  340. if self.closed:
  341. raise ValueError("I/O operation on closed socket.")
  342. return self._reading
  343. def writable(self):
  344. """True if the SocketIO is open for writing.
  345. """
  346. if self.closed:
  347. raise ValueError("I/O operation on closed socket.")
  348. return self._writing
  349. def seekable(self):
  350. """True if the SocketIO is open for seeking.
  351. """
  352. if self.closed:
  353. raise ValueError("I/O operation on closed socket.")
  354. return super().seekable()
  355. def fileno(self):
  356. """Return the file descriptor of the underlying socket.
  357. """
  358. self._checkClosed()
  359. return self._sock.fileno()
  360. @property
  361. def name(self):
  362. if not self.closed:
  363. return self.fileno()
  364. else:
  365. return -1
  366. @property
  367. def mode(self):
  368. return self._mode
  369. def close(self):
  370. """Close the SocketIO object. This doesn't close the underlying
  371. socket, except if all references to it have disappeared.
  372. """
  373. if self.closed:
  374. return
  375. io.RawIOBase.close(self)
  376. self._sock._decref_socketios()
  377. self._sock = None
  378. def getfqdn(name=''):
  379. """Get fully qualified domain name from name.
  380. An empty argument is interpreted as meaning the local host.
  381. First the hostname returned by gethostbyaddr() is checked, then
  382. possibly existing aliases. In case no FQDN is available, hostname
  383. from gethostname() is returned.
  384. """
  385. name = name.strip()
  386. if not name or name == '0.0.0.0':
  387. name = gethostname()
  388. try:
  389. hostname, aliases, ipaddrs = gethostbyaddr(name)
  390. except error:
  391. pass
  392. else:
  393. aliases.insert(0, hostname)
  394. for name in aliases:
  395. if '.' in name:
  396. break
  397. else:
  398. name = hostname
  399. return name
  400. _GLOBAL_DEFAULT_TIMEOUT = object()
  401. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
  402. source_address=None):
  403. """Connect to *address* and return the socket object.
  404. Convenience function. Connect to *address* (a 2-tuple ``(host,
  405. port)``) and return the socket object. Passing the optional
  406. *timeout* parameter will set the timeout on the socket instance
  407. before attempting to connect. If no *timeout* is supplied, the
  408. global default timeout setting returned by :func:`getdefaulttimeout`
  409. is used. If *source_address* is set it must be a tuple of (host, port)
  410. for the socket to bind as a source address before making the connection.
  411. An host of '' or port 0 tells the OS to use the default.
  412. """
  413. host, port = address
  414. err = None
  415. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  416. af, socktype, proto, canonname, sa = res
  417. sock = None
  418. try:
  419. sock = socket(af, socktype, proto)
  420. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  421. sock.settimeout(timeout)
  422. if source_address:
  423. sock.bind(source_address)
  424. sock.connect(sa)
  425. return sock
  426. except error as _:
  427. err = _
  428. if sock is not None:
  429. sock.close()
  430. if err is not None:
  431. raise err
  432. else:
  433. raise error("getaddrinfo returns an empty list")
  434. def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
  435. """Resolve host and port into list of address info entries.
  436. Translate the host/port argument into a sequence of 5-tuples that contain
  437. all the necessary arguments for creating a socket connected to that service.
  438. host is a domain name, a string representation of an IPv4/v6 address or
  439. None. port is a string service name such as 'http', a numeric port number or
  440. None. By passing None as the value of host and port, you can pass NULL to
  441. the underlying C API.
  442. The family, type and proto arguments can be optionally specified in order to
  443. narrow the list of addresses returned. Passing zero as a value for each of
  444. these arguments selects the full range of results.
  445. """
  446. # We override this function since we want to translate the numeric family
  447. # and socket type values to enum constants.
  448. addrlist = []
  449. for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
  450. af, socktype, proto, canonname, sa = res
  451. addrlist.append((_intenum_converter(af, AddressFamily),
  452. _intenum_converter(socktype, SocketType),
  453. proto, canonname, sa))
  454. return addrlist