sslproto.py 26 KB

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