usernet 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- usernet/__init__.py +81 -0
- usernet/aio.py +24 -0
- usernet/errors.py +69 -0
- usernet/http.py +357 -0
- usernet/link.py +107 -0
- usernet/log.py +90 -0
- usernet/net/__init__.py +14 -0
- usernet/net/backend.py +127 -0
- usernet/net/checksum.py +63 -0
- usernet/net/events.py +96 -0
- usernet/net/icmp.py +144 -0
- usernet/net/ipv4.py +205 -0
- usernet/net/stack.py +604 -0
- usernet/net/tcb.py +1169 -0
- usernet/net/tcp.py +385 -0
- usernet/net/udp.py +88 -0
- usernet/pcap.py +74 -0
- usernet/py.typed +0 -0
- usernet/resolve.py +93 -0
- usernet/routing.py +44 -0
- usernet/runtime/__init__.py +10 -0
- usernet/runtime/driver.py +466 -0
- usernet/runtime/stdio.py +167 -0
- usernet/runtime/tls.py +201 -0
- usernet/runtime/transport.py +283 -0
- usernet/socks/__init__.py +9 -0
- usernet/socks/client.py +91 -0
- usernet/socks/protocol.py +316 -0
- usernet/socks/server.py +377 -0
- usernet/testing/__init__.py +24 -0
- usernet/testing/link.py +153 -0
- usernet/testing/pcap.py +46 -0
- usernet/testing/peer.py +235 -0
- usernet/testing/pipes.py +99 -0
- usernet/testing/tls_endpoint.py +78 -0
- usernet/version.py +24 -0
- usernet-0.7.0.dist-info/METADATA +116 -0
- usernet-0.7.0.dist-info/RECORD +41 -0
- usernet-0.7.0.dist-info/WHEEL +4 -0
- usernet-0.7.0.dist-info/licenses/LICENSE +5 -0
- usernet-0.7.0.dist-info/licenses/LICENSES/0BSD.txt +5 -0
usernet/__init__.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 René de Hesselle <dehesselle@web.de>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: 0BSD
|
|
4
|
+
|
|
5
|
+
"""usernet -- a userspace TCP/IP stack for tunnels that carry raw IP.
|
|
6
|
+
|
|
7
|
+
A VPN client written against this package never asks the operating system for
|
|
8
|
+
anything: no tun device, no virtual adapter, no routing change, no
|
|
9
|
+
administrator privilege. It hands decapsulated IPv4 packets to
|
|
10
|
+
:class:`~usernet.net.stack.PyStack`, which terminates IP itself, and gets back
|
|
11
|
+
ordinary asyncio streams.
|
|
12
|
+
|
|
13
|
+
driver = Driver(link) # link is anything satisfying IpLink
|
|
14
|
+
driver.start()
|
|
15
|
+
stream = await driver.connect("10.0.0.5", 22)
|
|
16
|
+
await Socks5Server(driver, port=1080).start()
|
|
17
|
+
|
|
18
|
+
The one thing you must supply is the tunnel: an :class:`~usernet.link.IpLink`
|
|
19
|
+
that moves packets between here and the far side. ``pyac`` supplies CSTP over
|
|
20
|
+
TLS, ``pyts`` WireGuard over DERP, and :mod:`usernet.testing` supplies one made
|
|
21
|
+
of nothing at all.
|
|
22
|
+
|
|
23
|
+
Importing this package stays free of side effects: the names below are bound
|
|
24
|
+
lazily, so ``import usernet`` does not drag in asyncio and the whole stack for
|
|
25
|
+
a program that only wanted the version.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
from typing import TYPE_CHECKING, Any
|
|
31
|
+
|
|
32
|
+
from usernet.version import __version__
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"Driver",
|
|
36
|
+
"IpLink",
|
|
37
|
+
"LinkConfig",
|
|
38
|
+
"PyStack",
|
|
39
|
+
"SimpleLinkConfig",
|
|
40
|
+
"Socks5Server",
|
|
41
|
+
"StackConfig",
|
|
42
|
+
"TcpStream",
|
|
43
|
+
"__version__",
|
|
44
|
+
"describe_routes",
|
|
45
|
+
"route_allows",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
if TYPE_CHECKING:
|
|
49
|
+
from usernet.link import IpLink, LinkConfig, SimpleLinkConfig
|
|
50
|
+
from usernet.net.stack import PyStack, StackConfig
|
|
51
|
+
from usernet.routing import describe_routes, route_allows
|
|
52
|
+
from usernet.runtime.driver import Driver, TcpStream
|
|
53
|
+
from usernet.socks import Socks5Server
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def __getattr__(name: str) -> Any:
|
|
57
|
+
if name in ("IpLink", "LinkConfig", "SimpleLinkConfig"):
|
|
58
|
+
from usernet import link
|
|
59
|
+
|
|
60
|
+
return getattr(link, name)
|
|
61
|
+
|
|
62
|
+
if name in ("PyStack", "StackConfig"):
|
|
63
|
+
from usernet.net import stack
|
|
64
|
+
|
|
65
|
+
return getattr(stack, name)
|
|
66
|
+
if name in ("Driver", "TcpStream"):
|
|
67
|
+
from usernet.runtime import driver
|
|
68
|
+
|
|
69
|
+
return getattr(driver, name)
|
|
70
|
+
|
|
71
|
+
if name == "Socks5Server":
|
|
72
|
+
from usernet.socks import Socks5Server
|
|
73
|
+
|
|
74
|
+
return Socks5Server
|
|
75
|
+
|
|
76
|
+
if name in ("describe_routes", "route_allows"):
|
|
77
|
+
from usernet import routing
|
|
78
|
+
|
|
79
|
+
return getattr(routing, name)
|
|
80
|
+
|
|
81
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
usernet/aio.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 René de Hesselle <dehesselle@web.de>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: 0BSD
|
|
4
|
+
|
|
5
|
+
"""Small asyncio helpers shared across layers.
|
|
6
|
+
|
|
7
|
+
Lives at the top level rather than in ``runtime`` because a tunnel's link
|
|
8
|
+
implementation may need it too, and a link importing from the layer that
|
|
9
|
+
drives it would invert the dependency the whole design rests on.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
async def first_of(*events: asyncio.Event, seconds: float | None = None) -> None:
|
|
18
|
+
"""Wait until any of ``events`` is set, cancelling the rest."""
|
|
19
|
+
waiters = [asyncio.ensure_future(event.wait()) for event in events]
|
|
20
|
+
try:
|
|
21
|
+
await asyncio.wait(waiters, timeout=seconds, return_when=asyncio.FIRST_COMPLETED)
|
|
22
|
+
finally:
|
|
23
|
+
for waiter in waiters:
|
|
24
|
+
waiter.cancel()
|
usernet/errors.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 René de Hesselle <dehesselle@web.de>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: 0BSD
|
|
4
|
+
|
|
5
|
+
"""Exception hierarchy for usernet.
|
|
6
|
+
|
|
7
|
+
Every error raised below the tunnel derives from :class:`UsernetError`. The
|
|
8
|
+
``NetworkError`` branch mirrors the errors an ordinary socket would raise, so
|
|
9
|
+
the SOCKS5 layer can map them onto reply codes with a single table.
|
|
10
|
+
|
|
11
|
+
A tunnel implementation on top of this package (``pyac``, ``pyts``) roots its
|
|
12
|
+
own hierarchy here, so that ``except`` on its base class keeps catching stack
|
|
13
|
+
and socket failures too. What must *not* happen is the inverse: nothing in this
|
|
14
|
+
package may know what a gateway, a tailnet, or a login is.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class UsernetError(Exception):
|
|
21
|
+
"""Base class for every error this package raises."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ProtocolParseError(UsernetError):
|
|
25
|
+
"""Malformed input from the network, the tunnel, or a SOCKS client.
|
|
26
|
+
|
|
27
|
+
Parsers raise only this. Never let ``IndexError``, ``struct.error``, or
|
|
28
|
+
``UnicodeDecodeError`` escape a parser -- callers cannot distinguish those
|
|
29
|
+
from genuine bugs.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# --- network (socket-level, mapped onto SOCKS5 reply codes) ----------------
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class NetworkError(UsernetError):
|
|
37
|
+
"""Base for errors on a connection carried by the tunnel."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ConnectionRefused(NetworkError):
|
|
41
|
+
"""RST in response to SYN, or an ICMP hard error during connect."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ConnectionReset(NetworkError):
|
|
45
|
+
"""RST on an established connection."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ConnectionTimeout(NetworkError):
|
|
49
|
+
"""Connect timed out, or retransmission backoff was exhausted."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class HostUnreachable(NetworkError):
|
|
53
|
+
"""ICMP destination unreachable, or the name did not resolve."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class RouteNotAllowed(NetworkError):
|
|
57
|
+
"""The destination lies outside the tunnel's split-tunnel scope.
|
|
58
|
+
|
|
59
|
+
Raised eagerly rather than letting the peer drop the packets silently,
|
|
60
|
+
which would otherwise surface as an unexplained connect timeout.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(self, dst: str) -> None:
|
|
64
|
+
super().__init__(f"{dst} is outside the tunnel's split-include routes")
|
|
65
|
+
self.dst = dst
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class ResolveError(NetworkError):
|
|
69
|
+
"""In-tunnel DNS resolution failed."""
|
usernet/http.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 René de Hesselle <dehesselle@web.de>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: 0BSD
|
|
4
|
+
|
|
5
|
+
"""An httpcore network backend that dials through the tunnel.
|
|
6
|
+
|
|
7
|
+
httpcore exposes a documented seam -- ``AsyncNetworkBackend`` -- for replacing
|
|
8
|
+
how connections are made. Filling it in gets connection pooling, keep-alive,
|
|
9
|
+
redirects, HTTP/1.1 framing, and the whole httpx API for the price of three
|
|
10
|
+
methods, which is a far better trade than writing an HTTP client.
|
|
11
|
+
|
|
12
|
+
``httpx.AsyncHTTPTransport`` does not accept a ``network_backend``, so
|
|
13
|
+
:class:`PoolTransport` drives an
|
|
14
|
+
``httpcore.AsyncConnectionPool`` itself, which *does* take a backend and is
|
|
15
|
+
public httpcore API, behind ``httpx.AsyncBaseTransport``, which is httpx's
|
|
16
|
+
documented extension point. No private attribute is touched anywhere, and the
|
|
17
|
+
seam tests pin the signatures either way.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import asyncio
|
|
23
|
+
import contextlib
|
|
24
|
+
import ssl
|
|
25
|
+
import time
|
|
26
|
+
import typing
|
|
27
|
+
|
|
28
|
+
import httpcore
|
|
29
|
+
import httpx
|
|
30
|
+
from httpcore import AsyncNetworkBackend, AsyncNetworkStream
|
|
31
|
+
|
|
32
|
+
from usernet.errors import NetworkError
|
|
33
|
+
from usernet.runtime.driver import Driver, TcpStream
|
|
34
|
+
from usernet.runtime.tls import TlsStream, wrap
|
|
35
|
+
|
|
36
|
+
if typing.TYPE_CHECKING:
|
|
37
|
+
from httpcore._backends.base import SOCKET_OPTION
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class TunnelStream(AsyncNetworkStream):
|
|
41
|
+
"""One connection through the tunnel, in the shape httpcore expects."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, stream: TcpStream, driver: Driver) -> None:
|
|
44
|
+
self._stream = stream
|
|
45
|
+
self._driver = driver
|
|
46
|
+
|
|
47
|
+
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
|
48
|
+
# Timeouts are httpx's to enforce around the call; adding our own here
|
|
49
|
+
# would produce two competing deadlines and confusing error messages.
|
|
50
|
+
return await self._stream.read(max_bytes)
|
|
51
|
+
|
|
52
|
+
async def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
|
53
|
+
await self._stream.write(buffer)
|
|
54
|
+
|
|
55
|
+
async def aclose(self) -> None:
|
|
56
|
+
self._stream.close()
|
|
57
|
+
|
|
58
|
+
async def start_tls(
|
|
59
|
+
self,
|
|
60
|
+
ssl_context: ssl.SSLContext,
|
|
61
|
+
server_hostname: str | None = None,
|
|
62
|
+
timeout: float | None = None,
|
|
63
|
+
) -> AsyncNetworkStream:
|
|
64
|
+
tls = await wrap(
|
|
65
|
+
_TransportAdapter(self._stream),
|
|
66
|
+
ssl_context,
|
|
67
|
+
server_hostname=server_hostname,
|
|
68
|
+
)
|
|
69
|
+
return TlsNetworkStream(tls)
|
|
70
|
+
|
|
71
|
+
def get_extra_info(self, info: str) -> typing.Any:
|
|
72
|
+
if info == "client_addr":
|
|
73
|
+
return (self._driver.link.config.address, 0)
|
|
74
|
+
if info == "server_addr":
|
|
75
|
+
return self._stream.peer
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class _TransportAdapter:
|
|
80
|
+
"""Presents a :class:`TcpStream` as the transport ``TlsStream`` expects."""
|
|
81
|
+
|
|
82
|
+
def __init__(self, stream: TcpStream) -> None:
|
|
83
|
+
self._stream = stream
|
|
84
|
+
|
|
85
|
+
async def read(self, size: int = 65536) -> bytes:
|
|
86
|
+
return await self._stream.read(size)
|
|
87
|
+
|
|
88
|
+
async def write(self, data: bytes) -> None:
|
|
89
|
+
await self._stream.write(data)
|
|
90
|
+
|
|
91
|
+
def close(self) -> None:
|
|
92
|
+
self._stream.close()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class TlsNetworkStream(AsyncNetworkStream):
|
|
96
|
+
"""A :class:`~usernet.runtime.tls.TlsStream`, in httpcore's shape."""
|
|
97
|
+
|
|
98
|
+
def __init__(self, tls: TlsStream) -> None:
|
|
99
|
+
self._tls = tls
|
|
100
|
+
|
|
101
|
+
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
|
102
|
+
return await self._tls.read(max_bytes)
|
|
103
|
+
|
|
104
|
+
async def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
|
105
|
+
await self._tls.write(buffer)
|
|
106
|
+
|
|
107
|
+
async def aclose(self) -> None:
|
|
108
|
+
await self._tls.aclose()
|
|
109
|
+
|
|
110
|
+
async def start_tls(
|
|
111
|
+
self,
|
|
112
|
+
ssl_context: ssl.SSLContext,
|
|
113
|
+
server_hostname: str | None = None,
|
|
114
|
+
timeout: float | None = None,
|
|
115
|
+
) -> AsyncNetworkStream:
|
|
116
|
+
raise NetworkError("TLS is already established on this connection")
|
|
117
|
+
|
|
118
|
+
def get_extra_info(self, info: str) -> typing.Any:
|
|
119
|
+
if info == "ssl_object":
|
|
120
|
+
return self._tls
|
|
121
|
+
if info == "server_hostname":
|
|
122
|
+
return None
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class UsernetNetworkBackend(AsyncNetworkBackend):
|
|
127
|
+
"""Makes httpx dial through the VPN instead of the operating system."""
|
|
128
|
+
|
|
129
|
+
def __init__(self, driver: Driver, *, connect_timeout: float = 30.0) -> None:
|
|
130
|
+
self._driver = driver
|
|
131
|
+
self._connect_timeout = connect_timeout
|
|
132
|
+
self.connections = 0
|
|
133
|
+
self.last_connect_ms = 0.0
|
|
134
|
+
"""How long the most recent handshake took. One round trip through the
|
|
135
|
+
tunnel, which is the single most useful number when something feels
|
|
136
|
+
slow -- and httpx has no way to report it."""
|
|
137
|
+
|
|
138
|
+
async def connect_tcp(
|
|
139
|
+
self,
|
|
140
|
+
host: str,
|
|
141
|
+
port: int,
|
|
142
|
+
timeout: float | None = None,
|
|
143
|
+
local_address: str | None = None,
|
|
144
|
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
|
145
|
+
) -> AsyncNetworkStream:
|
|
146
|
+
# local_address and socket_options are meaningless here: the source
|
|
147
|
+
# address is whatever the gateway assigned, and there is no OS socket
|
|
148
|
+
# to set options on. Accepting and ignoring them beats refusing.
|
|
149
|
+
started = time.monotonic()
|
|
150
|
+
stream = await self._driver.connect(
|
|
151
|
+
host, port, timeout=timeout if timeout is not None else self._connect_timeout
|
|
152
|
+
)
|
|
153
|
+
self.last_connect_ms = (time.monotonic() - started) * 1000
|
|
154
|
+
self.connections += 1
|
|
155
|
+
return TunnelStream(stream, self._driver)
|
|
156
|
+
|
|
157
|
+
async def connect_unix_socket(
|
|
158
|
+
self,
|
|
159
|
+
path: str,
|
|
160
|
+
timeout: float | None = None,
|
|
161
|
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
|
162
|
+
) -> AsyncNetworkStream:
|
|
163
|
+
raise NetworkError("a VPN tunnel carries no unix sockets")
|
|
164
|
+
|
|
165
|
+
async def sleep(self, seconds: float) -> None:
|
|
166
|
+
await asyncio.sleep(seconds)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# Specific before general: ConnectTimeout is a TimeoutException, and a dict
|
|
170
|
+
# preserves insertion order, so the first match wins.
|
|
171
|
+
_MAPPED_EXCEPTIONS = (
|
|
172
|
+
"ConnectTimeout",
|
|
173
|
+
"ReadTimeout",
|
|
174
|
+
"WriteTimeout",
|
|
175
|
+
"PoolTimeout",
|
|
176
|
+
"TimeoutException",
|
|
177
|
+
"ConnectError",
|
|
178
|
+
"ReadError",
|
|
179
|
+
"WriteError",
|
|
180
|
+
"NetworkError",
|
|
181
|
+
"LocalProtocolError",
|
|
182
|
+
"RemoteProtocolError",
|
|
183
|
+
"ProtocolError",
|
|
184
|
+
"ProxyError",
|
|
185
|
+
"UnsupportedProtocol",
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
EXCEPTION_MAP: dict[type[Exception], type[Exception]] = {
|
|
189
|
+
getattr(httpcore, name): getattr(httpx, name)
|
|
190
|
+
for name in _MAPPED_EXCEPTIONS
|
|
191
|
+
if hasattr(httpcore, name) and hasattr(httpx, name)
|
|
192
|
+
}
|
|
193
|
+
"""httpcore errors, translated so callers can catch ordinary httpx exceptions.
|
|
194
|
+
|
|
195
|
+
Built by name rather than written out, so a version that renames one drops it
|
|
196
|
+
from the map instead of failing to import.
|
|
197
|
+
"""
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@contextlib.contextmanager
|
|
201
|
+
def _as_httpx_errors() -> typing.Iterator[None]:
|
|
202
|
+
try:
|
|
203
|
+
yield
|
|
204
|
+
except Exception as exc:
|
|
205
|
+
for source, target in EXCEPTION_MAP.items():
|
|
206
|
+
if isinstance(exc, source):
|
|
207
|
+
raise target(str(exc)) from exc
|
|
208
|
+
# Anything else -- notably our own NetworkError subclasses -- passes
|
|
209
|
+
# through untouched. "10.9.8.7 is outside the gateway's split routes"
|
|
210
|
+
# is worth far more to whoever reads it than "ConnectError".
|
|
211
|
+
raise
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def build_ssl_context(
|
|
215
|
+
verify: bool | str | ssl.SSLContext = True, *, http2: bool = False
|
|
216
|
+
) -> ssl.SSLContext:
|
|
217
|
+
"""How to verify the *target's* certificate.
|
|
218
|
+
|
|
219
|
+
Nothing to do with the gateway's: reaching an internal API over an internal
|
|
220
|
+
CA is an entirely separate trust decision from trusting the VPN's front
|
|
221
|
+
door, and a flag governing one must never quietly govern the other.
|
|
222
|
+
"""
|
|
223
|
+
if isinstance(verify, ssl.SSLContext):
|
|
224
|
+
context = verify
|
|
225
|
+
elif verify is False:
|
|
226
|
+
context = ssl.create_default_context()
|
|
227
|
+
context.check_hostname = False
|
|
228
|
+
context.verify_mode = ssl.CERT_NONE
|
|
229
|
+
else:
|
|
230
|
+
context = ssl.create_default_context(cafile=verify if isinstance(verify, str) else None)
|
|
231
|
+
context.set_alpn_protocols(["h2", "http/1.1"] if http2 else ["http/1.1"])
|
|
232
|
+
return context
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class PoolTransport(httpx.AsyncBaseTransport):
|
|
236
|
+
"""An httpx transport over an httpcore pool with a backend you supply.
|
|
237
|
+
|
|
238
|
+
Split out from :class:`TunnelTransport` because "where do the bytes come
|
|
239
|
+
from" is the only thing a caller ever wants to change, and everything else
|
|
240
|
+
-- HTTP/2 flow control, streaming response bodies, the error translation --
|
|
241
|
+
is httpcore's and worth not reimplementing. ``pyts`` uses this to run
|
|
242
|
+
HTTP/2 inside a Noise session, which is not a tunnel and has no driver.
|
|
243
|
+
|
|
244
|
+
The alternative is reaching into ``client._transport._pool`` to swap the
|
|
245
|
+
backend after the fact, which works until httpx renames something.
|
|
246
|
+
"""
|
|
247
|
+
|
|
248
|
+
def __init__(
|
|
249
|
+
self,
|
|
250
|
+
backend: AsyncNetworkBackend,
|
|
251
|
+
*,
|
|
252
|
+
ssl_context: ssl.SSLContext | None = None,
|
|
253
|
+
http1: bool = True,
|
|
254
|
+
http2: bool = False,
|
|
255
|
+
**pool_options: typing.Any,
|
|
256
|
+
) -> None:
|
|
257
|
+
self.backend = backend
|
|
258
|
+
self._pool = httpcore.AsyncConnectionPool(
|
|
259
|
+
ssl_context=ssl_context,
|
|
260
|
+
network_backend=backend,
|
|
261
|
+
http1=http1,
|
|
262
|
+
http2=http2,
|
|
263
|
+
**pool_options,
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
|
|
267
|
+
assert isinstance(request.stream, httpx.AsyncByteStream)
|
|
268
|
+
wrapped = httpcore.Request(
|
|
269
|
+
method=request.method,
|
|
270
|
+
url=httpcore.URL(
|
|
271
|
+
scheme=request.url.raw_scheme,
|
|
272
|
+
host=request.url.raw_host,
|
|
273
|
+
port=request.url.port,
|
|
274
|
+
target=request.url.raw_path,
|
|
275
|
+
),
|
|
276
|
+
headers=request.headers.raw,
|
|
277
|
+
content=request.stream,
|
|
278
|
+
extensions=request.extensions,
|
|
279
|
+
)
|
|
280
|
+
with _as_httpx_errors():
|
|
281
|
+
response = await self._pool.handle_async_request(wrapped)
|
|
282
|
+
|
|
283
|
+
assert isinstance(response.stream, typing.AsyncIterable)
|
|
284
|
+
return httpx.Response(
|
|
285
|
+
status_code=response.status,
|
|
286
|
+
headers=response.headers,
|
|
287
|
+
stream=_ResponseStream(response.stream),
|
|
288
|
+
extensions=response.extensions,
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
async def aclose(self) -> None:
|
|
292
|
+
await self._pool.aclose()
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class TunnelTransport(PoolTransport):
|
|
296
|
+
"""An httpx transport whose connections all run through the tunnel.
|
|
297
|
+
|
|
298
|
+
``verify`` belongs here rather than on the client. ``httpx.AsyncClient``
|
|
299
|
+
only applies its own ``verify`` to the transport *it* builds, so passing
|
|
300
|
+
one alongside a custom transport silently does nothing -- which would make
|
|
301
|
+
a caller's "skip verification" or "trust this CA" look like it worked
|
|
302
|
+
while changing nothing at all.
|
|
303
|
+
"""
|
|
304
|
+
|
|
305
|
+
def __init__(
|
|
306
|
+
self,
|
|
307
|
+
driver: Driver,
|
|
308
|
+
*,
|
|
309
|
+
verify: bool | str | ssl.SSLContext = True,
|
|
310
|
+
connect_timeout: float = 30.0,
|
|
311
|
+
http2: bool = False,
|
|
312
|
+
**pool_options: typing.Any,
|
|
313
|
+
) -> None:
|
|
314
|
+
backend = UsernetNetworkBackend(driver, connect_timeout=connect_timeout)
|
|
315
|
+
super().__init__(
|
|
316
|
+
backend,
|
|
317
|
+
ssl_context=build_ssl_context(verify, http2=http2),
|
|
318
|
+
http1=True,
|
|
319
|
+
http2=http2,
|
|
320
|
+
**pool_options,
|
|
321
|
+
)
|
|
322
|
+
self._backend = backend
|
|
323
|
+
|
|
324
|
+
@property
|
|
325
|
+
def last_connect_ms(self) -> float:
|
|
326
|
+
"""How long the most recent handshake took. See ``UsernetNetworkBackend``."""
|
|
327
|
+
return self._backend.last_connect_ms
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
class _ResponseStream(httpx.AsyncByteStream):
|
|
331
|
+
def __init__(self, stream: typing.AsyncIterable[bytes]) -> None:
|
|
332
|
+
self._stream = stream
|
|
333
|
+
|
|
334
|
+
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
|
|
335
|
+
with _as_httpx_errors():
|
|
336
|
+
async for part in self._stream:
|
|
337
|
+
yield part
|
|
338
|
+
|
|
339
|
+
async def aclose(self) -> None:
|
|
340
|
+
if hasattr(self._stream, "aclose"):
|
|
341
|
+
await self._stream.aclose()
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def httpx_transport(driver: Driver, **kwargs: typing.Any) -> TunnelTransport:
|
|
345
|
+
"""An httpx transport whose connections run through the tunnel."""
|
|
346
|
+
return TunnelTransport(driver, **kwargs)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def httpx_client(driver: Driver, **kwargs: typing.Any) -> httpx.AsyncClient:
|
|
350
|
+
"""An ``httpx.AsyncClient`` that reaches only inside the VPN.
|
|
351
|
+
|
|
352
|
+
``verify`` and friends apply to the *target's* certificate, which has
|
|
353
|
+
nothing to do with the gateway's -- those two trust decisions are separate
|
|
354
|
+
and must stay that way.
|
|
355
|
+
"""
|
|
356
|
+
transport = kwargs.pop("transport", None) or httpx_transport(driver)
|
|
357
|
+
return httpx.AsyncClient(transport=transport, **kwargs)
|
usernet/link.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 René de Hesselle <dehesselle@web.de>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: 0BSD
|
|
4
|
+
|
|
5
|
+
"""The seam between a tunnel and the stack that rides on it.
|
|
6
|
+
|
|
7
|
+
Everything below this module -- the sans-IO stack, the driver, the SOCKS
|
|
8
|
+
server -- is written against :class:`IpLink` and nothing else. A tunnel is
|
|
9
|
+
whatever can carry raw IPv4 packets in both directions and say what address it
|
|
10
|
+
assigned us: CSTP over TLS in ``pyac``, WireGuard over DERP in ``pyts``, a
|
|
11
|
+
Linux tun device in the conformance tests, an in-memory queue in the unit
|
|
12
|
+
tests. None of those appear in this package's imports, which is the point.
|
|
13
|
+
|
|
14
|
+
:class:`LinkConfig` is a ``Protocol`` rather than a base class deliberately. A
|
|
15
|
+
tunnel's configuration object is mostly tunnel-specific -- DPD timers, rekey
|
|
16
|
+
methods, DERP regions -- and only a handful of fields are the stack's business.
|
|
17
|
+
Structural typing lets those objects stay whole instead of being split in two
|
|
18
|
+
or forced into an inheritance chain that means nothing to them.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import asyncio
|
|
24
|
+
import ipaddress
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from typing import Protocol, runtime_checkable
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@runtime_checkable
|
|
30
|
+
class LinkConfig(Protocol):
|
|
31
|
+
"""The part of a tunnel's configuration the stack actually reads."""
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def address(self) -> str:
|
|
35
|
+
"""Our address inside the tunnel, as dotted quad."""
|
|
36
|
+
...
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def netmask(self) -> str:
|
|
40
|
+
"""Its netmask. ``255.255.255.255`` when the tunnel assigns a bare host
|
|
41
|
+
address and there is no on-link subnet at all."""
|
|
42
|
+
...
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def mtu(self) -> int:
|
|
46
|
+
"""The largest IP packet the tunnel will carry."""
|
|
47
|
+
...
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def split_include(self) -> tuple[ipaddress.IPv4Network, ...]:
|
|
51
|
+
"""Destinations the tunnel carries. Empty means all of them."""
|
|
52
|
+
...
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def split_exclude(self) -> tuple[ipaddress.IPv4Network, ...]:
|
|
56
|
+
"""Destinations it refuses, which win over ``split_include``."""
|
|
57
|
+
...
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True, slots=True)
|
|
61
|
+
class SimpleLinkConfig:
|
|
62
|
+
"""A :class:`LinkConfig` for links that have nothing more to say.
|
|
63
|
+
|
|
64
|
+
Tests and minimal links use this; a real tunnel is expected to satisfy the
|
|
65
|
+
protocol with its own richer object instead.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
address: str
|
|
69
|
+
netmask: str = "255.255.255.255"
|
|
70
|
+
mtu: int = 1500
|
|
71
|
+
split_include: tuple[ipaddress.IPv4Network, ...] = ()
|
|
72
|
+
split_exclude: tuple[ipaddress.IPv4Network, ...] = ()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@runtime_checkable
|
|
76
|
+
class IpLink(Protocol):
|
|
77
|
+
"""A bidirectional channel carrying raw IPv4 packets."""
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def config(self) -> LinkConfig:
|
|
81
|
+
"""The tunnel's parameters: address, netmask, MTU, routes."""
|
|
82
|
+
...
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def wake(self) -> asyncio.Event:
|
|
86
|
+
"""Set whenever inbound packets arrive, so the driver can wait on it."""
|
|
87
|
+
...
|
|
88
|
+
|
|
89
|
+
def send(self, packet: bytes) -> None:
|
|
90
|
+
"""Queue one IP packet. Non-blocking; the writer task coalesces."""
|
|
91
|
+
...
|
|
92
|
+
|
|
93
|
+
def take_inbound(self) -> list[bytes]:
|
|
94
|
+
"""Drain every IP packet received since the last call."""
|
|
95
|
+
...
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def closed(self) -> asyncio.Event:
|
|
99
|
+
"""Set when the link is finished; :attr:`close_reason` says why."""
|
|
100
|
+
...
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def close_reason(self) -> str: ...
|
|
104
|
+
|
|
105
|
+
async def aclose(self) -> None:
|
|
106
|
+
"""Shut the link down cleanly."""
|
|
107
|
+
...
|