PageRenderTime 45ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/kbe/res/scripts/common/Lib/socket.py

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