blob: afe85a143870c264e4a2fa4a8b33f4de87d9dacb [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 Selivanova05a6ef2016-09-11 21:11:02 -0400308 def set_protocol(self, protocol):
309 self._app_protocol = protocol
310
311 def get_protocol(self):
312 return self._app_protocol
313
Yury Selivanov5bb1afb2015-11-16 12:43:21 -0500314 def is_closing(self):
315 return self._closed
316
Victor Stinner231b4042015-01-14 00:19:09 +0100317 def close(self):
318 """Close the transport.
319
320 Buffered data will be flushed asynchronously. No more data
321 will be received. After all buffered data is flushed, the
322 protocol's connection_lost() method will (eventually) called
323 with None as its argument.
324 """
Victor Stinner978a9af2015-01-29 17:50:58 +0100325 self._closed = True
Victor Stinner231b4042015-01-14 00:19:09 +0100326 self._ssl_protocol._start_shutdown()
327
Victor Stinner978a9af2015-01-29 17:50:58 +0100328 # On Python 3.3 and older, objects with a destructor part of a reference
329 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
330 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400331 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100332 def __del__(self):
333 if not self._closed:
334 warnings.warn("unclosed transport %r" % self, ResourceWarning)
335 self.close()
336
Victor Stinner231b4042015-01-14 00:19:09 +0100337 def pause_reading(self):
338 """Pause the receiving end.
339
340 No data will be passed to the protocol's data_received()
341 method until resume_reading() is called.
342 """
343 self._ssl_protocol._transport.pause_reading()
344
345 def resume_reading(self):
346 """Resume the receiving end.
347
348 Data received will once again be passed to the protocol's
349 data_received() method.
350 """
351 self._ssl_protocol._transport.resume_reading()
352
353 def set_write_buffer_limits(self, high=None, low=None):
354 """Set the high- and low-water limits for write flow control.
355
356 These two values control when to call the protocol's
357 pause_writing() and resume_writing() methods. If specified,
358 the low-water limit must be less than or equal to the
359 high-water limit. Neither value can be negative.
360
361 The defaults are implementation-specific. If only the
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200362 high-water limit is given, the low-water limit defaults to an
Victor Stinner231b4042015-01-14 00:19:09 +0100363 implementation-specific value less than or equal to the
364 high-water limit. Setting high to zero forces low to zero as
365 well, and causes pause_writing() to be called whenever the
366 buffer becomes non-empty. Setting low to zero causes
367 resume_writing() to be called only once the buffer is empty.
368 Use of zero for either limit is generally sub-optimal as it
369 reduces opportunities for doing I/O and computation
370 concurrently.
371 """
372 self._ssl_protocol._transport.set_write_buffer_limits(high, low)
373
374 def get_write_buffer_size(self):
375 """Return the current size of the write buffer."""
376 return self._ssl_protocol._transport.get_write_buffer_size()
377
378 def write(self, data):
379 """Write some data bytes to the transport.
380
381 This does not block; it buffers the data and arranges for it
382 to be sent out asynchronously.
383 """
384 if not isinstance(data, (bytes, bytearray, memoryview)):
385 raise TypeError("data: expecting a bytes-like instance, got {!r}"
386 .format(type(data).__name__))
387 if not data:
388 return
389 self._ssl_protocol._write_appdata(data)
390
391 def can_write_eof(self):
392 """Return True if this transport supports write_eof(), False if not."""
393 return False
394
395 def abort(self):
396 """Close the transport immediately.
397
398 Buffered data will be lost. No more data will be received.
399 The protocol's connection_lost() method will (eventually) be
400 called with None as its argument.
401 """
402 self._ssl_protocol._abort()
403
404
405class SSLProtocol(protocols.Protocol):
406 """SSL protocol.
407
408 Implementation of SSL on top of a socket using incoming and outgoing
409 buffers which are ssl.MemoryBIO objects.
410 """
411
412 def __init__(self, loop, app_protocol, sslcontext, waiter,
413 server_side=False, server_hostname=None):
414 if ssl is None:
415 raise RuntimeError('stdlib ssl module not available')
416
417 if not sslcontext:
418 sslcontext = _create_transport_context(server_side, server_hostname)
419
420 self._server_side = server_side
421 if server_hostname and not server_side:
422 self._server_hostname = server_hostname
423 else:
424 self._server_hostname = None
425 self._sslcontext = sslcontext
426 # SSL-specific extra info. More info are set when the handshake
427 # completes.
428 self._extra = dict(sslcontext=sslcontext)
429
430 # App data write buffering
431 self._write_backlog = collections.deque()
432 self._write_buffer_size = 0
433
434 self._waiter = waiter
Victor Stinner231b4042015-01-14 00:19:09 +0100435 self._loop = loop
436 self._app_protocol = app_protocol
437 self._app_transport = _SSLProtocolTransport(self._loop,
438 self, self._app_protocol)
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200439 # _SSLPipe instance (None until the connection is made)
Victor Stinner231b4042015-01-14 00:19:09 +0100440 self._sslpipe = None
441 self._session_established = False
442 self._in_handshake = False
443 self._in_shutdown = False
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200444 # transport, ex: SelectorSocketTransport
Victor Stinner7e222f42015-01-15 13:16:27 +0100445 self._transport = None
Victor Stinner231b4042015-01-14 00:19:09 +0100446
Victor Stinnerf07801b2015-01-29 00:36:35 +0100447 def _wakeup_waiter(self, exc=None):
448 if self._waiter is None:
449 return
450 if not self._waiter.cancelled():
451 if exc is not None:
452 self._waiter.set_exception(exc)
453 else:
454 self._waiter.set_result(None)
455 self._waiter = None
456
Victor Stinner231b4042015-01-14 00:19:09 +0100457 def connection_made(self, transport):
458 """Called when the low-level connection is made.
459
460 Start the SSL handshake.
461 """
462 self._transport = transport
463 self._sslpipe = _SSLPipe(self._sslcontext,
464 self._server_side,
465 self._server_hostname)
466 self._start_handshake()
467
468 def connection_lost(self, exc):
469 """Called when the low-level connection is lost or closed.
470
471 The argument is an exception object or None (the latter
472 meaning a regular EOF is received or the connection was
473 aborted or closed).
474 """
475 if self._session_established:
476 self._session_established = False
477 self._loop.call_soon(self._app_protocol.connection_lost, exc)
478 self._transport = None
479 self._app_transport = None
480
481 def pause_writing(self):
482 """Called when the low-level transport's buffer goes over
483 the high-water mark.
484 """
485 self._app_protocol.pause_writing()
486
487 def resume_writing(self):
488 """Called when the low-level transport's buffer drains below
489 the low-water mark.
490 """
491 self._app_protocol.resume_writing()
492
493 def data_received(self, data):
494 """Called when some SSL data is received.
495
496 The argument is a bytes object.
497 """
498 try:
499 ssldata, appdata = self._sslpipe.feed_ssldata(data)
500 except ssl.SSLError as e:
501 if self._loop.get_debug():
502 logger.warning('%r: SSL error %s (reason %s)',
503 self, e.errno, e.reason)
504 self._abort()
505 return
506
507 for chunk in ssldata:
508 self._transport.write(chunk)
509
510 for chunk in appdata:
511 if chunk:
512 self._app_protocol.data_received(chunk)
513 else:
514 self._start_shutdown()
515 break
516
517 def eof_received(self):
518 """Called when the other end of the low-level stream
519 is half-closed.
520
521 If this returns a false value (including None), the transport
522 will close itself. If it returns a true value, closing the
523 transport is up to the protocol.
524 """
525 try:
526 if self._loop.get_debug():
527 logger.debug("%r received EOF", self)
Victor Stinnerb507cba2015-01-29 00:35:56 +0100528
Victor Stinnerf07801b2015-01-29 00:36:35 +0100529 self._wakeup_waiter(ConnectionResetError)
Victor Stinnerb507cba2015-01-29 00:35:56 +0100530
Victor Stinner231b4042015-01-14 00:19:09 +0100531 if not self._in_handshake:
532 keep_open = self._app_protocol.eof_received()
533 if keep_open:
534 logger.warning('returning true from eof_received() '
535 'has no effect when using ssl')
536 finally:
537 self._transport.close()
538
539 def _get_extra_info(self, name, default=None):
540 if name in self._extra:
541 return self._extra[name]
542 else:
543 return self._transport.get_extra_info(name, default)
544
545 def _start_shutdown(self):
546 if self._in_shutdown:
547 return
548 self._in_shutdown = True
549 self._write_appdata(b'')
550
551 def _write_appdata(self, data):
552 self._write_backlog.append((data, 0))
553 self._write_buffer_size += len(data)
554 self._process_write_backlog()
555
556 def _start_handshake(self):
557 if self._loop.get_debug():
558 logger.debug("%r starts SSL handshake", self)
559 self._handshake_start_time = self._loop.time()
560 else:
561 self._handshake_start_time = None
562 self._in_handshake = True
563 # (b'', 1) is a special value in _process_write_backlog() to do
564 # the SSL handshake
565 self._write_backlog.append((b'', 1))
566 self._loop.call_soon(self._process_write_backlog)
567
568 def _on_handshake_complete(self, handshake_exc):
569 self._in_handshake = False
570
571 sslobj = self._sslpipe.ssl_object
Victor Stinner231b4042015-01-14 00:19:09 +0100572 try:
573 if handshake_exc is not None:
574 raise handshake_exc
Victor Stinner177e9f02015-01-14 16:56:20 +0100575
576 peercert = sslobj.getpeercert()
Victor Stinner231b4042015-01-14 00:19:09 +0100577 if not hasattr(self._sslcontext, 'check_hostname'):
578 # Verify hostname if requested, Python 3.4+ uses check_hostname
579 # and checks the hostname in do_handshake()
580 if (self._server_hostname
581 and self._sslcontext.verify_mode != ssl.CERT_NONE):
582 ssl.match_hostname(peercert, self._server_hostname)
583 except BaseException as exc:
584 if self._loop.get_debug():
585 if isinstance(exc, ssl.CertificateError):
586 logger.warning("%r: SSL handshake failed "
587 "on verifying the certificate",
588 self, exc_info=True)
589 else:
590 logger.warning("%r: SSL handshake failed",
591 self, exc_info=True)
592 self._transport.close()
593 if isinstance(exc, Exception):
Victor Stinnerf07801b2015-01-29 00:36:35 +0100594 self._wakeup_waiter(exc)
Victor Stinner231b4042015-01-14 00:19:09 +0100595 return
596 else:
597 raise
598
599 if self._loop.get_debug():
600 dt = self._loop.time() - self._handshake_start_time
601 logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3)
602
603 # Add extra info that becomes available after handshake.
604 self._extra.update(peercert=peercert,
605 cipher=sslobj.cipher(),
606 compression=sslobj.compression(),
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200607 ssl_object=sslobj,
Victor Stinner231b4042015-01-14 00:19:09 +0100608 )
609 self._app_protocol.connection_made(self._app_transport)
Victor Stinnerf07801b2015-01-29 00:36:35 +0100610 self._wakeup_waiter()
Victor Stinner231b4042015-01-14 00:19:09 +0100611 self._session_established = True
Victor Stinner042dad72015-01-15 09:41:48 +0100612 # In case transport.write() was already called. Don't call
Martin Panter46f50722016-05-26 05:35:26 +0000613 # immediately _process_write_backlog(), but schedule it:
Victor Stinner042dad72015-01-15 09:41:48 +0100614 # _on_handshake_complete() can be called indirectly from
615 # _process_write_backlog(), and _process_write_backlog() is not
616 # reentrant.
Victor Stinner72bdefb2015-01-15 09:44:13 +0100617 self._loop.call_soon(self._process_write_backlog)
Victor Stinner231b4042015-01-14 00:19:09 +0100618
619 def _process_write_backlog(self):
620 # Try to make progress on the write backlog.
621 if self._transport is None:
622 return
623
624 try:
625 for i in range(len(self._write_backlog)):
626 data, offset = self._write_backlog[0]
627 if data:
628 ssldata, offset = self._sslpipe.feed_appdata(data, offset)
629 elif offset:
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400630 ssldata = self._sslpipe.do_handshake(
631 self._on_handshake_complete)
Victor Stinner231b4042015-01-14 00:19:09 +0100632 offset = 1
633 else:
634 ssldata = self._sslpipe.shutdown(self._finalize)
635 offset = 1
636
637 for chunk in ssldata:
638 self._transport.write(chunk)
639
640 if offset < len(data):
641 self._write_backlog[0] = (data, offset)
642 # A short write means that a write is blocked on a read
643 # We need to enable reading if it is paused!
644 assert self._sslpipe.need_ssldata
645 if self._transport._paused:
646 self._transport.resume_reading()
647 break
648
649 # An entire chunk from the backlog was processed. We can
650 # delete it and reduce the outstanding buffer size.
651 del self._write_backlog[0]
652 self._write_buffer_size -= len(data)
653 except BaseException as exc:
654 if self._in_handshake:
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400655 # BaseExceptions will be re-raised in _on_handshake_complete.
Victor Stinner231b4042015-01-14 00:19:09 +0100656 self._on_handshake_complete(exc)
657 else:
658 self._fatal_error(exc, 'Fatal error on SSL transport')
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400659 if not isinstance(exc, Exception):
660 # BaseException
661 raise
Victor Stinner231b4042015-01-14 00:19:09 +0100662
663 def _fatal_error(self, exc, message='Fatal error on transport'):
664 # Should be called from exception handler only.
Victor Stinnerc94a93a2016-04-01 21:43:39 +0200665 if isinstance(exc, base_events._FATAL_ERROR_IGNORE):
Victor Stinner231b4042015-01-14 00:19:09 +0100666 if self._loop.get_debug():
667 logger.debug("%r: %s", self, message, exc_info=True)
668 else:
669 self._loop.call_exception_handler({
670 'message': message,
671 'exception': exc,
672 'transport': self._transport,
673 'protocol': self,
674 })
675 if self._transport:
676 self._transport._force_close(exc)
677
678 def _finalize(self):
679 if self._transport is not None:
680 self._transport.close()
681
682 def _abort(self):
683 if self._transport is not None:
684 try:
685 self._transport.abort()
686 finally:
687 self._finalize()