| 105 | # https://github.com/pyca/pyopenssl/issues/176 |
| 106 | # https://docs.python.org/3/library/ssl.html#notes-on-non-blocking-sockets |
| 107 | class _sslConn(_SSL.Connection): |
| 108 | def __init__( |
| 109 | self, |
| 110 | ctx: _SSL.Context, |
| 111 | sock: Optional[_socket.socket], |
| 112 | suppress_ragged_eofs: bool, |
| 113 | ): |
| 114 | self.socket_checker = _SocketChecker() |
| 115 | self.suppress_ragged_eofs = suppress_ragged_eofs |
| 116 | super().__init__(ctx, sock) |
| 117 | |
| 118 | def _call(self, call: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: |
| 119 | timeout = self.gettimeout() |
| 120 | if timeout: |
| 121 | start = _time.monotonic() |
| 122 | while True: |
| 123 | try: |
| 124 | return call(*args, **kwargs) |
| 125 | except BLOCKING_IO_ERRORS as exc: |
| 126 | # Do not retry if the connection is in non-blocking mode. |
| 127 | if timeout == 0: |
| 128 | raise exc |
| 129 | # Check for closed socket. |
| 130 | if self.fileno() == -1: |
| 131 | if timeout and _time.monotonic() - start > timeout: |
| 132 | raise _socket.timeout("timed out") from None |
| 133 | raise SSLError("Underlying socket has been closed") from None |
| 134 | if isinstance(exc, _SSL.WantReadError): |
| 135 | want_read = True |
| 136 | want_write = False |
| 137 | elif isinstance(exc, _SSL.WantWriteError): |
| 138 | want_read = False |
| 139 | want_write = True |
| 140 | else: |
| 141 | want_read = True |
| 142 | want_write = True |
| 143 | self.socket_checker.select(self, want_read, want_write, timeout) |
| 144 | if timeout and _time.monotonic() - start > timeout: |
| 145 | raise _socket.timeout("timed out") from None |
| 146 | continue |
| 147 | |
| 148 | def do_handshake(self, *args: Any, **kwargs: Any) -> None: |
| 149 | return self._call(super().do_handshake, *args, **kwargs) |
| 150 | |
| 151 | def recv(self, *args: Any, **kwargs: Any) -> bytes: |
| 152 | try: |
| 153 | return self._call(super().recv, *args, **kwargs) |
| 154 | except _SSL.SysCallError as exc: |
| 155 | # Suppress ragged EOFs to match the stdlib. |
| 156 | if self.suppress_ragged_eofs and _ragged_eof(exc): |
| 157 | return b"" |
| 158 | raise |
| 159 | |
| 160 | def recv_into(self, *args: Any, **kwargs: Any) -> int: |
| 161 | try: |
| 162 | return self._call(super().recv_into, *args, **kwargs) |
| 163 | except _SSL.SysCallError as exc: |
| 164 | # Suppress ragged EOFs to match the stdlib. |