sslproto.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. import collections
  2. import warnings
  3. try:
  4. import ssl
  5. except ImportError: # pragma: no cover
  6. ssl = None
  7. from . import constants
  8. from . import protocols
  9. from . import transports
  10. from .log import logger
  11. def _create_transport_context(server_side, server_hostname):
  12. if server_side:
  13. raise ValueError('Server side SSL needs a valid SSLContext')
  14. # Client side may pass ssl=True to use a default
  15. # context; in that case the sslcontext passed is None.
  16. # The default is secure for client connections.
  17. # Python 3.4+: use up-to-date strong settings.
  18. sslcontext = ssl.create_default_context()
  19. if not server_hostname:
  20. sslcontext.check_hostname = False
  21. return sslcontext
  22. # States of an _SSLPipe.
  23. _UNWRAPPED = "UNWRAPPED"
  24. _DO_HANDSHAKE = "DO_HANDSHAKE"
  25. _WRAPPED = "WRAPPED"
  26. _SHUTDOWN = "SHUTDOWN"
  27. class _SSLPipe(object):
  28. """An SSL "Pipe".
  29. An SSL pipe allows you to communicate with an SSL/TLS protocol instance
  30. through memory buffers. It can be used to implement a security layer for an
  31. existing connection where you don't have access to the connection's file
  32. descriptor, or for some reason you don't want to use it.
  33. An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
  34. data is passed through untransformed. In wrapped mode, application level
  35. data is encrypted to SSL record level data and vice versa. The SSL record
  36. level is the lowest level in the SSL protocol suite and is what travels
  37. as-is over the wire.
  38. An SslPipe initially is in "unwrapped" mode. To start SSL, call
  39. do_handshake(). To shutdown SSL again, call unwrap().
  40. """
  41. max_size = 256 * 1024 # Buffer size passed to read()
  42. def __init__(self, context, server_side, server_hostname=None):
  43. """
  44. The *context* argument specifies the ssl.SSLContext to use.
  45. The *server_side* argument indicates whether this is a server side or
  46. client side transport.
  47. The optional *server_hostname* argument can be used to specify the
  48. hostname you are connecting to. You may only specify this parameter if
  49. the _ssl module supports Server Name Indication (SNI).
  50. """
  51. self._context = context
  52. self._server_side = server_side
  53. self._server_hostname = server_hostname
  54. self._state = _UNWRAPPED
  55. self._incoming = ssl.MemoryBIO()
  56. self._outgoing = ssl.MemoryBIO()
  57. self._sslobj = None
  58. self._need_ssldata = False
  59. self._handshake_cb = None
  60. self._shutdown_cb = None
  61. @property
  62. def context(self):
  63. """The SSL context passed to the constructor."""
  64. return self._context
  65. @property
  66. def ssl_object(self):
  67. """The internal ssl.SSLObject instance.
  68. Return None if the pipe is not wrapped.
  69. """
  70. return self._sslobj
  71. @property
  72. def need_ssldata(self):
  73. """Whether more record level data is needed to complete a handshake
  74. that is currently in progress."""
  75. return self._need_ssldata
  76. @property
  77. def wrapped(self):
  78. """
  79. Whether a security layer is currently in effect.
  80. Return False during handshake.
  81. """
  82. return self._state == _WRAPPED
  83. def do_handshake(self, callback=None):
  84. """Start the SSL handshake.
  85. Return a list of ssldata. A ssldata element is a list of buffers
  86. The optional *callback* argument can be used to install a callback that
  87. will be called when the handshake is complete. The callback will be
  88. called with None if successful, else an exception instance.
  89. """
  90. if self._state != _UNWRAPPED:
  91. raise RuntimeError('handshake in progress or completed')
  92. self._sslobj = self._context.wrap_bio(
  93. self._incoming, self._outgoing,
  94. server_side=self._server_side,
  95. server_hostname=self._server_hostname)
  96. self._state = _DO_HANDSHAKE
  97. self._handshake_cb = callback
  98. ssldata, appdata = self.feed_ssldata(b'', only_handshake=True)
  99. assert len(appdata) == 0
  100. return ssldata
  101. def shutdown(self, callback=None):
  102. """Start the SSL shutdown sequence.
  103. Return a list of ssldata. A ssldata element is a list of buffers
  104. The optional *callback* argument can be used to install a callback that
  105. will be called when the shutdown is complete. The callback will be
  106. called without arguments.
  107. """
  108. if self._state == _UNWRAPPED:
  109. raise RuntimeError('no security layer present')
  110. if self._state == _SHUTDOWN:
  111. raise RuntimeError('shutdown in progress')
  112. assert self._state in (_WRAPPED, _DO_HANDSHAKE)
  113. self._state = _SHUTDOWN
  114. self._shutdown_cb = callback
  115. ssldata, appdata = self.feed_ssldata(b'')
  116. assert appdata == [] or appdata == [b'']
  117. return ssldata
  118. def feed_eof(self):
  119. """Send a potentially "ragged" EOF.
  120. This method will raise an SSL_ERROR_EOF exception if the EOF is
  121. unexpected.
  122. """
  123. self._incoming.write_eof()
  124. ssldata, appdata = self.feed_ssldata(b'')
  125. assert appdata == [] or appdata == [b'']
  126. def feed_ssldata(self, data, only_handshake=False):
  127. """Feed SSL record level data into the pipe.
  128. The data must be a bytes instance. It is OK to send an empty bytes
  129. instance. This can be used to get ssldata for a handshake initiated by
  130. this endpoint.
  131. Return a (ssldata, appdata) tuple. The ssldata element is a list of
  132. buffers containing SSL data that needs to be sent to the remote SSL.
  133. The appdata element is a list of buffers containing plaintext data that
  134. needs to be forwarded to the application. The appdata list may contain
  135. an empty buffer indicating an SSL "close_notify" alert. This alert must
  136. be acknowledged by calling shutdown().
  137. """
  138. if self._state == _UNWRAPPED:
  139. # If unwrapped, pass plaintext data straight through.
  140. if data:
  141. appdata = [data]
  142. else:
  143. appdata = []
  144. return ([], appdata)
  145. self._need_ssldata = False
  146. if data:
  147. self._incoming.write(data)
  148. ssldata = []
  149. appdata = []
  150. try:
  151. if self._state == _DO_HANDSHAKE:
  152. # Call do_handshake() until it doesn't raise anymore.
  153. self._sslobj.do_handshake()
  154. self._state = _WRAPPED
  155. if self._handshake_cb:
  156. self._handshake_cb(None)
  157. if only_handshake:
  158. return (ssldata, appdata)
  159. # Handshake done: execute the wrapped block
  160. if self._state == _WRAPPED:
  161. # Main state: read data from SSL until close_notify
  162. while True:
  163. chunk = self._sslobj.read(self.max_size)
  164. appdata.append(chunk)
  165. if not chunk: # close_notify
  166. break
  167. elif self._state == _SHUTDOWN:
  168. # Call shutdown() until it doesn't raise anymore.
  169. self._sslobj.unwrap()
  170. self._sslobj = None
  171. self._state = _UNWRAPPED
  172. if self._shutdown_cb:
  173. self._shutdown_cb()
  174. elif self._state == _UNWRAPPED:
  175. # Drain possible plaintext data after close_notify.
  176. appdata.append(self._incoming.read())
  177. except (ssl.SSLError, ssl.CertificateError) as exc:
  178. exc_errno = getattr(exc, 'errno', None)
  179. if exc_errno not in (
  180. ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE,
  181. ssl.SSL_ERROR_SYSCALL):
  182. if self._state == _DO_HANDSHAKE and self._handshake_cb:
  183. self._handshake_cb(exc)
  184. raise
  185. self._need_ssldata = (exc_errno == ssl.SSL_ERROR_WANT_READ)
  186. # Check for record level data that needs to be sent back.
  187. # Happens for the initial handshake and renegotiations.
  188. if self._outgoing.pending:
  189. ssldata.append(self._outgoing.read())
  190. return (ssldata, appdata)
  191. def feed_appdata(self, data, offset=0):
  192. """Feed plaintext data into the pipe.
  193. Return an (ssldata, offset) tuple. The ssldata element is a list of
  194. buffers containing record level data that needs to be sent to the
  195. remote SSL instance. The offset is the number of plaintext bytes that
  196. were processed, which may be less than the length of data.
  197. NOTE: In case of short writes, this call MUST be retried with the SAME
  198. buffer passed into the *data* argument (i.e. the id() must be the
  199. same). This is an OpenSSL requirement. A further particularity is that
  200. a short write will always have offset == 0, because the _ssl module
  201. does not enable partial writes. And even though the offset is zero,
  202. there will still be encrypted data in ssldata.
  203. """
  204. assert 0 <= offset <= len(data)
  205. if self._state == _UNWRAPPED:
  206. # pass through data in unwrapped mode
  207. if offset < len(data):
  208. ssldata = [data[offset:]]
  209. else:
  210. ssldata = []
  211. return (ssldata, len(data))
  212. ssldata = []
  213. view = memoryview(data)
  214. while True:
  215. self._need_ssldata = False
  216. try:
  217. if offset < len(view):
  218. offset += self._sslobj.write(view[offset:])
  219. except ssl.SSLError as exc:
  220. # It is not allowed to call write() after unwrap() until the
  221. # close_notify is acknowledged. We return the condition to the
  222. # caller as a short write.
  223. exc_errno = getattr(exc, 'errno', None)
  224. if exc.reason == 'PROTOCOL_IS_SHUTDOWN':
  225. exc_errno = exc.errno = ssl.SSL_ERROR_WANT_READ
  226. if exc_errno not in (ssl.SSL_ERROR_WANT_READ,
  227. ssl.SSL_ERROR_WANT_WRITE,
  228. ssl.SSL_ERROR_SYSCALL):
  229. raise
  230. self._need_ssldata = (exc_errno == ssl.SSL_ERROR_WANT_READ)
  231. # See if there's any record level data back for us.
  232. if self._outgoing.pending:
  233. ssldata.append(self._outgoing.read())
  234. if offset == len(view) or self._need_ssldata:
  235. break
  236. return (ssldata, offset)
  237. class _SSLProtocolTransport(transports._FlowControlMixin,
  238. transports.Transport):
  239. _sendfile_compatible = constants._SendfileMode.FALLBACK
  240. def __init__(self, loop, ssl_protocol):
  241. self._loop = loop
  242. # SSLProtocol instance
  243. self._ssl_protocol = ssl_protocol
  244. self._closed = False
  245. def get_extra_info(self, name, default=None):
  246. """Get optional transport information."""
  247. return self._ssl_protocol._get_extra_info(name, default)
  248. def set_protocol(self, protocol):
  249. self._ssl_protocol._set_app_protocol(protocol)
  250. def get_protocol(self):
  251. return self._ssl_protocol._app_protocol
  252. def is_closing(self):
  253. return self._closed
  254. def close(self):
  255. """Close the transport.
  256. Buffered data will be flushed asynchronously. No more data
  257. will be received. After all buffered data is flushed, the
  258. protocol's connection_lost() method will (eventually) called
  259. with None as its argument.
  260. """
  261. self._closed = True
  262. self._ssl_protocol._start_shutdown()
  263. def __del__(self, _warn=warnings.warn):
  264. if not self._closed:
  265. _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
  266. self.close()
  267. def is_reading(self):
  268. tr = self._ssl_protocol._transport
  269. if tr is None:
  270. raise RuntimeError('SSL transport has not been initialized yet')
  271. return tr.is_reading()
  272. def pause_reading(self):
  273. """Pause the receiving end.
  274. No data will be passed to the protocol's data_received()
  275. method until resume_reading() is called.
  276. """
  277. self._ssl_protocol._transport.pause_reading()
  278. def resume_reading(self):
  279. """Resume the receiving end.
  280. Data received will once again be passed to the protocol's
  281. data_received() method.
  282. """
  283. self._ssl_protocol._transport.resume_reading()
  284. def set_write_buffer_limits(self, high=None, low=None):
  285. """Set the high- and low-water limits for write flow control.
  286. These two values control when to call the protocol's
  287. pause_writing() and resume_writing() methods. If specified,
  288. the low-water limit must be less than or equal to the
  289. high-water limit. Neither value can be negative.
  290. The defaults are implementation-specific. If only the
  291. high-water limit is given, the low-water limit defaults to an
  292. implementation-specific value less than or equal to the
  293. high-water limit. Setting high to zero forces low to zero as
  294. well, and causes pause_writing() to be called whenever the
  295. buffer becomes non-empty. Setting low to zero causes
  296. resume_writing() to be called only once the buffer is empty.
  297. Use of zero for either limit is generally sub-optimal as it
  298. reduces opportunities for doing I/O and computation
  299. concurrently.
  300. """
  301. self._ssl_protocol._transport.set_write_buffer_limits(high, low)
  302. def get_write_buffer_size(self):
  303. """Return the current size of the write buffer."""
  304. return self._ssl_protocol._transport.get_write_buffer_size()
  305. def get_write_buffer_limits(self):
  306. """Get the high and low watermarks for write flow control.
  307. Return a tuple (low, high) where low and high are
  308. positive number of bytes."""
  309. return self._ssl_protocol._transport.get_write_buffer_limits()
  310. @property
  311. def _protocol_paused(self):
  312. # Required for sendfile fallback pause_writing/resume_writing logic
  313. return self._ssl_protocol._transport._protocol_paused
  314. def write(self, data):
  315. """Write some data bytes to the transport.
  316. This does not block; it buffers the data and arranges for it
  317. to be sent out asynchronously.
  318. """
  319. if not isinstance(data, (bytes, bytearray, memoryview)):
  320. raise TypeError(f"data: expecting a bytes-like instance, "
  321. f"got {type(data).__name__}")
  322. if not data:
  323. return
  324. self._ssl_protocol._write_appdata(data)
  325. def can_write_eof(self):
  326. """Return True if this transport supports write_eof(), False if not."""
  327. return False
  328. def abort(self):
  329. """Close the transport immediately.
  330. Buffered data will be lost. No more data will be received.
  331. The protocol's connection_lost() method will (eventually) be
  332. called with None as its argument.
  333. """
  334. self._ssl_protocol._abort()
  335. self._closed = True
  336. class SSLProtocol(protocols.Protocol):
  337. """SSL protocol.
  338. Implementation of SSL on top of a socket using incoming and outgoing
  339. buffers which are ssl.MemoryBIO objects.
  340. """
  341. def __init__(self, loop, app_protocol, sslcontext, waiter,
  342. server_side=False, server_hostname=None,
  343. call_connection_made=True,
  344. ssl_handshake_timeout=None):
  345. if ssl is None:
  346. raise RuntimeError('stdlib ssl module not available')
  347. if ssl_handshake_timeout is None:
  348. ssl_handshake_timeout = constants.SSL_HANDSHAKE_TIMEOUT
  349. elif ssl_handshake_timeout <= 0:
  350. raise ValueError(
  351. f"ssl_handshake_timeout should be a positive number, "
  352. f"got {ssl_handshake_timeout}")
  353. if not sslcontext:
  354. sslcontext = _create_transport_context(
  355. server_side, server_hostname)
  356. self._server_side = server_side
  357. if server_hostname and not server_side:
  358. self._server_hostname = server_hostname
  359. else:
  360. self._server_hostname = None
  361. self._sslcontext = sslcontext
  362. # SSL-specific extra info. More info are set when the handshake
  363. # completes.
  364. self._extra = dict(sslcontext=sslcontext)
  365. # App data write buffering
  366. self._write_backlog = collections.deque()
  367. self._write_buffer_size = 0
  368. self._waiter = waiter
  369. self._loop = loop
  370. self._set_app_protocol(app_protocol)
  371. self._app_transport = _SSLProtocolTransport(self._loop, self)
  372. # _SSLPipe instance (None until the connection is made)
  373. self._sslpipe = None
  374. self._session_established = False
  375. self._in_handshake = False
  376. self._in_shutdown = False
  377. # transport, ex: SelectorSocketTransport
  378. self._transport = None
  379. self._call_connection_made = call_connection_made
  380. self._ssl_handshake_timeout = ssl_handshake_timeout
  381. def _set_app_protocol(self, app_protocol):
  382. self._app_protocol = app_protocol
  383. self._app_protocol_is_buffer = \
  384. isinstance(app_protocol, protocols.BufferedProtocol)
  385. def _wakeup_waiter(self, exc=None):
  386. if self._waiter is None:
  387. return
  388. if not self._waiter.cancelled():
  389. if exc is not None:
  390. self._waiter.set_exception(exc)
  391. else:
  392. self._waiter.set_result(None)
  393. self._waiter = None
  394. def connection_made(self, transport):
  395. """Called when the low-level connection is made.
  396. Start the SSL handshake.
  397. """
  398. self._transport = transport
  399. self._sslpipe = _SSLPipe(self._sslcontext,
  400. self._server_side,
  401. self._server_hostname)
  402. self._start_handshake()
  403. def connection_lost(self, exc):
  404. """Called when the low-level connection is lost or closed.
  405. The argument is an exception object or None (the latter
  406. meaning a regular EOF is received or the connection was
  407. aborted or closed).
  408. """
  409. if self._session_established:
  410. self._session_established = False
  411. self._loop.call_soon(self._app_protocol.connection_lost, exc)
  412. else:
  413. # Most likely an exception occurred while in SSL handshake.
  414. # Just mark the app transport as closed so that its __del__
  415. # doesn't complain.
  416. if self._app_transport is not None:
  417. self._app_transport._closed = True
  418. self._transport = None
  419. self._app_transport = None
  420. if getattr(self, '_handshake_timeout_handle', None):
  421. self._handshake_timeout_handle.cancel()
  422. self._wakeup_waiter(exc)
  423. self._app_protocol = None
  424. self._sslpipe = None
  425. def pause_writing(self):
  426. """Called when the low-level transport's buffer goes over
  427. the high-water mark.
  428. """
  429. self._app_protocol.pause_writing()
  430. def resume_writing(self):
  431. """Called when the low-level transport's buffer drains below
  432. the low-water mark.
  433. """
  434. self._app_protocol.resume_writing()
  435. def data_received(self, data):
  436. """Called when some SSL data is received.
  437. The argument is a bytes object.
  438. """
  439. if self._sslpipe is None:
  440. # transport closing, sslpipe is destroyed
  441. return
  442. try:
  443. ssldata, appdata = self._sslpipe.feed_ssldata(data)
  444. except (SystemExit, KeyboardInterrupt):
  445. raise
  446. except BaseException as e:
  447. self._fatal_error(e, 'SSL error in data received')
  448. return
  449. for chunk in ssldata:
  450. self._transport.write(chunk)
  451. for chunk in appdata:
  452. if chunk:
  453. try:
  454. if self._app_protocol_is_buffer:
  455. protocols._feed_data_to_buffered_proto(
  456. self._app_protocol, chunk)
  457. else:
  458. self._app_protocol.data_received(chunk)
  459. except (SystemExit, KeyboardInterrupt):
  460. raise
  461. except BaseException as ex:
  462. self._fatal_error(
  463. ex, 'application protocol failed to receive SSL data')
  464. return
  465. else:
  466. self._start_shutdown()
  467. break
  468. def eof_received(self):
  469. """Called when the other end of the low-level stream
  470. is half-closed.
  471. If this returns a false value (including None), the transport
  472. will close itself. If it returns a true value, closing the
  473. transport is up to the protocol.
  474. """
  475. try:
  476. if self._loop.get_debug():
  477. logger.debug("%r received EOF", self)
  478. self._wakeup_waiter(ConnectionResetError)
  479. if not self._in_handshake:
  480. keep_open = self._app_protocol.eof_received()
  481. if keep_open:
  482. logger.warning('returning true from eof_received() '
  483. 'has no effect when using ssl')
  484. finally:
  485. self._transport.close()
  486. def _get_extra_info(self, name, default=None):
  487. if name in self._extra:
  488. return self._extra[name]
  489. elif self._transport is not None:
  490. return self._transport.get_extra_info(name, default)
  491. else:
  492. return default
  493. def _start_shutdown(self):
  494. if self._in_shutdown:
  495. return
  496. if self._in_handshake:
  497. self._abort()
  498. else:
  499. self._in_shutdown = True
  500. self._write_appdata(b'')
  501. def _write_appdata(self, data):
  502. self._write_backlog.append((data, 0))
  503. self._write_buffer_size += len(data)
  504. self._process_write_backlog()
  505. def _start_handshake(self):
  506. if self._loop.get_debug():
  507. logger.debug("%r starts SSL handshake", self)
  508. self._handshake_start_time = self._loop.time()
  509. else:
  510. self._handshake_start_time = None
  511. self._in_handshake = True
  512. # (b'', 1) is a special value in _process_write_backlog() to do
  513. # the SSL handshake
  514. self._write_backlog.append((b'', 1))
  515. self._handshake_timeout_handle = \
  516. self._loop.call_later(self._ssl_handshake_timeout,
  517. self._check_handshake_timeout)
  518. self._process_write_backlog()
  519. def _check_handshake_timeout(self):
  520. if self._in_handshake is True:
  521. msg = (
  522. f"SSL handshake is taking longer than "
  523. f"{self._ssl_handshake_timeout} seconds: "
  524. f"aborting the connection"
  525. )
  526. self._fatal_error(ConnectionAbortedError(msg))
  527. def _on_handshake_complete(self, handshake_exc):
  528. self._in_handshake = False
  529. self._handshake_timeout_handle.cancel()
  530. sslobj = self._sslpipe.ssl_object
  531. try:
  532. if handshake_exc is not None:
  533. raise handshake_exc
  534. peercert = sslobj.getpeercert()
  535. except (SystemExit, KeyboardInterrupt):
  536. raise
  537. except BaseException as exc:
  538. if isinstance(exc, ssl.CertificateError):
  539. msg = 'SSL handshake failed on verifying the certificate'
  540. else:
  541. msg = 'SSL handshake failed'
  542. self._fatal_error(exc, msg)
  543. return
  544. if self._loop.get_debug():
  545. dt = self._loop.time() - self._handshake_start_time
  546. logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3)
  547. # Add extra info that becomes available after handshake.
  548. self._extra.update(peercert=peercert,
  549. cipher=sslobj.cipher(),
  550. compression=sslobj.compression(),
  551. ssl_object=sslobj,
  552. )
  553. if self._call_connection_made:
  554. self._app_protocol.connection_made(self._app_transport)
  555. self._wakeup_waiter()
  556. self._session_established = True
  557. # In case transport.write() was already called. Don't call
  558. # immediately _process_write_backlog(), but schedule it:
  559. # _on_handshake_complete() can be called indirectly from
  560. # _process_write_backlog(), and _process_write_backlog() is not
  561. # reentrant.
  562. self._loop.call_soon(self._process_write_backlog)
  563. def _process_write_backlog(self):
  564. # Try to make progress on the write backlog.
  565. if self._transport is None or self._sslpipe is None:
  566. return
  567. try:
  568. for i in range(len(self._write_backlog)):
  569. data, offset = self._write_backlog[0]
  570. if data:
  571. ssldata, offset = self._sslpipe.feed_appdata(data, offset)
  572. elif offset:
  573. ssldata = self._sslpipe.do_handshake(
  574. self._on_handshake_complete)
  575. offset = 1
  576. else:
  577. ssldata = self._sslpipe.shutdown(self._finalize)
  578. offset = 1
  579. for chunk in ssldata:
  580. self._transport.write(chunk)
  581. if offset < len(data):
  582. self._write_backlog[0] = (data, offset)
  583. # A short write means that a write is blocked on a read
  584. # We need to enable reading if it is paused!
  585. assert self._sslpipe.need_ssldata
  586. if self._transport._paused:
  587. self._transport.resume_reading()
  588. break
  589. # An entire chunk from the backlog was processed. We can
  590. # delete it and reduce the outstanding buffer size.
  591. del self._write_backlog[0]
  592. self._write_buffer_size -= len(data)
  593. except (SystemExit, KeyboardInterrupt):
  594. raise
  595. except BaseException as exc:
  596. if self._in_handshake:
  597. # Exceptions will be re-raised in _on_handshake_complete.
  598. self._on_handshake_complete(exc)
  599. else:
  600. self._fatal_error(exc, 'Fatal error on SSL transport')
  601. def _fatal_error(self, exc, message='Fatal error on transport'):
  602. if isinstance(exc, OSError):
  603. if self._loop.get_debug():
  604. logger.debug("%r: %s", self, message, exc_info=True)
  605. else:
  606. self._loop.call_exception_handler({
  607. 'message': message,
  608. 'exception': exc,
  609. 'transport': self._transport,
  610. 'protocol': self,
  611. })
  612. if self._transport:
  613. self._transport._force_close(exc)
  614. def _finalize(self):
  615. self._sslpipe = None
  616. if self._transport is not None:
  617. self._transport.close()
  618. def _abort(self):
  619. try:
  620. if self._transport is not None:
  621. self._transport.abort()
  622. finally:
  623. self._finalize()