PageRenderTime 41ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/gevent/socket.py

https://github.com/Taik/gevent
Python | 669 lines | 555 code | 41 blank | 73 comment | 69 complexity | 8d0ffa95fc0ae256c356d23104417d07 MD5 | raw file
Possible License(s): BSD-2-Clause
  1. # Copyright (c) 2005-2006, Bob Ippolito
  2. # Copyright (c) 2007, Linden Research, Inc.
  3. # Copyright (c) 2009-2012 Denis Bilenko
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. # THE SOFTWARE.
  22. """Cooperative socket module.
  23. This module provides socket operations and some related functions.
  24. The API of the functions and classes matches the API of the corresponding
  25. items in standard :mod:`socket` module exactly, but the synchronous functions
  26. in this module only block the current greenlet and let the others run.
  27. For convenience, exceptions (like :class:`error <socket.error>` and :class:`timeout <socket.timeout>`)
  28. as well as the constants from :mod:`socket` module are imported into this module.
  29. """
  30. from __future__ import absolute_import
  31. # standard functions and classes that this module re-implements in a gevent-aware way:
  32. __implements__ = ['create_connection',
  33. 'socket',
  34. 'SocketType',
  35. 'fromfd',
  36. 'socketpair']
  37. __dns__ = ['getaddrinfo',
  38. 'gethostbyname',
  39. 'gethostbyname_ex',
  40. 'gethostbyaddr',
  41. 'getnameinfo',
  42. 'getfqdn']
  43. __implements__ += __dns__
  44. # non-standard functions that this module provides:
  45. __extensions__ = ['wait_read',
  46. 'wait_write',
  47. 'wait_readwrite']
  48. # standard functions and classes that this module re-imports
  49. __imports__ = ['error',
  50. 'gaierror',
  51. 'herror',
  52. 'htonl',
  53. 'htons',
  54. 'ntohl',
  55. 'ntohs',
  56. 'inet_aton',
  57. 'inet_ntoa',
  58. 'inet_pton',
  59. 'inet_ntop',
  60. 'timeout',
  61. 'gethostname',
  62. 'getprotobyname',
  63. 'getservbyname',
  64. 'getservbyport',
  65. 'getdefaulttimeout',
  66. 'setdefaulttimeout',
  67. # Python 2.5 and older:
  68. 'RAND_add',
  69. 'RAND_egd',
  70. 'RAND_status',
  71. # Windows:
  72. 'errorTab']
  73. import sys
  74. import time
  75. from gevent.hub import get_hub, string_types, integer_types
  76. from gevent.timeout import Timeout
  77. is_windows = sys.platform == 'win32'
  78. if is_windows:
  79. # no such thing as WSAEPERM or error code 10001 according to winsock.h or MSDN
  80. from errno import WSAEINVAL as EINVAL
  81. from errno import WSAEWOULDBLOCK as EWOULDBLOCK
  82. from errno import WSAEINPROGRESS as EINPROGRESS
  83. from errno import WSAEALREADY as EALREADY
  84. from errno import WSAEISCONN as EISCONN
  85. from gevent.win32util import formatError as strerror
  86. EAGAIN = EWOULDBLOCK
  87. else:
  88. from errno import EINVAL
  89. from errno import EWOULDBLOCK
  90. from errno import EINPROGRESS
  91. from errno import EALREADY
  92. from errno import EAGAIN
  93. from errno import EISCONN
  94. from os import strerror
  95. try:
  96. from errno import EBADF
  97. except ImportError:
  98. EBADF = 9
  99. import _socket
  100. _realsocket = _socket.socket
  101. import socket as __socket__
  102. _fileobject = __socket__._fileobject
  103. for name in __imports__[:]:
  104. try:
  105. value = getattr(__socket__, name)
  106. globals()[name] = value
  107. except AttributeError:
  108. __imports__.remove(name)
  109. for name in __socket__.__all__:
  110. value = getattr(__socket__, name)
  111. if isinstance(value, integer_types) or isinstance(value, string_types):
  112. globals()[name] = value
  113. __imports__.append(name)
  114. del name, value
  115. def wait(io, timeout=None, timeout_exc=timeout('timed out')):
  116. """Block the current greenlet until *io* is ready.
  117. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  118. By default *timeout_exc* is ``socket.timeout('timed out')``.
  119. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  120. """
  121. assert io.callback is None, 'This socket is already used by another greenlet: %r' % (io.callback, )
  122. if timeout is not None:
  123. timeout = Timeout.start_new(timeout, timeout_exc)
  124. try:
  125. return get_hub().wait(io)
  126. finally:
  127. if timeout is not None:
  128. timeout.cancel()
  129. # rename "io" to "watcher" because wait() works with any watcher
  130. def wait_read(fileno, timeout=None, timeout_exc=timeout('timed out')):
  131. """Block the current greenlet until *fileno* is ready to read.
  132. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  133. By default *timeout_exc* is ``socket.timeout('timed out')``.
  134. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  135. """
  136. io = get_hub().loop.io(fileno, 1)
  137. return wait(io, timeout, timeout_exc)
  138. def wait_write(fileno, timeout=None, timeout_exc=timeout('timed out'), event=None):
  139. """Block the current greenlet until *fileno* is ready to write.
  140. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  141. By default *timeout_exc* is ``socket.timeout('timed out')``.
  142. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  143. """
  144. io = get_hub().loop.io(fileno, 2)
  145. return wait(io, timeout, timeout_exc)
  146. def wait_readwrite(fileno, timeout=None, timeout_exc=timeout('timed out'), event=None):
  147. """Block the current greenlet until *fileno* is ready to read or write.
  148. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  149. By default *timeout_exc* is ``socket.timeout('timed out')``.
  150. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  151. """
  152. io = get_hub().loop.io(fileno, 3)
  153. return wait(io, timeout, timeout_exc)
  154. cancel_wait_ex = error(EBADF, 'File descriptor was closed in another greenlet')
  155. def cancel_wait(watcher):
  156. get_hub().cancel_wait(watcher, cancel_wait_ex)
  157. if sys.version_info[:2] < (2, 7):
  158. _get_memory = buffer
  159. elif sys.version_info[:2] < (3, 0):
  160. def _get_memory(string, offset):
  161. try:
  162. return memoryview(string)[offset:]
  163. except TypeError:
  164. return buffer(string, offset)
  165. else:
  166. def _get_memory(string, offset):
  167. return memoryview(string)[offset:]
  168. class _closedsocket(object):
  169. __slots__ = []
  170. def _dummy(*args, **kwargs):
  171. raise error(EBADF, 'Bad file descriptor')
  172. # All _delegate_methods must also be initialized here.
  173. send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
  174. __getattr__ = _dummy
  175. timeout_default = object()
  176. class socket(object):
  177. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
  178. if _sock is None:
  179. self._sock = _realsocket(family, type, proto)
  180. self.timeout = _socket.getdefaulttimeout()
  181. else:
  182. if hasattr(_sock, '_sock'):
  183. self._sock = _sock._sock
  184. self.timeout = getattr(_sock, 'timeout', False)
  185. if self.timeout is False:
  186. self.timeout = _socket.getdefaulttimeout()
  187. else:
  188. self._sock = _sock
  189. self.timeout = _socket.getdefaulttimeout()
  190. self._sock.setblocking(0)
  191. fileno = self._sock.fileno()
  192. self.hub = get_hub()
  193. io = self.hub.loop.io
  194. self._read_event = io(fileno, 1)
  195. self._write_event = io(fileno, 2)
  196. def __repr__(self):
  197. return '<%s at %s %s>' % (type(self).__name__, hex(id(self)), self._formatinfo())
  198. def __str__(self):
  199. return '<%s %s>' % (type(self).__name__, self._formatinfo())
  200. def _formatinfo(self):
  201. try:
  202. fileno = self.fileno()
  203. except Exception:
  204. fileno = str(sys.exc_info()[1])
  205. try:
  206. sockname = self.getsockname()
  207. sockname = '%s:%s' % sockname
  208. except Exception:
  209. sockname = None
  210. try:
  211. peername = self.getpeername()
  212. peername = '%s:%s' % peername
  213. except Exception:
  214. peername = None
  215. result = 'fileno=%s' % fileno
  216. if sockname is not None:
  217. result += ' sock=' + str(sockname)
  218. if peername is not None:
  219. result += ' peer=' + str(peername)
  220. if getattr(self, 'timeout', None) is not None:
  221. result += ' timeout=' + str(self.timeout)
  222. return result
  223. def _get_ref(self):
  224. return self._read_event.ref or self._write_event.ref
  225. def _set_ref(self, value):
  226. self._read_event.ref = value
  227. self._write_event.ref = value
  228. ref = property(_get_ref, _set_ref)
  229. def _wait(self, watcher, timeout_exc=timeout('timed out')):
  230. """Block the current greenlet until *watcher* has pending events.
  231. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  232. By default *timeout_exc* is ``socket.timeout('timed out')``.
  233. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  234. """
  235. assert watcher.callback is None, 'This socket is already used by another greenlet: %r' % (watcher.callback, )
  236. if self.timeout is not None:
  237. timeout = Timeout.start_new(self.timeout, timeout_exc, ref=False)
  238. else:
  239. timeout = None
  240. try:
  241. self.hub.wait(watcher)
  242. finally:
  243. if timeout is not None:
  244. timeout.cancel()
  245. def accept(self):
  246. sock = self._sock
  247. while True:
  248. try:
  249. client_socket, address = sock.accept()
  250. break
  251. except error:
  252. ex = sys.exc_info()[1]
  253. if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
  254. raise
  255. sys.exc_clear()
  256. self._wait(self._read_event)
  257. return socket(_sock=client_socket), address
  258. def close(self, _closedsocket=_closedsocket, cancel_wait_ex=cancel_wait_ex):
  259. # This function should not reference any globals. See Python issue #808164.
  260. self.hub.cancel_wait(self._read_event, cancel_wait_ex)
  261. self.hub.cancel_wait(self._write_event, cancel_wait_ex)
  262. self._sock = _closedsocket()
  263. @property
  264. def closed(self):
  265. return isinstance(self._sock, _closedsocket)
  266. def connect(self, address):
  267. if self.timeout == 0.0:
  268. return self._sock.connect(address)
  269. sock = self._sock
  270. if isinstance(address, tuple):
  271. r = getaddrinfo(address[0], address[1], sock.family, sock.type, sock.proto)
  272. address = r[0][-1]
  273. if self.timeout is not None:
  274. timer = Timeout.start_new(self.timeout, timeout('timed out'))
  275. else:
  276. timer = None
  277. try:
  278. while True:
  279. err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
  280. if err:
  281. raise error(err, strerror(err))
  282. result = sock.connect_ex(address)
  283. if not result or result == EISCONN:
  284. break
  285. elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
  286. self._wait(self._write_event)
  287. else:
  288. raise error(result, strerror(result))
  289. finally:
  290. if timer is not None:
  291. timer.cancel()
  292. def connect_ex(self, address):
  293. try:
  294. return self.connect(address) or 0
  295. except timeout:
  296. return EAGAIN
  297. except error:
  298. ex = sys.exc_info()[1]
  299. if type(ex) is error:
  300. return ex.args[0]
  301. else:
  302. raise # gaierror is not silented by connect_ex
  303. def dup(self):
  304. """dup() -> socket object
  305. Return a new socket object connected to the same system resource.
  306. Note, that the new socket does not inherit the timeout."""
  307. return socket(_sock=self._sock)
  308. def makefile(self, mode='r', bufsize=-1):
  309. # Two things to look out for:
  310. # 1) Closing the original socket object should not close the
  311. # socket (hence creating a new instance)
  312. # 2) The resulting fileobject must keep the timeout in order
  313. # to be compatible with the stdlib's socket.makefile.
  314. return _fileobject(type(self)(_sock=self), mode, bufsize)
  315. def recv(self, *args):
  316. sock = self._sock # keeping the reference so that fd is not closed during waiting
  317. while True:
  318. try:
  319. return sock.recv(*args)
  320. except error:
  321. ex = sys.exc_info()[1]
  322. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  323. raise
  324. # QQQ without clearing exc_info test__refcount.test_clean_exit fails
  325. sys.exc_clear()
  326. self._wait(self._read_event)
  327. def recvfrom(self, *args):
  328. sock = self._sock
  329. while True:
  330. try:
  331. return sock.recvfrom(*args)
  332. except error:
  333. ex = sys.exc_info()[1]
  334. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  335. raise
  336. sys.exc_clear()
  337. self._wait(self._read_event)
  338. def recvfrom_into(self, *args):
  339. sock = self._sock
  340. while True:
  341. try:
  342. return sock.recvfrom_into(*args)
  343. except error:
  344. ex = sys.exc_info()[1]
  345. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  346. raise
  347. sys.exc_clear()
  348. self._wait(self._read_event)
  349. def recv_into(self, *args):
  350. sock = self._sock
  351. while True:
  352. try:
  353. return sock.recv_into(*args)
  354. except error:
  355. ex = sys.exc_info()[1]
  356. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  357. raise
  358. sys.exc_clear()
  359. self._wait(self._read_event)
  360. def send(self, data, flags=0, timeout=timeout_default):
  361. sock = self._sock
  362. if timeout is timeout_default:
  363. timeout = self.timeout
  364. try:
  365. return sock.send(data, flags)
  366. except error:
  367. ex = sys.exc_info()[1]
  368. if ex.args[0] != EWOULDBLOCK or timeout == 0.0:
  369. raise
  370. sys.exc_clear()
  371. self._wait(self._write_event)
  372. try:
  373. return sock.send(data, flags)
  374. except error:
  375. ex2 = sys.exc_info()[1]
  376. if ex2.args[0] == EWOULDBLOCK:
  377. return 0
  378. raise
  379. def sendall(self, data, flags=0):
  380. if isinstance(data, unicode):
  381. data = data.encode()
  382. # this sendall is also reused by gevent.ssl.SSLSocket subclass,
  383. # so it should not call self._sock methods directly
  384. if self.timeout is None:
  385. data_sent = 0
  386. while data_sent < len(data):
  387. data_sent += self.send(_get_memory(data, data_sent), flags)
  388. else:
  389. timeleft = self.timeout
  390. end = time.time() + timeleft
  391. data_sent = 0
  392. while True:
  393. data_sent += self.send(_get_memory(data, data_sent), flags, timeout=timeleft)
  394. if data_sent >= len(data):
  395. break
  396. timeleft = end - time.time()
  397. if timeleft <= 0:
  398. raise timeout('timed out')
  399. def sendto(self, *args):
  400. sock = self._sock
  401. try:
  402. return sock.sendto(*args)
  403. except error:
  404. ex = sys.exc_info()[1]
  405. if ex.args[0] != EWOULDBLOCK or timeout == 0.0:
  406. raise
  407. sys.exc_clear()
  408. self._wait(self._write_event)
  409. try:
  410. return sock.sendto(*args)
  411. except error:
  412. ex2 = sys.exc_info()[1]
  413. if ex2.args[0] == EWOULDBLOCK:
  414. return 0
  415. raise
  416. def setblocking(self, flag):
  417. if flag:
  418. self.timeout = None
  419. else:
  420. self.timeout = 0.0
  421. def settimeout(self, howlong):
  422. if howlong is not None:
  423. try:
  424. f = howlong.__float__
  425. except AttributeError:
  426. raise TypeError('a float is required')
  427. howlong = f()
  428. if howlong < 0.0:
  429. raise ValueError('Timeout value out of range')
  430. self.timeout = howlong
  431. def gettimeout(self):
  432. return self.timeout
  433. def shutdown(self, how):
  434. if how == 0: # SHUT_RD
  435. self.hub.cancel_wait(self._read_event, cancel_wait_ex)
  436. elif how == 1: # SHUT_WR
  437. self.hub.cancel_wait(self._write_event, cancel_wait_ex)
  438. else:
  439. self.hub.cancel_wait(self._read_event, cancel_wait_ex)
  440. self.hub.cancel_wait(self._write_event, cancel_wait_ex)
  441. self._sock.shutdown(how)
  442. family = property(lambda self: self._sock.family, doc="the socket family")
  443. type = property(lambda self: self._sock.type, doc="the socket type")
  444. proto = property(lambda self: self._sock.proto, doc="the socket protocol")
  445. # delegate the functions that we haven't implemented to the real socket object
  446. _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
  447. "%s.__doc__ = _realsocket.%s.__doc__\n")
  448. for _m in set(__socket__._socketmethods) - set(locals()):
  449. exec (_s % (_m, _m, _m, _m))
  450. del _m, _s
  451. SocketType = socket
  452. if hasattr(_socket, 'socketpair'):
  453. def socketpair(*args):
  454. one, two = _socket.socketpair(*args)
  455. return socket(_sock=one), socket(_sock=two)
  456. else:
  457. __implements__.remove('socketpair')
  458. if hasattr(_socket, 'fromfd'):
  459. def fromfd(*args):
  460. return socket(_sock=_socket.fromfd(*args))
  461. else:
  462. __implements__.remove('fromfd')
  463. try:
  464. _GLOBAL_DEFAULT_TIMEOUT = __socket__._GLOBAL_DEFAULT_TIMEOUT
  465. except AttributeError:
  466. _GLOBAL_DEFAULT_TIMEOUT = object()
  467. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  468. """Connect to *address* and return the socket object.
  469. Convenience function. Connect to *address* (a 2-tuple ``(host,
  470. port)``) and return the socket object. Passing the optional
  471. *timeout* parameter will set the timeout on the socket instance
  472. before attempting to connect. If no *timeout* is supplied, the
  473. global default timeout setting returned by :func:`getdefaulttimeout`
  474. is used. If *source_address* is set it must be a tuple of (host, port)
  475. for the socket to bind as a source address before making the connection.
  476. An host of '' or port 0 tells the OS to use the default.
  477. """
  478. host, port = address
  479. err = None
  480. for res in getaddrinfo(host, port, 0 if has_ipv6 else AF_INET, SOCK_STREAM):
  481. af, socktype, proto, _canonname, sa = res
  482. sock = None
  483. try:
  484. sock = socket(af, socktype, proto)
  485. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  486. sock.settimeout(timeout)
  487. if source_address:
  488. sock.bind(source_address)
  489. sock.connect(sa)
  490. return sock
  491. except error:
  492. err = sys.exc_info()[1]
  493. # without exc_clear(), if connect() fails once, the socket is referenced by the frame in exc_info
  494. # and the next bind() fails (see test__socket.TestCreateConnection)
  495. # that does not happen with regular sockets though, because _socket.socket.connect() is a built-in.
  496. # this is similar to "getnameinfo loses a reference" failure in test_socket.py
  497. sys.exc_clear()
  498. if sock is not None:
  499. sock.close()
  500. if err is not None:
  501. raise err
  502. else:
  503. raise error("getaddrinfo returns an empty list")
  504. class BlockingResolver(object):
  505. def __init__(self, hub=None):
  506. pass
  507. def close(self):
  508. pass
  509. for method in ['gethostbyname',
  510. 'gethostbyname_ex',
  511. 'getaddrinfo',
  512. 'gethostbyaddr',
  513. 'getnameinfo']:
  514. locals()[method] = staticmethod(getattr(_socket, method))
  515. def gethostbyname(hostname):
  516. return get_hub().resolver.gethostbyname(hostname)
  517. def gethostbyname_ex(hostname):
  518. return get_hub().resolver.gethostbyname_ex(hostname)
  519. def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0):
  520. return get_hub().resolver.getaddrinfo(host, port, family, socktype, proto, flags)
  521. def gethostbyaddr(ip_address):
  522. return get_hub().resolver.gethostbyaddr(ip_address)
  523. def getnameinfo(sockaddr, flags):
  524. return get_hub().resolver.getnameinfo(sockaddr, flags)
  525. def getfqdn(name=''):
  526. """Get fully qualified domain name from name.
  527. An empty argument is interpreted as meaning the local host.
  528. First the hostname returned by gethostbyaddr() is checked, then
  529. possibly existing aliases. In case no FQDN is available, hostname
  530. from gethostname() is returned.
  531. """
  532. name = name.strip()
  533. if not name or name == '0.0.0.0':
  534. name = gethostname()
  535. try:
  536. hostname, aliases, ipaddrs = gethostbyaddr(name)
  537. except error:
  538. pass
  539. else:
  540. aliases.insert(0, hostname)
  541. for name in aliases:
  542. if '.' in name:
  543. break
  544. else:
  545. name = hostname
  546. return name
  547. try:
  548. from gevent.ssl import sslwrap_simple as ssl, SSLError as sslerror, SSLSocket as SSLType
  549. _have_ssl = True
  550. except ImportError:
  551. _have_ssl = False
  552. if sys.version_info[:2] <= (2, 5) and _have_ssl:
  553. __implements__.extend(['ssl', 'sslerror', 'SSLType'])
  554. __all__ = __implements__ + __extensions__ + __imports__