blob: f0f642e4eabd8a09e10ac95a4657ff83e4900358 [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
Victor Stinner231b4042015-01-14 00:19:09 +010010from . import protocols
11from . import transports
12from .log import logger
13
14
15def _create_transport_context(server_side, server_hostname):
16 if server_side:
17 raise ValueError('Server side SSL needs a valid SSLContext')
18
19 # Client side may pass ssl=True to use a default
20 # context; in that case the sslcontext passed is None.
21 # The default is secure for client connections.
22 if hasattr(ssl, 'create_default_context'):
23 # Python 3.4+: use up-to-date strong settings.
24 sslcontext = ssl.create_default_context()
25 if not server_hostname:
26 sslcontext.check_hostname = False
27 else:
28 # Fallback for Python 3.3.
29 sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
30 sslcontext.options |= ssl.OP_NO_SSLv2
31 sslcontext.options |= ssl.OP_NO_SSLv3
32 sslcontext.set_default_verify_paths()
33 sslcontext.verify_mode = ssl.CERT_REQUIRED
34 return sslcontext
35
36
37def _is_sslproto_available():
38 return hasattr(ssl, "MemoryBIO")
39
40
41# States of an _SSLPipe.
42_UNWRAPPED = "UNWRAPPED"
43_DO_HANDSHAKE = "DO_HANDSHAKE"
44_WRAPPED = "WRAPPED"
45_SHUTDOWN = "SHUTDOWN"
46
47
48class _SSLPipe(object):
49 """An SSL "Pipe".
50
51 An SSL pipe allows you to communicate with an SSL/TLS protocol instance
52 through memory buffers. It can be used to implement a security layer for an
53 existing connection where you don't have access to the connection's file
54 descriptor, or for some reason you don't want to use it.
55
56 An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
57 data is passed through untransformed. In wrapped mode, application level
58 data is encrypted to SSL record level data and vice versa. The SSL record
59 level is the lowest level in the SSL protocol suite and is what travels
60 as-is over the wire.
61
62 An SslPipe initially is in "unwrapped" mode. To start SSL, call
63 do_handshake(). To shutdown SSL again, call unwrap().
64 """
65
66 max_size = 256 * 1024 # Buffer size passed to read()
67
68 def __init__(self, context, server_side, server_hostname=None):
69 """
70 The *context* argument specifies the ssl.SSLContext to use.
71
72 The *server_side* argument indicates whether this is a server side or
73 client side transport.
74
75 The optional *server_hostname* argument can be used to specify the
76 hostname you are connecting to. You may only specify this parameter if
77 the _ssl module supports Server Name Indication (SNI).
78 """
79 self._context = context
80 self._server_side = server_side
81 self._server_hostname = server_hostname
82 self._state = _UNWRAPPED
83 self._incoming = ssl.MemoryBIO()
84 self._outgoing = ssl.MemoryBIO()
85 self._sslobj = None
86 self._need_ssldata = False
87 self._handshake_cb = None
88 self._shutdown_cb = None
89
90 @property
91 def context(self):
92 """The SSL context passed to the constructor."""
93 return self._context
94
95 @property
96 def ssl_object(self):
97 """The internal ssl.SSLObject instance.
98
99 Return None if the pipe is not wrapped.
100 """
101 return self._sslobj
102
103 @property
104 def need_ssldata(self):
105 """Whether more record level data is needed to complete a handshake
106 that is currently in progress."""
107 return self._need_ssldata
108
109 @property
110 def wrapped(self):
111 """
112 Whether a security layer is currently in effect.
113
114 Return False during handshake.
115 """
116 return self._state == _WRAPPED
117
118 def do_handshake(self, callback=None):
119 """Start the SSL handshake.
120
121 Return a list of ssldata. A ssldata element is a list of buffers
122
123 The optional *callback* argument can be used to install a callback that
124 will be called when the handshake is complete. The callback will be
125 called with None if successful, else an exception instance.
126 """
127 if self._state != _UNWRAPPED:
128 raise RuntimeError('handshake in progress or completed')
129 self._sslobj = self._context.wrap_bio(
130 self._incoming, self._outgoing,
131 server_side=self._server_side,
132 server_hostname=self._server_hostname)
133 self._state = _DO_HANDSHAKE
134 self._handshake_cb = callback
135 ssldata, appdata = self.feed_ssldata(b'', only_handshake=True)
136 assert len(appdata) == 0
137 return ssldata
138
139 def shutdown(self, callback=None):
140 """Start the SSL shutdown sequence.
141
142 Return a list of ssldata. A ssldata element is a list of buffers
143
144 The optional *callback* argument can be used to install a callback that
145 will be called when the shutdown is complete. The callback will be
146 called without arguments.
147 """
148 if self._state == _UNWRAPPED:
149 raise RuntimeError('no security layer present')
150 if self._state == _SHUTDOWN:
151 raise RuntimeError('shutdown in progress')
152 assert self._state in (_WRAPPED, _DO_HANDSHAKE)
153 self._state = _SHUTDOWN
154 self._shutdown_cb = callback
155 ssldata, appdata = self.feed_ssldata(b'')
156 assert appdata == [] or appdata == [b'']
157 return ssldata
158
159 def feed_eof(self):
160 """Send a potentially "ragged" EOF.
161
162 This method will raise an SSL_ERROR_EOF exception if the EOF is
163 unexpected.
164 """
165 self._incoming.write_eof()
166 ssldata, appdata = self.feed_ssldata(b'')
167 assert appdata == [] or appdata == [b'']
168
169 def feed_ssldata(self, data, only_handshake=False):
170 """Feed SSL record level data into the pipe.
171
172 The data must be a bytes instance. It is OK to send an empty bytes
173 instance. This can be used to get ssldata for a handshake initiated by
174 this endpoint.
175
176 Return a (ssldata, appdata) tuple. The ssldata element is a list of
177 buffers containing SSL data that needs to be sent to the remote SSL.
178
179 The appdata element is a list of buffers containing plaintext data that
180 needs to be forwarded to the application. The appdata list may contain
181 an empty buffer indicating an SSL "close_notify" alert. This alert must
182 be acknowledged by calling shutdown().
183 """
184 if self._state == _UNWRAPPED:
185 # If unwrapped, pass plaintext data straight through.
186 if data:
187 appdata = [data]
188 else:
189 appdata = []
190 return ([], appdata)
191
192 self._need_ssldata = False
193 if data:
194 self._incoming.write(data)
195
196 ssldata = []
197 appdata = []
198 try:
199 if self._state == _DO_HANDSHAKE:
200 # Call do_handshake() until it doesn't raise anymore.
201 self._sslobj.do_handshake()
202 self._state = _WRAPPED
203 if self._handshake_cb:
204 self._handshake_cb(None)
205 if only_handshake:
206 return (ssldata, appdata)
207 # Handshake done: execute the wrapped block
208
209 if self._state == _WRAPPED:
210 # Main state: read data from SSL until close_notify
211 while True:
212 chunk = self._sslobj.read(self.max_size)
213 appdata.append(chunk)
214 if not chunk: # close_notify
215 break
216
217 elif self._state == _SHUTDOWN:
218 # Call shutdown() until it doesn't raise anymore.
219 self._sslobj.unwrap()
220 self._sslobj = None
221 self._state = _UNWRAPPED
222 if self._shutdown_cb:
223 self._shutdown_cb()
224
225 elif self._state == _UNWRAPPED:
226 # Drain possible plaintext data after close_notify.
227 appdata.append(self._incoming.read())
228 except (ssl.SSLError, ssl.CertificateError) as exc:
229 if getattr(exc, 'errno', None) not in (
230 ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE,
231 ssl.SSL_ERROR_SYSCALL):
232 if self._state == _DO_HANDSHAKE and self._handshake_cb:
233 self._handshake_cb(exc)
234 raise
235 self._need_ssldata = (exc.errno == ssl.SSL_ERROR_WANT_READ)
236
237 # Check for record level data that needs to be sent back.
238 # Happens for the initial handshake and renegotiations.
239 if self._outgoing.pending:
240 ssldata.append(self._outgoing.read())
241 return (ssldata, appdata)
242
243 def feed_appdata(self, data, offset=0):
244 """Feed plaintext data into the pipe.
245
246 Return an (ssldata, offset) tuple. The ssldata element is a list of
247 buffers containing record level data that needs to be sent to the
248 remote SSL instance. The offset is the number of plaintext bytes that
249 were processed, which may be less than the length of data.
250
251 NOTE: In case of short writes, this call MUST be retried with the SAME
252 buffer passed into the *data* argument (i.e. the id() must be the
253 same). This is an OpenSSL requirement. A further particularity is that
254 a short write will always have offset == 0, because the _ssl module
255 does not enable partial writes. And even though the offset is zero,
256 there will still be encrypted data in ssldata.
257 """
258 assert 0 <= offset <= len(data)
259 if self._state == _UNWRAPPED:
260 # pass through data in unwrapped mode
261 if offset < len(data):
262 ssldata = [data[offset:]]
263 else:
264 ssldata = []
265 return (ssldata, len(data))
266
267 ssldata = []
268 view = memoryview(data)
269 while True:
270 self._need_ssldata = False
271 try:
272 if offset < len(view):
273 offset += self._sslobj.write(view[offset:])
274 except ssl.SSLError as exc:
275 # It is not allowed to call write() after unwrap() until the
276 # close_notify is acknowledged. We return the condition to the
277 # caller as a short write.
278 if exc.reason == 'PROTOCOL_IS_SHUTDOWN':
279 exc.errno = ssl.SSL_ERROR_WANT_READ
280 if exc.errno not in (ssl.SSL_ERROR_WANT_READ,
281 ssl.SSL_ERROR_WANT_WRITE,
282 ssl.SSL_ERROR_SYSCALL):
283 raise
284 self._need_ssldata = (exc.errno == ssl.SSL_ERROR_WANT_READ)
285
286 # See if there's any record level data back for us.
287 if self._outgoing.pending:
288 ssldata.append(self._outgoing.read())
289 if offset == len(view) or self._need_ssldata:
290 break
291 return (ssldata, offset)
292
293
294class _SSLProtocolTransport(transports._FlowControlMixin,
295 transports.Transport):
296
297 def __init__(self, loop, ssl_protocol, app_protocol):
298 self._loop = loop
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200299 # SSLProtocol instance
Victor Stinner231b4042015-01-14 00:19:09 +0100300 self._ssl_protocol = ssl_protocol
301 self._app_protocol = app_protocol
Victor Stinner978a9af2015-01-29 17:50:58 +0100302 self._closed = False
Victor Stinner231b4042015-01-14 00:19:09 +0100303
304 def get_extra_info(self, name, default=None):
305 """Get optional transport information."""
306 return self._ssl_protocol._get_extra_info(name, default)
307
Yury Selivanov5bb1afb2015-11-16 12:43:21 -0500308 def is_closing(self):
309 return self._closed
310
Victor Stinner231b4042015-01-14 00:19:09 +0100311 def close(self):
312 """Close the transport.
313
314 Buffered data will be flushed asynchronously. No more data
315 will be received. After all buffered data is flushed, the
316 protocol's connection_lost() method will (eventually) called
317 with None as its argument.
318 """
Victor Stinner978a9af2015-01-29 17:50:58 +0100319 self._closed = True
Victor Stinner231b4042015-01-14 00:19:09 +0100320 self._ssl_protocol._start_shutdown()
321
Victor Stinner978a9af2015-01-29 17:50:58 +0100322 # On Python 3.3 and older, objects with a destructor part of a reference
323 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
324 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400325 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100326 def __del__(self):
327 if not self._closed:
Victor Stinnere19558a2016-03-23 00:28:08 +0100328 warnings.warn("unclosed transport %r" % self, ResourceWarning,
329 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100330 self.close()
331
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,
408 server_side=False, server_hostname=None):
409 if ssl is None:
410 raise RuntimeError('stdlib ssl module not available')
411
412 if not sslcontext:
413 sslcontext = _create_transport_context(server_side, server_hostname)
414
415 self._server_side = server_side
416 if server_hostname and not server_side:
417 self._server_hostname = server_hostname
418 else:
419 self._server_hostname = None
420 self._sslcontext = sslcontext
421 # SSL-specific extra info. More info are set when the handshake
422 # completes.
423 self._extra = dict(sslcontext=sslcontext)
424
425 # App data write buffering
426 self._write_backlog = collections.deque()
427 self._write_buffer_size = 0
428
429 self._waiter = waiter
Victor Stinner231b4042015-01-14 00:19:09 +0100430 self._loop = loop
431 self._app_protocol = app_protocol
432 self._app_transport = _SSLProtocolTransport(self._loop,
433 self, self._app_protocol)
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
Victor Stinner231b4042015-01-14 00:19:09 +0100441
Victor Stinnerf07801b2015-01-29 00:36:35 +0100442 def _wakeup_waiter(self, exc=None):
443 if self._waiter is None:
444 return
445 if not self._waiter.cancelled():
446 if exc is not None:
447 self._waiter.set_exception(exc)
448 else:
449 self._waiter.set_result(None)
450 self._waiter = None
451
Victor Stinner231b4042015-01-14 00:19:09 +0100452 def connection_made(self, transport):
453 """Called when the low-level connection is made.
454
455 Start the SSL handshake.
456 """
457 self._transport = transport
458 self._sslpipe = _SSLPipe(self._sslcontext,
459 self._server_side,
460 self._server_hostname)
461 self._start_handshake()
462
463 def connection_lost(self, exc):
464 """Called when the low-level connection is lost or closed.
465
466 The argument is an exception object or None (the latter
467 meaning a regular EOF is received or the connection was
468 aborted or closed).
469 """
470 if self._session_established:
471 self._session_established = False
472 self._loop.call_soon(self._app_protocol.connection_lost, exc)
473 self._transport = None
474 self._app_transport = None
475
476 def pause_writing(self):
477 """Called when the low-level transport's buffer goes over
478 the high-water mark.
479 """
480 self._app_protocol.pause_writing()
481
482 def resume_writing(self):
483 """Called when the low-level transport's buffer drains below
484 the low-water mark.
485 """
486 self._app_protocol.resume_writing()
487
488 def data_received(self, data):
489 """Called when some SSL data is received.
490
491 The argument is a bytes object.
492 """
493 try:
494 ssldata, appdata = self._sslpipe.feed_ssldata(data)
495 except ssl.SSLError as e:
496 if self._loop.get_debug():
497 logger.warning('%r: SSL error %s (reason %s)',
498 self, e.errno, e.reason)
499 self._abort()
500 return
501
502 for chunk in ssldata:
503 self._transport.write(chunk)
504
505 for chunk in appdata:
506 if chunk:
507 self._app_protocol.data_received(chunk)
508 else:
509 self._start_shutdown()
510 break
511
512 def eof_received(self):
513 """Called when the other end of the low-level stream
514 is half-closed.
515
516 If this returns a false value (including None), the transport
517 will close itself. If it returns a true value, closing the
518 transport is up to the protocol.
519 """
520 try:
521 if self._loop.get_debug():
522 logger.debug("%r received EOF", self)
Victor Stinnerb507cba2015-01-29 00:35:56 +0100523
Victor Stinnerf07801b2015-01-29 00:36:35 +0100524 self._wakeup_waiter(ConnectionResetError)
Victor Stinnerb507cba2015-01-29 00:35:56 +0100525
Victor Stinner231b4042015-01-14 00:19:09 +0100526 if not self._in_handshake:
527 keep_open = self._app_protocol.eof_received()
528 if keep_open:
529 logger.warning('returning true from eof_received() '
530 'has no effect when using ssl')
531 finally:
532 self._transport.close()
533
534 def _get_extra_info(self, name, default=None):
535 if name in self._extra:
536 return self._extra[name]
537 else:
538 return self._transport.get_extra_info(name, default)
539
540 def _start_shutdown(self):
541 if self._in_shutdown:
542 return
543 self._in_shutdown = True
544 self._write_appdata(b'')
545
546 def _write_appdata(self, data):
547 self._write_backlog.append((data, 0))
548 self._write_buffer_size += len(data)
549 self._process_write_backlog()
550
551 def _start_handshake(self):
552 if self._loop.get_debug():
553 logger.debug("%r starts SSL handshake", self)
554 self._handshake_start_time = self._loop.time()
555 else:
556 self._handshake_start_time = None
557 self._in_handshake = True
558 # (b'', 1) is a special value in _process_write_backlog() to do
559 # the SSL handshake
560 self._write_backlog.append((b'', 1))
561 self._loop.call_soon(self._process_write_backlog)
562
563 def _on_handshake_complete(self, handshake_exc):
564 self._in_handshake = False
565
566 sslobj = self._sslpipe.ssl_object
Victor Stinner231b4042015-01-14 00:19:09 +0100567 try:
568 if handshake_exc is not None:
569 raise handshake_exc
Victor Stinner177e9f02015-01-14 16:56:20 +0100570
571 peercert = sslobj.getpeercert()
Victor Stinner231b4042015-01-14 00:19:09 +0100572 if not hasattr(self._sslcontext, 'check_hostname'):
573 # Verify hostname if requested, Python 3.4+ uses check_hostname
574 # and checks the hostname in do_handshake()
575 if (self._server_hostname
576 and self._sslcontext.verify_mode != ssl.CERT_NONE):
577 ssl.match_hostname(peercert, self._server_hostname)
578 except BaseException as exc:
579 if self._loop.get_debug():
580 if isinstance(exc, ssl.CertificateError):
581 logger.warning("%r: SSL handshake failed "
582 "on verifying the certificate",
583 self, exc_info=True)
584 else:
585 logger.warning("%r: SSL handshake failed",
586 self, exc_info=True)
587 self._transport.close()
588 if isinstance(exc, Exception):
Victor Stinnerf07801b2015-01-29 00:36:35 +0100589 self._wakeup_waiter(exc)
Victor Stinner231b4042015-01-14 00:19:09 +0100590 return
591 else:
592 raise
593
594 if self._loop.get_debug():
595 dt = self._loop.time() - self._handshake_start_time
596 logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3)
597
598 # Add extra info that becomes available after handshake.
599 self._extra.update(peercert=peercert,
600 cipher=sslobj.cipher(),
601 compression=sslobj.compression(),
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200602 ssl_object=sslobj,
Victor Stinner231b4042015-01-14 00:19:09 +0100603 )
604 self._app_protocol.connection_made(self._app_transport)
Victor Stinnerf07801b2015-01-29 00:36:35 +0100605 self._wakeup_waiter()
Victor Stinner231b4042015-01-14 00:19:09 +0100606 self._session_established = True
Victor Stinner042dad72015-01-15 09:41:48 +0100607 # In case transport.write() was already called. Don't call
Martin Panter46f50722016-05-26 05:35:26 +0000608 # immediately _process_write_backlog(), but schedule it:
Victor Stinner042dad72015-01-15 09:41:48 +0100609 # _on_handshake_complete() can be called indirectly from
610 # _process_write_backlog(), and _process_write_backlog() is not
611 # reentrant.
Victor Stinner72bdefb2015-01-15 09:44:13 +0100612 self._loop.call_soon(self._process_write_backlog)
Victor Stinner231b4042015-01-14 00:19:09 +0100613
614 def _process_write_backlog(self):
615 # Try to make progress on the write backlog.
616 if self._transport is None:
617 return
618
619 try:
620 for i in range(len(self._write_backlog)):
621 data, offset = self._write_backlog[0]
622 if data:
623 ssldata, offset = self._sslpipe.feed_appdata(data, offset)
624 elif offset:
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400625 ssldata = self._sslpipe.do_handshake(
626 self._on_handshake_complete)
Victor Stinner231b4042015-01-14 00:19:09 +0100627 offset = 1
628 else:
629 ssldata = self._sslpipe.shutdown(self._finalize)
630 offset = 1
631
632 for chunk in ssldata:
633 self._transport.write(chunk)
634
635 if offset < len(data):
636 self._write_backlog[0] = (data, offset)
637 # A short write means that a write is blocked on a read
638 # We need to enable reading if it is paused!
639 assert self._sslpipe.need_ssldata
640 if self._transport._paused:
641 self._transport.resume_reading()
642 break
643
644 # An entire chunk from the backlog was processed. We can
645 # delete it and reduce the outstanding buffer size.
646 del self._write_backlog[0]
647 self._write_buffer_size -= len(data)
648 except BaseException as exc:
649 if self._in_handshake:
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400650 # BaseExceptions will be re-raised in _on_handshake_complete.
Victor Stinner231b4042015-01-14 00:19:09 +0100651 self._on_handshake_complete(exc)
652 else:
653 self._fatal_error(exc, 'Fatal error on SSL transport')
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400654 if not isinstance(exc, Exception):
655 # BaseException
656 raise
Victor Stinner231b4042015-01-14 00:19:09 +0100657
658 def _fatal_error(self, exc, message='Fatal error on transport'):
659 # Should be called from exception handler only.
Victor Stinnerc94a93a2016-04-01 21:43:39 +0200660 if isinstance(exc, base_events._FATAL_ERROR_IGNORE):
Victor Stinner231b4042015-01-14 00:19:09 +0100661 if self._loop.get_debug():
662 logger.debug("%r: %s", self, message, exc_info=True)
663 else:
664 self._loop.call_exception_handler({
665 'message': message,
666 'exception': exc,
667 'transport': self._transport,
668 'protocol': self,
669 })
670 if self._transport:
671 self._transport._force_close(exc)
672
673 def _finalize(self):
674 if self._transport is not None:
675 self._transport.close()
676
677 def _abort(self):
678 if self._transport is not None:
679 try:
680 self._transport.abort()
681 finally:
682 self._finalize()