blob: 2bfa45dd1585afa4290579a15f1aa07fb9fb6371 [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
Neil Aspinallf7686c12017-12-19 19:45:42 +00009from . import constants
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.
Andrew Svetlov51d546a2017-11-18 18:54:05 +020022 # Python 3.4+: use up-to-date strong settings.
23 sslcontext = ssl.create_default_context()
24 if not server_hostname:
25 sslcontext.check_hostname = False
Victor Stinner231b4042015-01-14 00:19:09 +010026 return sslcontext
27
28
Victor Stinner231b4042015-01-14 00:19:09 +010029# States of an _SSLPipe.
30_UNWRAPPED = "UNWRAPPED"
31_DO_HANDSHAKE = "DO_HANDSHAKE"
32_WRAPPED = "WRAPPED"
33_SHUTDOWN = "SHUTDOWN"
34
35
36class _SSLPipe(object):
37 """An SSL "Pipe".
38
39 An SSL pipe allows you to communicate with an SSL/TLS protocol instance
40 through memory buffers. It can be used to implement a security layer for an
41 existing connection where you don't have access to the connection's file
42 descriptor, or for some reason you don't want to use it.
43
44 An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
45 data is passed through untransformed. In wrapped mode, application level
46 data is encrypted to SSL record level data and vice versa. The SSL record
47 level is the lowest level in the SSL protocol suite and is what travels
48 as-is over the wire.
49
50 An SslPipe initially is in "unwrapped" mode. To start SSL, call
51 do_handshake(). To shutdown SSL again, call unwrap().
52 """
53
54 max_size = 256 * 1024 # Buffer size passed to read()
55
56 def __init__(self, context, server_side, server_hostname=None):
57 """
58 The *context* argument specifies the ssl.SSLContext to use.
59
60 The *server_side* argument indicates whether this is a server side or
61 client side transport.
62
63 The optional *server_hostname* argument can be used to specify the
64 hostname you are connecting to. You may only specify this parameter if
65 the _ssl module supports Server Name Indication (SNI).
66 """
67 self._context = context
68 self._server_side = server_side
69 self._server_hostname = server_hostname
70 self._state = _UNWRAPPED
71 self._incoming = ssl.MemoryBIO()
72 self._outgoing = ssl.MemoryBIO()
73 self._sslobj = None
74 self._need_ssldata = False
75 self._handshake_cb = None
76 self._shutdown_cb = None
77
78 @property
79 def context(self):
80 """The SSL context passed to the constructor."""
81 return self._context
82
83 @property
84 def ssl_object(self):
85 """The internal ssl.SSLObject instance.
86
87 Return None if the pipe is not wrapped.
88 """
89 return self._sslobj
90
91 @property
92 def need_ssldata(self):
93 """Whether more record level data is needed to complete a handshake
94 that is currently in progress."""
95 return self._need_ssldata
96
97 @property
98 def wrapped(self):
99 """
100 Whether a security layer is currently in effect.
101
102 Return False during handshake.
103 """
104 return self._state == _WRAPPED
105
106 def do_handshake(self, callback=None):
107 """Start the SSL handshake.
108
109 Return a list of ssldata. A ssldata element is a list of buffers
110
111 The optional *callback* argument can be used to install a callback that
112 will be called when the handshake is complete. The callback will be
113 called with None if successful, else an exception instance.
114 """
115 if self._state != _UNWRAPPED:
116 raise RuntimeError('handshake in progress or completed')
117 self._sslobj = self._context.wrap_bio(
118 self._incoming, self._outgoing,
119 server_side=self._server_side,
120 server_hostname=self._server_hostname)
121 self._state = _DO_HANDSHAKE
122 self._handshake_cb = callback
123 ssldata, appdata = self.feed_ssldata(b'', only_handshake=True)
124 assert len(appdata) == 0
125 return ssldata
126
127 def shutdown(self, callback=None):
128 """Start the SSL shutdown sequence.
129
130 Return a list of ssldata. A ssldata element is a list of buffers
131
132 The optional *callback* argument can be used to install a callback that
133 will be called when the shutdown is complete. The callback will be
134 called without arguments.
135 """
136 if self._state == _UNWRAPPED:
137 raise RuntimeError('no security layer present')
138 if self._state == _SHUTDOWN:
139 raise RuntimeError('shutdown in progress')
140 assert self._state in (_WRAPPED, _DO_HANDSHAKE)
141 self._state = _SHUTDOWN
142 self._shutdown_cb = callback
143 ssldata, appdata = self.feed_ssldata(b'')
144 assert appdata == [] or appdata == [b'']
145 return ssldata
146
147 def feed_eof(self):
148 """Send a potentially "ragged" EOF.
149
150 This method will raise an SSL_ERROR_EOF exception if the EOF is
151 unexpected.
152 """
153 self._incoming.write_eof()
154 ssldata, appdata = self.feed_ssldata(b'')
155 assert appdata == [] or appdata == [b'']
156
157 def feed_ssldata(self, data, only_handshake=False):
158 """Feed SSL record level data into the pipe.
159
160 The data must be a bytes instance. It is OK to send an empty bytes
161 instance. This can be used to get ssldata for a handshake initiated by
162 this endpoint.
163
164 Return a (ssldata, appdata) tuple. The ssldata element is a list of
165 buffers containing SSL data that needs to be sent to the remote SSL.
166
167 The appdata element is a list of buffers containing plaintext data that
168 needs to be forwarded to the application. The appdata list may contain
169 an empty buffer indicating an SSL "close_notify" alert. This alert must
170 be acknowledged by calling shutdown().
171 """
172 if self._state == _UNWRAPPED:
173 # If unwrapped, pass plaintext data straight through.
174 if data:
175 appdata = [data]
176 else:
177 appdata = []
178 return ([], appdata)
179
180 self._need_ssldata = False
181 if data:
182 self._incoming.write(data)
183
184 ssldata = []
185 appdata = []
186 try:
187 if self._state == _DO_HANDSHAKE:
188 # Call do_handshake() until it doesn't raise anymore.
189 self._sslobj.do_handshake()
190 self._state = _WRAPPED
191 if self._handshake_cb:
192 self._handshake_cb(None)
193 if only_handshake:
194 return (ssldata, appdata)
195 # Handshake done: execute the wrapped block
196
197 if self._state == _WRAPPED:
198 # Main state: read data from SSL until close_notify
199 while True:
200 chunk = self._sslobj.read(self.max_size)
201 appdata.append(chunk)
202 if not chunk: # close_notify
203 break
204
205 elif self._state == _SHUTDOWN:
206 # Call shutdown() until it doesn't raise anymore.
207 self._sslobj.unwrap()
208 self._sslobj = None
209 self._state = _UNWRAPPED
210 if self._shutdown_cb:
211 self._shutdown_cb()
212
213 elif self._state == _UNWRAPPED:
214 # Drain possible plaintext data after close_notify.
215 appdata.append(self._incoming.read())
216 except (ssl.SSLError, ssl.CertificateError) as exc:
217 if getattr(exc, 'errno', None) not in (
218 ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE,
219 ssl.SSL_ERROR_SYSCALL):
220 if self._state == _DO_HANDSHAKE and self._handshake_cb:
221 self._handshake_cb(exc)
222 raise
223 self._need_ssldata = (exc.errno == ssl.SSL_ERROR_WANT_READ)
224
225 # Check for record level data that needs to be sent back.
226 # Happens for the initial handshake and renegotiations.
227 if self._outgoing.pending:
228 ssldata.append(self._outgoing.read())
229 return (ssldata, appdata)
230
231 def feed_appdata(self, data, offset=0):
232 """Feed plaintext data into the pipe.
233
234 Return an (ssldata, offset) tuple. The ssldata element is a list of
235 buffers containing record level data that needs to be sent to the
236 remote SSL instance. The offset is the number of plaintext bytes that
237 were processed, which may be less than the length of data.
238
239 NOTE: In case of short writes, this call MUST be retried with the SAME
240 buffer passed into the *data* argument (i.e. the id() must be the
241 same). This is an OpenSSL requirement. A further particularity is that
242 a short write will always have offset == 0, because the _ssl module
243 does not enable partial writes. And even though the offset is zero,
244 there will still be encrypted data in ssldata.
245 """
246 assert 0 <= offset <= len(data)
247 if self._state == _UNWRAPPED:
248 # pass through data in unwrapped mode
249 if offset < len(data):
250 ssldata = [data[offset:]]
251 else:
252 ssldata = []
253 return (ssldata, len(data))
254
255 ssldata = []
256 view = memoryview(data)
257 while True:
258 self._need_ssldata = False
259 try:
260 if offset < len(view):
261 offset += self._sslobj.write(view[offset:])
262 except ssl.SSLError as exc:
263 # It is not allowed to call write() after unwrap() until the
264 # close_notify is acknowledged. We return the condition to the
265 # caller as a short write.
266 if exc.reason == 'PROTOCOL_IS_SHUTDOWN':
267 exc.errno = ssl.SSL_ERROR_WANT_READ
268 if exc.errno not in (ssl.SSL_ERROR_WANT_READ,
269 ssl.SSL_ERROR_WANT_WRITE,
270 ssl.SSL_ERROR_SYSCALL):
271 raise
272 self._need_ssldata = (exc.errno == ssl.SSL_ERROR_WANT_READ)
273
274 # See if there's any record level data back for us.
275 if self._outgoing.pending:
276 ssldata.append(self._outgoing.read())
277 if offset == len(view) or self._need_ssldata:
278 break
279 return (ssldata, offset)
280
281
282class _SSLProtocolTransport(transports._FlowControlMixin,
283 transports.Transport):
284
Andrew Svetlov7c684072018-01-27 21:22:47 +0200285 _sendfile_compatible = constants._SendfileMode.FALLBACK
286
jlacolineea2ef5d2017-10-19 19:49:57 +0200287 def __init__(self, loop, ssl_protocol):
Victor Stinner231b4042015-01-14 00:19:09 +0100288 self._loop = loop
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200289 # SSLProtocol instance
Victor Stinner231b4042015-01-14 00:19:09 +0100290 self._ssl_protocol = ssl_protocol
Victor Stinner978a9af2015-01-29 17:50:58 +0100291 self._closed = False
Victor Stinner231b4042015-01-14 00:19:09 +0100292
293 def get_extra_info(self, name, default=None):
294 """Get optional transport information."""
295 return self._ssl_protocol._get_extra_info(name, default)
296
Yury Selivanova05a6ef2016-09-11 21:11:02 -0400297 def set_protocol(self, protocol):
jlacolineea2ef5d2017-10-19 19:49:57 +0200298 self._ssl_protocol._app_protocol = protocol
Yury Selivanova05a6ef2016-09-11 21:11:02 -0400299
300 def get_protocol(self):
jlacolineea2ef5d2017-10-19 19:49:57 +0200301 return self._ssl_protocol._app_protocol
Yury Selivanova05a6ef2016-09-11 21:11:02 -0400302
Yury Selivanov5bb1afb2015-11-16 12:43:21 -0500303 def is_closing(self):
304 return self._closed
305
Victor Stinner231b4042015-01-14 00:19:09 +0100306 def close(self):
307 """Close the transport.
308
309 Buffered data will be flushed asynchronously. No more data
310 will be received. After all buffered data is flushed, the
311 protocol's connection_lost() method will (eventually) called
312 with None as its argument.
313 """
Victor Stinner978a9af2015-01-29 17:50:58 +0100314 self._closed = True
Victor Stinner231b4042015-01-14 00:19:09 +0100315 self._ssl_protocol._start_shutdown()
316
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900317 def __del__(self):
318 if not self._closed:
Yury Selivanov6370f342017-12-10 18:36:12 -0500319 warnings.warn(f"unclosed transport {self!r}", ResourceWarning,
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900320 source=self)
321 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100322
Yury Selivanovd757aaf2017-12-18 17:03:23 -0500323 def is_reading(self):
324 tr = self._ssl_protocol._transport
325 if tr is None:
326 raise RuntimeError('SSL transport has not been initialized yet')
327 return tr.is_reading()
328
Victor Stinner231b4042015-01-14 00:19:09 +0100329 def pause_reading(self):
330 """Pause the receiving end.
331
332 No data will be passed to the protocol's data_received()
333 method until resume_reading() is called.
334 """
335 self._ssl_protocol._transport.pause_reading()
336
337 def resume_reading(self):
338 """Resume the receiving end.
339
340 Data received will once again be passed to the protocol's
341 data_received() method.
342 """
343 self._ssl_protocol._transport.resume_reading()
344
345 def set_write_buffer_limits(self, high=None, low=None):
346 """Set the high- and low-water limits for write flow control.
347
348 These two values control when to call the protocol's
349 pause_writing() and resume_writing() methods. If specified,
350 the low-water limit must be less than or equal to the
351 high-water limit. Neither value can be negative.
352
353 The defaults are implementation-specific. If only the
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200354 high-water limit is given, the low-water limit defaults to an
Victor Stinner231b4042015-01-14 00:19:09 +0100355 implementation-specific value less than or equal to the
356 high-water limit. Setting high to zero forces low to zero as
357 well, and causes pause_writing() to be called whenever the
358 buffer becomes non-empty. Setting low to zero causes
359 resume_writing() to be called only once the buffer is empty.
360 Use of zero for either limit is generally sub-optimal as it
361 reduces opportunities for doing I/O and computation
362 concurrently.
363 """
364 self._ssl_protocol._transport.set_write_buffer_limits(high, low)
365
366 def get_write_buffer_size(self):
367 """Return the current size of the write buffer."""
368 return self._ssl_protocol._transport.get_write_buffer_size()
369
Andrew Svetlov7c684072018-01-27 21:22:47 +0200370 @property
371 def _protocol_paused(self):
372 # Required for sendfile fallback pause_writing/resume_writing logic
373 return self._ssl_protocol._transport._protocol_paused
374
Victor Stinner231b4042015-01-14 00:19:09 +0100375 def write(self, data):
376 """Write some data bytes to the transport.
377
378 This does not block; it buffers the data and arranges for it
379 to be sent out asynchronously.
380 """
381 if not isinstance(data, (bytes, bytearray, memoryview)):
Yury Selivanov6370f342017-12-10 18:36:12 -0500382 raise TypeError(f"data: expecting a bytes-like instance, "
383 f"got {type(data).__name__}")
Victor Stinner231b4042015-01-14 00:19:09 +0100384 if not data:
385 return
386 self._ssl_protocol._write_appdata(data)
387
388 def can_write_eof(self):
389 """Return True if this transport supports write_eof(), False if not."""
390 return False
391
392 def abort(self):
393 """Close the transport immediately.
394
395 Buffered data will be lost. No more data will be received.
396 The protocol's connection_lost() method will (eventually) be
397 called with None as its argument.
398 """
399 self._ssl_protocol._abort()
400
401
402class SSLProtocol(protocols.Protocol):
403 """SSL protocol.
404
405 Implementation of SSL on top of a socket using incoming and outgoing
406 buffers which are ssl.MemoryBIO objects.
407 """
408
409 def __init__(self, loop, app_protocol, sslcontext, waiter,
Yury Selivanov92e7c7f2016-10-05 19:39:54 -0400410 server_side=False, server_hostname=None,
Neil Aspinallf7686c12017-12-19 19:45:42 +0000411 call_connection_made=True,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200412 ssl_handshake_timeout=None):
Victor Stinner231b4042015-01-14 00:19:09 +0100413 if ssl is None:
414 raise RuntimeError('stdlib ssl module not available')
415
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200416 if ssl_handshake_timeout is None:
417 ssl_handshake_timeout = constants.SSL_HANDSHAKE_TIMEOUT
418 elif ssl_handshake_timeout <= 0:
419 raise ValueError(
420 f"ssl_handshake_timeout should be a positive number, "
421 f"got {ssl_handshake_timeout}")
422
Victor Stinner231b4042015-01-14 00:19:09 +0100423 if not sslcontext:
Yury Selivanov6370f342017-12-10 18:36:12 -0500424 sslcontext = _create_transport_context(
425 server_side, server_hostname)
Victor Stinner231b4042015-01-14 00:19:09 +0100426
427 self._server_side = server_side
428 if server_hostname and not server_side:
429 self._server_hostname = server_hostname
430 else:
431 self._server_hostname = None
432 self._sslcontext = sslcontext
433 # SSL-specific extra info. More info are set when the handshake
434 # completes.
435 self._extra = dict(sslcontext=sslcontext)
436
437 # App data write buffering
438 self._write_backlog = collections.deque()
439 self._write_buffer_size = 0
440
441 self._waiter = waiter
Victor Stinner231b4042015-01-14 00:19:09 +0100442 self._loop = loop
443 self._app_protocol = app_protocol
Miss Islington (bot)bc3a0022018-05-28 11:50:45 -0700444 self._app_protocol_is_buffer = \
445 isinstance(app_protocol, protocols.BufferedProtocol)
jlacolineea2ef5d2017-10-19 19:49:57 +0200446 self._app_transport = _SSLProtocolTransport(self._loop, self)
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200447 # _SSLPipe instance (None until the connection is made)
Victor Stinner231b4042015-01-14 00:19:09 +0100448 self._sslpipe = None
449 self._session_established = False
450 self._in_handshake = False
451 self._in_shutdown = False
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200452 # transport, ex: SelectorSocketTransport
Victor Stinner7e222f42015-01-15 13:16:27 +0100453 self._transport = None
Yury Selivanov92e7c7f2016-10-05 19:39:54 -0400454 self._call_connection_made = call_connection_made
Neil Aspinallf7686c12017-12-19 19:45:42 +0000455 self._ssl_handshake_timeout = ssl_handshake_timeout
Victor Stinner231b4042015-01-14 00:19:09 +0100456
Victor Stinnerf07801b2015-01-29 00:36:35 +0100457 def _wakeup_waiter(self, exc=None):
458 if self._waiter is None:
459 return
460 if not self._waiter.cancelled():
461 if exc is not None:
462 self._waiter.set_exception(exc)
463 else:
464 self._waiter.set_result(None)
465 self._waiter = None
466
Victor Stinner231b4042015-01-14 00:19:09 +0100467 def connection_made(self, transport):
468 """Called when the low-level connection is made.
469
470 Start the SSL handshake.
471 """
472 self._transport = transport
473 self._sslpipe = _SSLPipe(self._sslcontext,
474 self._server_side,
475 self._server_hostname)
476 self._start_handshake()
477
478 def connection_lost(self, exc):
479 """Called when the low-level connection is lost or closed.
480
481 The argument is an exception object or None (the latter
482 meaning a regular EOF is received or the connection was
483 aborted or closed).
484 """
485 if self._session_established:
486 self._session_established = False
487 self._loop.call_soon(self._app_protocol.connection_lost, exc)
488 self._transport = None
489 self._app_transport = None
Yury Selivanovb1461aa2016-12-16 11:50:41 -0500490 self._wakeup_waiter(exc)
Victor Stinner231b4042015-01-14 00:19:09 +0100491
492 def pause_writing(self):
493 """Called when the low-level transport's buffer goes over
494 the high-water mark.
495 """
496 self._app_protocol.pause_writing()
497
498 def resume_writing(self):
499 """Called when the low-level transport's buffer drains below
500 the low-water mark.
501 """
502 self._app_protocol.resume_writing()
503
504 def data_received(self, data):
505 """Called when some SSL data is received.
506
507 The argument is a bytes object.
508 """
Miss Islington (bot)bf0d1162018-03-10 08:27:01 -0800509 if self._sslpipe is None:
510 # transport closing, sslpipe is destroyed
511 return
512
Victor Stinner231b4042015-01-14 00:19:09 +0100513 try:
514 ssldata, appdata = self._sslpipe.feed_ssldata(data)
515 except ssl.SSLError as e:
516 if self._loop.get_debug():
517 logger.warning('%r: SSL error %s (reason %s)',
518 self, e.errno, e.reason)
519 self._abort()
520 return
521
522 for chunk in ssldata:
523 self._transport.write(chunk)
524
525 for chunk in appdata:
526 if chunk:
Miss Islington (bot)bc3a0022018-05-28 11:50:45 -0700527 try:
528 if self._app_protocol_is_buffer:
529 _feed_data_to_bufferred_proto(
530 self._app_protocol, chunk)
531 else:
532 self._app_protocol.data_received(chunk)
533 except Exception as ex:
534 self._fatal_error(
535 ex, 'application protocol failed to receive SSL data')
536 return
Victor Stinner231b4042015-01-14 00:19:09 +0100537 else:
538 self._start_shutdown()
539 break
540
541 def eof_received(self):
542 """Called when the other end of the low-level stream
543 is half-closed.
544
545 If this returns a false value (including None), the transport
546 will close itself. If it returns a true value, closing the
547 transport is up to the protocol.
548 """
549 try:
550 if self._loop.get_debug():
551 logger.debug("%r received EOF", self)
Victor Stinnerb507cba2015-01-29 00:35:56 +0100552
Victor Stinnerf07801b2015-01-29 00:36:35 +0100553 self._wakeup_waiter(ConnectionResetError)
Victor Stinnerb507cba2015-01-29 00:35:56 +0100554
Victor Stinner231b4042015-01-14 00:19:09 +0100555 if not self._in_handshake:
556 keep_open = self._app_protocol.eof_received()
557 if keep_open:
558 logger.warning('returning true from eof_received() '
559 'has no effect when using ssl')
560 finally:
561 self._transport.close()
562
563 def _get_extra_info(self, name, default=None):
564 if name in self._extra:
565 return self._extra[name]
Nikolay Kim2b27e2e2017-03-12 12:23:30 -0700566 elif self._transport is not None:
Victor Stinner231b4042015-01-14 00:19:09 +0100567 return self._transport.get_extra_info(name, default)
Nikolay Kim2b27e2e2017-03-12 12:23:30 -0700568 else:
569 return default
Victor Stinner231b4042015-01-14 00:19:09 +0100570
571 def _start_shutdown(self):
572 if self._in_shutdown:
573 return
Nikolay Kima0e3d2d2017-06-09 14:46:14 -0700574 if self._in_handshake:
575 self._abort()
576 else:
577 self._in_shutdown = True
578 self._write_appdata(b'')
Victor Stinner231b4042015-01-14 00:19:09 +0100579
580 def _write_appdata(self, data):
581 self._write_backlog.append((data, 0))
582 self._write_buffer_size += len(data)
583 self._process_write_backlog()
584
585 def _start_handshake(self):
586 if self._loop.get_debug():
587 logger.debug("%r starts SSL handshake", self)
588 self._handshake_start_time = self._loop.time()
589 else:
590 self._handshake_start_time = None
591 self._in_handshake = True
592 # (b'', 1) is a special value in _process_write_backlog() to do
593 # the SSL handshake
594 self._write_backlog.append((b'', 1))
595 self._loop.call_soon(self._process_write_backlog)
Neil Aspinallf7686c12017-12-19 19:45:42 +0000596 self._handshake_timeout_handle = \
597 self._loop.call_later(self._ssl_handshake_timeout,
598 self._check_handshake_timeout)
599
600 def _check_handshake_timeout(self):
601 if self._in_handshake is True:
602 logger.warning("%r stalled during handshake", self)
603 self._abort()
Victor Stinner231b4042015-01-14 00:19:09 +0100604
605 def _on_handshake_complete(self, handshake_exc):
606 self._in_handshake = False
Neil Aspinallf7686c12017-12-19 19:45:42 +0000607 self._handshake_timeout_handle.cancel()
Victor Stinner231b4042015-01-14 00:19:09 +0100608
609 sslobj = self._sslpipe.ssl_object
Victor Stinner231b4042015-01-14 00:19:09 +0100610 try:
611 if handshake_exc is not None:
612 raise handshake_exc
Victor Stinner177e9f02015-01-14 16:56:20 +0100613
614 peercert = sslobj.getpeercert()
Victor Stinner231b4042015-01-14 00:19:09 +0100615 except BaseException as exc:
616 if self._loop.get_debug():
617 if isinstance(exc, ssl.CertificateError):
618 logger.warning("%r: SSL handshake failed "
619 "on verifying the certificate",
620 self, exc_info=True)
621 else:
622 logger.warning("%r: SSL handshake failed",
623 self, exc_info=True)
624 self._transport.close()
625 if isinstance(exc, Exception):
Victor Stinnerf07801b2015-01-29 00:36:35 +0100626 self._wakeup_waiter(exc)
Victor Stinner231b4042015-01-14 00:19:09 +0100627 return
628 else:
629 raise
630
631 if self._loop.get_debug():
632 dt = self._loop.time() - self._handshake_start_time
633 logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3)
634
635 # Add extra info that becomes available after handshake.
636 self._extra.update(peercert=peercert,
637 cipher=sslobj.cipher(),
638 compression=sslobj.compression(),
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200639 ssl_object=sslobj,
Victor Stinner231b4042015-01-14 00:19:09 +0100640 )
Yury Selivanov92e7c7f2016-10-05 19:39:54 -0400641 if self._call_connection_made:
642 self._app_protocol.connection_made(self._app_transport)
Victor Stinnerf07801b2015-01-29 00:36:35 +0100643 self._wakeup_waiter()
Victor Stinner231b4042015-01-14 00:19:09 +0100644 self._session_established = True
Victor Stinner042dad72015-01-15 09:41:48 +0100645 # In case transport.write() was already called. Don't call
Martin Panter46f50722016-05-26 05:35:26 +0000646 # immediately _process_write_backlog(), but schedule it:
Victor Stinner042dad72015-01-15 09:41:48 +0100647 # _on_handshake_complete() can be called indirectly from
648 # _process_write_backlog(), and _process_write_backlog() is not
649 # reentrant.
Victor Stinner72bdefb2015-01-15 09:44:13 +0100650 self._loop.call_soon(self._process_write_backlog)
Victor Stinner231b4042015-01-14 00:19:09 +0100651
652 def _process_write_backlog(self):
653 # Try to make progress on the write backlog.
Miss Islington (bot)bf0d1162018-03-10 08:27:01 -0800654 if self._transport is None or self._sslpipe is None:
Victor Stinner231b4042015-01-14 00:19:09 +0100655 return
656
657 try:
658 for i in range(len(self._write_backlog)):
659 data, offset = self._write_backlog[0]
660 if data:
661 ssldata, offset = self._sslpipe.feed_appdata(data, offset)
662 elif offset:
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400663 ssldata = self._sslpipe.do_handshake(
664 self._on_handshake_complete)
Victor Stinner231b4042015-01-14 00:19:09 +0100665 offset = 1
666 else:
667 ssldata = self._sslpipe.shutdown(self._finalize)
668 offset = 1
669
670 for chunk in ssldata:
671 self._transport.write(chunk)
672
673 if offset < len(data):
674 self._write_backlog[0] = (data, offset)
675 # A short write means that a write is blocked on a read
676 # We need to enable reading if it is paused!
677 assert self._sslpipe.need_ssldata
678 if self._transport._paused:
679 self._transport.resume_reading()
680 break
681
682 # An entire chunk from the backlog was processed. We can
683 # delete it and reduce the outstanding buffer size.
684 del self._write_backlog[0]
685 self._write_buffer_size -= len(data)
686 except BaseException as exc:
687 if self._in_handshake:
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400688 # BaseExceptions will be re-raised in _on_handshake_complete.
Victor Stinner231b4042015-01-14 00:19:09 +0100689 self._on_handshake_complete(exc)
690 else:
691 self._fatal_error(exc, 'Fatal error on SSL transport')
Yury Selivanov8c125eb2015-08-05 14:06:23 -0400692 if not isinstance(exc, Exception):
693 # BaseException
694 raise
Victor Stinner231b4042015-01-14 00:19:09 +0100695
696 def _fatal_error(self, exc, message='Fatal error on transport'):
697 # Should be called from exception handler only.
Victor Stinnerc94a93a2016-04-01 21:43:39 +0200698 if isinstance(exc, base_events._FATAL_ERROR_IGNORE):
Victor Stinner231b4042015-01-14 00:19:09 +0100699 if self._loop.get_debug():
700 logger.debug("%r: %s", self, message, exc_info=True)
701 else:
702 self._loop.call_exception_handler({
703 'message': message,
704 'exception': exc,
705 'transport': self._transport,
706 'protocol': self,
707 })
708 if self._transport:
709 self._transport._force_close(exc)
710
711 def _finalize(self):
Michaël Sghaïerd1f57512017-06-09 18:29:46 -0400712 self._sslpipe = None
713
Victor Stinner231b4042015-01-14 00:19:09 +0100714 if self._transport is not None:
715 self._transport.close()
716
717 def _abort(self):
Michaël Sghaïerd1f57512017-06-09 18:29:46 -0400718 try:
719 if self._transport is not None:
Victor Stinner231b4042015-01-14 00:19:09 +0100720 self._transport.abort()
Michaël Sghaïerd1f57512017-06-09 18:29:46 -0400721 finally:
722 self._finalize()
Miss Islington (bot)bc3a0022018-05-28 11:50:45 -0700723
724
725def _feed_data_to_bufferred_proto(proto, data):
726 data_len = len(data)
727 while data_len:
728 buf = proto.get_buffer(data_len)
729 buf_len = len(buf)
730 if not buf_len:
731 raise RuntimeError('get_buffer() returned an empty buffer')
732
733 if buf_len >= data_len:
734 buf[:data_len] = data
735 proto.buffer_updated(data_len)
736 return
737 else:
738 buf[:buf_len] = data[:buf_len]
739 proto.buffer_updated(buf_len)
740 data = data[buf_len:]
741 data_len = len(data)