blob: 3b1eb993dfc7a8dabb6806c715d8fa43d837ee21 [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
Yury Selivanov2a8911c2015-08-04 15:56:33 -04009from . import compat
Yury Selivanov6e14fd22017-06-10 10:00:45 -040010from . 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
Victor Stinner978a9af2015-01-29 17:50:58 +0100329 # On Python 3.3 and older, objects with a destructor part of a reference
330 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
331 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400332 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100333 def __del__(self):
334 if not self._closed:
Victor Stinnere19558a2016-03-23 00:28:08 +0100335 warnings.warn("unclosed transport %r" % self, ResourceWarning,
336 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100337 self.close()
338
Victor Stinner231b4042015-01-14 00:19:09 +0100339 def pause_reading(self):
340 """Pause the receiving end.
341
342 No data will be passed to the protocol's data_received()
343 method until resume_reading() is called.
344 """
345 self._ssl_protocol._transport.pause_reading()
346
347 def resume_reading(self):
348 """Resume the receiving end.
349
350 Data received will once again be passed to the protocol's
351 data_received() method.
352 """
353 self._ssl_protocol._transport.resume_reading()
354
355 def set_write_buffer_limits(self, high=None, low=None):
356 """Set the high- and low-water limits for write flow control.
357
358 These two values control when to call the protocol's
359 pause_writing() and resume_writing() methods. If specified,
360 the low-water limit must be less than or equal to the
361 high-water limit. Neither value can be negative.
362
363 The defaults are implementation-specific. If only the
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200364 high-water limit is given, the low-water limit defaults to an
Victor Stinner231b4042015-01-14 00:19:09 +0100365 implementation-specific value less than or equal to the
366 high-water limit. Setting high to zero forces low to zero as
367 well, and causes pause_writing() to be called whenever the
368 buffer becomes non-empty. Setting low to zero causes
369 resume_writing() to be called only once the buffer is empty.
370 Use of zero for either limit is generally sub-optimal as it
371 reduces opportunities for doing I/O and computation
372 concurrently.
373 """
374 self._ssl_protocol._transport.set_write_buffer_limits(high, low)
375
376 def get_write_buffer_size(self):
377 """Return the current size of the write buffer."""
378 return self._ssl_protocol._transport.get_write_buffer_size()
379
380 def write(self, data):
381 """Write some data bytes to the transport.
382
383 This does not block; it buffers the data and arranges for it
384 to be sent out asynchronously.
385 """
386 if not isinstance(data, (bytes, bytearray, memoryview)):
387 raise TypeError("data: expecting a bytes-like instance, got {!r}"
388 .format(type(data).__name__))
389 if not data:
390 return
391 self._ssl_protocol._write_appdata(data)
392
393 def can_write_eof(self):
394 """Return True if this transport supports write_eof(), False if not."""
395 return False
396
397 def abort(self):
398 """Close the transport immediately.
399
400 Buffered data will be lost. No more data will be received.
401 The protocol's connection_lost() method will (eventually) be
402 called with None as its argument.
403 """
404 self._ssl_protocol._abort()
405
406
407class SSLProtocol(protocols.Protocol):
408 """SSL protocol.
409
410 Implementation of SSL on top of a socket using incoming and outgoing
411 buffers which are ssl.MemoryBIO objects.
412 """
413
414 def __init__(self, loop, app_protocol, sslcontext, waiter,
Yury Selivanov92e7c7f2016-10-05 19:39:54 -0400415 server_side=False, server_hostname=None,
Yury Selivanov6e14fd22017-06-10 10:00:45 -0400416 call_connection_made=True, shutdown_timeout=5.0):
Victor Stinner231b4042015-01-14 00:19:09 +0100417 if ssl is None:
418 raise RuntimeError('stdlib ssl module not available')
419
420 if not sslcontext:
421 sslcontext = _create_transport_context(server_side, server_hostname)
422
423 self._server_side = server_side
424 if server_hostname and not server_side:
425 self._server_hostname = server_hostname
426 else:
427 self._server_hostname = None
428 self._sslcontext = sslcontext
429 # SSL-specific extra info. More info are set when the handshake
430 # completes.
431 self._extra = dict(sslcontext=sslcontext)
432
433 # App data write buffering
434 self._write_backlog = collections.deque()
435 self._write_buffer_size = 0
436
437 self._waiter = waiter
Victor Stinner231b4042015-01-14 00:19:09 +0100438 self._loop = loop
439 self._app_protocol = app_protocol
440 self._app_transport = _SSLProtocolTransport(self._loop,
441 self, self._app_protocol)
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200442 # _SSLPipe instance (None until the connection is made)
Victor Stinner231b4042015-01-14 00:19:09 +0100443 self._sslpipe = None
444 self._session_established = False
445 self._in_handshake = False
446 self._in_shutdown = False
Yury Selivanov6e14fd22017-06-10 10:00:45 -0400447 self._shutdown_timeout = shutdown_timeout
448 self._shutdown_timeout_handle = None
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200449 # transport, ex: SelectorSocketTransport
Victor Stinner7e222f42015-01-15 13:16:27 +0100450 self._transport = None
Yury Selivanov92e7c7f2016-10-05 19:39:54 -0400451 self._call_connection_made = call_connection_made
Victor Stinner231b4042015-01-14 00:19:09 +0100452
Victor Stinnerf07801b2015-01-29 00:36:35 +0100453 def _wakeup_waiter(self, exc=None):
454 if self._waiter is None:
455 return
456 if not self._waiter.cancelled():
457 if exc is not None:
458 self._waiter.set_exception(exc)
459 else:
460 self._waiter.set_result(None)
461 self._waiter = None
462
Victor Stinner231b4042015-01-14 00:19:09 +0100463 def connection_made(self, transport):
464 """Called when the low-level connection is made.
465
466 Start the SSL handshake.
467 """
468 self._transport = transport
469 self._sslpipe = _SSLPipe(self._sslcontext,
470 self._server_side,
471 self._server_hostname)
472 self._start_handshake()
473
474 def connection_lost(self, exc):
475 """Called when the low-level connection is lost or closed.
476
477 The argument is an exception object or None (the latter
478 meaning a regular EOF is received or the connection was
479 aborted or closed).
480 """
481 if self._session_established:
482 self._session_established = False
483 self._loop.call_soon(self._app_protocol.connection_lost, exc)
484 self._transport = None
485 self._app_transport = None
Yury Selivanovb1461aa2016-12-16 11:50:41 -0500486 self._wakeup_waiter(exc)
Victor Stinner231b4042015-01-14 00:19:09 +0100487
488 def pause_writing(self):
489 """Called when the low-level transport's buffer goes over
490 the high-water mark.
491 """
492 self._app_protocol.pause_writing()
493
494 def resume_writing(self):
495 """Called when the low-level transport's buffer drains below
496 the low-water mark.
497 """
498 self._app_protocol.resume_writing()
499
500 def data_received(self, data):
501 """Called when some SSL data is received.
502
503 The argument is a bytes object.
504 """
505 try:
506 ssldata, appdata = self._sslpipe.feed_ssldata(data)
507 except ssl.SSLError as e:
508 if self._loop.get_debug():
509 logger.warning('%r: SSL error %s (reason %s)',
510 self, e.errno, e.reason)
511 self._abort()
512 return
513
514 for chunk in ssldata:
515 self._transport.write(chunk)
516
517 for chunk in appdata:
518 if chunk:
519 self._app_protocol.data_received(chunk)
520 else:
521 self._start_shutdown()
522 break
523
524 def eof_received(self):
525 """Called when the other end of the low-level stream
526 is half-closed.
527
528 If this returns a false value (including None), the transport
529 will close itself. If it returns a true value, closing the
530 transport is up to the protocol.
531 """
532 try:
533 if self._loop.get_debug():
534 logger.debug("%r received EOF", self)
Victor Stinnerb507cba2015-01-29 00:35:56 +0100535
Victor Stinnerf07801b2015-01-29 00:36:35 +0100536 self._wakeup_waiter(ConnectionResetError)
Victor Stinnerb507cba2015-01-29 00:35:56 +0100537
Victor Stinner231b4042015-01-14 00:19:09 +0100538 if not self._in_handshake:
539 keep_open = self._app_protocol.eof_received()
540 if keep_open:
541 logger.warning('returning true from eof_received() '
542 'has no effect when using ssl')
543 finally:
544 self._transport.close()
545
546 def _get_extra_info(self, name, default=None):
547 if name in self._extra:
548 return self._extra[name]
Yury Selivanov99f8d332017-03-12 17:06:16 -0400549 elif self._transport is not None:
Victor Stinner231b4042015-01-14 00:19:09 +0100550 return self._transport.get_extra_info(name, default)
Yury Selivanov99f8d332017-03-12 17:06:16 -0400551 else:
552 return default
Victor Stinner231b4042015-01-14 00:19:09 +0100553
554 def _start_shutdown(self):
555 if self._in_shutdown:
556 return
Yury Selivanov7a16a452017-06-09 18:33:31 -0400557 if self._in_handshake:
558 self._abort()
559 else:
560 self._in_shutdown = True
561 self._write_appdata(b'')
Victor Stinner231b4042015-01-14 00:19:09 +0100562
Yury Selivanov6e14fd22017-06-10 10:00:45 -0400563 if self._shutdown_timeout is not None:
564 self._shutdown_timeout_handle = self._loop.call_later(
565 self._shutdown_timeout, self._on_shutdown_timeout)
566
567 def _on_shutdown_timeout(self):
568 if self._transport is not None:
569 self._fatal_error(
570 futures.TimeoutError(), 'Can not complete shitdown operation')
571
Victor Stinner231b4042015-01-14 00:19:09 +0100572 def _write_appdata(self, data):
573 self._write_backlog.append((data, 0))
574 self._write_buffer_size += len(data)
575 self._process_write_backlog()
576
577 def _start_handshake(self):
578 if self._loop.get_debug():
579 logger.debug("%r starts SSL handshake", self)
580 self._handshake_start_time = self._loop.time()
581 else:
582 self._handshake_start_time = None
583 self._in_handshake = True
584 # (b'', 1) is a special value in _process_write_backlog() to do
585 # the SSL handshake
586 self._write_backlog.append((b'', 1))
587 self._loop.call_soon(self._process_write_backlog)
588
589 def _on_handshake_complete(self, handshake_exc):
590 self._in_handshake = False
591
592 sslobj = self._sslpipe.ssl_object
Victor Stinner231b4042015-01-14 00:19:09 +0100593 try:
594 if handshake_exc is not None:
595 raise handshake_exc
Victor Stinner177e9f02015-01-14 16:56:20 +0100596
597 peercert = sslobj.getpeercert()
Victor Stinner231b4042015-01-14 00:19:09 +0100598 if not hasattr(self._sslcontext, 'check_hostname'):
599 # Verify hostname if requested, Python 3.4+ uses check_hostname
600 # and checks the hostname in do_handshake()
601 if (self._server_hostname
602 and self._sslcontext.verify_mode != ssl.CERT_NONE):
603 ssl.match_hostname(peercert, self._server_hostname)
604 except BaseException as exc:
605 if self._loop.get_debug():
606 if isinstance(exc, ssl.CertificateError):
607 logger.warning("%r: SSL handshake failed "
608 "on verifying the certificate",
609 self, exc_info=True)
610 else:
611 logger.warning("%r: SSL handshake failed",
612 self, exc_info=True)
613 self._transport.close()
614 if isinstance(exc, Exception):
Victor Stinnerf07801b2015-01-29 00:36:35 +0100615 self._wakeup_waiter(exc)
Victor Stinner231b4042015-01-14 00:19:09 +0100616 return
617 else:
618 raise
619
620 if self._loop.get_debug():
621 dt = self._loop.time() - self._handshake_start_time
622 logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3)
623
624 # Add extra info that becomes available after handshake.
625 self._extra.update(peercert=peercert,
626 cipher=sslobj.cipher(),
627 compression=sslobj.compression(),
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200628 ssl_object=sslobj,
Victor Stinner231b4042015-01-14 00:19:09 +0100629 )
Yury Selivanov92e7c7f2016-10-05 19:39:54 -0400630 if self._call_connection_made:
631 self._app_protocol.connection_made(self._app_transport)
Victor Stinnerf07801b2015-01-29 00:36:35 +0100632 self._wakeup_waiter()
Victor Stinner231b4042015-01-14 00:19:09 +0100633 self._session_established = True
Victor Stinner042dad72015-01-15 09:41:48 +0100634 # In case transport.write() was already called. Don't call
Martin Panter46f50722016-05-26 05:35:26 +0000635 # immediately _process_write_backlog(), but schedule it:
Victor Stinner042dad72015-01-15 09:41:48 +0100636 # _on_handshake_complete() can be called indirectly from
637 # _process_write_backlog(), and _process_write_backlog() is not
638 # reentrant.
Victor Stinner72bdefb2015-01-15 09:44:13 +0100639 self._loop.call_soon(self._process_write_backlog)
Victor Stinner231b4042015-01-14 00:19:09 +0100640
641 def _process_write_backlog(self):
642 # Try to make progress on the write backlog.
643 if self._transport is None:
644 return
645
646 try:
647 for i in range(len(self._write_backlog)):
648 data, offset = self._write_backlog[0]
649 if data:
650 ssldata, offset = self._sslpipe.feed_appdata(data, offset)
651 elif offset:
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400652 ssldata = self._sslpipe.do_handshake(
653 self._on_handshake_complete)
Victor Stinner231b4042015-01-14 00:19:09 +0100654 offset = 1
655 else:
656 ssldata = self._sslpipe.shutdown(self._finalize)
657 offset = 1
658
659 for chunk in ssldata:
660 self._transport.write(chunk)
661
662 if offset < len(data):
663 self._write_backlog[0] = (data, offset)
664 # A short write means that a write is blocked on a read
665 # We need to enable reading if it is paused!
666 assert self._sslpipe.need_ssldata
667 if self._transport._paused:
668 self._transport.resume_reading()
669 break
670
671 # An entire chunk from the backlog was processed. We can
672 # delete it and reduce the outstanding buffer size.
673 del self._write_backlog[0]
674 self._write_buffer_size -= len(data)
675 except BaseException as exc:
676 if self._in_handshake:
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400677 # BaseExceptions will be re-raised in _on_handshake_complete.
Victor Stinner231b4042015-01-14 00:19:09 +0100678 self._on_handshake_complete(exc)
679 else:
680 self._fatal_error(exc, 'Fatal error on SSL transport')
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400681 if not isinstance(exc, Exception):
682 # BaseException
683 raise
Victor Stinner231b4042015-01-14 00:19:09 +0100684
685 def _fatal_error(self, exc, message='Fatal error on transport'):
686 # Should be called from exception handler only.
Victor Stinnerc94a93a2016-04-01 21:43:39 +0200687 if isinstance(exc, base_events._FATAL_ERROR_IGNORE):
Victor Stinner231b4042015-01-14 00:19:09 +0100688 if self._loop.get_debug():
689 logger.debug("%r: %s", self, message, exc_info=True)
690 else:
691 self._loop.call_exception_handler({
692 'message': message,
693 'exception': exc,
694 'transport': self._transport,
695 'protocol': self,
696 })
697 if self._transport:
698 self._transport._force_close(exc)
Yury Selivanov6e14fd22017-06-10 10:00:45 -0400699 self._transport = None
700
701 if self._shutdown_timeout_handle is not None:
702 self._shutdown_timeout_handle.cancel()
703 self._shutdown_timeout_handle = None
Victor Stinner231b4042015-01-14 00:19:09 +0100704
705 def _finalize(self):
Yury Selivanovfe9c7a02017-06-09 19:14:35 -0400706 self._sslpipe = None
707
Victor Stinner231b4042015-01-14 00:19:09 +0100708 if self._transport is not None:
709 self._transport.close()
Yury Selivanov6e14fd22017-06-10 10:00:45 -0400710 self._transport = None
711
712 if self._shutdown_timeout_handle is not None:
713 self._shutdown_timeout_handle.cancel()
714 self._shutdown_timeout_handle = None
Victor Stinner231b4042015-01-14 00:19:09 +0100715
716 def _abort(self):
Yury Selivanovfe9c7a02017-06-09 19:14:35 -0400717 try:
718 if self._transport is not None:
Victor Stinner231b4042015-01-14 00:19:09 +0100719 self._transport.abort()
Yury Selivanovfe9c7a02017-06-09 19:14:35 -0400720 finally:
721 self._finalize()