PageRenderTime 54ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/gevent/socket.py

https://bitbucket.org/andrix/gevent
Python | 744 lines | 669 code | 31 blank | 44 comment | 22 complexity | e6c6bc31a8e8f8a7a4c77335be8b123d MD5 | raw file
  1. # Copyright (c) 2005-2006, Bob Ippolito
  2. # Copyright (c) 2007, Linden Research, Inc.
  3. # Copyright (c) 2009-2010 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. 'getaddrinfo',
  33. 'gethostbyname',
  34. 'socket',
  35. 'SocketType',
  36. 'fromfd',
  37. 'socketpair']
  38. # non-standard functions that this module provides:
  39. __extensions__ = ['wait_read',
  40. 'wait_write',
  41. 'wait_readwrite']
  42. # standard functions and classes that this module re-imports
  43. __imports__ = ['error',
  44. 'gaierror',
  45. 'getfqdn',
  46. 'herror',
  47. 'htonl',
  48. 'htons',
  49. 'ntohl',
  50. 'ntohs',
  51. 'inet_aton',
  52. 'inet_ntoa',
  53. 'inet_pton',
  54. 'inet_ntop',
  55. 'timeout',
  56. 'gethostname',
  57. 'getprotobyname',
  58. 'getservbyname',
  59. 'getservbyport',
  60. 'getdefaulttimeout',
  61. 'setdefaulttimeout',
  62. # Python 2.5 and older:
  63. 'RAND_add',
  64. 'RAND_egd',
  65. 'RAND_status',
  66. # Windows:
  67. 'errorTab']
  68. import sys
  69. import time
  70. import random
  71. import re
  72. is_windows = sys.platform == 'win32'
  73. if is_windows:
  74. # no such thing as WSAEPERM or error code 10001 according to winsock.h or MSDN
  75. from errno import WSAEINVAL as EINVAL
  76. from errno import WSAEWOULDBLOCK as EWOULDBLOCK
  77. from errno import WSAEINPROGRESS as EINPROGRESS
  78. from errno import WSAEALREADY as EALREADY
  79. from errno import WSAEISCONN as EISCONN
  80. from gevent.win32util import formatError as strerror
  81. EAGAIN = EWOULDBLOCK
  82. else:
  83. from errno import EINVAL
  84. from errno import EWOULDBLOCK
  85. from errno import EINPROGRESS
  86. from errno import EALREADY
  87. from errno import EAGAIN
  88. from errno import EISCONN
  89. from os import strerror
  90. try:
  91. from errno import EBADF
  92. except ImportError:
  93. EBADF = 9
  94. import _socket
  95. _realsocket = _socket.socket
  96. __socket__ = __import__('socket')
  97. _fileobject = __socket__._fileobject
  98. for name in __imports__[:]:
  99. try:
  100. value = getattr(__socket__, name)
  101. globals()[name] = value
  102. except AttributeError:
  103. __imports__.remove(name)
  104. for name in __socket__.__all__:
  105. value = getattr(__socket__, name)
  106. if isinstance(value, (int, long, basestring)):
  107. globals()[name] = value
  108. __imports__.append(name)
  109. del name, value
  110. if 'inet_ntop' not in globals():
  111. # inet_ntop is required by our implementation of getaddrinfo
  112. def inet_ntop(address_family, packed_ip):
  113. if address_family == AF_INET:
  114. return inet_ntoa(packed_ip)
  115. # XXX: ipv6 won't work on windows
  116. raise NotImplementedError('inet_ntop() is not available on this platform')
  117. # XXX: implement blocking functions that are not yet implemented
  118. from gevent.hub import getcurrent, get_hub
  119. from gevent import core
  120. _ip4_re = re.compile('^[\d\.]+$')
  121. def _wait_helper(ev, evtype):
  122. current, timeout_exc = ev.arg
  123. if evtype & core.EV_TIMEOUT:
  124. current.throw(timeout_exc)
  125. else:
  126. current.switch(ev)
  127. def wait_read(fileno, timeout=None, timeout_exc=timeout('timed out'), event=None):
  128. """Block the current greenlet until *fileno* is ready to read.
  129. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  130. By default *timeout_exc* is ``socket.timeout('timed out')``.
  131. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  132. """
  133. if event is None:
  134. event = core.read_event(fileno, _wait_helper, timeout, (getcurrent(), timeout_exc))
  135. else:
  136. assert event.callback == _wait_helper, event.callback
  137. assert event.arg is None, 'This event is already used by another greenlet: %r' % (event.arg, )
  138. event.arg = (getcurrent(), timeout_exc)
  139. event.add(timeout)
  140. try:
  141. switch_result = get_hub().switch()
  142. assert event is switch_result, 'Invalid switch into wait_read(): %r' % (switch_result, )
  143. finally:
  144. event.cancel()
  145. event.arg = None
  146. def wait_write(fileno, timeout=None, timeout_exc=timeout('timed out'), event=None):
  147. """Block the current greenlet until *fileno* is ready to 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. if event is None:
  153. event = core.write_event(fileno, _wait_helper, timeout, (getcurrent(), timeout_exc))
  154. else:
  155. assert event.callback == _wait_helper, event.callback
  156. assert event.arg is None, 'This event is already used by another greenlet: %r' % (event.arg, )
  157. event.arg = (getcurrent(), timeout_exc)
  158. event.add(timeout)
  159. try:
  160. switch_result = get_hub().switch()
  161. assert event is switch_result, 'Invalid switch into wait_write(): %r' % (switch_result, )
  162. finally:
  163. event.arg = None
  164. event.cancel()
  165. def wait_readwrite(fileno, timeout=None, timeout_exc=timeout('timed out'), event=None):
  166. """Block the current greenlet until *fileno* is ready to read or write.
  167. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  168. By default *timeout_exc* is ``socket.timeout('timed out')``.
  169. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  170. """
  171. if event is None:
  172. event = core.readwrite_event(fileno, _wait_helper, timeout, (getcurrent(), timeout_exc))
  173. else:
  174. assert event.callback == _wait_helper, event.callback
  175. assert event.arg is None, 'This event is already used by another greenlet: %r' % (event.arg, )
  176. event.arg = (getcurrent(), timeout_exc)
  177. event.add(timeout)
  178. try:
  179. switch_result = get_hub().switch()
  180. assert event is switch_result, 'Invalid switch into wait_readwrite(): %r' % (switch_result, )
  181. finally:
  182. event.arg = None
  183. event.cancel()
  184. def __cancel_wait(event):
  185. if event.pending:
  186. arg = event.arg
  187. if arg is not None:
  188. arg[0].throw(error(EBADF, 'File descriptor was closed in another greenlet'))
  189. def cancel_wait(event):
  190. core.active_event(__cancel_wait, event)
  191. if sys.version_info[:2] <= (2, 4):
  192. # implement close argument to _fileobject that we require
  193. realfileobject = _fileobject
  194. class _fileobject(realfileobject):
  195. __slots__ = realfileobject.__slots__ + ['_close']
  196. def __init__(self, *args, **kwargs):
  197. self._close = kwargs.pop('close', False)
  198. realfileobject.__init__(self, *args, **kwargs)
  199. def close(self):
  200. try:
  201. if self._sock:
  202. self.flush()
  203. finally:
  204. if self._close:
  205. self._sock.close()
  206. self._sock = None
  207. if sys.version_info[:2] < (2, 7):
  208. _get_memory = buffer
  209. else:
  210. def _get_memory(string, offset):
  211. return memoryview(string)[offset:]
  212. class _closedsocket(object):
  213. __slots__ = []
  214. def _dummy(*args):
  215. raise error(EBADF, 'Bad file descriptor')
  216. # All _delegate_methods must also be initialized here.
  217. send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
  218. __getattr__ = _dummy
  219. _delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into", "send", "sendto", 'sendall')
  220. timeout_default = object()
  221. class socket(object):
  222. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
  223. if _sock is None:
  224. self._sock = _realsocket(family, type, proto)
  225. self.timeout = _socket.getdefaulttimeout()
  226. else:
  227. if hasattr(_sock, '_sock'):
  228. self._sock = _sock._sock
  229. self.timeout = getattr(_sock, 'timeout', False)
  230. if self.timeout is False:
  231. self.timeout = _socket.getdefaulttimeout()
  232. else:
  233. self._sock = _sock
  234. self.timeout = _socket.getdefaulttimeout()
  235. self._sock.setblocking(0)
  236. self._read_event = core.event(core.EV_READ, self.fileno(), _wait_helper)
  237. self._write_event = core.event(core.EV_WRITE, self.fileno(), _wait_helper)
  238. self._rw_event = core.event(core.EV_READ | core.EV_WRITE, self.fileno(), _wait_helper)
  239. def __repr__(self):
  240. return '<%s at %s %s>' % (type(self).__name__, hex(id(self)), self._formatinfo())
  241. def __str__(self):
  242. return '<%s %s>' % (type(self).__name__, self._formatinfo())
  243. def _formatinfo(self):
  244. try:
  245. fileno = self.fileno()
  246. except Exception, ex:
  247. fileno = str(ex)
  248. try:
  249. sockname = self.getsockname()
  250. sockname = '%s:%s' % sockname
  251. except Exception:
  252. sockname = None
  253. try:
  254. peername = self.getpeername()
  255. peername = '%s:%s' % peername
  256. except Exception:
  257. peername = None
  258. result = 'fileno=%s' % fileno
  259. if sockname is not None:
  260. result += ' sock=' + str(sockname)
  261. if peername is not None:
  262. result += ' peer=' + str(peername)
  263. if getattr(self, 'timeout', None) is not None:
  264. result += ' timeout=' + str(self.timeout)
  265. return result
  266. def accept(self):
  267. sock = self._sock
  268. while True:
  269. try:
  270. client_socket, address = sock.accept()
  271. break
  272. except error, ex:
  273. if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
  274. raise
  275. sys.exc_clear()
  276. wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event)
  277. return socket(_sock=client_socket), address
  278. def close(self):
  279. cancel_wait(self._rw_event)
  280. cancel_wait(self._read_event)
  281. cancel_wait(self._write_event)
  282. self._sock = _closedsocket()
  283. dummy = self._sock._dummy
  284. for method in _delegate_methods:
  285. setattr(self, method, dummy)
  286. def connect(self, address):
  287. if isinstance(address, tuple) and len(address) == 2:
  288. address = gethostbyname(address[0]), address[1]
  289. if self.timeout == 0.0:
  290. return self._sock.connect(address)
  291. sock = self._sock
  292. if self.timeout is None:
  293. while True:
  294. err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
  295. if err:
  296. raise error(err, strerror(err))
  297. result = sock.connect_ex(address)
  298. if not result or result == EISCONN:
  299. break
  300. elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
  301. wait_readwrite(sock.fileno(), event=self._rw_event)
  302. else:
  303. raise error(result, strerror(result))
  304. else:
  305. end = time.time() + self.timeout
  306. while True:
  307. err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
  308. if err:
  309. raise error(err, strerror(err))
  310. result = sock.connect_ex(address)
  311. if not result or result == EISCONN:
  312. break
  313. elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
  314. timeleft = end - time.time()
  315. if timeleft <= 0:
  316. raise timeout('timed out')
  317. wait_readwrite(sock.fileno(), timeout=timeleft, event=self._rw_event)
  318. else:
  319. raise error(result, strerror(result))
  320. def connect_ex(self, address):
  321. try:
  322. return self.connect(address) or 0
  323. except timeout:
  324. return EAGAIN
  325. except error, ex:
  326. if type(ex) is error:
  327. return ex[0]
  328. else:
  329. raise # gaierror is not silented by connect_ex
  330. def dup(self):
  331. """dup() -> socket object
  332. Return a new socket object connected to the same system resource.
  333. Note, that the new socket does not inherit the timeout."""
  334. return socket(_sock=self._sock)
  335. def makefile(self, mode='r', bufsize=-1):
  336. # note that this does not inherit timeout either (intentionally, because that's
  337. # how the standard socket behaves)
  338. return _fileobject(self.dup(), mode, bufsize)
  339. def recv(self, *args):
  340. sock = self._sock # keeping the reference so that fd is not closed during waiting
  341. while True:
  342. try:
  343. return sock.recv(*args)
  344. except error, ex:
  345. if ex[0] == EBADF:
  346. return ''
  347. if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
  348. raise
  349. # QQQ without clearing exc_info test__refcount.test_clean_exit fails
  350. sys.exc_clear()
  351. try:
  352. wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event)
  353. except error, ex:
  354. if ex[0] == EBADF:
  355. return ''
  356. raise
  357. def recvfrom(self, *args):
  358. sock = self._sock
  359. while True:
  360. try:
  361. return sock.recvfrom(*args)
  362. except error, ex:
  363. if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
  364. raise
  365. sys.exc_clear()
  366. wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event)
  367. def recvfrom_into(self, *args):
  368. sock = self._sock
  369. while True:
  370. try:
  371. return sock.recvfrom_into(*args)
  372. except error, ex:
  373. if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
  374. raise
  375. sys.exc_clear()
  376. wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event)
  377. def recv_into(self, *args):
  378. sock = self._sock
  379. while True:
  380. try:
  381. return sock.recv_into(*args)
  382. except error, ex:
  383. if ex[0] == EBADF:
  384. return 0
  385. if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
  386. raise
  387. sys.exc_clear()
  388. try:
  389. wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event)
  390. except error, ex:
  391. if ex[0] == EBADF:
  392. return 0
  393. raise
  394. def send(self, data, flags=0, timeout=timeout_default):
  395. sock = self._sock
  396. if timeout is timeout_default:
  397. timeout = self.timeout
  398. try:
  399. return sock.send(data, flags)
  400. except error, ex:
  401. if ex[0] != EWOULDBLOCK or timeout == 0.0:
  402. raise
  403. sys.exc_clear()
  404. try:
  405. wait_write(sock.fileno(), timeout=timeout, event=self._write_event)
  406. except error, ex:
  407. if ex[0] == EBADF:
  408. return 0
  409. raise
  410. try:
  411. return sock.send(data, flags)
  412. except error, ex2:
  413. if ex2[0] == EWOULDBLOCK:
  414. return 0
  415. raise
  416. def sendall(self, data, flags=0):
  417. if isinstance(data, unicode):
  418. data = data.encode()
  419. # this sendall is also reused by SSL subclasses (both from ssl and sslold modules),
  420. # so it should not call self._sock methods directly
  421. if self.timeout is None:
  422. data_sent = 0
  423. while data_sent < len(data):
  424. data_sent += self.send(_get_memory(data, data_sent), flags)
  425. else:
  426. timeleft = self.timeout
  427. end = time.time() + timeleft
  428. data_sent = 0
  429. while True:
  430. data_sent += self.send(_get_memory(data, data_sent), flags, timeout=timeleft)
  431. if data_sent >= len(data):
  432. break
  433. timeleft = end - time.time()
  434. if timeleft <= 0:
  435. raise timeout('timed out')
  436. def sendto(self, *args):
  437. sock = self._sock
  438. try:
  439. return sock.sendto(*args)
  440. except error, ex:
  441. if ex[0] != EWOULDBLOCK or timeout == 0.0:
  442. raise
  443. sys.exc_clear()
  444. wait_write(sock.fileno(), timeout=self.timeout, event=self._write_event)
  445. try:
  446. return sock.sendto(*args)
  447. except error, ex2:
  448. if ex2[0] == EWOULDBLOCK:
  449. return 0
  450. raise
  451. def setblocking(self, flag):
  452. if flag:
  453. self.timeout = None
  454. else:
  455. self.timeout = 0.0
  456. def settimeout(self, howlong):
  457. if howlong is not None:
  458. try:
  459. f = howlong.__float__
  460. except AttributeError:
  461. raise TypeError('a float is required')
  462. howlong = f()
  463. if howlong < 0.0:
  464. raise ValueError('Timeout value out of range')
  465. self.timeout = howlong
  466. def gettimeout(self):
  467. return self.timeout
  468. def shutdown(self, how):
  469. cancel_wait(self._rw_event)
  470. if how == 0: # SHUT_RD
  471. cancel_wait(self._read_event)
  472. elif how == 1: # SHUT_RW
  473. cancel_wait(self._write_event)
  474. else:
  475. cancel_wait(self._read_event)
  476. cancel_wait(self._write_event)
  477. self._sock.shutdown(how)
  478. family = property(lambda self: self._sock.family, doc="the socket family")
  479. type = property(lambda self: self._sock.type, doc="the socket type")
  480. proto = property(lambda self: self._sock.proto, doc="the socket protocol")
  481. # delegate the functions that we haven't implemented to the real socket object
  482. _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
  483. "%s.__doc__ = _realsocket.%s.__doc__\n")
  484. for _m in set(__socket__._socketmethods) - set(locals()):
  485. exec _s % (_m, _m, _m, _m)
  486. del _m, _s
  487. SocketType = socket
  488. if hasattr(_socket, 'socketpair'):
  489. def socketpair(*args):
  490. one, two = _socket.socketpair(*args)
  491. return socket(_sock=one), socket(_sock=two)
  492. else:
  493. __implements__.remove('socketpair')
  494. if hasattr(_socket, 'fromfd'):
  495. def fromfd(*args):
  496. return socket(_sock=_socket.fromfd(*args))
  497. else:
  498. __implements__.remove('fromfd')
  499. def bind_and_listen(descriptor, address=('', 0), backlog=50, reuse_addr=True):
  500. if reuse_addr:
  501. try:
  502. descriptor.setsockopt(SOL_SOCKET, SO_REUSEADDR, descriptor.getsockopt(SOL_SOCKET, SO_REUSEADDR) | 1)
  503. except error:
  504. pass
  505. descriptor.bind(address)
  506. descriptor.listen(backlog)
  507. def tcp_listener(address, backlog=50, reuse_addr=True):
  508. """A shortcut to create a TCP socket, bind it and put it into listening state."""
  509. sock = socket()
  510. bind_and_listen(sock, address, backlog=backlog, reuse_addr=reuse_addr)
  511. return sock
  512. try:
  513. _GLOBAL_DEFAULT_TIMEOUT = __socket__._GLOBAL_DEFAULT_TIMEOUT
  514. except AttributeError:
  515. _GLOBAL_DEFAULT_TIMEOUT = object()
  516. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  517. """Connect to *address* and return the socket object.
  518. Convenience function. Connect to *address* (a 2-tuple ``(host,
  519. port)``) and return the socket object. Passing the optional
  520. *timeout* parameter will set the timeout on the socket instance
  521. before attempting to connect. If no *timeout* is supplied, the
  522. global default timeout setting returned by :func:`getdefaulttimeout`
  523. is used. If *source_address* is set it must be a tuple of (host, port)
  524. for the socket to bind as a source address before making the connection.
  525. An host of '' or port 0 tells the OS to use the default.
  526. """
  527. msg = "getaddrinfo returns an empty list"
  528. host, port = address
  529. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  530. af, socktype, proto, _canonname, sa = res
  531. sock = None
  532. try:
  533. sock = socket(af, socktype, proto)
  534. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  535. sock.settimeout(timeout)
  536. if source_address:
  537. sock.bind(source_address)
  538. sock.connect(sa)
  539. return sock
  540. except error, msg:
  541. sys.exc_clear()
  542. if sock is not None:
  543. sock.close()
  544. raise msg
  545. try:
  546. from gevent.dns import resolve_ipv4, resolve_ipv6
  547. except Exception:
  548. import traceback
  549. traceback.print_exc()
  550. __implements__.remove('gethostbyname')
  551. __implements__.remove('getaddrinfo')
  552. else:
  553. def gethostbyname(hostname):
  554. """:func:`socket.gethostbyname` implemented using :mod:`gevent.dns`.
  555. Differs in the following ways:
  556. * raises :class:`DNSError` (a subclass of :class:`socket.gaierror`) with dns error
  557. codes instead of standard socket error codes
  558. * does not support ``/etc/hosts`` but calls the original :func:`socket.gethostbyname`
  559. if *hostname* has no dots
  560. * does not iterate through all addresses, instead picks a random one each time
  561. """
  562. # TODO: this is supposed to iterate through all the addresses
  563. # could use a global dict(hostname, iter)
  564. # - fix these nasty hacks for localhost, ips, etc.
  565. if not isinstance(hostname, str) or '.' not in hostname:
  566. return _socket.gethostbyname(hostname)
  567. if _ip4_re.match(hostname):
  568. return hostname
  569. if hostname == _socket.gethostname():
  570. return _socket.gethostbyname(hostname)
  571. _ttl, addrs = resolve_ipv4(hostname)
  572. return inet_ntoa(random.choice(addrs))
  573. def getaddrinfo(host, port, *args, **kwargs):
  574. """*Some* approximation of :func:`socket.getaddrinfo` implemented using :mod:`gevent.dns`.
  575. If *host* is not a string, does not has any dots or is a numeric IP address, then
  576. the standard :func:`socket.getaddrinfo` is called.
  577. Otherwise, calls either :func:`resolve_ipv4` or :func:`resolve_ipv6` and
  578. formats the result the way :func:`socket.getaddrinfo` does it.
  579. Differs in the following ways:
  580. * raises :class:`DNSError` (a subclass of :class:`gaierror`) with libevent-dns error
  581. codes instead of standard socket error codes
  582. * IPv6 support is untested.
  583. * AF_UNSPEC only tries IPv4
  584. * only supports TCP, UDP, IP protocols
  585. * port must be numeric, does not support string service names. see socket.getservbyname
  586. * *flags* argument is ignored
  587. Additionally, supports *evdns_flags* keyword arguments (default ``0``) that is passed
  588. to :mod:`dns` functions.
  589. """
  590. family, socktype, proto, _flags = args + (None, ) * (4 - len(args))
  591. if not isinstance(host, str) or '.' not in host or _ip4_re.match(host):
  592. return _socket.getaddrinfo(host, port, *args)
  593. evdns_flags = kwargs.pop('evdns_flags', 0)
  594. if kwargs:
  595. raise TypeError('Unsupported keyword arguments: %s' % (kwargs.keys(), ))
  596. if family in (None, AF_INET, AF_UNSPEC):
  597. family = AF_INET
  598. # TODO: AF_UNSPEC means try both AF_INET and AF_INET6
  599. _ttl, addrs = resolve_ipv4(host, evdns_flags)
  600. elif family == AF_INET6:
  601. _ttl, addrs = resolve_ipv6(host, evdns_flags)
  602. else:
  603. raise NotImplementedError('family is not among AF_UNSPEC/AF_INET/AF_INET6: %r' % (family, ))
  604. socktype_proto = [(SOCK_STREAM, 6), (SOCK_DGRAM, 17), (SOCK_RAW, 0)]
  605. if socktype:
  606. socktype_proto = [(x, y) for (x, y) in socktype_proto if socktype == x]
  607. if proto:
  608. socktype_proto = [(x, y) for (x, y) in socktype_proto if proto == y]
  609. result = []
  610. for addr in addrs:
  611. for socktype, proto in socktype_proto:
  612. result.append((family, socktype, proto, '', (inet_ntop(family, addr), port)))
  613. return result
  614. # TODO libevent2 has getaddrinfo that is probably better than the hack above; should wrap that.
  615. _have_ssl = False
  616. try:
  617. from gevent.ssl import sslwrap_simple as ssl, SSLError as sslerror, SSLSocket as SSLType
  618. _have_ssl = True
  619. except ImportError:
  620. try:
  621. from gevent.sslold import ssl, sslerror, SSLObject as SSLType
  622. _have_ssl = True
  623. except ImportError:
  624. pass
  625. if sys.version_info[:2] <= (2, 5) and _have_ssl:
  626. __implements__.extend(['ssl', 'sslerror', 'SSLType'])
  627. __all__ = __implements__ + __extensions__ + __imports__