selenium-netwire 0.1.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.
- netwire/__init__.py +17 -0
- netwire/_backend.py +459 -0
- netwire/_cdp.py +133 -0
- netwire/_config.py +115 -0
- netwire/_har.py +92 -0
- netwire/_mixin.py +134 -0
- netwire/_relay.py +258 -0
- netwire/request.py +229 -0
- netwire/utils.py +39 -0
- netwire/webdriver.py +70 -0
- selenium_netwire-0.1.0.dist-info/METADATA +194 -0
- selenium_netwire-0.1.0.dist-info/RECORD +14 -0
- selenium_netwire-0.1.0.dist-info/WHEEL +4 -0
- selenium_netwire-0.1.0.dist-info/licenses/LICENSE +21 -0
netwire/_config.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""selenium-wire's options, read into what netwire needs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import warnings
|
|
7
|
+
from urllib.parse import unquote, urlsplit
|
|
8
|
+
|
|
9
|
+
# Options that only configured selenium-wire's own proxy. netwire has no proxy
|
|
10
|
+
# of its own, so they are accepted and ignored.
|
|
11
|
+
_NO_LONGER_NEEDED = {
|
|
12
|
+
"addr",
|
|
13
|
+
"port",
|
|
14
|
+
"auto_config",
|
|
15
|
+
"ca_cert",
|
|
16
|
+
"ca_key",
|
|
17
|
+
"verify_ssl",
|
|
18
|
+
"suppress_connection_errors",
|
|
19
|
+
"request_storage",
|
|
20
|
+
"request_storage_base_dir",
|
|
21
|
+
"disable_encoding",
|
|
22
|
+
"mitm_http2",
|
|
23
|
+
"standalone",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
_KNOWN = _NO_LONGER_NEEDED | {
|
|
27
|
+
"proxy",
|
|
28
|
+
"exclude_hosts",
|
|
29
|
+
"ignore_http_methods",
|
|
30
|
+
"disable_capture",
|
|
31
|
+
"request_storage_max_size",
|
|
32
|
+
"enable_har",
|
|
33
|
+
"relay",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Config:
|
|
38
|
+
def __init__(self, options: dict | None) -> None:
|
|
39
|
+
options = dict(options or {})
|
|
40
|
+
unknown = set(options) - _KNOWN
|
|
41
|
+
if unknown:
|
|
42
|
+
warnings.warn(f"netwire: unknown options ignored: {sorted(unknown)}", stacklevel=3)
|
|
43
|
+
self.exclude_hosts: list[str] = list(options.get("exclude_hosts", []))
|
|
44
|
+
self.ignore_http_methods: set[str] = {m.upper() for m in options.get("ignore_http_methods", ["OPTIONS"])}
|
|
45
|
+
self.disable_capture: bool = bool(options.get("disable_capture", False))
|
|
46
|
+
self.request_storage_max_size: int | None = options.get("request_storage_max_size")
|
|
47
|
+
self.enable_har: bool = bool(options.get("enable_har", False))
|
|
48
|
+
|
|
49
|
+
proxy = options.get("proxy")
|
|
50
|
+
if proxy is None:
|
|
51
|
+
proxy = self._proxy_from_env()
|
|
52
|
+
self.proxy_server: str | None = None
|
|
53
|
+
self.proxy_bypass: str | None = None
|
|
54
|
+
self.proxy_credentials: tuple[str, str] | None = None
|
|
55
|
+
# A local relay is used when Chrome cannot do the proxy part alone, or
|
|
56
|
+
# when asked for, so the proxy can be switched later (driver.proxy).
|
|
57
|
+
self.use_relay: bool = bool(options.get("relay", False))
|
|
58
|
+
self.upstream = None
|
|
59
|
+
self.relay = None
|
|
60
|
+
self.proxy_settings: dict = dict(proxy or {})
|
|
61
|
+
if proxy:
|
|
62
|
+
self._read_proxy(proxy)
|
|
63
|
+
|
|
64
|
+
@staticmethod
|
|
65
|
+
def _proxy_from_env() -> dict:
|
|
66
|
+
env = {k.lower(): v for k, v in os.environ.items() if k.lower() in ("http_proxy", "https_proxy", "no_proxy")}
|
|
67
|
+
proxy = {}
|
|
68
|
+
if env.get("https_proxy"):
|
|
69
|
+
proxy["https"] = env["https_proxy"]
|
|
70
|
+
if env.get("http_proxy"):
|
|
71
|
+
proxy["http"] = env["http_proxy"]
|
|
72
|
+
if proxy and env.get("no_proxy"):
|
|
73
|
+
proxy["no_proxy"] = env["no_proxy"]
|
|
74
|
+
return proxy
|
|
75
|
+
|
|
76
|
+
def _read_proxy(self, proxy: dict) -> None:
|
|
77
|
+
from ._relay import Upstream
|
|
78
|
+
|
|
79
|
+
url = proxy.get("https") or proxy.get("http")
|
|
80
|
+
if proxy.get("no_proxy"):
|
|
81
|
+
self.proxy_bypass = ";".join(h.strip() for h in proxy["no_proxy"].split(",") if h.strip())
|
|
82
|
+
if not url:
|
|
83
|
+
return
|
|
84
|
+
if proxy.get("http") and proxy.get("https") and urlsplit(proxy["http"]).netloc != urlsplit(proxy["https"]).netloc:
|
|
85
|
+
warnings.warn("netwire: different http and https proxies are not supported; using the https one", stacklevel=4)
|
|
86
|
+
parts = urlsplit(url)
|
|
87
|
+
scheme = (parts.scheme or "http").lower()
|
|
88
|
+
if scheme.startswith("socks") and parts.username or proxy.get("custom_authorization"):
|
|
89
|
+
self.use_relay = True
|
|
90
|
+
if self.use_relay:
|
|
91
|
+
self.upstream = Upstream.from_url(url, proxy.get("custom_authorization"))
|
|
92
|
+
return
|
|
93
|
+
if scheme == "socks5h":
|
|
94
|
+
scheme = "socks5" # Chrome resolves names through SOCKS5 proxies already.
|
|
95
|
+
host = parts.hostname or ""
|
|
96
|
+
if ":" in host:
|
|
97
|
+
host = f"[{host}]"
|
|
98
|
+
self.proxy_server = f"{scheme}://{host}" + (f":{parts.port}" if parts.port else "")
|
|
99
|
+
if parts.username:
|
|
100
|
+
self.proxy_credentials = (unquote(parts.username), unquote(parts.password or ""))
|
|
101
|
+
|
|
102
|
+
def start_relay(self) -> None:
|
|
103
|
+
if self.use_relay and self.relay is None:
|
|
104
|
+
from ._relay import Relay
|
|
105
|
+
|
|
106
|
+
self.relay = Relay(self.upstream)
|
|
107
|
+
self.proxy_server = self.relay.address
|
|
108
|
+
|
|
109
|
+
def browser_arguments(self) -> list[str]:
|
|
110
|
+
args = []
|
|
111
|
+
if self.proxy_server:
|
|
112
|
+
args.append(f"--proxy-server={self.proxy_server}")
|
|
113
|
+
if self.proxy_bypass:
|
|
114
|
+
args.append(f"--proxy-bypass-list={self.proxy_bypass}")
|
|
115
|
+
return args
|
netwire/_har.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""HAR 1.2 export of captured requests (http://www.softwareishard.com/blog/har-12-spec/)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
from datetime import timezone
|
|
8
|
+
from urllib.parse import parse_qsl
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .request import Request
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _headers(headers) -> list[dict]:
|
|
15
|
+
return [{"name": k, "value": v} for k, v in headers.items()]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _content(body: bytes, mime_type: str) -> dict:
|
|
19
|
+
content = {"size": len(body), "mimeType": mime_type}
|
|
20
|
+
if not body:
|
|
21
|
+
return content
|
|
22
|
+
try:
|
|
23
|
+
content["text"] = body.decode("utf-8")
|
|
24
|
+
except UnicodeDecodeError:
|
|
25
|
+
content["text"] = base64.b64encode(body).decode()
|
|
26
|
+
content["encoding"] = "base64"
|
|
27
|
+
return content
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _entry(request: Request) -> dict:
|
|
31
|
+
started = request.date.astimezone(timezone.utc) if request.date.tzinfo else request.date.astimezone()
|
|
32
|
+
entry_request = {
|
|
33
|
+
"method": request.method,
|
|
34
|
+
"url": request.url,
|
|
35
|
+
"httpVersion": "HTTP/1.1",
|
|
36
|
+
"cookies": [],
|
|
37
|
+
"headers": _headers(request.headers),
|
|
38
|
+
"queryString": [{"name": k, "value": v} for k, v in parse_qsl(request.querystring, keep_blank_values=True)],
|
|
39
|
+
"headersSize": -1,
|
|
40
|
+
"bodySize": len(request.body),
|
|
41
|
+
}
|
|
42
|
+
if request.body:
|
|
43
|
+
entry_request["postData"] = {
|
|
44
|
+
"mimeType": request.headers.get("Content-Type") or "",
|
|
45
|
+
"text": request.body.decode("utf-8", "replace"),
|
|
46
|
+
}
|
|
47
|
+
response = request.response
|
|
48
|
+
if response is not None:
|
|
49
|
+
entry_response = {
|
|
50
|
+
"status": response.status_code,
|
|
51
|
+
"statusText": response.reason,
|
|
52
|
+
"httpVersion": "HTTP/1.1",
|
|
53
|
+
"cookies": [],
|
|
54
|
+
"headers": _headers(response.headers),
|
|
55
|
+
"content": _content(response.body, response.headers.get("Content-Type") or ""),
|
|
56
|
+
"redirectURL": response.headers.get("Location") or "",
|
|
57
|
+
"headersSize": -1,
|
|
58
|
+
"bodySize": len(response.body),
|
|
59
|
+
}
|
|
60
|
+
elapsed = max((response.date - request.date).total_seconds() * 1000, 0)
|
|
61
|
+
else:
|
|
62
|
+
entry_response = {
|
|
63
|
+
"status": 0,
|
|
64
|
+
"statusText": request.error or "",
|
|
65
|
+
"httpVersion": "",
|
|
66
|
+
"cookies": [],
|
|
67
|
+
"headers": [],
|
|
68
|
+
"content": {"size": 0, "mimeType": ""},
|
|
69
|
+
"redirectURL": "",
|
|
70
|
+
"headersSize": -1,
|
|
71
|
+
"bodySize": -1,
|
|
72
|
+
}
|
|
73
|
+
elapsed = 0
|
|
74
|
+
return {
|
|
75
|
+
"startedDateTime": started.isoformat(),
|
|
76
|
+
"time": elapsed,
|
|
77
|
+
"request": entry_request,
|
|
78
|
+
"response": entry_response,
|
|
79
|
+
"cache": {},
|
|
80
|
+
"timings": {"send": 0, "wait": elapsed, "receive": 0},
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def to_har(requests: list[Request]) -> str:
|
|
85
|
+
har = {
|
|
86
|
+
"log": {
|
|
87
|
+
"version": "1.2",
|
|
88
|
+
"creator": {"name": "selenium-netwire", "version": __version__},
|
|
89
|
+
"entries": [_entry(r) for r in requests if r.method and not r.url.startswith(("ws:", "wss:"))],
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return json.dumps(har, indent=2)
|
netwire/_mixin.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""The selenium-wire API on a webdriver."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Callable, Iterator
|
|
7
|
+
|
|
8
|
+
from selenium.common.exceptions import TimeoutException
|
|
9
|
+
|
|
10
|
+
from ._backend import Backend
|
|
11
|
+
from .request import Request
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _complete(request: Request) -> bool:
|
|
15
|
+
"""A request whose response (and body) has arrived, or that failed."""
|
|
16
|
+
if request.error:
|
|
17
|
+
return True
|
|
18
|
+
response = request.response
|
|
19
|
+
if response is None:
|
|
20
|
+
return False
|
|
21
|
+
return request._body_loaded or 300 <= response.status_code < 400 or response.status_code == 101
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class InspectRequestsMixin:
|
|
25
|
+
_netwire: Backend
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def requests(self) -> list[Request]:
|
|
29
|
+
"""Every captured request, oldest first."""
|
|
30
|
+
return self._netwire.storage.all()
|
|
31
|
+
|
|
32
|
+
@requests.deleter
|
|
33
|
+
def requests(self) -> None:
|
|
34
|
+
self._netwire.storage.clear()
|
|
35
|
+
|
|
36
|
+
def iter_requests(self) -> Iterator[Request]:
|
|
37
|
+
yield from self._netwire.storage.all()
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def last_request(self) -> Request | None:
|
|
41
|
+
captured = self._netwire.storage.all()
|
|
42
|
+
return captured[-1] if captured else None
|
|
43
|
+
|
|
44
|
+
def wait_for_request(self, pat: str, timeout: float = 10) -> Request:
|
|
45
|
+
"""Wait until a request whose URL matches ``pat`` (a regex or substring)
|
|
46
|
+
has its response, and return it."""
|
|
47
|
+
pattern = re.compile(pat)
|
|
48
|
+
found = self._netwire.storage.wait_for(lambda r: bool(pattern.search(r.url)) and _complete(r), timeout)
|
|
49
|
+
if found is None:
|
|
50
|
+
raise TimeoutException(f"Timed out after {timeout}s waiting for request matching {pat}")
|
|
51
|
+
return found
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def scopes(self) -> list[str]:
|
|
55
|
+
"""Only capture requests whose URL matches one of these regexes."""
|
|
56
|
+
return list(self._netwire.scopes)
|
|
57
|
+
|
|
58
|
+
@scopes.setter
|
|
59
|
+
def scopes(self, scopes: list[str]) -> None:
|
|
60
|
+
self._netwire.scopes = list(scopes)
|
|
61
|
+
|
|
62
|
+
@scopes.deleter
|
|
63
|
+
def scopes(self) -> None:
|
|
64
|
+
self._netwire.scopes = []
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def request_interceptor(self) -> Callable | None:
|
|
68
|
+
return self._netwire.request_interceptor
|
|
69
|
+
|
|
70
|
+
@request_interceptor.setter
|
|
71
|
+
def request_interceptor(self, interceptor: Callable) -> None:
|
|
72
|
+
self._netwire.request_interceptor = interceptor
|
|
73
|
+
self._netwire.refresh_interception()
|
|
74
|
+
|
|
75
|
+
@request_interceptor.deleter
|
|
76
|
+
def request_interceptor(self) -> None:
|
|
77
|
+
self._netwire.request_interceptor = None
|
|
78
|
+
self._netwire.refresh_interception()
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def response_interceptor(self) -> Callable | None:
|
|
82
|
+
return self._netwire.response_interceptor
|
|
83
|
+
|
|
84
|
+
@response_interceptor.setter
|
|
85
|
+
def response_interceptor(self, interceptor: Callable) -> None:
|
|
86
|
+
self._netwire.response_interceptor = interceptor
|
|
87
|
+
self._netwire.refresh_interception()
|
|
88
|
+
|
|
89
|
+
@response_interceptor.deleter
|
|
90
|
+
def response_interceptor(self) -> None:
|
|
91
|
+
self._netwire.response_interceptor = None
|
|
92
|
+
self._netwire.refresh_interception()
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def har(self) -> str:
|
|
96
|
+
"""The captured requests as a HAR 1.2 archive (a JSON string)."""
|
|
97
|
+
from ._har import to_har
|
|
98
|
+
|
|
99
|
+
return to_har(self._netwire.storage.all())
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def proxy(self) -> dict:
|
|
103
|
+
"""The upstream proxy settings, in selenium-wire's format."""
|
|
104
|
+
return dict(self._netwire.config.proxy_settings)
|
|
105
|
+
|
|
106
|
+
@proxy.setter
|
|
107
|
+
def proxy(self, proxy: dict) -> None:
|
|
108
|
+
"""Switch the upstream proxy; ``{}`` connects directly.
|
|
109
|
+
|
|
110
|
+
Needs the relay: create the driver with ``netwire_options={"relay": True}``
|
|
111
|
+
(it is on already for SOCKS logins and custom_authorization).
|
|
112
|
+
"""
|
|
113
|
+
from ._relay import Upstream
|
|
114
|
+
|
|
115
|
+
config = self._netwire.config
|
|
116
|
+
if config.relay is None:
|
|
117
|
+
raise RuntimeError(
|
|
118
|
+
"netwire: switching the proxy needs the relay; create the driver with "
|
|
119
|
+
"netwire_options={'relay': True}"
|
|
120
|
+
)
|
|
121
|
+
url = (proxy or {}).get("https") or (proxy or {}).get("http")
|
|
122
|
+
upstream = Upstream.from_url(url, proxy.get("custom_authorization")) if url else None
|
|
123
|
+
config.relay.set_upstream(upstream)
|
|
124
|
+
config.proxy_settings = dict(proxy or {})
|
|
125
|
+
|
|
126
|
+
@proxy.deleter
|
|
127
|
+
def proxy(self) -> None:
|
|
128
|
+
self.proxy = {}
|
|
129
|
+
|
|
130
|
+
def quit(self) -> None:
|
|
131
|
+
backend = getattr(self, "_netwire", None)
|
|
132
|
+
if backend is not None:
|
|
133
|
+
backend.close()
|
|
134
|
+
super().quit()
|
netwire/_relay.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""A local relay between the browser and an upstream proxy.
|
|
2
|
+
|
|
3
|
+
Chrome can log in to HTTP proxies (netwire answers its Basic auth challenge)
|
|
4
|
+
but not to SOCKS proxies, cannot send a custom Proxy-Authorization header, and
|
|
5
|
+
cannot change its proxy once started. For those cases the browser is pointed at
|
|
6
|
+
this relay as a plain, login-free SOCKS5 proxy on 127.0.0.1, and the relay opens
|
|
7
|
+
each connection through the real upstream proxy:
|
|
8
|
+
|
|
9
|
+
* SOCKS5 upstream: SOCKS5 with username/password (RFC 1929);
|
|
10
|
+
* HTTP/HTTPS upstream: a CONNECT tunnel with the Proxy-Authorization header;
|
|
11
|
+
* no upstream: a direct connection.
|
|
12
|
+
|
|
13
|
+
It only moves bytes. It does not parse HTTP, decrypt TLS or need certificates.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import base64
|
|
19
|
+
import ipaddress
|
|
20
|
+
import logging
|
|
21
|
+
import select
|
|
22
|
+
import socket
|
|
23
|
+
import ssl
|
|
24
|
+
import struct
|
|
25
|
+
import threading
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from urllib.parse import unquote, urlsplit
|
|
28
|
+
|
|
29
|
+
log = logging.getLogger("netwire")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RelayError(Exception):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class Upstream:
|
|
38
|
+
scheme: str # "http", "https", "socks5" or "socks5h"
|
|
39
|
+
host: str
|
|
40
|
+
port: int
|
|
41
|
+
username: str | None = None
|
|
42
|
+
password: str | None = None
|
|
43
|
+
authorization: str | None = None # full Proxy-Authorization value for HTTP proxies
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def from_url(cls, url: str, custom_authorization: str | None = None) -> "Upstream":
|
|
47
|
+
parts = urlsplit(url)
|
|
48
|
+
scheme = (parts.scheme or "http").lower()
|
|
49
|
+
if scheme not in ("http", "https", "socks5", "socks5h"):
|
|
50
|
+
raise ValueError(f"netwire: unsupported proxy scheme {scheme!r}")
|
|
51
|
+
default_port = {"http": 80, "https": 443}.get(scheme, 1080)
|
|
52
|
+
return cls(
|
|
53
|
+
scheme=scheme,
|
|
54
|
+
host=parts.hostname or "",
|
|
55
|
+
port=parts.port or default_port,
|
|
56
|
+
username=unquote(parts.username) if parts.username else None,
|
|
57
|
+
password=unquote(parts.password or "") if parts.username else None,
|
|
58
|
+
authorization=custom_authorization,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _recv_exact(sock: socket.socket, n: int) -> bytes:
|
|
63
|
+
data = b""
|
|
64
|
+
while len(data) < n:
|
|
65
|
+
chunk = sock.recv(n - len(data))
|
|
66
|
+
if not chunk:
|
|
67
|
+
raise RelayError("connection closed during handshake")
|
|
68
|
+
data += chunk
|
|
69
|
+
return data
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _socks_address(host: str) -> bytes:
|
|
73
|
+
try:
|
|
74
|
+
ip = ipaddress.ip_address(host)
|
|
75
|
+
except ValueError:
|
|
76
|
+
encoded = host.encode("idna")
|
|
77
|
+
return b"\x03" + bytes([len(encoded)]) + encoded
|
|
78
|
+
return (b"\x01" if ip.version == 4 else b"\x04") + ip.packed
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _read_socks_reply_address(sock: socket.socket) -> None:
|
|
82
|
+
kind = _recv_exact(sock, 1)[0]
|
|
83
|
+
if kind == 1:
|
|
84
|
+
_recv_exact(sock, 4 + 2)
|
|
85
|
+
elif kind == 4:
|
|
86
|
+
_recv_exact(sock, 16 + 2)
|
|
87
|
+
elif kind == 3:
|
|
88
|
+
_recv_exact(sock, _recv_exact(sock, 1)[0] + 2)
|
|
89
|
+
else:
|
|
90
|
+
raise RelayError("bad SOCKS reply")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def open_via(upstream: Upstream | None, host: str, port: int, timeout: float = 30) -> socket.socket:
|
|
94
|
+
"""Open a TCP connection to host:port, through ``upstream`` if given."""
|
|
95
|
+
if upstream is None:
|
|
96
|
+
return socket.create_connection((host, port), timeout=timeout)
|
|
97
|
+
sock = socket.create_connection((upstream.host, upstream.port), timeout=timeout)
|
|
98
|
+
try:
|
|
99
|
+
if upstream.scheme.startswith("socks5"):
|
|
100
|
+
methods = b"\x00\x02" if upstream.username is not None else b"\x00"
|
|
101
|
+
sock.sendall(b"\x05" + bytes([len(methods)]) + methods)
|
|
102
|
+
version, method = _recv_exact(sock, 2)
|
|
103
|
+
if version != 5 or method == 0xFF:
|
|
104
|
+
raise RelayError("SOCKS proxy refused every login method")
|
|
105
|
+
if method == 2:
|
|
106
|
+
user = (upstream.username or "").encode()
|
|
107
|
+
password = (upstream.password or "").encode()
|
|
108
|
+
sock.sendall(b"\x01" + bytes([len(user)]) + user + bytes([len(password)]) + password)
|
|
109
|
+
if _recv_exact(sock, 2)[1] != 0:
|
|
110
|
+
raise RelayError("SOCKS proxy rejected the username or password")
|
|
111
|
+
sock.sendall(b"\x05\x01\x00" + _socks_address(host) + struct.pack(">H", port))
|
|
112
|
+
reply = _recv_exact(sock, 3)
|
|
113
|
+
if reply[1] != 0:
|
|
114
|
+
raise RelayError(f"SOCKS proxy could not connect to {host}:{port} (code {reply[1]})")
|
|
115
|
+
_read_socks_reply_address(sock)
|
|
116
|
+
else:
|
|
117
|
+
if upstream.scheme == "https":
|
|
118
|
+
context = ssl.create_default_context()
|
|
119
|
+
sock = context.wrap_socket(sock, server_hostname=upstream.host)
|
|
120
|
+
target = f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
|
|
121
|
+
lines = [f"CONNECT {target} HTTP/1.1", f"Host: {target}"]
|
|
122
|
+
if upstream.authorization:
|
|
123
|
+
lines.append(f"Proxy-Authorization: {upstream.authorization}")
|
|
124
|
+
elif upstream.username is not None:
|
|
125
|
+
token = base64.b64encode(f"{upstream.username}:{upstream.password}".encode()).decode()
|
|
126
|
+
lines.append(f"Proxy-Authorization: Basic {token}")
|
|
127
|
+
sock.sendall(("\r\n".join(lines) + "\r\n\r\n").encode())
|
|
128
|
+
head = b""
|
|
129
|
+
while b"\r\n\r\n" not in head:
|
|
130
|
+
chunk = sock.recv(4096)
|
|
131
|
+
if not chunk:
|
|
132
|
+
raise RelayError("proxy closed the connection during CONNECT")
|
|
133
|
+
head += chunk
|
|
134
|
+
if len(head) > 65536:
|
|
135
|
+
raise RelayError("proxy sent an oversized CONNECT reply")
|
|
136
|
+
status_line = head.split(b"\r\n", 1)[0].decode("latin-1")
|
|
137
|
+
parts = status_line.split()
|
|
138
|
+
if len(parts) < 2 or parts[1] != "200":
|
|
139
|
+
raise RelayError(f"proxy refused CONNECT {target}: {status_line}")
|
|
140
|
+
# Nothing should follow the reply before the client speaks; drop it if so.
|
|
141
|
+
sock.settimeout(None)
|
|
142
|
+
return sock
|
|
143
|
+
except Exception:
|
|
144
|
+
sock.close()
|
|
145
|
+
raise
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _splice(a: socket.socket, b: socket.socket, stop: threading.Event) -> None:
|
|
149
|
+
sockets = [a, b]
|
|
150
|
+
try:
|
|
151
|
+
while not stop.is_set():
|
|
152
|
+
readable, _, errored = select.select(sockets, [], sockets, 1.0)
|
|
153
|
+
if errored:
|
|
154
|
+
return
|
|
155
|
+
for src in readable:
|
|
156
|
+
data = src.recv(65536)
|
|
157
|
+
if not data:
|
|
158
|
+
return
|
|
159
|
+
(b if src is a else a).sendall(data)
|
|
160
|
+
except OSError:
|
|
161
|
+
return
|
|
162
|
+
finally:
|
|
163
|
+
for s in sockets:
|
|
164
|
+
try:
|
|
165
|
+
s.close()
|
|
166
|
+
except OSError:
|
|
167
|
+
pass
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class Relay:
|
|
171
|
+
"""A SOCKS5 server on 127.0.0.1 (no login) that forwards through ``upstream``."""
|
|
172
|
+
|
|
173
|
+
def __init__(self, upstream: Upstream | None) -> None:
|
|
174
|
+
self.upstream = upstream
|
|
175
|
+
self._server = socket.create_server(("127.0.0.1", 0))
|
|
176
|
+
self.port = self._server.getsockname()[1]
|
|
177
|
+
self._stop = threading.Event()
|
|
178
|
+
self._generation = threading.Event() # set to drop connections made through an old upstream
|
|
179
|
+
self._lock = threading.Lock()
|
|
180
|
+
threading.Thread(target=self._accept, name="netwire-relay", daemon=True).start()
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def address(self) -> str:
|
|
184
|
+
return f"socks5://127.0.0.1:{self.port}"
|
|
185
|
+
|
|
186
|
+
def set_upstream(self, upstream: Upstream | None) -> None:
|
|
187
|
+
"""Send new connections through ``upstream`` and drop the open ones,
|
|
188
|
+
so the browser reconnects through it."""
|
|
189
|
+
with self._lock:
|
|
190
|
+
self.upstream = upstream
|
|
191
|
+
old, self._generation = self._generation, threading.Event()
|
|
192
|
+
old.set()
|
|
193
|
+
|
|
194
|
+
def close(self) -> None:
|
|
195
|
+
self._stop.set()
|
|
196
|
+
self._generation.set()
|
|
197
|
+
try:
|
|
198
|
+
self._server.close()
|
|
199
|
+
except OSError:
|
|
200
|
+
pass
|
|
201
|
+
|
|
202
|
+
def _accept(self) -> None:
|
|
203
|
+
while not self._stop.is_set():
|
|
204
|
+
try:
|
|
205
|
+
client, _ = self._server.accept()
|
|
206
|
+
except OSError:
|
|
207
|
+
return
|
|
208
|
+
threading.Thread(target=self._handle, args=(client,), daemon=True).start()
|
|
209
|
+
|
|
210
|
+
def _handle(self, client: socket.socket) -> None:
|
|
211
|
+
try:
|
|
212
|
+
client.settimeout(30)
|
|
213
|
+
version, count = _recv_exact(client, 2)
|
|
214
|
+
if version != 5:
|
|
215
|
+
raise RelayError("not a SOCKS5 client")
|
|
216
|
+
_recv_exact(client, count)
|
|
217
|
+
client.sendall(b"\x05\x00")
|
|
218
|
+
version, command, _ = _recv_exact(client, 3)
|
|
219
|
+
kind = _recv_exact(client, 1)[0]
|
|
220
|
+
if kind == 1:
|
|
221
|
+
host = socket.inet_ntoa(_recv_exact(client, 4))
|
|
222
|
+
elif kind == 4:
|
|
223
|
+
host = socket.inet_ntop(socket.AF_INET6, _recv_exact(client, 16))
|
|
224
|
+
elif kind == 3:
|
|
225
|
+
host = _recv_exact(client, _recv_exact(client, 1)[0]).decode("idna")
|
|
226
|
+
else:
|
|
227
|
+
raise RelayError("bad address type")
|
|
228
|
+
port = struct.unpack(">H", _recv_exact(client, 2))[0]
|
|
229
|
+
if command != 1:
|
|
230
|
+
client.sendall(b"\x05\x07\x00\x01" + b"\x00" * 6) # only CONNECT
|
|
231
|
+
raise RelayError("only CONNECT is supported")
|
|
232
|
+
with self._lock:
|
|
233
|
+
upstream, generation = self.upstream, self._generation
|
|
234
|
+
try:
|
|
235
|
+
remote = open_via(upstream, host, port)
|
|
236
|
+
except Exception as exc:
|
|
237
|
+
log.warning("netwire relay: %s:%s failed: %s", host, port, exc)
|
|
238
|
+
client.sendall(b"\x05\x05\x00\x01" + b"\x00" * 6)
|
|
239
|
+
raise
|
|
240
|
+
client.sendall(b"\x05\x00\x00\x01" + b"\x00" * 6)
|
|
241
|
+
client.settimeout(None)
|
|
242
|
+
except Exception:
|
|
243
|
+
try:
|
|
244
|
+
client.close()
|
|
245
|
+
except OSError:
|
|
246
|
+
pass
|
|
247
|
+
return
|
|
248
|
+
_splice(client, remote, _AnyEvent(self._stop, generation))
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class _AnyEvent:
|
|
252
|
+
"""Set when any of the given events is set."""
|
|
253
|
+
|
|
254
|
+
def __init__(self, *events: threading.Event) -> None:
|
|
255
|
+
self._events = events
|
|
256
|
+
|
|
257
|
+
def is_set(self) -> bool:
|
|
258
|
+
return any(e.is_set() for e in self._events)
|