API-compatibility wrapper for Python OpenSSL's Connection-class.
| 271 | |
| 272 | |
| 273 | class WrappedSocket: |
| 274 | """API-compatibility wrapper for Python OpenSSL's Connection-class.""" |
| 275 | |
| 276 | def __init__( |
| 277 | self, |
| 278 | connection: OpenSSL.SSL.Connection, |
| 279 | socket: socket_cls, |
| 280 | suppress_ragged_eofs: bool = True, |
| 281 | ) -> None: |
| 282 | self.connection = connection |
| 283 | self.socket = socket |
| 284 | self.suppress_ragged_eofs = suppress_ragged_eofs |
| 285 | self._io_refs = 0 |
| 286 | self._closed = False |
| 287 | |
| 288 | def fileno(self) -> int: |
| 289 | return self.socket.fileno() |
| 290 | |
| 291 | # Copy-pasted from Python 3.5 source code |
| 292 | def _decref_socketios(self) -> None: |
| 293 | if self._io_refs > 0: |
| 294 | self._io_refs -= 1 |
| 295 | if self._closed: |
| 296 | self.close() |
| 297 | |
| 298 | def recv(self, *args: typing.Any, **kwargs: typing.Any) -> bytes: |
| 299 | try: |
| 300 | data = self.connection.recv(*args, **kwargs) |
| 301 | except OpenSSL.SSL.SysCallError as e: |
| 302 | if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): |
| 303 | return b"" |
| 304 | else: |
| 305 | raise OSError(e.args[0], str(e)) from e |
| 306 | except OpenSSL.SSL.ZeroReturnError: |
| 307 | if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: |
| 308 | return b"" |
| 309 | else: |
| 310 | raise |
| 311 | except OpenSSL.SSL.WantReadError as e: |
| 312 | if not util.wait_for_read(self.socket, self.socket.gettimeout()): |
| 313 | raise TimeoutError("The read operation timed out") from e |
| 314 | else: |
| 315 | return self.recv(*args, **kwargs) |
| 316 | |
| 317 | # TLS 1.3 post-handshake authentication |
| 318 | except OpenSSL.SSL.Error as e: |
| 319 | raise ssl.SSLError(f"read error: {e!r}") from e |
| 320 | else: |
| 321 | return data # type: ignore[no-any-return] |
| 322 | |
| 323 | def recv_into(self, *args: typing.Any, **kwargs: typing.Any) -> int: |
| 324 | try: |
| 325 | return self.connection.recv_into(*args, **kwargs) # type: ignore[no-any-return] |
| 326 | except OpenSSL.SSL.SysCallError as e: |
| 327 | if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): |
| 328 | return 0 |
| 329 | else: |
| 330 | raise OSError(e.args[0], str(e)) from e |