blob: a36725e0e4453d9077b3efa77d4fc9cfa2bd8164 [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
Nikolay Kima608d2d2017-06-09 21:04:39 -07009from . import compat
10from . import futures
Victor Stinner231b4042015-01-14 00:19:09 +010011from . import protocols
12from . import transports
13from .log import logger
14
15
16def _create_transport_context(server_side, server_hostname):
17 if server_side:
18 raise ValueError('Server side SSL needs a valid SSLContext')
19
20 # Client side may pass ssl=True to use a default
21 # context; in that case the sslcontext passed is None.
22 # The default is secure for client connections.
23 if hasattr(ssl, 'create_default_context'):
24 # Python 3.4+: use up-to-date strong settings.
25 sslcontext = ssl.create_default_context()
26 if not server_hostname:
27 sslcontext.check_hostname = False
28 else:
29 # Fallback for Python 3.3.
30 sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
31 sslcontext.options |= ssl.OP_NO_SSLv2
32 sslcontext.options |= ssl.OP_NO_SSLv3
33 sslcontext.set_default_verify_paths()
34 sslcontext.verify_mode = ssl.CERT_REQUIRED
35 return sslcontext
36
37
38def _is_sslproto_available():
39 return hasattr(ssl, "MemoryBIO")
40
41
42# States of an _SSLPipe.
43_UNWRAPPED = "UNWRAPPED"
44_DO_HANDSHAKE = "DO_HANDSHAKE"
45_WRAPPED = "WRAPPED"
46_SHUTDOWN = "SHUTDOWN"
47
48
49class _SSLPipe(object):
50 """An SSL "Pipe".
51
52 An SSL pipe allows you to communicate with an SSL/TLS protocol instance
53 through memory buffers. It can be used to implement a security layer for an
54 existing connection where you don't have access to the connection's file
55 descriptor, or for some reason you don't want to use it.
56
57 An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
58 data is passed through untransformed. In wrapped mode, application level
59 data is encrypted to SSL record level data and vice versa. The SSL record
60 level is the lowest level in the SSL protocol suite and is what travels
61 as-is over the wire.
62
63 An SslPipe initially is in "unwrapped" mode. To start SSL, call
64 do_handshake(). To shutdown SSL again, call unwrap().
65 """
66
67 max_size = 256 * 1024 # Buffer size passed to read()
68
69 def __init__(self, context, server_side, server_hostname=None):
70 """
71 The *context* argument specifies the ssl.SSLContext to use.
72
73 The *server_side* argument indicates whether this is a server side or
74 client side transport.
75
76 The optional *server_hostname* argument can be used to specify the
77 hostname you are connecting to. You may only specify this parameter if
78 the _ssl module supports Server Name Indication (SNI).
79 """
80 self._context = context
81 self._server_side = server_side
82 self._server_hostname = server_hostname
83 self._state = _UNWRAPPED
84 self._incoming = ssl.MemoryBIO()
85 self._outgoing = ssl.MemoryBIO()
86 self._sslobj = None
87 self._need_ssldata = False
88 self._handshake_cb = None
89 self._shutdown_cb = None
90
91 @property
92 def context(self):
93 """The SSL context passed to the constructor."""
94 return self._context
95
96 @property
97 def ssl_object(self):
98 """The internal ssl.SSLObject instance.
99
100 Return None if the pipe is not wrapped.
101 """
102 return self._sslobj
103
104 @property
105 def need_ssldata(self):
106 """Whether more record level data is needed to complete a handshake
107 that is currently in progress."""
108 return self._need_ssldata
109
110 @property
111 def wrapped(self):
112 """
113 Whether a security layer is currently in effect.
114
115 Return False during handshake.
116 """
117 return self._state == _WRAPPED
118
119 def do_handshake(self, callback=None):
120 """Start the SSL handshake.
121
122 Return a list of ssldata. A ssldata element is a list of buffers
123
124 The optional *callback* argument can be used to install a callback that
125 will be called when the handshake is complete. The callback will be
126 called with None if successful, else an exception instance.
127 """
128 if self._state != _UNWRAPPED:
129 raise RuntimeError('handshake in progress or completed')
130 self._sslobj = self._context.wrap_bio(
131 self._incoming, self._outgoing,
132 server_side=self._server_side,
133 server_hostname=self._server_hostname)
134 self._state = _DO_HANDSHAKE
135 self._handshake_cb = callback
136 ssldata, appdata = self.feed_ssldata(b'', only_handshake=True)
137 assert len(appdata) == 0
138 return ssldata
139
140 def shutdown(self, callback=None):
141 """Start the SSL shutdown sequence.
142
143 Return a list of ssldata. A ssldata element is a list of buffers
144
145 The optional *callback* argument can be used to install a callback that
146 will be called when the shutdown is complete. The callback will be
147 called without arguments.
148 """
149 if self._state == _UNWRAPPED:
150 raise RuntimeError('no security layer present')
151 if self._state == _SHUTDOWN:
152 raise RuntimeError('shutdown in progress')
153 assert self._state in (_WRAPPED, _DO_HANDSHAKE)
154 self._state = _SHUTDOWN
155 self._shutdown_cb = callback
156 ssldata, appdata = self.feed_ssldata(b'')
157 assert appdata == [] or appdata == [b'']
158 return ssldata
159
160 def feed_eof(self):
161 """Send a potentially "ragged" EOF.
162
163 This method will raise an SSL_ERROR_EOF exception if the EOF is
164 unexpected.
165 """
166 self._incoming.write_eof()
167 ssldata, appdata = self.feed_ssldata(b'')
168 assert appdata == [] or appdata == [b'']
169
170 def feed_ssldata(self, data, only_handshake=False):
171 """Feed SSL record level data into the pipe.
172
173 The data must be a bytes instance. It is OK to send an empty bytes
174 instance. This can be used to get ssldata for a handshake initiated by
175 this endpoint.
176
177 Return a (ssldata, appdata) tuple. The ssldata element is a list of
178 buffers containing SSL data that needs to be sent to the remote SSL.
179
180 The appdata element is a list of buffers containing plaintext data that
181 needs to be forwarded to the application. The appdata list may contain
182 an empty buffer indicating an SSL "close_notify" alert. This alert must
183 be acknowledged by calling shutdown().
184 """
185 if self._state == _UNWRAPPED:
186 # If unwrapped, pass plaintext data straight through.
187 if data:
188 appdata = [data]
189 else:
190 appdata = []
191 return ([], appdata)
192
193 self._need_ssldata = False
194 if data:
195 self._incoming.write(data)
196
197 ssldata = []
198 appdata = []
199 try:
200 if self._state == _DO_HANDSHAKE:
201 # Call do_handshake() until it doesn't raise anymore.
202 self._sslobj.do_handshake()
203 self._state = _WRAPPED
204 if self._handshake_cb:
205 self._handshake_cb(None)
206 if only_handshake:
207 return (ssldata, appdata)
208 # Handshake done: execute the wrapped block
209
210 if self._state == _WRAPPED:
211 # Main state: read data from SSL until close_notify
212 while True:
213 chunk = self._sslobj.read(self.max_size)
214 appdata.append(chunk)
215 if not chunk: # close_notify
216 break
217
218 elif self._state == _SHUTDOWN:
219 # Call shutdown() until it doesn't raise anymore.
220 self._sslobj.unwrap()
221 self._sslobj = None
222 self._state = _UNWRAPPED
223 if self._shutdown_cb:
224 self._shutdown_cb()
225
226 elif self._state == _UNWRAPPED:
227 # Drain possible plaintext data after close_notify.
228 appdata.append(self._incoming.read())
229 except (ssl.SSLError, ssl.CertificateError) as exc:
230 if getattr(exc, 'errno', None) not in (
231 ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE,
232 ssl.SSL_ERROR_SYSCALL):
233 if self._state == _DO_HANDSHAKE and self._handshake_cb:
234 self._handshake_cb(exc)
235 raise
236 self._need_ssldata = (exc.errno == ssl.SSL_ERROR_WANT_READ)
237
238 # Check for record level data that needs to be sent back.
239 # Happens for the initial handshake and renegotiations.
240 if self._outgoing.pending:
241 ssldata.append(self._outgoing.read())
242 return (ssldata, appdata)
243
244 def feed_appdata(self, data, offset=0):
245 """Feed plaintext data into the pipe.
246
247 Return an (ssldata, offset) tuple. The ssldata element is a list of
248 buffers containing record level data that needs to be sent to the
249 remote SSL instance. The offset is the number of plaintext bytes that
250 were processed, which may be less than the length of data.
251
252 NOTE: In case of short writes, this call MUST be retried with the SAME
253 buffer passed into the *data* argument (i.e. the id() must be the
254 same). This is an OpenSSL requirement. A further particularity is that
255 a short write will always have offset == 0, because the _ssl module
256 does not enable partial writes. And even though the offset is zero,
257 there will still be encrypted data in ssldata.
258 """
259 assert 0 <= offset <= len(data)
260 if self._state == _UNWRAPPED:
261 # pass through data in unwrapped mode
262 if offset < len(data):
263 ssldata = [data[offset:]]
264 else:
265 ssldata = []
266 return (ssldata, len(data))
267
268 ssldata = []
269 view = memoryview(data)
270 while True:
271 self._need_ssldata = False
272 try:
273 if offset < len(view):
274 offset += self._sslobj.write(view[offset:])
275 except ssl.SSLError as exc:
276 # It is not allowed to call write() after unwrap() until the
277 # close_notify is acknowledged. We return the condition to the
278 # caller as a short write.
279 if exc.reason == 'PROTOCOL_IS_SHUTDOWN':
280 exc.errno = ssl.SSL_ERROR_WANT_READ
281 if exc.errno not in (ssl.SSL_ERROR_WANT_READ,
282 ssl.SSL_ERROR_WANT_WRITE,
283 ssl.SSL_ERROR_SYSCALL):
284 raise
285 self._need_ssldata = (exc.errno == ssl.SSL_ERROR_WANT_READ)
286
287 # See if there's any record level data back for us.
288 if self._outgoing.pending:
289 ssldata.append(self._outgoing.read())
290 if offset == len(view) or self._need_ssldata:
291 break
292 return (ssldata, offset)
293
294
295class _SSLProtocolTransport(transports._FlowControlMixin,
296 transports.Transport):
297
298 def __init__(self, loop, ssl_protocol, app_protocol):
299 self._loop = loop
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200300 # SSLProtocol instance
Victor Stinner231b4042015-01-14 00:19:09 +0100301 self._ssl_protocol = ssl_protocol
302 self._app_protocol = app_protocol
Victor Stinner978a9af2015-01-29 17:50:58 +0100303 self._closed = False
Victor Stinner231b4042015-01-14 00:19:09 +0100304
305 def get_extra_info(self, name, default=None):
306 """Get optional transport information."""
307 return self._ssl_protocol._get_extra_info(name, default)
308
Yury Selivanova05a6ef2016-09-11 21:11:02 -0400309 def set_protocol(self, protocol):
310 self._app_protocol = protocol
311
312 def get_protocol(self):
313 return self._app_protocol
314
Yury Selivanov5bb1afb2015-11-16 12:43:21 -0500315 def is_closing(self):
316 return self._closed
317
Victor Stinner231b4042015-01-14 00:19:09 +0100318 def close(self):
319 """Close the transport.
320
321 Buffered data will be flushed asynchronously. No more data
322 will be received. After all buffered data is flushed, the
323 protocol's connection_lost() method will (eventually) called
324 with None as its argument.
325 """
Victor Stinner978a9af2015-01-29 17:50:58 +0100326 self._closed = True
Victor Stinner231b4042015-01-14 00:19:09 +0100327 self._ssl_protocol._start_shutdown()
328
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900329 def __del__(self):
330 if not self._closed:
331 warnings.warn("unclosed transport %r" % self, ResourceWarning,
332 source=self)
333 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100334
Victor Stinner231b4042015-01-14 00:19:09 +0100335 def pause_reading(self):
336 """Pause the receiving end.
337
338 No data will be passed to the protocol's data_received()
339 method until resume_reading() is called.
340 """
341 self._ssl_protocol._transport.pause_reading()
342
343 def resume_reading(self):
344 """Resume the receiving end.
345
346 Data received will once again be passed to the protocol's
347 data_received() method.
348 """
349 self._ssl_protocol._transport.resume_reading()
350
351 def set_write_buffer_limits(self, high=None, low=None):
352 """Set the high- and low-water limits for write flow control.
353
354 These two values control when to call the protocol's
355 pause_writing() and resume_writing() methods. If specified,
356 the low-water limit must be less than or equal to the
357 high-water limit. Neither value can be negative.
358
359 The defaults are implementation-specific. If only the
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200360 high-water limit is given, the low-water limit defaults to an
Victor Stinner231b4042015-01-14 00:19:09 +0100361 implementation-specific value less than or equal to the
362 high-water limit. Setting high to zero forces low to zero as
363 well, and causes pause_writing() to be called whenever the
364 buffer becomes non-empty. Setting low to zero causes
365 resume_writing() to be called only once the buffer is empty.
366 Use of zero for either limit is generally sub-optimal as it
367 reduces opportunities for doing I/O and computation
368 concurrently.
369 """
370 self._ssl_protocol._transport.set_write_buffer_limits(high, low)
371
372 def get_write_buffer_size(self):
373 """Return the current size of the write buffer."""
374 return self._ssl_protocol._transport.get_write_buffer_size()
375
376 def write(self, data):
377 """Write some data bytes to the transport.
378
379 This does not block; it buffers the data and arranges for it
380 to be sent out asynchronously.
381 """
382 if not isinstance(data, (bytes, bytearray, memoryview)):
383 raise TypeError("data: expecting a bytes-like instance, got {!r}"
384 .format(type(data).__name__))
385 if not data:
386 return
387 self._ssl_protocol._write_appdata(data)
388
389 def can_write_eof(self):
390 """Return True if this transport supports write_eof(), False if not."""
391 return False
392
393 def abort(self):
394 """Close the transport immediately.
395
396 Buffered data will be lost. No more data will be received.
397 The protocol's connection_lost() method will (eventually) be
398 called with None as its argument.
399 """
400 self._ssl_protocol._abort()
401
402
403class SSLProtocol(protocols.Protocol):
404 """SSL protocol.
405
406 Implementation of SSL on top of a socket using incoming and outgoing
407 buffers which are ssl.MemoryBIO objects.
408 """
409
410 def __init__(self, loop, app_protocol, sslcontext, waiter,
Yury Selivanov92e7c7f2016-10-05 19:39:54 -0400411 server_side=False, server_hostname=None,
Nikolay Kima608d2d2017-06-09 21:04:39 -0700412 call_connection_made=True, shutdown_timeout=5.0):
Victor Stinner231b4042015-01-14 00:19:09 +0100413 if ssl is None:
414 raise RuntimeError('stdlib ssl module not available')
415
416 if not sslcontext:
417 sslcontext = _create_transport_context(server_side, server_hostname)
418
419 self._server_side = server_side
420 if server_hostname and not server_side:
421 self._server_hostname = server_hostname
422 else:
423 self._server_hostname = None
424 self._sslcontext = sslcontext
425 # SSL-specific extra info. More info are set when the handshake
426 # completes.
427 self._extra = dict(sslcontext=sslcontext)
428
429 # App data write buffering
430 self._write_backlog = collections.deque()
431 self._write_buffer_size = 0
432
433 self._waiter = waiter
Victor Stinner231b4042015-01-14 00:19:09 +0100434 self._loop = loop
435 self._app_protocol = app_protocol
436 self._app_transport = _SSLProtocolTransport(self._loop,
437 self, self._app_protocol)
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200438 # _SSLPipe instance (None until the connection is made)
Victor Stinner231b4042015-01-14 00:19:09 +0100439 self._sslpipe = None
440 self._session_established = False
441 self._in_handshake = False
442 self._in_shutdown = False
Nikolay Kima608d2d2017-06-09 21:04:39 -0700443 self._shutdown_timeout = shutdown_timeout
444 self._shutdown_timeout_handle = None
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200445 # transport, ex: SelectorSocketTransport
Victor Stinner7e222f42015-01-15 13:16:27 +0100446 self._transport = None
Yury Selivanov92e7c7f2016-10-05 19:39:54 -0400447 self._call_connection_made = call_connection_made
Victor Stinner231b4042015-01-14 00:19:09 +0100448
Victor Stinnerf07801b2015-01-29 00:36:35 +0100449 def _wakeup_waiter(self, exc=None):
450 if self._waiter is None:
451 return
452 if not self._waiter.cancelled():
453 if exc is not None:
454 self._waiter.set_exception(exc)
455 else:
456 self._waiter.set_result(None)
457 self._waiter = None
458
Victor Stinner231b4042015-01-14 00:19:09 +0100459 def connection_made(self, transport):
460 """Called when the low-level connection is made.
461
462 Start the SSL handshake.
463 """
464 self._transport = transport
465 self._sslpipe = _SSLPipe(self._sslcontext,
466 self._server_side,
467 self._server_hostname)
468 self._start_handshake()
469
470 def connection_lost(self, exc):
471 """Called when the low-level connection is lost or closed.
472
473 The argument is an exception object or None (the latter
474 meaning a regular EOF is received or the connection was
475 aborted or closed).
476 """
477 if self._session_established:
478 self._session_established = False
479 self._loop.call_soon(self._app_protocol.connection_lost, exc)
480 self._transport = None
481 self._app_transport = None
Yury Selivanovb1461aa2016-12-16 11:50:41 -0500482 self._wakeup_waiter(exc)
Victor Stinner231b4042015-01-14 00:19:09 +0100483
484 def pause_writing(self):
485 """Called when the low-level transport's buffer goes over
486 the high-water mark.
487 """
488 self._app_protocol.pause_writing()
489
490 def resume_writing(self):
491 """Called when the low-level transport's buffer drains below
492 the low-water mark.
493 """
494 self._app_protocol.resume_writing()
495
496 def data_received(self, data):
497 """Called when some SSL data is received.
498
499 The argument is a bytes object.
500 """
501 try:
502 ssldata, appdata = self._sslpipe.feed_ssldata(data)
503 except ssl.SSLError as e:
504 if self._loop.get_debug():
505 logger.warning('%r: SSL error %s (reason %s)',
506 self, e.errno, e.reason)
507 self._abort()
508 return
509
510 for chunk in ssldata:
511 self._transport.write(chunk)
512
513 for chunk in appdata:
514 if chunk:
515 self._app_protocol.data_received(chunk)
516 else:
517 self._start_shutdown()
518 break
519
520 def eof_received(self):
521 """Called when the other end of the low-level stream
522 is half-closed.
523
524 If this returns a false value (including None), the transport
525 will close itself. If it returns a true value, closing the
526 transport is up to the protocol.
527 """
528 try:
529 if self._loop.get_debug():
530 logger.debug("%r received EOF", self)
Victor Stinnerb507cba2015-01-29 00:35:56 +0100531
Victor Stinnerf07801b2015-01-29 00:36:35 +0100532 self._wakeup_waiter(ConnectionResetError)
Victor Stinnerb507cba2015-01-29 00:35:56 +0100533
Victor Stinner231b4042015-01-14 00:19:09 +0100534 if not self._in_handshake:
535 keep_open = self._app_protocol.eof_received()
536 if keep_open:
537 logger.warning('returning true from eof_received() '
538 'has no effect when using ssl')
539 finally:
540 self._transport.close()
541
542 def _get_extra_info(self, name, default=None):
543 if name in self._extra:
544 return self._extra[name]
Nikolay Kim2b27e2e2017-03-12 12:23:30 -0700545 elif self._transport is not None:
Victor Stinner231b4042015-01-14 00:19:09 +0100546 return self._transport.get_extra_info(name, default)
Nikolay Kim2b27e2e2017-03-12 12:23:30 -0700547 else:
548 return default
Victor Stinner231b4042015-01-14 00:19:09 +0100549
550 def _start_shutdown(self):
551 if self._in_shutdown:
552 return
Nikolay Kima0e3d2d2017-06-09 14:46:14 -0700553 if self._in_handshake:
554 self._abort()
555 else:
556 self._in_shutdown = True
557 self._write_appdata(b'')
Victor Stinner231b4042015-01-14 00:19:09 +0100558
Nikolay Kima608d2d2017-06-09 21:04:39 -0700559 if self._shutdown_timeout is not None:
560 self._shutdown_timeout_handle = self._loop.call_later(
561 self._shutdown_timeout, self._on_shutdown_timeout)
562
563 def _on_shutdown_timeout(self):
564 if self._transport is not None:
565 self._fatal_error(
566 futures.TimeoutError(), 'Can not complete shitdown operation')
567
Victor Stinner231b4042015-01-14 00:19:09 +0100568 def _write_appdata(self, data):
569 self._write_backlog.append((data, 0))
570 self._write_buffer_size += len(data)
571 self._process_write_backlog()
572
573 def _start_handshake(self):
574 if self._loop.get_debug():
575 logger.debug("%r starts SSL handshake", self)
576 self._handshake_start_time = self._loop.time()
577 else:
578 self._handshake_start_time = None
579 self._in_handshake = True
580 # (b'', 1) is a special value in _process_write_backlog() to do
581 # the SSL handshake
582 self._write_backlog.append((b'', 1))
583 self._loop.call_soon(self._process_write_backlog)
584
585 def _on_handshake_complete(self, handshake_exc):
586 self._in_handshake = False
587
588 sslobj = self._sslpipe.ssl_object
Victor Stinner231b4042015-01-14 00:19:09 +0100589 try:
590 if handshake_exc is not None:
591 raise handshake_exc
Victor Stinner177e9f02015-01-14 16:56:20 +0100592
593 peercert = sslobj.getpeercert()
Victor Stinner231b4042015-01-14 00:19:09 +0100594 if not hasattr(self._sslcontext, 'check_hostname'):
595 # Verify hostname if requested, Python 3.4+ uses check_hostname
596 # and checks the hostname in do_handshake()
597 if (self._server_hostname
598 and self._sslcontext.verify_mode != ssl.CERT_NONE):
599 ssl.match_hostname(peercert, self._server_hostname)
600 except BaseException as exc:
601 if self._loop.get_debug():
602 if isinstance(exc, ssl.CertificateError):
603 logger.warning("%r: SSL handshake failed "
604 "on verifying the certificate",
605 self, exc_info=True)
606 else:
607 logger.warning("%r: SSL handshake failed",
608 self, exc_info=True)
609 self._transport.close()
610 if isinstance(exc, Exception):
Victor Stinnerf07801b2015-01-29 00:36:35 +0100611 self._wakeup_waiter(exc)
Victor Stinner231b4042015-01-14 00:19:09 +0100612 return
613 else:
614 raise
615
616 if self._loop.get_debug():
617 dt = self._loop.time() - self._handshake_start_time
618 logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3)
619
620 # Add extra info that becomes available after handshake.
621 self._extra.update(peercert=peercert,
622 cipher=sslobj.cipher(),
623 compression=sslobj.compression(),
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200624 ssl_object=sslobj,
Victor Stinner231b4042015-01-14 00:19:09 +0100625 )
Yury Selivanov92e7c7f2016-10-05 19:39:54 -0400626 if self._call_connection_made:
627 self._app_protocol.connection_made(self._app_transport)
Victor Stinnerf07801b2015-01-29 00:36:35 +0100628 self._wakeup_waiter()
Victor Stinner231b4042015-01-14 00:19:09 +0100629 self._session_established = True
Victor Stinner042dad72015-01-15 09:41:48 +0100630 # In case transport.write() was already called. Don't call
Martin Panter46f50722016-05-26 05:35:26 +0000631 # immediately _process_write_backlog(), but schedule it:
Victor Stinner042dad72015-01-15 09:41:48 +0100632 # _on_handshake_complete() can be called indirectly from
633 # _process_write_backlog(), and _process_write_backlog() is not
634 # reentrant.
Victor Stinner72bdefb2015-01-15 09:44:13 +0100635 self._loop.call_soon(self._process_write_backlog)
Victor Stinner231b4042015-01-14 00:19:09 +0100636
637 def _process_write_backlog(self):
638 # Try to make progress on the write backlog.
639 if self._transport is None:
640 return
641
642 try:
643 for i in range(len(self._write_backlog)):
644 data, offset = self._write_backlog[0]
645 if data:
646 ssldata, offset = self._sslpipe.feed_appdata(data, offset)
647 elif offset:
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400648 ssldata = self._sslpipe.do_handshake(
649 self._on_handshake_complete)
Victor Stinner231b4042015-01-14 00:19:09 +0100650 offset = 1
651 else:
652 ssldata = self._sslpipe.shutdown(self._finalize)
653 offset = 1
654
655 for chunk in ssldata:
656 self._transport.write(chunk)
657
658 if offset < len(data):
659 self._write_backlog[0] = (data, offset)
660 # A short write means that a write is blocked on a read
661 # We need to enable reading if it is paused!
662 assert self._sslpipe.need_ssldata
663 if self._transport._paused:
664 self._transport.resume_reading()
665 break
666
667 # An entire chunk from the backlog was processed. We can
668 # delete it and reduce the outstanding buffer size.
669 del self._write_backlog[0]
670 self._write_buffer_size -= len(data)
671 except BaseException as exc:
672 if self._in_handshake:
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400673 # BaseExceptions will be re-raised in _on_handshake_complete.
Victor Stinner231b4042015-01-14 00:19:09 +0100674 self._on_handshake_complete(exc)
675 else:
676 self._fatal_error(exc, 'Fatal error on SSL transport')
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400677 if not isinstance(exc, Exception):
678 # BaseException
679 raise
Victor Stinner231b4042015-01-14 00:19:09 +0100680
681 def _fatal_error(self, exc, message='Fatal error on transport'):
682 # Should be called from exception handler only.
Victor Stinnerc94a93a2016-04-01 21:43:39 +0200683 if isinstance(exc, base_events._FATAL_ERROR_IGNORE):
Victor Stinner231b4042015-01-14 00:19:09 +0100684 if self._loop.get_debug():
685 logger.debug("%r: %s", self, message, exc_info=True)
686 else:
687 self._loop.call_exception_handler({
688 'message': message,
689 'exception': exc,
690 'transport': self._transport,
691 'protocol': self,
692 })
693 if self._transport:
694 self._transport._force_close(exc)
Nikolay Kima608d2d2017-06-09 21:04:39 -0700695 self._transport = None
696
697 if self._shutdown_timeout_handle is not None:
698 self._shutdown_timeout_handle.cancel()
699 self._shutdown_timeout_handle = None
Victor Stinner231b4042015-01-14 00:19:09 +0100700
701 def _finalize(self):
Michaël Sghaïerd1f57512017-06-09 18:29:46 -0400702 self._sslpipe = None
703
Victor Stinner231b4042015-01-14 00:19:09 +0100704 if self._transport is not None:
705 self._transport.close()
Nikolay Kima608d2d2017-06-09 21:04:39 -0700706 self._transport = None
707
708 if self._shutdown_timeout_handle is not None:
709 self._shutdown_timeout_handle.cancel()
710 self._shutdown_timeout_handle = None
Victor Stinner231b4042015-01-14 00:19:09 +0100711
712 def _abort(self):
Michaël Sghaïerd1f57512017-06-09 18:29:46 -0400713 try:
714 if self._transport is not None:
Victor Stinner231b4042015-01-14 00:19:09 +0100715 self._transport.abort()
Michaël Sghaïerd1f57512017-06-09 18:29:46 -0400716 finally:
717 self._finalize()