PageRenderTime 83ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/gevent/socket.py

https://bitbucket.org/evjan/gevent
Python | 687 lines | 589 code | 28 blank | 70 comment | 21 complexity | a6a2ac938eda26ebeb33cde6dd687457 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-2011 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. # standard functions and classes that this module re-implements in a gevent-aware way:
  31. __implements__ = ['create_connection',
  32. 'socket',
  33. 'SocketType',
  34. 'fromfd',
  35. 'socketpair']
  36. __dns__ = ['getaddrinfo',
  37. 'gethostbyname',
  38. 'gethostbyname_ex',
  39. 'gethostbyaddr',
  40. 'getnameinfo',
  41. 'getfqdn']
  42. __implements__ += __dns__
  43. # non-standard functions that this module provides:
  44. __extensions__ = ['wait_read',
  45. 'wait_write',
  46. 'wait_readwrite']
  47. # standard functions and classes that this module re-imports
  48. __imports__ = ['error',
  49. 'gaierror',
  50. 'herror',
  51. 'htonl',
  52. 'htons',
  53. 'ntohl',
  54. 'ntohs',
  55. 'inet_aton',
  56. 'inet_ntoa',
  57. 'inet_pton',
  58. 'inet_ntop',
  59. 'timeout',
  60. 'gethostname',
  61. 'getprotobyname',
  62. 'getservbyname',
  63. 'getservbyport',
  64. 'getdefaulttimeout',
  65. 'setdefaulttimeout',
  66. # Python 2.5 and older:
  67. 'RAND_add',
  68. 'RAND_egd',
  69. 'RAND_status',
  70. # Windows:
  71. 'errorTab']
  72. import sys
  73. import time
  74. from gevent.hub import get_hub, basestring
  75. from gevent.timeout import Timeout
  76. is_windows = sys.platform == 'win32'
  77. if is_windows:
  78. # no such thing as WSAEPERM or error code 10001 according to winsock.h or MSDN
  79. from errno import WSAEINVAL as EINVAL
  80. from errno import WSAEWOULDBLOCK as EWOULDBLOCK
  81. from errno import WSAEINPROGRESS as EINPROGRESS
  82. from errno import WSAEALREADY as EALREADY
  83. from errno import WSAEISCONN as EISCONN
  84. from gevent.win32util import formatError as strerror
  85. EAGAIN = EWOULDBLOCK
  86. else:
  87. from errno import EINVAL
  88. from errno import EWOULDBLOCK
  89. from errno import EINPROGRESS
  90. from errno import EALREADY
  91. from errno import EAGAIN
  92. from errno import EISCONN
  93. from os import strerror
  94. try:
  95. from errno import EBADF
  96. except ImportError:
  97. EBADF = 9
  98. import _socket
  99. _realsocket = _socket.socket
  100. __socket__ = __import__('socket')
  101. _fileobject = __socket__._fileobject
  102. for name in __imports__[:]:
  103. try:
  104. value = getattr(__socket__, name)
  105. globals()[name] = value
  106. except AttributeError:
  107. __imports__.remove(name)
  108. for name in __socket__.__all__:
  109. value = getattr(__socket__, name)
  110. if isinstance(value, (int, long, basestring)):
  111. globals()[name] = value
  112. __imports__.append(name)
  113. del name, value
  114. def wait(io, timeout=None, timeout_exc=timeout('timed out')):
  115. """Block the current greenlet until *io* is ready.
  116. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  117. By default *timeout_exc* is ``socket.timeout('timed out')``.
  118. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  119. """
  120. assert io.callback is None, 'This socket is already used by another greenlet: %r' % (io.callback, )
  121. if timeout is not None:
  122. timeout = Timeout.start_new(timeout, timeout_exc)
  123. try:
  124. return get_hub().wait(io)
  125. finally:
  126. if timeout is not None:
  127. timeout.cancel()
  128. # rename "io" to "watcher" because wait() works with any watcher
  129. def wait_read(fileno, timeout=None, timeout_exc=timeout('timed out')):
  130. """Block the current greenlet until *fileno* is ready to read.
  131. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  132. By default *timeout_exc* is ``socket.timeout('timed out')``.
  133. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  134. """
  135. io = get_hub().loop.io(fileno, 1)
  136. return wait(io, timeout, timeout_exc)
  137. def wait_write(fileno, timeout=None, timeout_exc=timeout('timed out'), event=None):
  138. """Block the current greenlet until *fileno* is ready to write.
  139. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  140. By default *timeout_exc* is ``socket.timeout('timed out')``.
  141. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  142. """
  143. io = get_hub().loop.io(fileno, 2)
  144. return wait(io, timeout, timeout_exc)
  145. def wait_readwrite(fileno, timeout=None, timeout_exc=timeout('timed out'), event=None):
  146. """Block the current greenlet until *fileno* is ready to read or write.
  147. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  148. By default *timeout_exc* is ``socket.timeout('timed out')``.
  149. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  150. """
  151. io = get_hub().loop.io(fileno, 3)
  152. return wait(io, timeout, timeout_exc)
  153. cancel_wait_ex = error(EBADF, 'File descriptor was closed in another greenlet')
  154. def _cancel_wait(watcher):
  155. if watcher.active:
  156. switch = watcher.callback
  157. if switch is not None:
  158. greenlet = getattr(switch, '__self__', None)
  159. if greenlet is not None:
  160. greenlet.throw(cancel_wait_ex)
  161. def cancel_wait(event):
  162. get_hub().loop.run_callback(_cancel_wait, event)
  163. if sys.version_info[:2] < (2, 7):
  164. _get_memory = buffer
  165. elif sys.version_info[:2] < (3, 0):
  166. def _get_memory(string, offset):
  167. try:
  168. return memoryview(string)[offset:]
  169. except TypeError:
  170. return buffer(string, offset)
  171. else:
  172. def _get_memory(string, offset):
  173. return memoryview(string)[offset:]
  174. class _closedsocket(object):
  175. __slots__ = []
  176. def _dummy(*args):
  177. raise error(EBADF, 'Bad file descriptor')
  178. # All _delegate_methods must also be initialized here.
  179. send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
  180. __getattr__ = _dummy
  181. _delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into", "send", "sendto", 'sendall')
  182. timeout_default = object()
  183. class socket(object):
  184. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
  185. if _sock is None:
  186. self._sock = _realsocket(family, type, proto)
  187. self.timeout = _socket.getdefaulttimeout()
  188. else:
  189. if hasattr(_sock, '_sock'):
  190. self._sock = _sock._sock
  191. self.timeout = getattr(_sock, 'timeout', False)
  192. if self.timeout is False:
  193. self.timeout = _socket.getdefaulttimeout()
  194. else:
  195. self._sock = _sock
  196. self.timeout = _socket.getdefaulttimeout()
  197. self._sock.setblocking(0)
  198. fileno = self._sock.fileno()
  199. self.hub = get_hub()
  200. io = self.hub.loop.io
  201. self._read_event = io(fileno, 1)
  202. self._write_event = io(fileno, 2)
  203. def __repr__(self):
  204. return '<%s at %s %s>' % (type(self).__name__, hex(id(self)), self._formatinfo())
  205. def __str__(self):
  206. return '<%s %s>' % (type(self).__name__, self._formatinfo())
  207. def _formatinfo(self):
  208. try:
  209. fileno = self.fileno()
  210. except Exception:
  211. fileno = str(sys.exc_info()[1])
  212. try:
  213. sockname = self.getsockname()
  214. sockname = '%s:%s' % sockname
  215. except Exception:
  216. sockname = None
  217. try:
  218. peername = self.getpeername()
  219. peername = '%s:%s' % peername
  220. except Exception:
  221. peername = None
  222. result = 'fileno=%s' % fileno
  223. if sockname is not None:
  224. result += ' sock=' + str(sockname)
  225. if peername is not None:
  226. result += ' peer=' + str(peername)
  227. if getattr(self, 'timeout', None) is not None:
  228. result += ' timeout=' + str(self.timeout)
  229. return result
  230. def _wait(self, watcher, timeout_exc=timeout('timed out')):
  231. """Block the current greenlet until *watcher* has pending events.
  232. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  233. By default *timeout_exc* is ``socket.timeout('timed out')``.
  234. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  235. """
  236. assert watcher.callback is None, 'This socket is already used by another greenlet: %r' % (watcher.callback, )
  237. if self.timeout is not None:
  238. timeout = Timeout.start_new(self.timeout, timeout_exc)
  239. else:
  240. timeout = None
  241. try:
  242. self.hub.wait(watcher)
  243. finally:
  244. if timeout is not None:
  245. timeout.cancel()
  246. def accept(self):
  247. sock = self._sock
  248. while True:
  249. try:
  250. client_socket, address = sock.accept()
  251. break
  252. except error:
  253. ex = sys.exc_info()[1]
  254. if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
  255. raise
  256. sys.exc_clear()
  257. self._wait(self._read_event)
  258. return socket(_sock=client_socket), address
  259. def close(self,_closedsocket=_closedsocket, _delegate_methods=_delegate_methods, setattr=setattr):
  260. # This function should not reference any globals. See Python issue #808164.
  261. self.hub.cancel_wait(self._read_event, cancel_wait_ex)
  262. self.hub.cancel_wait(self._write_event, cancel_wait_ex)
  263. self._sock = _closedsocket()
  264. dummy = self._sock._dummy
  265. for method in _delegate_methods:
  266. setattr(self, method, dummy)
  267. def connect(self, address):
  268. if self.timeout == 0.0:
  269. return self._sock.connect(address)
  270. sock = self._sock
  271. if isinstance(address, tuple):
  272. r = getaddrinfo(address[0], address[1], sock.family, sock.type, sock.proto)
  273. address = r[0][-1]
  274. if self.timeout is not None:
  275. timer = Timeout.start_new(self.timeout, timeout('timed out'))
  276. else:
  277. timer = None
  278. try:
  279. while True:
  280. err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
  281. if err:
  282. raise error(err, strerror(err))
  283. result = sock.connect_ex(address)
  284. if not result or result == EISCONN:
  285. break
  286. elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
  287. self._wait(self._write_event)
  288. else:
  289. raise error(result, strerror(result))
  290. finally:
  291. if timer is not None:
  292. timer.cancel()
  293. def connect_ex(self, address):
  294. try:
  295. return self.connect(address) or 0
  296. except timeout:
  297. return EAGAIN
  298. except error:
  299. ex = sys.exc_info()[1]
  300. if type(ex) is error:
  301. return ex.args[0]
  302. else:
  303. raise # gaierror is not silented by connect_ex
  304. def dup(self):
  305. """dup() -> socket object
  306. Return a new socket object connected to the same system resource.
  307. Note, that the new socket does not inherit the timeout."""
  308. return socket(_sock=self._sock)
  309. def makefile(self, mode='r', bufsize=-1):
  310. # note that this does not inherit timeout either (intentionally, because that's
  311. # how the standard socket behaves)
  312. return _fileobject(self.dup(), mode, bufsize)
  313. def recv(self, *args):
  314. sock = self._sock # keeping the reference so that fd is not closed during waiting
  315. while True:
  316. try:
  317. return sock.recv(*args)
  318. except error:
  319. ex = sys.exc_info()[1]
  320. if ex.args[0] == EBADF:
  321. return ''
  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. try:
  327. self._wait(self._read_event)
  328. except error:
  329. ex = sys.exc_info()[1]
  330. if ex.args[0] == EBADF:
  331. return ''
  332. raise
  333. def recvfrom(self, *args):
  334. sock = self._sock
  335. while True:
  336. try:
  337. return sock.recvfrom(*args)
  338. except error:
  339. ex = sys.exc_info()[1]
  340. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  341. raise
  342. sys.exc_clear()
  343. self._wait(self._read_event)
  344. def recvfrom_into(self, *args):
  345. sock = self._sock
  346. while True:
  347. try:
  348. return sock.recvfrom_into(*args)
  349. except error:
  350. ex = sys.exc_info()[1]
  351. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  352. raise
  353. sys.exc_clear()
  354. self._wait(self._read_event)
  355. def recv_into(self, *args):
  356. sock = self._sock
  357. while True:
  358. try:
  359. return sock.recv_into(*args)
  360. except error:
  361. ex = sys.exc_info()[1]
  362. if ex.args[0] == EBADF:
  363. return 0
  364. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  365. raise
  366. sys.exc_clear()
  367. try:
  368. self._wait(self._read_event)
  369. except error:
  370. ex = sys.exc_info()[1]
  371. if ex.args[0] == EBADF:
  372. return 0
  373. raise
  374. def send(self, data, flags=0, timeout=timeout_default):
  375. sock = self._sock
  376. if timeout is timeout_default:
  377. timeout = self.timeout
  378. try:
  379. return sock.send(data, flags)
  380. except error:
  381. ex = sys.exc_info()[1]
  382. if ex.args[0] != EWOULDBLOCK or timeout == 0.0:
  383. raise
  384. sys.exc_clear()
  385. try:
  386. self._wait(self._write_event)
  387. except error:
  388. ex = sys.exc_info()[1]
  389. if ex.args[0] == EBADF:
  390. return 0
  391. raise
  392. try:
  393. return sock.send(data, flags)
  394. except error:
  395. ex2 = sys.exc_info()[1]
  396. if ex2.args[0] == EWOULDBLOCK:
  397. return 0
  398. raise
  399. def sendall(self, data, flags=0):
  400. if isinstance(data, unicode):
  401. data = data.encode()
  402. # this sendall is also reused by gevent.ssl.SSLSocket subclass,
  403. # so it should not call self._sock methods directly
  404. if self.timeout is None:
  405. data_sent = 0
  406. while data_sent < len(data):
  407. data_sent += self.send(_get_memory(data, data_sent), flags)
  408. else:
  409. timeleft = self.timeout
  410. end = time.time() + timeleft
  411. data_sent = 0
  412. while True:
  413. data_sent += self.send(_get_memory(data, data_sent), flags, timeout=timeleft)
  414. if data_sent >= len(data):
  415. break
  416. timeleft = end - time.time()
  417. if timeleft <= 0:
  418. raise timeout('timed out')
  419. def sendto(self, *args):
  420. sock = self._sock
  421. try:
  422. return sock.sendto(*args)
  423. except error:
  424. ex = sys.exc_info()[1]
  425. if ex.args[0] != EWOULDBLOCK or timeout == 0.0:
  426. raise
  427. sys.exc_clear()
  428. self._wait(self._write_event)
  429. try:
  430. return sock.sendto(*args)
  431. except error:
  432. ex2 = sys.exc_info()[1]
  433. if ex2.args[0] == EWOULDBLOCK:
  434. return 0
  435. raise
  436. def setblocking(self, flag):
  437. if flag:
  438. self.timeout = None
  439. else:
  440. self.timeout = 0.0
  441. def settimeout(self, howlong):
  442. if howlong is not None:
  443. try:
  444. f = howlong.__float__
  445. except AttributeError:
  446. raise TypeError('a float is required')
  447. howlong = f()
  448. if howlong < 0.0:
  449. raise ValueError('Timeout value out of range')
  450. self.timeout = howlong
  451. def gettimeout(self):
  452. return self.timeout
  453. def shutdown(self, how):
  454. if how == 0: # SHUT_RD
  455. self.hub.cancel_wait(self._read_event, cancel_wait_ex)
  456. elif how == 1: # SHUT_RW
  457. self.hub.cancel_wait(self._write_event, cancel_wait_ex)
  458. else:
  459. self.hub.cancel_wait(self._read_event, cancel_wait_ex)
  460. self.hub.cancel_wait(self._write_event, cancel_wait_ex)
  461. self._sock.shutdown(how)
  462. family = property(lambda self: self._sock.family, doc="the socket family")
  463. type = property(lambda self: self._sock.type, doc="the socket type")
  464. proto = property(lambda self: self._sock.proto, doc="the socket protocol")
  465. # delegate the functions that we haven't implemented to the real socket object
  466. _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
  467. "%s.__doc__ = _realsocket.%s.__doc__\n")
  468. for _m in set(__socket__._socketmethods) - set(locals()):
  469. exec (_s % (_m, _m, _m, _m))
  470. del _m, _s
  471. SocketType = socket
  472. if hasattr(_socket, 'socketpair'):
  473. def socketpair(*args):
  474. one, two = _socket.socketpair(*args)
  475. return socket(_sock=one), socket(_sock=two)
  476. else:
  477. __implements__.remove('socketpair')
  478. if hasattr(_socket, 'fromfd'):
  479. def fromfd(*args):
  480. return socket(_sock=_socket.fromfd(*args))
  481. else:
  482. __implements__.remove('fromfd')
  483. try:
  484. _GLOBAL_DEFAULT_TIMEOUT = __socket__._GLOBAL_DEFAULT_TIMEOUT
  485. except AttributeError:
  486. _GLOBAL_DEFAULT_TIMEOUT = object()
  487. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  488. """Connect to *address* and return the socket object.
  489. Convenience function. Connect to *address* (a 2-tuple ``(host,
  490. port)``) and return the socket object. Passing the optional
  491. *timeout* parameter will set the timeout on the socket instance
  492. before attempting to connect. If no *timeout* is supplied, the
  493. global default timeout setting returned by :func:`getdefaulttimeout`
  494. is used. If *source_address* is set it must be a tuple of (host, port)
  495. for the socket to bind as a source address before making the connection.
  496. An host of '' or port 0 tells the OS to use the default.
  497. """
  498. host, port = address
  499. err = None
  500. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  501. af, socktype, proto, _canonname, sa = res
  502. sock = None
  503. try:
  504. sock = socket(af, socktype, proto)
  505. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  506. sock.settimeout(timeout)
  507. if source_address:
  508. sock.bind(source_address)
  509. sock.connect(sa)
  510. return sock
  511. except error:
  512. err = sys.exc_info()[1]
  513. # without exc_clear(), if connect() fails once, the socket is referenced by the frame in exc_info
  514. # and the next bind() fails (see test__socket.TestCreateConnection)
  515. # that does not happen with regular sockets though, because _socket.socket.connect() is a built-in.
  516. # this is similar to "getnameinfo loses a reference" failure in test_socket.py
  517. sys.exc_clear()
  518. if sock is not None:
  519. sock.close()
  520. if err is not None:
  521. raise err
  522. else:
  523. raise error("getaddrinfo returns an empty list")
  524. class BlockingResolver(object):
  525. def __init__(self, hub=None):
  526. pass
  527. def close(self):
  528. pass
  529. for method in ['gethostbyname',
  530. 'gethostbyname_ex',
  531. 'getaddrinfo',
  532. 'gethostbyaddr',
  533. 'getnameinfo']:
  534. locals()[method] = staticmethod(getattr(_socket, method))
  535. def gethostbyname(hostname):
  536. return get_hub().resolver.gethostbyname(hostname)
  537. def gethostbyname_ex(hostname):
  538. return get_hub().resolver.gethostbyname_ex(hostname)
  539. def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0):
  540. return get_hub().resolver.getaddrinfo(host, port, family, socktype, proto, flags)
  541. def gethostbyaddr(ip_address):
  542. return get_hub().resolver.gethostbyaddr(ip_address)
  543. def getnameinfo(sockaddr, flags):
  544. return get_hub().resolver.getnameinfo(sockaddr, flags)
  545. def getfqdn(name=''):
  546. """Get fully qualified domain name from name.
  547. An empty argument is interpreted as meaning the local host.
  548. First the hostname returned by gethostbyaddr() is checked, then
  549. possibly existing aliases. In case no FQDN is available, hostname
  550. from gethostname() is returned.
  551. """
  552. name = name.strip()
  553. if not name or name == '0.0.0.0':
  554. name = gethostname()
  555. try:
  556. hostname, aliases, ipaddrs = gethostbyaddr(name)
  557. except error:
  558. pass
  559. else:
  560. aliases.insert(0, hostname)
  561. for name in aliases:
  562. if '.' in name:
  563. break
  564. else:
  565. name = hostname
  566. return name
  567. try:
  568. from gevent.ssl import sslwrap_simple as ssl, SSLError as sslerror, SSLSocket as SSLType
  569. _have_ssl = True
  570. except ImportError:
  571. _have_ssl = False
  572. if sys.version_info[:2] <= (2, 5) and _have_ssl:
  573. __implements__.extend(['ssl', 'sslerror', 'SSLType'])
  574. __all__ = __implements__ + __extensions__ + __imports__