2023-09-17 19:52:08 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2023-01-12 01:04:47 +00:00
|
|
|
import io
|
|
|
|
import socket
|
|
|
|
import ssl
|
2023-09-17 19:52:08 +00:00
|
|
|
import typing
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
from ..exceptions import ProxySchemeUnsupported
|
2023-09-17 19:52:08 +00:00
|
|
|
|
|
|
|
if typing.TYPE_CHECKING:
|
|
|
|
from typing_extensions import Literal
|
|
|
|
|
|
|
|
from .ssl_ import _TYPE_PEER_CERT_RET, _TYPE_PEER_CERT_RET_DICT
|
|
|
|
|
|
|
|
|
|
|
|
_SelfT = typing.TypeVar("_SelfT", bound="SSLTransport")
|
|
|
|
_WriteBuffer = typing.Union[bytearray, memoryview]
|
|
|
|
_ReturnValue = typing.TypeVar("_ReturnValue")
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
SSL_BLOCKSIZE = 16384
|
|
|
|
|
|
|
|
|
|
|
|
class SSLTransport:
|
|
|
|
"""
|
|
|
|
The SSLTransport wraps an existing socket and establishes an SSL connection.
|
|
|
|
|
|
|
|
Contrary to Python's implementation of SSLSocket, it allows you to chain
|
|
|
|
multiple TLS connections together. It's particularly useful if you need to
|
|
|
|
implement TLS within TLS.
|
|
|
|
|
|
|
|
The class supports most of the socket API operations.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@staticmethod
|
2023-09-17 19:52:08 +00:00
|
|
|
def _validate_ssl_context_for_tls_in_tls(ssl_context: ssl.SSLContext) -> None:
|
2023-01-12 01:04:47 +00:00
|
|
|
"""
|
|
|
|
Raises a ProxySchemeUnsupported if the provided ssl_context can't be used
|
|
|
|
for TLS in TLS.
|
|
|
|
|
|
|
|
The only requirement is that the ssl_context provides the 'wrap_bio'
|
|
|
|
methods.
|
|
|
|
"""
|
|
|
|
|
|
|
|
if not hasattr(ssl_context, "wrap_bio"):
|
2023-09-17 19:52:08 +00:00
|
|
|
raise ProxySchemeUnsupported(
|
|
|
|
"TLS in TLS requires SSLContext.wrap_bio() which isn't "
|
|
|
|
"available on non-native SSLContext"
|
|
|
|
)
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
def __init__(
|
2023-09-17 19:52:08 +00:00
|
|
|
self,
|
|
|
|
socket: socket.socket,
|
|
|
|
ssl_context: ssl.SSLContext,
|
|
|
|
server_hostname: str | None = None,
|
|
|
|
suppress_ragged_eofs: bool = True,
|
|
|
|
) -> None:
|
2023-01-12 01:04:47 +00:00
|
|
|
"""
|
|
|
|
Create an SSLTransport around socket using the provided ssl_context.
|
|
|
|
"""
|
|
|
|
self.incoming = ssl.MemoryBIO()
|
|
|
|
self.outgoing = ssl.MemoryBIO()
|
|
|
|
|
|
|
|
self.suppress_ragged_eofs = suppress_ragged_eofs
|
|
|
|
self.socket = socket
|
|
|
|
|
|
|
|
self.sslobj = ssl_context.wrap_bio(
|
|
|
|
self.incoming, self.outgoing, server_hostname=server_hostname
|
|
|
|
)
|
|
|
|
|
|
|
|
# Perform initial handshake.
|
|
|
|
self._ssl_io_loop(self.sslobj.do_handshake)
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def __enter__(self: _SelfT) -> _SelfT:
|
2023-01-12 01:04:47 +00:00
|
|
|
return self
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def __exit__(self, *_: typing.Any) -> None:
|
2023-01-12 01:04:47 +00:00
|
|
|
self.close()
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def fileno(self) -> int:
|
2023-01-12 01:04:47 +00:00
|
|
|
return self.socket.fileno()
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def read(self, len: int = 1024, buffer: typing.Any | None = None) -> int | bytes:
|
2023-01-12 01:04:47 +00:00
|
|
|
return self._wrap_ssl_read(len, buffer)
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def recv(self, buflen: int = 1024, flags: int = 0) -> int | bytes:
|
2023-01-12 01:04:47 +00:00
|
|
|
if flags != 0:
|
|
|
|
raise ValueError("non-zero flags not allowed in calls to recv")
|
2023-09-17 19:52:08 +00:00
|
|
|
return self._wrap_ssl_read(buflen)
|
|
|
|
|
|
|
|
def recv_into(
|
|
|
|
self,
|
|
|
|
buffer: _WriteBuffer,
|
|
|
|
nbytes: int | None = None,
|
|
|
|
flags: int = 0,
|
|
|
|
) -> None | int | bytes:
|
2023-01-12 01:04:47 +00:00
|
|
|
if flags != 0:
|
|
|
|
raise ValueError("non-zero flags not allowed in calls to recv_into")
|
2023-09-17 19:52:08 +00:00
|
|
|
if nbytes is None:
|
2023-01-12 01:04:47 +00:00
|
|
|
nbytes = len(buffer)
|
|
|
|
return self.read(nbytes, buffer)
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def sendall(self, data: bytes, flags: int = 0) -> None:
|
2023-01-12 01:04:47 +00:00
|
|
|
if flags != 0:
|
|
|
|
raise ValueError("non-zero flags not allowed in calls to sendall")
|
|
|
|
count = 0
|
|
|
|
with memoryview(data) as view, view.cast("B") as byte_view:
|
|
|
|
amount = len(byte_view)
|
|
|
|
while count < amount:
|
|
|
|
v = self.send(byte_view[count:])
|
|
|
|
count += v
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def send(self, data: bytes, flags: int = 0) -> int:
|
2023-01-12 01:04:47 +00:00
|
|
|
if flags != 0:
|
|
|
|
raise ValueError("non-zero flags not allowed in calls to send")
|
2023-09-17 19:52:08 +00:00
|
|
|
return self._ssl_io_loop(self.sslobj.write, data)
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
def makefile(
|
2023-09-17 19:52:08 +00:00
|
|
|
self,
|
|
|
|
mode: str,
|
|
|
|
buffering: int | None = None,
|
|
|
|
*,
|
|
|
|
encoding: str | None = None,
|
|
|
|
errors: str | None = None,
|
|
|
|
newline: str | None = None,
|
|
|
|
) -> typing.BinaryIO | typing.TextIO | socket.SocketIO:
|
2023-01-12 01:04:47 +00:00
|
|
|
"""
|
|
|
|
Python's httpclient uses makefile and buffered io when reading HTTP
|
|
|
|
messages and we need to support it.
|
|
|
|
|
|
|
|
This is unfortunately a copy and paste of socket.py makefile with small
|
|
|
|
changes to point to the socket directly.
|
|
|
|
"""
|
|
|
|
if not set(mode) <= {"r", "w", "b"}:
|
2023-09-17 19:52:08 +00:00
|
|
|
raise ValueError(f"invalid mode {mode!r} (only r, w, b allowed)")
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
writing = "w" in mode
|
|
|
|
reading = "r" in mode or not writing
|
|
|
|
assert reading or writing
|
|
|
|
binary = "b" in mode
|
|
|
|
rawmode = ""
|
|
|
|
if reading:
|
|
|
|
rawmode += "r"
|
|
|
|
if writing:
|
|
|
|
rawmode += "w"
|
2023-09-17 19:52:08 +00:00
|
|
|
raw = socket.SocketIO(self, rawmode) # type: ignore[arg-type]
|
|
|
|
self.socket._io_refs += 1 # type: ignore[attr-defined]
|
2023-01-12 01:04:47 +00:00
|
|
|
if buffering is None:
|
|
|
|
buffering = -1
|
|
|
|
if buffering < 0:
|
|
|
|
buffering = io.DEFAULT_BUFFER_SIZE
|
|
|
|
if buffering == 0:
|
|
|
|
if not binary:
|
|
|
|
raise ValueError("unbuffered streams must be binary")
|
|
|
|
return raw
|
2023-09-17 19:52:08 +00:00
|
|
|
buffer: typing.BinaryIO
|
2023-01-12 01:04:47 +00:00
|
|
|
if reading and writing:
|
2023-09-17 19:52:08 +00:00
|
|
|
buffer = io.BufferedRWPair(raw, raw, buffering) # type: ignore[assignment]
|
2023-01-12 01:04:47 +00:00
|
|
|
elif reading:
|
|
|
|
buffer = io.BufferedReader(raw, buffering)
|
|
|
|
else:
|
|
|
|
assert writing
|
|
|
|
buffer = io.BufferedWriter(raw, buffering)
|
|
|
|
if binary:
|
|
|
|
return buffer
|
|
|
|
text = io.TextIOWrapper(buffer, encoding, errors, newline)
|
2023-09-17 19:52:08 +00:00
|
|
|
text.mode = mode # type: ignore[misc]
|
2023-01-12 01:04:47 +00:00
|
|
|
return text
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def unwrap(self) -> None:
|
2023-01-12 01:04:47 +00:00
|
|
|
self._ssl_io_loop(self.sslobj.unwrap)
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def close(self) -> None:
|
2023-01-12 01:04:47 +00:00
|
|
|
self.socket.close()
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
@typing.overload
|
|
|
|
def getpeercert(
|
|
|
|
self, binary_form: Literal[False] = ...
|
|
|
|
) -> _TYPE_PEER_CERT_RET_DICT | None:
|
|
|
|
...
|
|
|
|
|
|
|
|
@typing.overload
|
|
|
|
def getpeercert(self, binary_form: Literal[True]) -> bytes | None:
|
|
|
|
...
|
2023-01-12 01:04:47 +00:00
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def getpeercert(self, binary_form: bool = False) -> _TYPE_PEER_CERT_RET:
|
|
|
|
return self.sslobj.getpeercert(binary_form) # type: ignore[return-value]
|
|
|
|
|
|
|
|
def version(self) -> str | None:
|
2023-01-12 01:04:47 +00:00
|
|
|
return self.sslobj.version()
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def cipher(self) -> tuple[str, str, int] | None:
|
2023-01-12 01:04:47 +00:00
|
|
|
return self.sslobj.cipher()
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def selected_alpn_protocol(self) -> str | None:
|
2023-01-12 01:04:47 +00:00
|
|
|
return self.sslobj.selected_alpn_protocol()
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def selected_npn_protocol(self) -> str | None:
|
2023-01-12 01:04:47 +00:00
|
|
|
return self.sslobj.selected_npn_protocol()
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def shared_ciphers(self) -> list[tuple[str, str, int]] | None:
|
2023-01-12 01:04:47 +00:00
|
|
|
return self.sslobj.shared_ciphers()
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def compression(self) -> str | None:
|
2023-01-12 01:04:47 +00:00
|
|
|
return self.sslobj.compression()
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def settimeout(self, value: float | None) -> None:
|
2023-01-12 01:04:47 +00:00
|
|
|
self.socket.settimeout(value)
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def gettimeout(self) -> float | None:
|
2023-01-12 01:04:47 +00:00
|
|
|
return self.socket.gettimeout()
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def _decref_socketios(self) -> None:
|
|
|
|
self.socket._decref_socketios() # type: ignore[attr-defined]
|
2023-01-12 01:04:47 +00:00
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
def _wrap_ssl_read(self, len: int, buffer: bytearray | None = None) -> int | bytes:
|
2023-01-12 01:04:47 +00:00
|
|
|
try:
|
|
|
|
return self._ssl_io_loop(self.sslobj.read, len, buffer)
|
|
|
|
except ssl.SSLError as e:
|
|
|
|
if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs:
|
|
|
|
return 0 # eof, return 0.
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
|
2023-09-17 19:52:08 +00:00
|
|
|
# func is sslobj.do_handshake or sslobj.unwrap
|
|
|
|
@typing.overload
|
|
|
|
def _ssl_io_loop(self, func: typing.Callable[[], None]) -> None:
|
|
|
|
...
|
|
|
|
|
|
|
|
# func is sslobj.write, arg1 is data
|
|
|
|
@typing.overload
|
|
|
|
def _ssl_io_loop(self, func: typing.Callable[[bytes], int], arg1: bytes) -> int:
|
|
|
|
...
|
|
|
|
|
|
|
|
# func is sslobj.read, arg1 is len, arg2 is buffer
|
|
|
|
@typing.overload
|
|
|
|
def _ssl_io_loop(
|
|
|
|
self,
|
|
|
|
func: typing.Callable[[int, bytearray | None], bytes],
|
|
|
|
arg1: int,
|
|
|
|
arg2: bytearray | None,
|
|
|
|
) -> bytes:
|
|
|
|
...
|
|
|
|
|
|
|
|
def _ssl_io_loop(
|
|
|
|
self,
|
|
|
|
func: typing.Callable[..., _ReturnValue],
|
|
|
|
arg1: None | bytes | int = None,
|
|
|
|
arg2: bytearray | None = None,
|
|
|
|
) -> _ReturnValue:
|
2023-01-12 01:04:47 +00:00
|
|
|
"""Performs an I/O loop between incoming/outgoing and the socket."""
|
|
|
|
should_loop = True
|
|
|
|
ret = None
|
|
|
|
|
|
|
|
while should_loop:
|
|
|
|
errno = None
|
|
|
|
try:
|
2023-09-17 19:52:08 +00:00
|
|
|
if arg1 is None and arg2 is None:
|
|
|
|
ret = func()
|
|
|
|
elif arg2 is None:
|
|
|
|
ret = func(arg1)
|
|
|
|
else:
|
|
|
|
ret = func(arg1, arg2)
|
2023-01-12 01:04:47 +00:00
|
|
|
except ssl.SSLError as e:
|
|
|
|
if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE):
|
|
|
|
# WANT_READ, and WANT_WRITE are expected, others are not.
|
|
|
|
raise e
|
|
|
|
errno = e.errno
|
|
|
|
|
|
|
|
buf = self.outgoing.read()
|
|
|
|
self.socket.sendall(buf)
|
|
|
|
|
|
|
|
if errno is None:
|
|
|
|
should_loop = False
|
|
|
|
elif errno == ssl.SSL_ERROR_WANT_READ:
|
|
|
|
buf = self.socket.recv(SSL_BLOCKSIZE)
|
|
|
|
if buf:
|
|
|
|
self.incoming.write(buf)
|
|
|
|
else:
|
|
|
|
self.incoming.write_eof()
|
2023-09-17 19:52:08 +00:00
|
|
|
return typing.cast(_ReturnValue, ret)
|