PageRenderTime 59ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/gevent/socket.py

https://bitbucket.org/nicholas/gevent
Python | 705 lines | 607 code | 28 blank | 70 comment | 21 complexity | 51f5a666d71ee6ca18cb9e68d0c6d97e 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, 4):
  164. # implement close argument to _fileobject that we require
  165. realfileobject = _fileobject
  166. class _fileobject(realfileobject):
  167. __slots__ = realfileobject.__slots__ + ['_close']
  168. def __init__(self, *args, **kwargs):
  169. self._close = kwargs.pop('close', False)
  170. realfileobject.__init__(self, *args, **kwargs)
  171. def close(self):
  172. try:
  173. if self._sock:
  174. self.flush()
  175. finally:
  176. if self._close:
  177. self._sock.close()
  178. self._sock = None
  179. if sys.version_info[:2] < (2, 7):
  180. _get_memory = buffer
  181. else:
  182. def _get_memory(string, offset):
  183. return memoryview(string)[offset:]
  184. class _closedsocket(object):
  185. __slots__ = []
  186. def _dummy(*args):
  187. raise error(EBADF, 'Bad file descriptor')
  188. # All _delegate_methods must also be initialized here.
  189. send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
  190. __getattr__ = _dummy
  191. _delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into", "send", "sendto", 'sendall')
  192. timeout_default = object()
  193. class socket(object):
  194. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
  195. if _sock is None:
  196. self._sock = _realsocket(family, type, proto)
  197. self.timeout = _socket.getdefaulttimeout()
  198. else:
  199. if hasattr(_sock, '_sock'):
  200. self._sock = _sock._sock
  201. self.timeout = getattr(_sock, 'timeout', False)
  202. if self.timeout is False:
  203. self.timeout = _socket.getdefaulttimeout()
  204. else:
  205. self._sock = _sock
  206. self.timeout = _socket.getdefaulttimeout()
  207. self._sock.setblocking(0)
  208. fileno = self._sock.fileno()
  209. self.hub = get_hub()
  210. io = self.hub.loop.io
  211. self._read_event = io(fileno, 1)
  212. self._write_event = io(fileno, 2)
  213. def __repr__(self):
  214. return '<%s at %s %s>' % (type(self).__name__, hex(id(self)), self._formatinfo())
  215. def __str__(self):
  216. return '<%s %s>' % (type(self).__name__, self._formatinfo())
  217. def _formatinfo(self):
  218. try:
  219. fileno = self.fileno()
  220. except Exception:
  221. fileno = str(sys.exc_info()[1])
  222. try:
  223. sockname = self.getsockname()
  224. sockname = '%s:%s' % sockname
  225. except Exception:
  226. sockname = None
  227. try:
  228. peername = self.getpeername()
  229. peername = '%s:%s' % peername
  230. except Exception:
  231. peername = None
  232. result = 'fileno=%s' % fileno
  233. if sockname is not None:
  234. result += ' sock=' + str(sockname)
  235. if peername is not None:
  236. result += ' peer=' + str(peername)
  237. if getattr(self, 'timeout', None) is not None:
  238. result += ' timeout=' + str(self.timeout)
  239. return result
  240. def _wait(self, watcher, timeout_exc=timeout('timed out')):
  241. """Block the current greenlet until *watcher* has pending events.
  242. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  243. By default *timeout_exc* is ``socket.timeout('timed out')``.
  244. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  245. """
  246. assert watcher.callback is None, 'This socket is already used by another greenlet: %r' % (watcher.callback, )
  247. if self.timeout is not None:
  248. timeout = Timeout.start_new(self.timeout, timeout_exc)
  249. else:
  250. timeout = None
  251. try:
  252. self.hub.wait(watcher)
  253. finally:
  254. if timeout is not None:
  255. timeout.cancel()
  256. def accept(self):
  257. sock = self._sock
  258. while True:
  259. try:
  260. client_socket, address = sock.accept()
  261. break
  262. except error:
  263. ex = sys.exc_info()[1]
  264. if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
  265. raise
  266. sys.exc_clear()
  267. self._wait(self._read_event)
  268. return socket(_sock=client_socket), address
  269. def close(self,_closedsocket=_closedsocket, _delegate_methods=_delegate_methods, setattr=setattr):
  270. # This function should not reference any globals. See Python issue #808164.
  271. self.hub.cancel_wait(self._read_event, cancel_wait_ex)
  272. self.hub.cancel_wait(self._write_event, cancel_wait_ex)
  273. self._sock = _closedsocket()
  274. dummy = self._sock._dummy
  275. for method in _delegate_methods:
  276. setattr(self, method, dummy)
  277. def connect(self, address):
  278. if self.timeout == 0.0:
  279. return self._sock.connect(address)
  280. sock = self._sock
  281. if isinstance(address, tuple):
  282. r = getaddrinfo(address[0], address[1], sock.family, sock.type, sock.proto)
  283. address = r[0][-1]
  284. if self.timeout is not None:
  285. timer = Timeout.start_new(self.timeout, timeout('timed out'))
  286. else:
  287. timer = None
  288. try:
  289. while True:
  290. err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
  291. if err:
  292. raise error(err, strerror(err))
  293. result = sock.connect_ex(address)
  294. if not result or result == EISCONN:
  295. break
  296. elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
  297. self._wait(self._write_event)
  298. else:
  299. raise error(result, strerror(result))
  300. finally:
  301. if timer is not None:
  302. timer.cancel()
  303. def connect_ex(self, address):
  304. try:
  305. return self.connect(address) or 0
  306. except timeout:
  307. return EAGAIN
  308. except error:
  309. ex = sys.exc_info()[1]
  310. if type(ex) is error:
  311. return ex.args[0]
  312. else:
  313. raise # gaierror is not silented by connect_ex
  314. def dup(self):
  315. """dup() -> socket object
  316. Return a new socket object connected to the same system resource.
  317. Note, that the new socket does not inherit the timeout."""
  318. return socket(_sock=self._sock)
  319. def makefile(self, mode='r', bufsize=-1):
  320. # note that this does not inherit timeout either (intentionally, because that's
  321. # how the standard socket behaves)
  322. return _fileobject(self.dup(), mode, bufsize)
  323. def recv(self, *args):
  324. sock = self._sock # keeping the reference so that fd is not closed during waiting
  325. while True:
  326. try:
  327. return sock.recv(*args)
  328. except error:
  329. ex = sys.exc_info()[1]
  330. if ex.args[0] == EBADF:
  331. return ''
  332. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  333. raise
  334. # QQQ without clearing exc_info test__refcount.test_clean_exit fails
  335. sys.exc_clear()
  336. try:
  337. self._wait(self._read_event)
  338. except error:
  339. ex = sys.exc_info()[1]
  340. if ex.args[0] == EBADF:
  341. return ''
  342. raise
  343. def recvfrom(self, *args):
  344. sock = self._sock
  345. while True:
  346. try:
  347. return sock.recvfrom(*args)
  348. except error:
  349. ex = sys.exc_info()[1]
  350. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  351. raise
  352. sys.exc_clear()
  353. self._wait(self._read_event)
  354. def recvfrom_into(self, *args):
  355. sock = self._sock
  356. while True:
  357. try:
  358. return sock.recvfrom_into(*args)
  359. except error:
  360. ex = sys.exc_info()[1]
  361. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  362. raise
  363. sys.exc_clear()
  364. self._wait(self._read_event)
  365. def recv_into(self, *args):
  366. sock = self._sock
  367. while True:
  368. try:
  369. return sock.recv_into(*args)
  370. except error:
  371. ex = sys.exc_info()[1]
  372. if ex.args[0] == EBADF:
  373. return 0
  374. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  375. raise
  376. sys.exc_clear()
  377. try:
  378. self._wait(self._read_event)
  379. except error:
  380. ex = sys.exc_info()[1]
  381. if ex.args[0] == EBADF:
  382. return 0
  383. raise
  384. def send(self, data, flags=0, timeout=timeout_default):
  385. sock = self._sock
  386. if timeout is timeout_default:
  387. timeout = self.timeout
  388. try:
  389. return sock.send(data, flags)
  390. except error:
  391. ex = sys.exc_info()[1]
  392. if ex.args[0] != EWOULDBLOCK or timeout == 0.0:
  393. raise
  394. sys.exc_clear()
  395. try:
  396. self._wait(self._write_event)
  397. except error:
  398. ex = sys.exc_info()[1]
  399. if ex.args[0] == EBADF:
  400. return 0
  401. raise
  402. try:
  403. return sock.send(data, flags)
  404. except error:
  405. ex2 = sys.exc_info()[1]
  406. if ex2.args[0] == EWOULDBLOCK:
  407. return 0
  408. raise
  409. def sendall(self, data, flags=0):
  410. if isinstance(data, unicode):
  411. data = data.encode()
  412. # this sendall is also reused by gevent.ssl.SSLSocket subclass,
  413. # so it should not call self._sock methods directly
  414. if self.timeout is None:
  415. data_sent = 0
  416. while data_sent < len(data):
  417. data_sent += self.send(_get_memory(data, data_sent), flags)
  418. else:
  419. timeleft = self.timeout
  420. end = time.time() + timeleft
  421. data_sent = 0
  422. while True:
  423. data_sent += self.send(_get_memory(data, data_sent), flags, timeout=timeleft)
  424. if data_sent >= len(data):
  425. break
  426. timeleft = end - time.time()
  427. if timeleft <= 0:
  428. raise timeout('timed out')
  429. def sendto(self, *args):
  430. sock = self._sock
  431. try:
  432. return sock.sendto(*args)
  433. except error:
  434. ex = sys.exc_info()[1]
  435. if ex.args[0] != EWOULDBLOCK or timeout == 0.0:
  436. raise
  437. sys.exc_clear()
  438. self._wait(self._write_event)
  439. try:
  440. return sock.sendto(*args)
  441. except error:
  442. ex2 = sys.exc_info()[1]
  443. if ex2.args[0] == EWOULDBLOCK:
  444. return 0
  445. raise
  446. def setblocking(self, flag):
  447. if flag:
  448. self.timeout = None
  449. else:
  450. self.timeout = 0.0
  451. def settimeout(self, howlong):
  452. if howlong is not None:
  453. try:
  454. f = howlong.__float__
  455. except AttributeError:
  456. raise TypeError('a float is required')
  457. howlong = f()
  458. if howlong < 0.0:
  459. raise ValueError('Timeout value out of range')
  460. self.timeout = howlong
  461. def gettimeout(self):
  462. return self.timeout
  463. def shutdown(self, how):
  464. if how == 0: # SHUT_RD
  465. self.hub.cancel_wait(self._read_event, cancel_wait_ex)
  466. elif how == 1: # SHUT_RW
  467. self.hub.cancel_wait(self._write_event, cancel_wait_ex)
  468. else:
  469. self.hub.cancel_wait(self._read_event, cancel_wait_ex)
  470. self.hub.cancel_wait(self._write_event, cancel_wait_ex)
  471. self._sock.shutdown(how)
  472. family = property(lambda self: self._sock.family, doc="the socket family")
  473. type = property(lambda self: self._sock.type, doc="the socket type")
  474. proto = property(lambda self: self._sock.proto, doc="the socket protocol")
  475. # delegate the functions that we haven't implemented to the real socket object
  476. _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
  477. "%s.__doc__ = _realsocket.%s.__doc__\n")
  478. for _m in set(__socket__._socketmethods) - set(locals()):
  479. exec (_s % (_m, _m, _m, _m))
  480. del _m, _s
  481. SocketType = socket
  482. if hasattr(_socket, 'socketpair'):
  483. def socketpair(*args):
  484. one, two = _socket.socketpair(*args)
  485. return socket(_sock=one), socket(_sock=two)
  486. else:
  487. __implements__.remove('socketpair')
  488. if hasattr(_socket, 'fromfd'):
  489. def fromfd(*args):
  490. return socket(_sock=_socket.fromfd(*args))
  491. else:
  492. __implements__.remove('fromfd')
  493. try:
  494. _GLOBAL_DEFAULT_TIMEOUT = __socket__._GLOBAL_DEFAULT_TIMEOUT
  495. except AttributeError:
  496. _GLOBAL_DEFAULT_TIMEOUT = object()
  497. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  498. """Connect to *address* and return the socket object.
  499. Convenience function. Connect to *address* (a 2-tuple ``(host,
  500. port)``) and return the socket object. Passing the optional
  501. *timeout* parameter will set the timeout on the socket instance
  502. before attempting to connect. If no *timeout* is supplied, the
  503. global default timeout setting returned by :func:`getdefaulttimeout`
  504. is used. If *source_address* is set it must be a tuple of (host, port)
  505. for the socket to bind as a source address before making the connection.
  506. An host of '' or port 0 tells the OS to use the default.
  507. """
  508. host, port = address
  509. err = None
  510. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  511. af, socktype, proto, _canonname, sa = res
  512. sock = None
  513. try:
  514. sock = socket(af, socktype, proto)
  515. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  516. sock.settimeout(timeout)
  517. if source_address:
  518. sock.bind(source_address)
  519. sock.connect(sa)
  520. return sock
  521. except error:
  522. err = sys.exc_info()[1]
  523. # without exc_clear(), if connect() fails once, the socket is referenced by the frame in exc_info
  524. # and the next bind() fails (see test__socket.TestCreateConnection)
  525. # that does not happen with regular sockets though, because _socket.socket.connect() is a built-in.
  526. # this is similar to "getnameinfo loses a reference" failure in test_socket.py
  527. sys.exc_clear()
  528. if sock is not None:
  529. sock.close()
  530. if err is not None:
  531. raise err
  532. else:
  533. raise error("getaddrinfo returns an empty list")
  534. class BlockingResolver(object):
  535. def __init__(self, hub=None):
  536. pass
  537. def close(self):
  538. pass
  539. for method in ['gethostbyname',
  540. 'gethostbyname_ex',
  541. 'getaddrinfo',
  542. 'gethostbyaddr',
  543. 'getnameinfo']:
  544. locals()[method] = staticmethod(getattr(_socket, method))
  545. def gethostbyname(hostname):
  546. return get_hub().resolver.gethostbyname(hostname)
  547. def gethostbyname_ex(hostname):
  548. return get_hub().resolver.gethostbyname_ex(hostname)
  549. def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0):
  550. return get_hub().resolver.getaddrinfo(host, port, family, socktype, proto, flags)
  551. def gethostbyaddr(ip_address):
  552. return get_hub().resolver.gethostbyaddr(ip_address)
  553. def getnameinfo(sockaddr, flags):
  554. return get_hub().resolver.getnameinfo(sockaddr, flags)
  555. def getfqdn(name=''):
  556. """Get fully qualified domain name from name.
  557. An empty argument is interpreted as meaning the local host.
  558. First the hostname returned by gethostbyaddr() is checked, then
  559. possibly existing aliases. In case no FQDN is available, hostname
  560. from gethostname() is returned.
  561. """
  562. name = name.strip()
  563. if not name or name == '0.0.0.0':
  564. name = gethostname()
  565. try:
  566. hostname, aliases, ipaddrs = gethostbyaddr(name)
  567. except error:
  568. pass
  569. else:
  570. aliases.insert(0, hostname)
  571. for name in aliases:
  572. if '.' in name:
  573. break
  574. else:
  575. name = hostname
  576. return name
  577. try:
  578. from gevent.ssl import sslwrap_simple as ssl, SSLError as sslerror, SSLSocket as SSLType
  579. _have_ssl = True
  580. except ImportError:
  581. _have_ssl = False
  582. if sys.version_info[:2] <= (2, 5) and _have_ssl:
  583. __implements__.extend(['ssl', 'sslerror', 'SSLType'])
  584. __all__ = __implements__ + __extensions__ + __imports__