Debian Codegraph @

lib-python/3/asyncio/sslproto.py

raw symbols SCIP
1 # Contains code from https://github.com/MagicStack/uvloop/tree/v0.16.0
2 # SPDX-License-Identifier: PSF-2.0 AND (MIT OR Apache-2.0)
3 # SPDX-FileCopyrightText: Copyright (c) 2015-2021 MagicStack Inc. http://magic.io
4
5 import collections
6 import enum
7 import warnings
8 try:
9 import ssl
10 except ImportError: # pragma: no cover
11 ssl = None
12
13 from . import constants
14 from . import exceptions
15 from . import protocols
16 from . import transports
17 from .log import logger
18
19 if ssl is not None:
20 SSLAgainErrors = (ssl.SSLWantReadError, ssl.SSLSyscallError)
21
22
23 class SSLProtocolState(enum.Enum):
24 UNWRAPPED = "UNWRAPPED"
25 DO_HANDSHAKE = "DO_HANDSHAKE"
26 WRAPPED = "WRAPPED"
27 FLUSHING = "FLUSHING"
28 SHUTDOWN = "SHUTDOWN"
29
30
31 class AppProtocolState(enum.Enum):
32 # This tracks the state of app protocol (https://git.io/fj59P):
33 #
34 # INIT -cm-> CON_MADE [-dr*->] [-er-> EOF?] -cl-> CON_LOST
35 #
36 # * cm: connection_made()
37 # * dr: data_received()
38 # * er: eof_received()
39 # * cl: connection_lost()
40
41 STATE_INIT = "STATE_INIT"
42 STATE_CON_MADE = "STATE_CON_MADE"
43 STATE_EOF = "STATE_EOF"
44 STATE_CON_LOST = "STATE_CON_LOST"
45
46
47 def _create_transport_context(server_side, server_hostname):
48 if server_side:
49 raise ValueError('Server side SSL needs a valid SSLContext')
50
51 # Client side may pass ssl=True to use a default
52 # context; in that case the sslcontext passed is None.
53 # The default is secure for client connections.
54 # Python 3.4+: use up-to-date strong settings.
55 sslcontext = ssl.create_default_context()
56 if not server_hostname:
57 sslcontext.check_hostname = False
58 return sslcontext
59
60
61 def add_flowcontrol_defaults(high, low, kb):
62 if high is None:
63 if low is None:
64 hi = kb * 1024
65 else:
66 lo = low
67 hi = 4 * lo
68 else:
69 hi = high
70 if low is None:
71 lo = hi // 4
72 else:
73 lo = low
74
75 if not hi >= lo >= 0:
76 raise ValueError('high (%r) must be >= low (%r) must be >= 0' %
77 (hi, lo))
78
79 return hi, lo
80
81
82 class _SSLProtocolTransport(transports._FlowControlMixin,
83 transports.Transport):
84
85 _start_tls_compatible = True
86 _sendfile_compatible = constants._SendfileMode.FALLBACK
87
88 def __init__(self, loop, ssl_protocol):
89 self._loop = loop
90 self._ssl_protocol = ssl_protocol
91 self._closed = False
92
93 def get_extra_info(self, name, default=None):
94 """Get optional transport information."""
95 return self._ssl_protocol._get_extra_info(name, default)
96
97 def set_protocol(self, protocol):
98 self._ssl_protocol._set_app_protocol(protocol)
99
100 def get_protocol(self):
101 return self._ssl_protocol._app_protocol
102
103 def is_closing(self):
104 return self._closed
105
106 def close(self):
107 """Close the transport.
108
109 Buffered data will be flushed asynchronously. No more data
110 will be received. After all buffered data is flushed, the
111 protocol's connection_lost() method will (eventually) called
112 with None as its argument.
113 """
114 if not self._closed:
115 self._closed = True
116 self._ssl_protocol._start_shutdown()
117 else:
118 self._ssl_protocol = None
119
120 def __del__(self, _warnings=warnings):
121 if not self._closed:
122 self._closed = True
123 _warnings.warn(
124 "unclosed transport <asyncio._SSLProtocolTransport "
125 "object>", ResourceWarning)
126
127 def is_reading(self):
128 return not self._ssl_protocol._app_reading_paused
129
130 def pause_reading(self):
131 """Pause the receiving end.
132
133 No data will be passed to the protocol's data_received()
134 method until resume_reading() is called.
135 """
136 self._ssl_protocol._pause_reading()
137
138 def resume_reading(self):
139 """Resume the receiving end.
140
141 Data received will once again be passed to the protocol's
142 data_received() method.
143 """
144 self._ssl_protocol._resume_reading()
145
146 def set_write_buffer_limits(self, high=None, low=None):
147 """Set the high- and low-water limits for write flow control.
148
149 These two values control when to call the protocol's
150 pause_writing() and resume_writing() methods. If specified,
151 the low-water limit must be less than or equal to the
152 high-water limit. Neither value can be negative.
153
154 The defaults are implementation-specific. If only the
155 high-water limit is given, the low-water limit defaults to an
156 implementation-specific value less than or equal to the
157 high-water limit. Setting high to zero forces low to zero as
158 well, and causes pause_writing() to be called whenever the
159 buffer becomes non-empty. Setting low to zero causes
160 resume_writing() to be called only once the buffer is empty.
161 Use of zero for either limit is generally sub-optimal as it
162 reduces opportunities for doing I/O and computation
163 concurrently.
164 """
165 self._ssl_protocol._set_write_buffer_limits(high, low)
166 self._ssl_protocol._control_app_writing()
167
168 def get_write_buffer_limits(self):
169 return (self._ssl_protocol._outgoing_low_water,
170 self._ssl_protocol._outgoing_high_water)
171
172 def get_write_buffer_size(self):
173 """Return the current size of the write buffers."""
174 return self._ssl_protocol._get_write_buffer_size()
175
176 def set_read_buffer_limits(self, high=None, low=None):
177 """Set the high- and low-water limits for read flow control.
178
179 These two values control when to call the upstream transport's
180 pause_reading() and resume_reading() methods. If specified,
181 the low-water limit must be less than or equal to the
182 high-water limit. Neither value can be negative.
183
184 The defaults are implementation-specific. If only the
185 high-water limit is given, the low-water limit defaults to an
186 implementation-specific value less than or equal to the
187 high-water limit. Setting high to zero forces low to zero as
188 well, and causes pause_reading() to be called whenever the
189 buffer becomes non-empty. Setting low to zero causes
190 resume_reading() to be called only once the buffer is empty.
191 Use of zero for either limit is generally sub-optimal as it
192 reduces opportunities for doing I/O and computation
193 concurrently.
194 """
195 self._ssl_protocol._set_read_buffer_limits(high, low)
196 self._ssl_protocol._control_ssl_reading()
197
198 def get_read_buffer_limits(self):
199 return (self._ssl_protocol._incoming_low_water,
200 self._ssl_protocol._incoming_high_water)
201
202 def get_read_buffer_size(self):
203 """Return the current size of the read buffer."""
204 return self._ssl_protocol._get_read_buffer_size()
205
206 @property
207 def _protocol_paused(self):
208 # Required for sendfile fallback pause_writing/resume_writing logic
209 return self._ssl_protocol._app_writing_paused
210
211 def write(self, data):
212 """Write some data bytes to the transport.
213
214 This does not block; it buffers the data and arranges for it
215 to be sent out asynchronously.
216 """
217 if not isinstance(data, (bytes, bytearray, memoryview)):
218 raise TypeError(f"data: expecting a bytes-like instance, "
219 f"got {type(data).__name__}")
220 if not data:
221 return
222 self._ssl_protocol._write_appdata((data,))
223
224 def writelines(self, list_of_data):
225 """Write a list (or any iterable) of data bytes to the transport.
226
227 The default implementation concatenates the arguments and
228 calls write() on the result.
229 """
230 self._ssl_protocol._write_appdata(list_of_data)
231
232 def write_eof(self):
233 """Close the write end after flushing buffered data.
234
235 This raises :exc:`NotImplementedError` right now.
236 """
237 raise NotImplementedError
238
239 def can_write_eof(self):
240 """Return True if this transport supports write_eof(), False if not."""
241 return False
242
243 def abort(self):
244 """Close the transport immediately.
245
246 Buffered data will be lost. No more data will be received.
247 The protocol's connection_lost() method will (eventually) be
248 called with None as its argument.
249 """
250 self._force_close(None)
251
252 def _force_close(self, exc):
253 self._closed = True
254 if self._ssl_protocol is not None:
255 self._ssl_protocol._abort(exc)
256
257 def _test__append_write_backlog(self, data):
258 # for test only
259 self._ssl_protocol._write_backlog.append(data)
260 self._ssl_protocol._write_buffer_size += len(data)
261
262
263 class SSLProtocol(protocols.BufferedProtocol):
264 max_size = 256 * 1024 # Buffer size passed to read()
265
266 _handshake_start_time = None
267 _handshake_timeout_handle = None
268 _shutdown_timeout_handle = None
269
270 def __init__(self, loop, app_protocol, sslcontext, waiter,
271 server_side=False, server_hostname=None,
272 call_connection_made=True,
273 ssl_handshake_timeout=None,
274 ssl_shutdown_timeout=None):
275 if ssl is None:
276 raise RuntimeError("stdlib ssl module not available")
277
278 self._ssl_buffer = bytearray(self.max_size)
279 self._ssl_buffer_view = memoryview(self._ssl_buffer)
280
281 if ssl_handshake_timeout is None:
282 ssl_handshake_timeout = constants.SSL_HANDSHAKE_TIMEOUT
283 elif ssl_handshake_timeout <= 0:
284 raise ValueError(
285 f"ssl_handshake_timeout should be a positive number, "
286 f"got {ssl_handshake_timeout}")
287 if ssl_shutdown_timeout is None:
288 ssl_shutdown_timeout = constants.SSL_SHUTDOWN_TIMEOUT
289 elif ssl_shutdown_timeout <= 0:
290 raise ValueError(
291 f"ssl_shutdown_timeout should be a positive number, "
292 f"got {ssl_shutdown_timeout}")
293
294 if not sslcontext:
295 sslcontext = _create_transport_context(
296 server_side, server_hostname)
297
298 self._server_side = server_side
299 if server_hostname and not server_side:
300 self._server_hostname = server_hostname
301 else:
302 self._server_hostname = None
303 self._sslcontext = sslcontext
304 # SSL-specific extra info. More info are set when the handshake
305 # completes.
306 self._extra = dict(sslcontext=sslcontext)
307
308 # App data write buffering
309 self._write_backlog = collections.deque()
310 self._write_buffer_size = 0
311
312 self._waiter = waiter
313 self._loop = loop
314 self._set_app_protocol(app_protocol)
315 self._app_transport = None
316 self._app_transport_created = False
317 # transport, ex: SelectorSocketTransport
318 self._transport = None
319 self._ssl_handshake_timeout = ssl_handshake_timeout
320 self._ssl_shutdown_timeout = ssl_shutdown_timeout
321 # SSL and state machine
322 self._incoming = ssl.MemoryBIO()
323 self._outgoing = ssl.MemoryBIO()
324 self._state = SSLProtocolState.UNWRAPPED
325 self._conn_lost = 0 # Set when connection_lost called
326 if call_connection_made:
327 self._app_state = AppProtocolState.STATE_INIT
328 else:
329 self._app_state = AppProtocolState.STATE_CON_MADE
330 self._sslobj = self._sslcontext.wrap_bio(
331 self._incoming, self._outgoing,
332 server_side=self._server_side,
333 server_hostname=self._server_hostname)
334
335 # Flow Control
336
337 self._ssl_writing_paused = False
338
339 self._app_reading_paused = False
340
341 self._ssl_reading_paused = False
342 self._incoming_high_water = 0
343 self._incoming_low_water = 0
344 self._set_read_buffer_limits()
345 self._eof_received = False
346
347 self._app_writing_paused = False
348 self._outgoing_high_water = 0
349 self._outgoing_low_water = 0
350 self._set_write_buffer_limits()
351 self._get_app_transport()
352
353 def _set_app_protocol(self, app_protocol):
354 self._app_protocol = app_protocol
355 # Make fast hasattr check first
356 if (hasattr(app_protocol, 'get_buffer') and
357 isinstance(app_protocol, protocols.BufferedProtocol)):
358 self._app_protocol_get_buffer = app_protocol.get_buffer
359 self._app_protocol_buffer_updated = app_protocol.buffer_updated
360 self._app_protocol_is_buffer = True
361 else:
362 self._app_protocol_is_buffer = False
363
364 def _wakeup_waiter(self, exc=None):
365 if self._waiter is None:
366 return
367 if not self._waiter.cancelled():
368 if exc is not None:
369 self._waiter.set_exception(exc)
370 else:
371 self._waiter.set_result(None)
372 self._waiter = None
373
374 def _get_app_transport(self):
375 if self._app_transport is None:
376 if self._app_transport_created:
377 raise RuntimeError('Creating _SSLProtocolTransport twice')
378 self._app_transport = _SSLProtocolTransport(self._loop, self)
379 self._app_transport_created = True
380 return self._app_transport
381
382 def connection_made(self, transport):
383 """Called when the low-level connection is made.
384
385 Start the SSL handshake.
386 """
387 self._transport = transport
388 self._start_handshake()
389
390 def connection_lost(self, exc):
391 """Called when the low-level connection is lost or closed.
392
393 The argument is an exception object or None (the latter
394 meaning a regular EOF is received or the connection was
395 aborted or closed).
396 """
397 self._write_backlog.clear()
398 self._outgoing.read()
399 self._conn_lost += 1
400
401 # Just mark the app transport as closed so that its __dealloc__
402 # doesn't complain.
403 if self._app_transport is not None:
404 self._app_transport._closed = True
405
406 if self._state != SSLProtocolState.DO_HANDSHAKE:
407 if (
408 self._app_state == AppProtocolState.STATE_CON_MADE or
409 self._app_state == AppProtocolState.STATE_EOF
410 ):
411 self._app_state = AppProtocolState.STATE_CON_LOST
412 self._loop.call_soon(self._app_protocol.connection_lost, exc)
413 self._set_state(SSLProtocolState.UNWRAPPED)
414 self._transport = None
415 self._app_transport = None
416 self._app_protocol = None
417 self._wakeup_waiter(exc)
418
419 if self._shutdown_timeout_handle:
420 self._shutdown_timeout_handle.cancel()
421 self._shutdown_timeout_handle = None
422 if self._handshake_timeout_handle:
423 self._handshake_timeout_handle.cancel()
424 self._handshake_timeout_handle = None
425
426 def get_buffer(self, n):
427 want = n
428 if want <= 0 or want > self.max_size:
429 want = self.max_size
430 if len(self._ssl_buffer) < want:
431 self._ssl_buffer = bytearray(want)
432 self._ssl_buffer_view = memoryview(self._ssl_buffer)
433 return self._ssl_buffer_view
434
435 def buffer_updated(self, nbytes):
436 self._incoming.write(self._ssl_buffer_view[:nbytes])
437
438 if self._state == SSLProtocolState.DO_HANDSHAKE:
439 self._do_handshake()
440
441 elif self._state == SSLProtocolState.WRAPPED:
442 self._do_read()
443
444 elif self._state == SSLProtocolState.FLUSHING:
445 self._do_flush()
446
447 elif self._state == SSLProtocolState.SHUTDOWN:
448 self._do_shutdown()
449
450 def eof_received(self):
451 """Called when the other end of the low-level stream
452 is half-closed.
453
454 If this returns a false value (including None), the transport
455 will close itself. If it returns a true value, closing the
456 transport is up to the protocol.
457 """
458 self._eof_received = True
459 try:
460 if self._loop.get_debug():
461 logger.debug("%r received EOF", self)
462
463 if self._state == SSLProtocolState.DO_HANDSHAKE:
464 self._on_handshake_complete(ConnectionResetError)
465
466 elif self._state == SSLProtocolState.WRAPPED:
467 self._set_state(SSLProtocolState.FLUSHING)
468 if self._app_reading_paused:
469 return True
470 else:
471 self._do_flush()
472
473 elif self._state == SSLProtocolState.FLUSHING:
474 self._do_write()
475 self._set_state(SSLProtocolState.SHUTDOWN)
476 self._do_shutdown()
477
478 elif self._state == SSLProtocolState.SHUTDOWN:
479 self._do_shutdown()
480
481 except Exception:
482 self._transport.close()
483 raise
484
485 def _get_extra_info(self, name, default=None):
486 if name in self._extra:
487 return self._extra[name]
488 elif self._transport is not None:
489 return self._transport.get_extra_info(name, default)
490 else:
491 return default
492
493 def _set_state(self, new_state):
494 allowed = False
495
496 if new_state == SSLProtocolState.UNWRAPPED:
497 allowed = True
498
499 elif (
500 self._state == SSLProtocolState.UNWRAPPED and
501 new_state == SSLProtocolState.DO_HANDSHAKE
502 ):
503 allowed = True
504
505 elif (
506 self._state == SSLProtocolState.DO_HANDSHAKE and
507 new_state == SSLProtocolState.WRAPPED
508 ):
509 allowed = True
510
511 elif (
512 self._state == SSLProtocolState.WRAPPED and
513 new_state == SSLProtocolState.FLUSHING
514 ):
515 allowed = True
516
517 elif (
518 self._state == SSLProtocolState.FLUSHING and
519 new_state == SSLProtocolState.SHUTDOWN
520 ):
521 allowed = True
522
523 if allowed:
524 self._state = new_state
525
526 else:
527 raise RuntimeError(
528 'cannot switch state from {} to {}'.format(
529 self._state, new_state))
530
531 # Handshake flow
532
533 def _start_handshake(self):
534 if self._loop.get_debug():
535 logger.debug("%r starts SSL handshake", self)
536 self._handshake_start_time = self._loop.time()
537 else:
538 self._handshake_start_time = None
539
540 self._set_state(SSLProtocolState.DO_HANDSHAKE)
541
542 # start handshake timeout count down
543 self._handshake_timeout_handle = \
544 self._loop.call_later(self._ssl_handshake_timeout,
545 lambda: self._check_handshake_timeout())
546
547 self._do_handshake()
548
549 def _check_handshake_timeout(self):
550 if self._state == SSLProtocolState.DO_HANDSHAKE:
551 msg = (
552 f"SSL handshake is taking longer than "
553 f"{self._ssl_handshake_timeout} seconds: "
554 f"aborting the connection"
555 )
556 self._fatal_error(ConnectionAbortedError(msg))
557
558 def _do_handshake(self):
559 try:
560 self._sslobj.do_handshake()
561 except SSLAgainErrors:
562 self._process_outgoing()
563 except ssl.SSLError as exc:
564 self._on_handshake_complete(exc)
565 else:
566 self._on_handshake_complete(None)
567
568 def _on_handshake_complete(self, handshake_exc):
569 if self._handshake_timeout_handle is not None:
570 self._handshake_timeout_handle.cancel()
571 self._handshake_timeout_handle = None
572
573 sslobj = self._sslobj
574 try:
575 if handshake_exc is None:
576 self._set_state(SSLProtocolState.WRAPPED)
577 else:
578 raise handshake_exc
579
580 peercert = sslobj.getpeercert()
581 except Exception as exc:
582 handshake_exc = None
583 self._set_state(SSLProtocolState.UNWRAPPED)
584 if isinstance(exc, ssl.CertificateError):
585 msg = 'SSL handshake failed on verifying the certificate'
586 else:
587 msg = 'SSL handshake failed'
588 self._fatal_error(exc, msg)
589 self._wakeup_waiter(exc)
590 return
591
592 if self._loop.get_debug():
593 dt = self._loop.time() - self._handshake_start_time
594 logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3)
595
596 # Add extra info that becomes available after handshake.
597 self._extra.update(peercert=peercert,
598 cipher=sslobj.cipher(),
599 compression=sslobj.compression(),
600 ssl_object=sslobj)
601 if self._app_state == AppProtocolState.STATE_INIT:
602 self._app_state = AppProtocolState.STATE_CON_MADE
603 self._app_protocol.connection_made(self._get_app_transport())
604 self._wakeup_waiter()
605 self._do_read()
606
607 # Shutdown flow
608
609 def _start_shutdown(self):
610 if (
611 self._state in (
612 SSLProtocolState.FLUSHING,
613 SSLProtocolState.SHUTDOWN,
614 SSLProtocolState.UNWRAPPED
615 )
616 ):
617 return
618 if self._app_transport is not None:
619 self._app_transport._closed = True
620 if self._state == SSLProtocolState.DO_HANDSHAKE:
621 self._abort(None)
622 else:
623 self._set_state(SSLProtocolState.FLUSHING)
624 self._shutdown_timeout_handle = self._loop.call_later(
625 self._ssl_shutdown_timeout,
626 lambda: self._check_shutdown_timeout()
627 )
628 self._do_flush()
629
630 def _check_shutdown_timeout(self):
631 if (
632 self._state in (
633 SSLProtocolState.FLUSHING,
634 SSLProtocolState.SHUTDOWN
635 )
636 ):
637 self._transport._force_close(
638 exceptions.TimeoutError('SSL shutdown timed out'))
639
640 def _do_flush(self):
641 self._do_read()
642 self._set_state(SSLProtocolState.SHUTDOWN)
643 self._do_shutdown()
644
645 def _do_shutdown(self):
646 try:
647 if not self._eof_received:
648 self._sslobj.unwrap()
649 except SSLAgainErrors:
650 self._process_outgoing()
651 except ssl.SSLError as exc:
652 self._on_shutdown_complete(exc)
653 else:
654 self._process_outgoing()
655 self._call_eof_received()
656 self._on_shutdown_complete(None)
657
658 def _on_shutdown_complete(self, shutdown_exc):
659 if self._shutdown_timeout_handle is not None:
660 self._shutdown_timeout_handle.cancel()
661 self._shutdown_timeout_handle = None
662
663 if shutdown_exc:
664 self._fatal_error(shutdown_exc)
665 else:
666 self._loop.call_soon(self._transport.close)
667
668 def _abort(self, exc):
669 self._set_state(SSLProtocolState.UNWRAPPED)
670 if self._transport is not None:
671 self._transport._force_close(exc)
672
673 # Outgoing flow
674
675 def _write_appdata(self, list_of_data):
676 if (
677 self._state in (
678 SSLProtocolState.FLUSHING,
679 SSLProtocolState.SHUTDOWN,
680 SSLProtocolState.UNWRAPPED
681 )
682 ):
683 if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
684 logger.warning('SSL connection is closed')
685 self._conn_lost += 1
686 return
687
688 for data in list_of_data:
689 self._write_backlog.append(data)
690 self._write_buffer_size += len(data)
691
692 try:
693 if self._state == SSLProtocolState.WRAPPED:
694 self._do_write()
695
696 except Exception as ex:
697 self._fatal_error(ex, 'Fatal error on SSL protocol')
698
699 def _do_write(self):
700 try:
701 while self._write_backlog:
702 data = self._write_backlog[0]
703 count = self._sslobj.write(data)
704 data_len = len(data)
705 if count < data_len:
706 self._write_backlog[0] = data[count:]
707 self._write_buffer_size -= count
708 else:
709 del self._write_backlog[0]
710 self._write_buffer_size -= data_len
711 except SSLAgainErrors:
712 pass
713 self._process_outgoing()
714
715 def _process_outgoing(self):
716 if not self._ssl_writing_paused:
717 data = self._outgoing.read()
718 if len(data):
719 self._transport.write(data)
720 self._control_app_writing()
721
722 # Incoming flow
723
724 def _do_read(self):
725 if (
726 self._state not in (
727 SSLProtocolState.WRAPPED,
728 SSLProtocolState.FLUSHING,
729 )
730 ):
731 return
732 try:
733 if not self._app_reading_paused:
734 if self._app_protocol_is_buffer:
735 self._do_read__buffered()
736 else:
737 self._do_read__copied()
738 if self._write_backlog:
739 self._do_write()
740 else:
741 self._process_outgoing()
742 self._control_ssl_reading()
743 except Exception as ex:
744 self._fatal_error(ex, 'Fatal error on SSL protocol')
745
746 def _do_read__buffered(self):
747 offset = 0
748 count = 1
749
750 buf = self._app_protocol_get_buffer(self._get_read_buffer_size())
751 wants = len(buf)
752
753 try:
754 count = self._sslobj.read(wants, buf)
755
756 if count > 0:
757 offset = count
758 while offset < wants:
759 count = self._sslobj.read(wants - offset, buf[offset:])
760 if count > 0:
761 offset += count
762 else:
763 break
764 else:
765 self._loop.call_soon(lambda: self._do_read())
766 except SSLAgainErrors:
767 pass
768 if offset > 0:
769 self._app_protocol_buffer_updated(offset)
770 if not count:
771 # close_notify
772 self._call_eof_received()
773 self._start_shutdown()
774
775 def _do_read__copied(self):
776 chunk = b'1'
777 zero = True
778 one = False
779
780 try:
781 while True:
782 chunk = self._sslobj.read(self.max_size)
783 if not chunk:
784 break
785 if zero:
786 zero = False
787 one = True
788 first = chunk
789 elif one:
790 one = False
791 data = [first, chunk]
792 else:
793 data.append(chunk)
794 except SSLAgainErrors:
795 pass
796 if one:
797 self._app_protocol.data_received(first)
798 elif not zero:
799 self._app_protocol.data_received(b''.join(data))
800 if not chunk:
801 # close_notify
802 self._call_eof_received()
803 self._start_shutdown()
804
805 def _call_eof_received(self):
806 try:
807 if self._app_state == AppProtocolState.STATE_CON_MADE:
808 self._app_state = AppProtocolState.STATE_EOF
809 keep_open = self._app_protocol.eof_received()
810 if keep_open:
811 logger.warning('returning true from eof_received() '
812 'has no effect when using ssl')
813 except (KeyboardInterrupt, SystemExit):
814 raise
815 except BaseException as ex:
816 self._fatal_error(ex, 'Error calling eof_received()')
817
818 # Flow control for writes from APP socket
819
820 def _control_app_writing(self):
821 size = self._get_write_buffer_size()
822 if size >= self._outgoing_high_water and not self._app_writing_paused:
823 self._app_writing_paused = True
824 try:
825 self._app_protocol.pause_writing()
826 except (KeyboardInterrupt, SystemExit):
827 raise
828 except BaseException as exc:
829 self._loop.call_exception_handler({
830 'message': 'protocol.pause_writing() failed',
831 'exception': exc,
832 'transport': self._app_transport,
833 'protocol': self,
834 })
835 elif size <= self._outgoing_low_water and self._app_writing_paused:
836 self._app_writing_paused = False
837 try:
838 self._app_protocol.resume_writing()
839 except (KeyboardInterrupt, SystemExit):
840 raise
841 except BaseException as exc:
842 self._loop.call_exception_handler({
843 'message': 'protocol.resume_writing() failed',
844 'exception': exc,
845 'transport': self._app_transport,
846 'protocol': self,
847 })
848
849 def _get_write_buffer_size(self):
850 return self._outgoing.pending + self._write_buffer_size
851
852 def _set_write_buffer_limits(self, high=None, low=None):
853 high, low = add_flowcontrol_defaults(
854 high, low, constants.FLOW_CONTROL_HIGH_WATER_SSL_WRITE)
855 self._outgoing_high_water = high
856 self._outgoing_low_water = low
857
858 # Flow control for reads to APP socket
859
860 def _pause_reading(self):
861 self._app_reading_paused = True
862
863 def _resume_reading(self):
864 if self._app_reading_paused:
865 self._app_reading_paused = False
866
867 def resume():
868 if self._state == SSLProtocolState.WRAPPED:
869 self._do_read()
870 elif self._state == SSLProtocolState.FLUSHING:
871 self._do_flush()
872 elif self._state == SSLProtocolState.SHUTDOWN:
873 self._do_shutdown()
874 self._loop.call_soon(resume)
875
876 # Flow control for reads from SSL socket
877
878 def _control_ssl_reading(self):
879 size = self._get_read_buffer_size()
880 if size >= self._incoming_high_water and not self._ssl_reading_paused:
881 self._ssl_reading_paused = True
882 self._transport.pause_reading()
883 elif size <= self._incoming_low_water and self._ssl_reading_paused:
884 self._ssl_reading_paused = False
885 self._transport.resume_reading()
886
887 def _set_read_buffer_limits(self, high=None, low=None):
888 high, low = add_flowcontrol_defaults(
889 high, low, constants.FLOW_CONTROL_HIGH_WATER_SSL_READ)
890 self._incoming_high_water = high
891 self._incoming_low_water = low
892
893 def _get_read_buffer_size(self):
894 return self._incoming.pending
895
896 # Flow control for writes to SSL socket
897
898 def pause_writing(self):
899 """Called when the low-level transport's buffer goes over
900 the high-water mark.
901 """
902 assert not self._ssl_writing_paused
903 self._ssl_writing_paused = True
904
905 def resume_writing(self):
906 """Called when the low-level transport's buffer drains below
907 the low-water mark.
908 """
909 assert self._ssl_writing_paused
910 self._ssl_writing_paused = False
911 self._process_outgoing()
912
913 def _fatal_error(self, exc, message='Fatal error on transport'):
914 if self._transport:
915 self._transport._force_close(exc)
916
917 if isinstance(exc, OSError):
918 if self._loop.get_debug():
919 logger.debug("%r: %s", self, message, exc_info=True)
920 elif not isinstance(exc, exceptions.CancelledError):
921 self._loop.call_exception_handler({
922 'message': message,
923 'exception': exc,
924 'transport': self._transport,
925 'protocol': self,
926 })