blob: 53e6d2b667b12cd179dc7da6054650d6cc732bff [file] [log] [blame]
Victor Stinner231b4042015-01-14 00:19:09 +01001import collections
Victor Stinner978a9af2015-01-29 17:50:58 +01002import warnings
Victor Stinner231b4042015-01-14 00:19:09 +01003try:
4 import ssl
5except ImportError: # pragma: no cover
6 ssl = None
7
Yury Selivanov77bc04a2016-06-28 10:55:36 -04008from . import base_events
Victor Stinner231b4042015-01-14 00:19:09 +01009from . import protocols
10from . import transports
11from .log import logger
12
13
14def _create_transport_context(server_side, server_hostname):
15 if server_side:
16 raise ValueError('Server side SSL needs a valid SSLContext')
17
18 # Client side may pass ssl=True to use a default
19 # context; in that case the sslcontext passed is None.
20 # The default is secure for client connections.
21 if hasattr(ssl, 'create_default_context'):
22 # Python 3.4+: use up-to-date strong settings.
23 sslcontext = ssl.create_default_context()
24 if not server_hostname:
25 sslcontext.check_hostname = False
26 else:
27 # Fallback for Python 3.3.
28 sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
29 sslcontext.options |= ssl.OP_NO_SSLv2
30 sslcontext.options |= ssl.OP_NO_SSLv3
31 sslcontext.set_default_verify_paths()
32 sslcontext.verify_mode = ssl.CERT_REQUIRED
33 return sslcontext
34
35
36def _is_sslproto_available():
37 return hasattr(ssl, "MemoryBIO")
38
39
40# States of an _SSLPipe.
41_UNWRAPPED = "UNWRAPPED"
42_DO_HANDSHAKE = "DO_HANDSHAKE"
43_WRAPPED = "WRAPPED"
44_SHUTDOWN = "SHUTDOWN"
45
46
47class _SSLPipe(object):
48 """An SSL "Pipe".
49
50 An SSL pipe allows you to communicate with an SSL/TLS protocol instance
51 through memory buffers. It can be used to implement a security layer for an
52 existing connection where you don't have access to the connection's file
53 descriptor, or for some reason you don't want to use it.
54
55 An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
56 data is passed through untransformed. In wrapped mode, application level
57 data is encrypted to SSL record level data and vice versa. The SSL record
58 level is the lowest level in the SSL protocol suite and is what travels
59 as-is over the wire.
60
61 An SslPipe initially is in "unwrapped" mode. To start SSL, call
62 do_handshake(). To shutdown SSL again, call unwrap().
63 """
64
65 max_size = 256 * 1024 # Buffer size passed to read()
66
67 def __init__(self, context, server_side, server_hostname=None):
68 """
69 The *context* argument specifies the ssl.SSLContext to use.
70
71 The *server_side* argument indicates whether this is a server side or
72 client side transport.
73
74 The optional *server_hostname* argument can be used to specify the
75 hostname you are connecting to. You may only specify this parameter if
76 the _ssl module supports Server Name Indication (SNI).
77 """
78 self._context = context
79 self._server_side = server_side
80 self._server_hostname = server_hostname
81 self._state = _UNWRAPPED
82 self._incoming = ssl.MemoryBIO()
83 self._outgoing = ssl.MemoryBIO()
84 self._sslobj = None
85 self._need_ssldata = False
86 self._handshake_cb = None
87 self._shutdown_cb = None
88
89 @property
90 def context(self):
91 """The SSL context passed to the constructor."""
92 return self._context
93
94 @property
95 def ssl_object(self):
96 """The internal ssl.SSLObject instance.
97
98 Return None if the pipe is not wrapped.
99 """
100 return self._sslobj
101
102 @property
103 def need_ssldata(self):
104 """Whether more record level data is needed to complete a handshake
105 that is currently in progress."""
106 return self._need_ssldata
107
108 @property
109 def wrapped(self):
110 """
111 Whether a security layer is currently in effect.
112
113 Return False during handshake.
114 """
115 return self._state == _WRAPPED
116
117 def do_handshake(self, callback=None):
118 """Start the SSL handshake.
119
120 Return a list of ssldata. A ssldata element is a list of buffers
121
122 The optional *callback* argument can be used to install a callback that
123 will be called when the handshake is complete. The callback will be
124 called with None if successful, else an exception instance.
125 """
126 if self._state != _UNWRAPPED:
127 raise RuntimeError('handshake in progress or completed')
128 self._sslobj = self._context.wrap_bio(
129 self._incoming, self._outgoing,
130 server_side=self._server_side,
131 server_hostname=self._server_hostname)
132 self._state = _DO_HANDSHAKE
133 self._handshake_cb = callback
134 ssldata, appdata = self.feed_ssldata(b'', only_handshake=True)
135 assert len(appdata) == 0
136 return ssldata
137
138 def shutdown(self, callback=None):
139 """Start the SSL shutdown sequence.
140
141 Return a list of ssldata. A ssldata element is a list of buffers
142
143 The optional *callback* argument can be used to install a callback that
144 will be called when the shutdown is complete. The callback will be
145 called without arguments.
146 """
147 if self._state == _UNWRAPPED:
148 raise RuntimeError('no security layer present')
149 if self._state == _SHUTDOWN:
150 raise RuntimeError('shutdown in progress')
151 assert self._state in (_WRAPPED, _DO_HANDSHAKE)
152 self._state = _SHUTDOWN
153 self._shutdown_cb = callback
154 ssldata, appdata = self.feed_ssldata(b'')
155 assert appdata == [] or appdata == [b'']
156 return ssldata
157
158 def feed_eof(self):
159 """Send a potentially "ragged" EOF.
160
161 This method will raise an SSL_ERROR_EOF exception if the EOF is
162 unexpected.
163 """
164 self._incoming.write_eof()
165 ssldata, appdata = self.feed_ssldata(b'')
166 assert appdata == [] or appdata == [b'']
167
168 def feed_ssldata(self, data, only_handshake=False):
169 """Feed SSL record level data into the pipe.
170
171 The data must be a bytes instance. It is OK to send an empty bytes
172 instance. This can be used to get ssldata for a handshake initiated by
173 this endpoint.
174
175 Return a (ssldata, appdata) tuple. The ssldata element is a list of
176 buffers containing SSL data that needs to be sent to the remote SSL.
177
178 The appdata element is a list of buffers containing plaintext data that
179 needs to be forwarded to the application. The appdata list may contain
180 an empty buffer indicating an SSL "close_notify" alert. This alert must
181 be acknowledged by calling shutdown().
182 """
183 if self._state == _UNWRAPPED:
184 # If unwrapped, pass plaintext data straight through.
185 if data:
186 appdata = [data]
187 else:
188 appdata = []
189 return ([], appdata)
190
191 self._need_ssldata = False
192 if data:
193 self._incoming.write(data)
194
195 ssldata = []
196 appdata = []
197 try:
198 if self._state == _DO_HANDSHAKE:
199 # Call do_handshake() until it doesn't raise anymore.
200 self._sslobj.do_handshake()
201 self._state = _WRAPPED
202 if self._handshake_cb:
203 self._handshake_cb(None)
204 if only_handshake:
205 return (ssldata, appdata)
206 # Handshake done: execute the wrapped block
207
208 if self._state == _WRAPPED:
209 # Main state: read data from SSL until close_notify
210 while True:
211 chunk = self._sslobj.read(self.max_size)
212 appdata.append(chunk)
213 if not chunk: # close_notify
214 break
215
216 elif self._state == _SHUTDOWN:
217 # Call shutdown() until it doesn't raise anymore.
218 self._sslobj.unwrap()
219 self._sslobj = None
220 self._state = _UNWRAPPED
221 if self._shutdown_cb:
222 self._shutdown_cb()
223
224 elif self._state == _UNWRAPPED:
225 # Drain possible plaintext data after close_notify.
226 appdata.append(self._incoming.read())
227 except (ssl.SSLError, ssl.CertificateError) as exc:
228 if getattr(exc, 'errno', None) not in (
229 ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE,
230 ssl.SSL_ERROR_SYSCALL):
231 if self._state == _DO_HANDSHAKE and self._handshake_cb:
232 self._handshake_cb(exc)
233 raise
234 self._need_ssldata = (exc.errno == ssl.SSL_ERROR_WANT_READ)
235
236 # Check for record level data that needs to be sent back.
237 # Happens for the initial handshake and renegotiations.
238 if self._outgoing.pending:
239 ssldata.append(self._outgoing.read())
240 return (ssldata, appdata)
241
242 def feed_appdata(self, data, offset=0):
243 """Feed plaintext data into the pipe.
244
245 Return an (ssldata, offset) tuple. The ssldata element is a list of
246 buffers containing record level data that needs to be sent to the
247 remote SSL instance. The offset is the number of plaintext bytes that
248 were processed, which may be less than the length of data.
249
250 NOTE: In case of short writes, this call MUST be retried with the SAME
251 buffer passed into the *data* argument (i.e. the id() must be the
252 same). This is an OpenSSL requirement. A further particularity is that
253 a short write will always have offset == 0, because the _ssl module
254 does not enable partial writes. And even though the offset is zero,
255 there will still be encrypted data in ssldata.
256 """
257 assert 0 <= offset <= len(data)
258 if self._state == _UNWRAPPED:
259 # pass through data in unwrapped mode
260 if offset < len(data):
261 ssldata = [data[offset:]]
262 else:
263 ssldata = []
264 return (ssldata, len(data))
265
266 ssldata = []
267 view = memoryview(data)
268 while True:
269 self._need_ssldata = False
270 try:
271 if offset < len(view):
272 offset += self._sslobj.write(view[offset:])
273 except ssl.SSLError as exc:
274 # It is not allowed to call write() after unwrap() until the
275 # close_notify is acknowledged. We return the condition to the
276 # caller as a short write.
277 if exc.reason == 'PROTOCOL_IS_SHUTDOWN':
278 exc.errno = ssl.SSL_ERROR_WANT_READ
279 if exc.errno not in (ssl.SSL_ERROR_WANT_READ,
280 ssl.SSL_ERROR_WANT_WRITE,
281 ssl.SSL_ERROR_SYSCALL):
282 raise
283 self._need_ssldata = (exc.errno == ssl.SSL_ERROR_WANT_READ)
284
285 # See if there's any record level data back for us.
286 if self._outgoing.pending:
287 ssldata.append(self._outgoing.read())
288 if offset == len(view) or self._need_ssldata:
289 break
290 return (ssldata, offset)
291
292
293class _SSLProtocolTransport(transports._FlowControlMixin,
294 transports.Transport):
295
jlacolineea2ef5d2017-10-19 19:49:57 +0200296 def __init__(self, loop, ssl_protocol):
Victor Stinner231b4042015-01-14 00:19:09 +0100297 self._loop = loop
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200298 # SSLProtocol instance
Victor Stinner231b4042015-01-14 00:19:09 +0100299 self._ssl_protocol = ssl_protocol
Victor Stinner978a9af2015-01-29 17:50:58 +0100300 self._closed = False
Victor Stinner231b4042015-01-14 00:19:09 +0100301
302 def get_extra_info(self, name, default=None):
303 """Get optional transport information."""
304 return self._ssl_protocol._get_extra_info(name, default)
305
Yury Selivanova05a6ef2016-09-11 21:11:02 -0400306 def set_protocol(self, protocol):
jlacolineea2ef5d2017-10-19 19:49:57 +0200307 self._ssl_protocol._app_protocol = protocol
Yury Selivanova05a6ef2016-09-11 21:11:02 -0400308
309 def get_protocol(self):
jlacolineea2ef5d2017-10-19 19:49:57 +0200310 return self._ssl_protocol._app_protocol
Yury Selivanova05a6ef2016-09-11 21:11:02 -0400311
Yury Selivanov5bb1afb2015-11-16 12:43:21 -0500312 def is_closing(self):
313 return self._closed
314
Victor Stinner231b4042015-01-14 00:19:09 +0100315 def close(self):
316 """Close the transport.
317
318 Buffered data will be flushed asynchronously. No more data
319 will be received. After all buffered data is flushed, the
320 protocol's connection_lost() method will (eventually) called
321 with None as its argument.
322 """
Victor Stinner978a9af2015-01-29 17:50:58 +0100323 self._closed = True
Victor Stinner231b4042015-01-14 00:19:09 +0100324 self._ssl_protocol._start_shutdown()
325
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900326 def __del__(self):
327 if not self._closed:
328 warnings.warn("unclosed transport %r" % self, ResourceWarning,
329 source=self)
330 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100331
Victor Stinner231b4042015-01-14 00:19:09 +0100332 def pause_reading(self):
333 """Pause the receiving end.
334
335 No data will be passed to the protocol's data_received()
336 method until resume_reading() is called.
337 """
338 self._ssl_protocol._transport.pause_reading()
339
340 def resume_reading(self):
341 """Resume the receiving end.
342
343 Data received will once again be passed to the protocol's
344 data_received() method.
345 """
346 self._ssl_protocol._transport.resume_reading()
347
348 def set_write_buffer_limits(self, high=None, low=None):
349 """Set the high- and low-water limits for write flow control.
350
351 These two values control when to call the protocol's
352 pause_writing() and resume_writing() methods. If specified,
353 the low-water limit must be less than or equal to the
354 high-water limit. Neither value can be negative.
355
356 The defaults are implementation-specific. If only the
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200357 high-water limit is given, the low-water limit defaults to an
Victor Stinner231b4042015-01-14 00:19:09 +0100358 implementation-specific value less than or equal to the
359 high-water limit. Setting high to zero forces low to zero as
360 well, and causes pause_writing() to be called whenever the
361 buffer becomes non-empty. Setting low to zero causes
362 resume_writing() to be called only once the buffer is empty.
363 Use of zero for either limit is generally sub-optimal as it
364 reduces opportunities for doing I/O and computation
365 concurrently.
366 """
367 self._ssl_protocol._transport.set_write_buffer_limits(high, low)
368
369 def get_write_buffer_size(self):
370 """Return the current size of the write buffer."""
371 return self._ssl_protocol._transport.get_write_buffer_size()
372
373 def write(self, data):
374 """Write some data bytes to the transport.
375
376 This does not block; it buffers the data and arranges for it
377 to be sent out asynchronously.
378 """
379 if not isinstance(data, (bytes, bytearray, memoryview)):
380 raise TypeError("data: expecting a bytes-like instance, got {!r}"
381 .format(type(data).__name__))
382 if not data:
383 return
384 self._ssl_protocol._write_appdata(data)
385
386 def can_write_eof(self):
387 """Return True if this transport supports write_eof(), False if not."""
388 return False
389
390 def abort(self):
391 """Close the transport immediately.
392
393 Buffered data will be lost. No more data will be received.
394 The protocol's connection_lost() method will (eventually) be
395 called with None as its argument.
396 """
397 self._ssl_protocol._abort()
398
399
400class SSLProtocol(protocols.Protocol):
401 """SSL protocol.
402
403 Implementation of SSL on top of a socket using incoming and outgoing
404 buffers which are ssl.MemoryBIO objects.
405 """
406
407 def __init__(self, loop, app_protocol, sslcontext, waiter,
Yury Selivanov92e7c7f2016-10-05 19:39:54 -0400408 server_side=False, server_hostname=None,
Yury Selivanov09663de2017-06-11 16:46:35 +0200409 call_connection_made=True):
Victor Stinner231b4042015-01-14 00:19:09 +0100410 if ssl is None:
411 raise RuntimeError('stdlib ssl module not available')
412
413 if not sslcontext:
414 sslcontext = _create_transport_context(server_side, server_hostname)
415
416 self._server_side = server_side
417 if server_hostname and not server_side:
418 self._server_hostname = server_hostname
419 else:
420 self._server_hostname = None
421 self._sslcontext = sslcontext
422 # SSL-specific extra info. More info are set when the handshake
423 # completes.
424 self._extra = dict(sslcontext=sslcontext)
425
426 # App data write buffering
427 self._write_backlog = collections.deque()
428 self._write_buffer_size = 0
429
430 self._waiter = waiter
Victor Stinner231b4042015-01-14 00:19:09 +0100431 self._loop = loop
432 self._app_protocol = app_protocol
jlacolineea2ef5d2017-10-19 19:49:57 +0200433 self._app_transport = _SSLProtocolTransport(self._loop, self)
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200434 # _SSLPipe instance (None until the connection is made)
Victor Stinner231b4042015-01-14 00:19:09 +0100435 self._sslpipe = None
436 self._session_established = False
437 self._in_handshake = False
438 self._in_shutdown = False
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200439 # transport, ex: SelectorSocketTransport
Victor Stinner7e222f42015-01-15 13:16:27 +0100440 self._transport = None
Yury Selivanov92e7c7f2016-10-05 19:39:54 -0400441 self._call_connection_made = call_connection_made
Victor Stinner231b4042015-01-14 00:19:09 +0100442
Victor Stinnerf07801b2015-01-29 00:36:35 +0100443 def _wakeup_waiter(self, exc=None):
444 if self._waiter is None:
445 return
446 if not self._waiter.cancelled():
447 if exc is not None:
448 self._waiter.set_exception(exc)
449 else:
450 self._waiter.set_result(None)
451 self._waiter = None
452
Victor Stinner231b4042015-01-14 00:19:09 +0100453 def connection_made(self, transport):
454 """Called when the low-level connection is made.
455
456 Start the SSL handshake.
457 """
458 self._transport = transport
459 self._sslpipe = _SSLPipe(self._sslcontext,
460 self._server_side,
461 self._server_hostname)
462 self._start_handshake()
463
464 def connection_lost(self, exc):
465 """Called when the low-level connection is lost or closed.
466
467 The argument is an exception object or None (the latter
468 meaning a regular EOF is received or the connection was
469 aborted or closed).
470 """
471 if self._session_established:
472 self._session_established = False
473 self._loop.call_soon(self._app_protocol.connection_lost, exc)
474 self._transport = None
475 self._app_transport = None
Yury Selivanovb1461aa2016-12-16 11:50:41 -0500476 self._wakeup_waiter(exc)
Victor Stinner231b4042015-01-14 00:19:09 +0100477
478 def pause_writing(self):
479 """Called when the low-level transport's buffer goes over
480 the high-water mark.
481 """
482 self._app_protocol.pause_writing()
483
484 def resume_writing(self):
485 """Called when the low-level transport's buffer drains below
486 the low-water mark.
487 """
488 self._app_protocol.resume_writing()
489
490 def data_received(self, data):
491 """Called when some SSL data is received.
492
493 The argument is a bytes object.
494 """
495 try:
496 ssldata, appdata = self._sslpipe.feed_ssldata(data)
497 except ssl.SSLError as e:
498 if self._loop.get_debug():
499 logger.warning('%r: SSL error %s (reason %s)',
500 self, e.errno, e.reason)
501 self._abort()
502 return
503
504 for chunk in ssldata:
505 self._transport.write(chunk)
506
507 for chunk in appdata:
508 if chunk:
509 self._app_protocol.data_received(chunk)
510 else:
511 self._start_shutdown()
512 break
513
514 def eof_received(self):
515 """Called when the other end of the low-level stream
516 is half-closed.
517
518 If this returns a false value (including None), the transport
519 will close itself. If it returns a true value, closing the
520 transport is up to the protocol.
521 """
522 try:
523 if self._loop.get_debug():
524 logger.debug("%r received EOF", self)
Victor Stinnerb507cba2015-01-29 00:35:56 +0100525
Victor Stinnerf07801b2015-01-29 00:36:35 +0100526 self._wakeup_waiter(ConnectionResetError)
Victor Stinnerb507cba2015-01-29 00:35:56 +0100527
Victor Stinner231b4042015-01-14 00:19:09 +0100528 if not self._in_handshake:
529 keep_open = self._app_protocol.eof_received()
530 if keep_open:
531 logger.warning('returning true from eof_received() '
532 'has no effect when using ssl')
533 finally:
534 self._transport.close()
535
536 def _get_extra_info(self, name, default=None):
537 if name in self._extra:
538 return self._extra[name]
Nikolay Kim2b27e2e2017-03-12 12:23:30 -0700539 elif self._transport is not None:
Victor Stinner231b4042015-01-14 00:19:09 +0100540 return self._transport.get_extra_info(name, default)
Nikolay Kim2b27e2e2017-03-12 12:23:30 -0700541 else:
542 return default
Victor Stinner231b4042015-01-14 00:19:09 +0100543
544 def _start_shutdown(self):
545 if self._in_shutdown:
546 return
Nikolay Kima0e3d2d2017-06-09 14:46:14 -0700547 if self._in_handshake:
548 self._abort()
549 else:
550 self._in_shutdown = True
551 self._write_appdata(b'')
Victor Stinner231b4042015-01-14 00:19:09 +0100552
553 def _write_appdata(self, data):
554 self._write_backlog.append((data, 0))
555 self._write_buffer_size += len(data)
556 self._process_write_backlog()
557
558 def _start_handshake(self):
559 if self._loop.get_debug():
560 logger.debug("%r starts SSL handshake", self)
561 self._handshake_start_time = self._loop.time()
562 else:
563 self._handshake_start_time = None
564 self._in_handshake = True
565 # (b'', 1) is a special value in _process_write_backlog() to do
566 # the SSL handshake
567 self._write_backlog.append((b'', 1))
568 self._loop.call_soon(self._process_write_backlog)
569
570 def _on_handshake_complete(self, handshake_exc):
571 self._in_handshake = False
572
573 sslobj = self._sslpipe.ssl_object
Victor Stinner231b4042015-01-14 00:19:09 +0100574 try:
575 if handshake_exc is not None:
576 raise handshake_exc
Victor Stinner177e9f02015-01-14 16:56:20 +0100577
578 peercert = sslobj.getpeercert()
Victor Stinner231b4042015-01-14 00:19:09 +0100579 if not hasattr(self._sslcontext, 'check_hostname'):
580 # Verify hostname if requested, Python 3.4+ uses check_hostname
581 # and checks the hostname in do_handshake()
582 if (self._server_hostname
583 and self._sslcontext.verify_mode != ssl.CERT_NONE):
584 ssl.match_hostname(peercert, self._server_hostname)
585 except BaseException as exc:
586 if self._loop.get_debug():
587 if isinstance(exc, ssl.CertificateError):
588 logger.warning("%r: SSL handshake failed "
589 "on verifying the certificate",
590 self, exc_info=True)
591 else:
592 logger.warning("%r: SSL handshake failed",
593 self, exc_info=True)
594 self._transport.close()
595 if isinstance(exc, Exception):
Victor Stinnerf07801b2015-01-29 00:36:35 +0100596 self._wakeup_waiter(exc)
Victor Stinner231b4042015-01-14 00:19:09 +0100597 return
598 else:
599 raise
600
601 if self._loop.get_debug():
602 dt = self._loop.time() - self._handshake_start_time
603 logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3)
604
605 # Add extra info that becomes available after handshake.
606 self._extra.update(peercert=peercert,
607 cipher=sslobj.cipher(),
608 compression=sslobj.compression(),
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200609 ssl_object=sslobj,
Victor Stinner231b4042015-01-14 00:19:09 +0100610 )
Yury Selivanov92e7c7f2016-10-05 19:39:54 -0400611 if self._call_connection_made:
612 self._app_protocol.connection_made(self._app_transport)
Victor Stinnerf07801b2015-01-29 00:36:35 +0100613 self._wakeup_waiter()
Victor Stinner231b4042015-01-14 00:19:09 +0100614 self._session_established = True
Victor Stinner042dad72015-01-15 09:41:48 +0100615 # In case transport.write() was already called. Don't call
Martin Panter46f50722016-05-26 05:35:26 +0000616 # immediately _process_write_backlog(), but schedule it:
Victor Stinner042dad72015-01-15 09:41:48 +0100617 # _on_handshake_complete() can be called indirectly from
618 # _process_write_backlog(), and _process_write_backlog() is not
619 # reentrant.
Victor Stinner72bdefb2015-01-15 09:44:13 +0100620 self._loop.call_soon(self._process_write_backlog)
Victor Stinner231b4042015-01-14 00:19:09 +0100621
622 def _process_write_backlog(self):
623 # Try to make progress on the write backlog.
624 if self._transport is None:
625 return
626
627 try:
628 for i in range(len(self._write_backlog)):
629 data, offset = self._write_backlog[0]
630 if data:
631 ssldata, offset = self._sslpipe.feed_appdata(data, offset)
632 elif offset:
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400633 ssldata = self._sslpipe.do_handshake(
634 self._on_handshake_complete)
Victor Stinner231b4042015-01-14 00:19:09 +0100635 offset = 1
636 else:
637 ssldata = self._sslpipe.shutdown(self._finalize)
638 offset = 1
639
640 for chunk in ssldata:
641 self._transport.write(chunk)
642
643 if offset < len(data):
644 self._write_backlog[0] = (data, offset)
645 # A short write means that a write is blocked on a read
646 # We need to enable reading if it is paused!
647 assert self._sslpipe.need_ssldata
648 if self._transport._paused:
649 self._transport.resume_reading()
650 break
651
652 # An entire chunk from the backlog was processed. We can
653 # delete it and reduce the outstanding buffer size.
654 del self._write_backlog[0]
655 self._write_buffer_size -= len(data)
656 except BaseException as exc:
657 if self._in_handshake:
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400658 # BaseExceptions will be re-raised in _on_handshake_complete.
Victor Stinner231b4042015-01-14 00:19:09 +0100659 self._on_handshake_complete(exc)
660 else:
661 self._fatal_error(exc, 'Fatal error on SSL transport')
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400662 if not isinstance(exc, Exception):
663 # BaseException
664 raise
Victor Stinner231b4042015-01-14 00:19:09 +0100665
666 def _fatal_error(self, exc, message='Fatal error on transport'):
667 # Should be called from exception handler only.
Victor Stinnerc94a93a2016-04-01 21:43:39 +0200668 if isinstance(exc, base_events._FATAL_ERROR_IGNORE):
Victor Stinner231b4042015-01-14 00:19:09 +0100669 if self._loop.get_debug():
670 logger.debug("%r: %s", self, message, exc_info=True)
671 else:
672 self._loop.call_exception_handler({
673 'message': message,
674 'exception': exc,
675 'transport': self._transport,
676 'protocol': self,
677 })
678 if self._transport:
679 self._transport._force_close(exc)
680
681 def _finalize(self):
Michaël Sghaïerd1f57512017-06-09 18:29:46 -0400682 self._sslpipe = None
683
Victor Stinner231b4042015-01-14 00:19:09 +0100684 if self._transport is not None:
685 self._transport.close()
686
687 def _abort(self):
Michaël Sghaïerd1f57512017-06-09 18:29:46 -0400688 try:
689 if self._transport is not None:
Victor Stinner231b4042015-01-14 00:19:09 +0100690 self._transport.abort()
Michaël Sghaïerd1f57512017-06-09 18:29:46 -0400691 finally:
692 self._finalize()