Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic
C ccybersecurityhttp3httpproxylinuxlinux-proxymacosmacos-appmacos-proxyproxifierproxifier-alternativeproxyclienttcpthick-clientudpwindivertwindows
test(macos): add end-to-end and logic regression tests
AnoF-Cyber9b755e5a0a91
diff --git a/MacOS/tests/.gitignore b/MacOS/tests/.gitignorenew file mode 100644index 0000000..ca29812--- /dev/null+++ b/MacOS/tests/.gitignore@@ -0,0 +1,3 @@+work/+__pycache__/+!*.pydiff --git a/MacOS/tests/README.md b/MacOS/tests/README.mdnew file mode 100644index 0000000..19315f8--- /dev/null+++ b/MacOS/tests/README.md@@ -0,0 +1,88 @@+# ProxyBridge macOS tests++Regression tests for the macOS app and system extension. They found the UDP association leak, the proxy+reply parsing bugs and the BLOCK-without-proxy bug, so run them before every release.++There are two kinds:++| | needs | time |+|---|---|---|+| **Logic tests** (`logic/run.sh`) | the Xcode command line tools | seconds |+| **End-to-end tests** (`pbtest.py`) | the app installed, the system extension approved, the test profile imported, internet | about 5 minutes (+2.5 with `--slow`) |++The end-to-end tests cannot run on a GitHub-hosted runner: macOS asks a person to approve the system extension+and the network configuration. Run them locally, or on a dedicated Mac where both are already approved.++## Logic tests++```+./logic/run.sh+```++Compiles `matcher_tests.swift` (rule matching: process, host, domain and port patterns) and `dnsmap_tests.swift`+(the IP to name map, the 5 minute name age, the safe-hostname check) against the real extension sources and runs them.++## End-to-end tests++One-time setup:++1. Install and start ProxyBridge, approve the system extension and the network configuration when macOS asks.+2. In the app, create a profile and import `pbtest.pbprofile` (Profiles menu, Import). It adds five test proxies+ on `127.0.0.1` (SOCKS5 1080, SOCKS5 1081 with auth, SOCKS5 1082 black hole, HTTP 8080, HTTP 8081 with auth;+ the credentials `pbtest` / `pbpass` are dummies) and ten rules. Make it the active profile.+3. Python 3 and a C compiler must be available (`xcode-select --install`).++Run:++```+python3 pbtest.py # functional replies hostnames stress dns leaks+python3 pbtest.py functional # one suite+python3 pbtest.py --slow # also the idle UDP reaper test (2.5 minutes)+sudo -v && python3 pbtest.py # `sudo -v` first so `leaks` and the DNS cache flush can run without a prompt+```++The runner starts the test proxies (`servers.py`) and builds `pbudp.c` itself. Rules match on process name, so+the tests run `curl`, `nc`, `openssl` and the small `pbudp` tool, which is why the profile has rules for those.+If the rules are not active it stops with a message instead of failing every test.++| suite | checks |+|---|---|+| `functional` | rules route correctly: SOCKS5, HTTP, HTTP with auth, DIRECT, BLOCK, no rule, UDP through SOCKS5 (with and without auth), a stuck proxy handshake is cut after about 20 s |+| `replies` | a SOCKS5 reply in the longer IPv6 form followed immediately by a banner, an HTTP `200` with a banner glued to the headers, a `407` whose headers contain "200" |+| `hostnames` | the proxy receives host names or IPs according to its own "Let proxy resolve DNS" box (flushes the DNS cache first when sudo is available, so the extension sees a fresh answer for each name) |+| `stress` | three bursts of 300 UDP flows (all closed, memory flat), 300 parallel TCP connections (all succeed, none left open) |+| `dns` | 200 uncached lookups through the DNS proxy all return the right answer |+| `idle` | 40 idle UDP flows are reaped after about 2 minutes while the app still holds the sockets |+| `leaks` | `leaks` on the extension reports 0 (the extension is a root process, so this needs sudo) |++### Hostname suite with a box unticked++`hostnames` expects every proxy to have "Let proxy resolve DNS (send hostname)" ticked (the default). To check that+the setting is per proxy, untick it on some proxies in the app and tell the runner which, by port:++```+python3 pbtest.py hostnames:off1080,8080+```++Those proxies must then receive IPs while the others still receive names.++## Not automated++- **BLOCK without any proxy configured.** Create an empty profile (new profiles start empty) with rules+ `openssl`, any host, any port, protocol BOTH, BLOCK and `nc`, any host, any port, UDP, BLOCK. With no proxies at all,+ `openssl s_client -connect example.net:443` must fail and `nc -u <ntp ip> 123` must get no reply.+- **Rule updates without a gap** (editing rules while traffic runs) and the **update download** need the GUI.+- **A client that half-closes** (`printf ... | nc`) cannot get a reply through a transparent proxy flow on macOS, the+ system closes the flow itself. That is a platform limit, so the tests keep stdin open.++## Notes++- `leaks` freezes the extension for several seconds while it scans, so it runs last. Names the system resolver+ answers from its cache (no DNS packet) are unknown to the extension and go to the proxy as IPs, that is the+ designed fallback. The `hostnames` suite flushes the cache first when sudo works.+- The tests need the internet (example.com, example.net, example.org, www.iana.org, www.apple.com, neverssl.com,+ `time.apple.com` for NTP and `sslip.io` for DNS). Set `PB_NTP_IP` to use a different NTP server.+- `192.0.2.0/24` is a documentation range. The tests use it for addresses nothing answers, the test proxies+ answer for a few of them by themselves.+- Everything the proxies see is logged to `work/events.log` (ignored by git).+- The test rules redirect `curl`, `nc`, `openssl` and `pbudp` traffic. Switch back to your normal profile afterwards.diff --git a/MacOS/tests/logic/dnsmap_tests.swift b/MacOS/tests/logic/dnsmap_tests.swiftnew file mode 100644index 0000000..041813d--- /dev/null+++ b/MacOS/tests/logic/dnsmap_tests.swift@@ -0,0 +1,55 @@+// DNSMapStore: lookups, newest-first, the 5 minute name age, caps, hostname safety. Compiled as main.swift by run.sh.+import Foundation++var fails = 0+func t(_ name: String, _ ok: Bool) { if !ok { fails += 1; print("FAIL", name) } }+let s = DNSMapStore.shared+s.clear()++s.record(domain: "A.Example.com", ips: ["1.1.1.1", "2606::1"], now: 100)+t("lookup is lowercased", s.domains(forIP: "1.1.1.1") == ["a.example.com"])+t("ipv6 key", s.domains(forIP: "2606::1") == ["a.example.com"])+s.record(domain: "b.example.com", ips: ["1.1.1.1"], now: 110)+t("newest first", s.domains(forIP: "1.1.1.1") == ["b.example.com", "a.example.com"])+s.record(domain: "a.example.com", ips: ["1.1.1.1"], now: 120)+t("seen again becomes newest without a duplicate", s.domains(forIP: "1.1.1.1") == ["a.example.com", "b.example.com"])+for i in 0..<20 { s.record(domain: "d\(i).test", ips: ["9.9.9.9"], now: 200) }+t("at most 8 names per ip, newest kept", s.domains(forIP: "9.9.9.9").count == 8 && s.domains(forIP: "9.9.9.9").first == "d19.test")+for i in 0..<3000 { s.record(domain: "x\(i).test", ips: ["10.\(i / 250).\(i % 250).1"], now: 300) }+t("map stays bounded, oldest evicted", s.domains(forIP: "10.0.0.1").isEmpty)+t("newest entries kept", s.domains(forIP: "10.11.249.1") == ["x2999.test"])+s.clear()+t("clear empties the map", s.domains(forIP: "1.1.1.1").isEmpty)++// the name handed to a proxy (Let proxy resolve DNS)+s.record(domain: "a.example.com", ips: ["1.1.1.1"], now: 100)+s.record(domain: "b.example.com", ips: ["1.1.1.1"], now: 110)+t("newest name wins", s.latestDomain(forIP: "1.1.1.1", maxAge: 300, now: 120) == "b.example.com")+t("still good at exactly 300 seconds", s.latestDomain(forIP: "1.1.1.1", maxAge: 300, now: 410) == "b.example.com")+t("expired after 300 seconds", s.latestDomain(forIP: "1.1.1.1", maxAge: 300, now: 411) == nil)+s.record(domain: "a.example.com", ips: ["1.1.1.1"], now: 500)+t("a fresh answer refreshes the age", s.latestDomain(forIP: "1.1.1.1", maxAge: 300, now: 600) == "a.example.com")+t("unknown address gives nil so the caller sends the ip", s.latestDomain(forIP: "8.8.4.4", maxAge: 300, now: 600) == nil)++// names come out of DNS packets, only plain host names may reach a proxy+let good = ["example.com", "a-b.c_d.example.org", "xn--bcher-kva.example", "localhost", "a"]+let bad = ["", "exa mple.com", "example.com\r\nHost: evil", "exam\u{0}ple.com", "ex\u{e9}ample.com", ".example.com", "example.com.",+ "1.2.3.4", "::1", "example.com:443", "a/b.com", "[email protected]", String(repeating: "a", count: 254)]+for g in good { t("safe name: \(g)", DNSMapStore.isSafeHostname(g)) }+for b in bad { t("unsafe name rejected: \(b.debugDescription.prefix(28))", !DNSMapStore.isSafeHostname(b)) }+s.record(domain: "bad name.com", ips: ["5.5.5.5"], now: 1000)+t("an unsafe newest name is never returned", s.latestDomain(forIP: "5.5.5.5", maxAge: 300, now: 1001) == nil)+s.record(domain: "1.2.3.4", ips: ["1.2.3.4"], now: 1000)+t("an ip literal is not a name", s.latestDomain(forIP: "1.2.3.4", maxAge: 300, now: 1001) == nil)++// several threads writing and reading at once+let group = DispatchGroup()+for w in 0..<8 {+ DispatchQueue.global().async(group: group) {+ for i in 0..<5000 { s.record(domain: "c\(w).test", ips: ["7.\(w).\(i % 200).1"]); _ = s.domains(forIP: "7.\(w).1.1") }+ }+}+group.wait()++print(fails == 0 ? "dns map tests: ALL PASS" : "dns map tests: \(fails) FAILED")+exit(fails == 0 ? 0 : 1)diff --git a/MacOS/tests/logic/matcher_tests.swift b/MacOS/tests/logic/matcher_tests.swiftnew file mode 100644index 0000000..9982a55--- /dev/null+++ b/MacOS/tests/logic/matcher_tests.swift@@ -0,0 +1,55 @@+// Rule matching (ProxyRule.Matcher in AppProxyProvider.swift). Compiled as main.swift by run.sh.+import Foundation++func matcher(_ p: String, _ h: String, _ pt: String) -> ProxyRule.Matcher {+ ProxyRule.Matcher(ProxyRule(ruleId: 1, processNames: p, targetHosts: h, targetPorts: pt, ruleProtocol: .both, action: "DIRECT", enabled: true))+}+var fails = 0+func t(_ name: String, _ got: Bool, _ expected: Bool) { if got != expected { fails += 1; print("FAIL", name) } }++let chrome = ProxyRule.FlowProcess(bundleId: "com.google.Chrome", processName: "Google Chrome")+let curl = ProxyRule.FlowProcess(bundleId: "curl-abc", processName: "curl")++// process patterns+t("star", matcher("*", "*", "*").matchesProcess(chrome), true)+t("prefix glob must match the start only", matcher("chrome*", "*", "*").matchesProcess(chrome), false)+t("contains glob", matcher("*chrome*", "*", "*").matchesProcess(chrome), true)+t("exact name", matcher("curl", "*", "*").matchesProcess(curl), true)+t("list with spaces", matcher("safari; curl", "*", "*").matchesProcess(curl), true)+t("comma list", matcher("safari,curl", "*", "*").matchesProcess(curl), true)+t("trailing separator is not a wildcard", matcher("safari;", "*", "*").matchesProcess(curl), false)+t("leading separator is not a wildcard", matcher(";safari", "*", "*").matchesProcess(curl), false)+t("bundle id glob", matcher("com.google.*", "*", "*").matchesProcess(chrome), true)+t("case insensitive", matcher("CURL", "*", "*").matchesProcess(curl), true)+t("no match", matcher("firefox", "*", "*").matchesProcess(curl), false)++// ports+t("port in list", matcher("*", "*", "80,443,8000-8100").matchesPort(8050), true)+t("port exact", matcher("*", "*", "80,443").matchesPort(443), true)+t("port miss", matcher("*", "*", "80,443").matchesPort(81), false)+t("port range edge low", matcher("*", "*", "8000-8100").matchesPort(8000), true)+t("port range edge high", matcher("*", "*", "8000-8100").matchesPort(8100), true)+t("port range just out", matcher("*", "*", "8000-8100").matchesPort(8101), false)+t("all ports", matcher("*", "*", "*").matchesPort(1), true)+t("garbage port never matches", matcher("*", "*", "abc").matchesPort(1), false)+t("trailing separator in ports is not a wildcard", matcher("*", "*", "80;").matchesPort(443), false)+t("reversed range never matches", matcher("*", "*", "9000-8000").matchesPort(8500), false)++// hosts: ips, ranges, v6, domains+func dom(_ names: String...) -> [(name: String, chars: [Character])] { names.map { (name: $0, chars: Array($0)) } }+t("ip exact", matcher("*", "10.0.0.5", "*").matchesHost(ip: "10.0.0.5", domains: []), true)+t("ip wildcard octet", matcher("*", "192.168.1.*", "*").matchesHost(ip: "192.168.1.9", domains: []), true)+t("ip range", matcher("*", "10.0.0.1-10.0.0.9", "*").matchesHost(ip: "10.0.0.5", domains: []), true)+t("ip miss", matcher("*", "10.0.0.5", "*").matchesHost(ip: "10.0.0.6", domains: []), false)+t("ipv6 exact", matcher("*", "::1", "*").matchesHost(ip: "::1", domains: []), true)+t("ipv6 prefix wildcard", matcher("*", "2001:db8:*", "*").matchesHost(ip: "2001:db8::5", domains: []), true)+t("domain glob", matcher("*", "*.github.com", "*").matchesHost(ip: "1.1.1.1", domains: dom("api.github.com")), true)+t("domain glob covers the apex", matcher("*", "*.github.com", "*").matchesHost(ip: "1.1.1.1", domains: dom("github.com")), true)+t("domain miss", matcher("*", "*.gitlab.com", "*").matchesHost(ip: "1.1.1.1", domains: dom("api.github.com")), false)+t("domain exact", matcher("*", "example.com", "*").matchesHost(ip: "1.1.1.1", domains: dom("example.com")), true)+t("list of ip and domain", matcher("*", "1.2.3.4;*.github.com", "*").matchesHost(ip: "9.9.9.9", domains: dom("api.github.com")), true)+t("domain rule without any known name", matcher("*", "*.github.com", "*").matchesHost(ip: "9.9.9.9", domains: []), false)+t("all hosts", matcher("*", "*", "*").matchesHost(ip: "9.9.9.9", domains: []), true)++print(fails == 0 ? "matcher tests: ALL PASS" : "matcher tests: \(fails) FAILED")+exit(fails == 0 ? 0 : 1)diff --git a/MacOS/tests/logic/run.sh b/MacOS/tests/logic/run.shnew file mode 100755index 0000000..8cad922--- /dev/null+++ b/MacOS/tests/logic/run.sh@@ -0,0 +1,19 @@+#!/bin/bash+# Compiles each logic test against the real extension sources and runs it. No installed extension or+# network needed, this is what could run on a hosted CI runner. Needs the Xcode command line tools.+set -e+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+EXT="$HERE/../../ProxyBridge/extension"+TMP="$(mktemp -d)"+trap 'rm -rf "$TMP"' EXIT++run_test() { # <test file> <extension sources...>+ local test="$1"; shift+ cp "$HERE/$test" "$TMP/main.swift"+ swiftc -o "$TMP/test" "$@" "$TMP/main.swift" -framework NetworkExtension 2>"$TMP/build.log" \+ || { echo "build failed for $test"; grep -E "error:" "$TMP/build.log" | head; exit 1; }+ "$TMP/test"+}++run_test matcher_tests.swift "$EXT/AppProxyProvider.swift" "$EXT/DNSMapStore.swift"+run_test dnsmap_tests.swift "$EXT/DNSMapStore.swift"diff --git a/MacOS/tests/pbtest.pbprofile b/MacOS/tests/pbtest.pbprofilenew file mode 100644index 0000000..bf34456--- /dev/null+++ b/MacOS/tests/pbtest.pbprofile@@ -0,0 +1,154 @@+{+ "closeToMenuBar": false,+ "name": "PBTest",+ "proxyConfigs": [+ {+ "host": "127.0.0.1",+ "id": "pbtest-socks-1080",+ "name": "pbtest socks5",+ "port": 1080,+ "sendDomain": true,+ "type": "socks5"+ },+ {+ "host": "127.0.0.1",+ "id": "pbtest-socks-1081",+ "name": "pbtest socks5 auth",+ "password": "pbpass",+ "port": 1081,+ "sendDomain": true,+ "type": "socks5",+ "username": "pbtest"+ },+ {+ "host": "127.0.0.1",+ "id": "pbtest-socks-1082",+ "name": "pbtest black hole",+ "port": 1082,+ "sendDomain": true,+ "type": "socks5"+ },+ {+ "host": "127.0.0.1",+ "id": "pbtest-http-8080",+ "name": "pbtest http",+ "port": 8080,+ "sendDomain": true,+ "type": "http"+ },+ {+ "host": "127.0.0.1",+ "id": "pbtest-http-8081",+ "name": "pbtest http auth",+ "password": "pbpass",+ "port": 8081,+ "sendDomain": true,+ "type": "http",+ "username": "pbtest"+ }+ ],+ "proxyRules": [+ {+ "action": "pbtest-socks-1080",+ "enabled": true,+ "localId": "pbtest-rule-01",+ "name": "",+ "processNames": "curl",+ "protocol": "TCP",+ "targetHosts": "example.com",+ "targetPorts": "*"+ },+ {+ "action": "pbtest-http-8081",+ "enabled": true,+ "localId": "pbtest-rule-02",+ "name": "",+ "processNames": "curl",+ "protocol": "TCP",+ "targetHosts": "example.net",+ "targetPorts": "*"+ },+ {+ "action": "pbtest-http-8080",+ "enabled": true,+ "localId": "pbtest-rule-03",+ "name": "",+ "processNames": "curl",+ "protocol": "TCP",+ "targetHosts": "example.org",+ "targetPorts": "*"+ },+ {+ "action": "DIRECT",+ "enabled": true,+ "localId": "pbtest-rule-04",+ "name": "",+ "processNames": "curl",+ "protocol": "TCP",+ "targetHosts": "www.iana.org",+ "targetPorts": "*"+ },+ {+ "action": "pbtest-socks-1082",+ "enabled": true,+ "localId": "pbtest-rule-05",+ "name": "",+ "processNames": "curl",+ "protocol": "TCP",+ "targetHosts": "neverssl.com",+ "targetPorts": "*"+ },+ {+ "action": "pbtest-socks-1081",+ "enabled": true,+ "localId": "pbtest-rule-06",+ "name": "",+ "processNames": "nc",+ "protocol": "TCP",+ "targetHosts": "*",+ "targetPorts": "80"+ },+ {+ "action": "pbtest-socks-1080",+ "enabled": true,+ "localId": "pbtest-rule-07",+ "name": "",+ "processNames": "pbudp",+ "protocol": "UDP",+ "targetHosts": "*",+ "targetPorts": "*"+ },+ {+ "action": "pbtest-socks-1081",+ "enabled": true,+ "localId": "pbtest-rule-08",+ "name": "",+ "processNames": "nc",+ "protocol": "UDP",+ "targetHosts": "*",+ "targetPorts": "*"+ },+ {+ "action": "BLOCK",+ "enabled": true,+ "localId": "pbtest-rule-09",+ "name": "",+ "processNames": "openssl",+ "protocol": "BOTH",+ "targetHosts": "*",+ "targetPorts": "*"+ },+ {+ "action": "pbtest-http-8080",+ "enabled": true,+ "localId": "pbtest-rule-10",+ "name": "",+ "processNames": "nc",+ "protocol": "TCP",+ "targetHosts": "192.0.2.20;192.0.2.21",+ "targetPorts": "22"+ }+ ],+ "runAtStartup": false,+ "trafficLoggingEnabled": true+}diff --git a/MacOS/tests/pbtest.py b/MacOS/tests/pbtest.pynew file mode 100644index 0000000..baeebae--- /dev/null+++ b/MacOS/tests/pbtest.py@@ -0,0 +1,348 @@+#!/usr/bin/env python3+"""ProxyBridge macOS end-to-end tests. Run on a Mac that has the app installed, the system extension+approved and the pbtest.pbprofile imported (see README.md). The runner starts the local test proxies+(servers.py) itself and builds pbudp.c when needed.++ python3 pbtest.py the default set: functional replies hostnames stress dns leaks+ python3 pbtest.py functional stress only those suites+ python3 pbtest.py --slow the default set plus the 2.5 minute idle-UDP test+ python3 pbtest.py hostnames:off1080,8080+ hostname suite when the "Let proxy resolve DNS" box is unticked on+ the proxies with those ports (plain "hostnames" = all ticked)++suites: functional rule routing, SOCKS5/HTTP/auth, DIRECT, BLOCK, UDP, stuck-handshake cut+ replies SOCKS5 reply in IPv6 form + banner, HTTP 200 + banner, 407 with "200" in the headers+ hostnames proxies receive host names (option on) or IPs (option off), per proxy+ stress 300 parallel TCP connections, three bursts of 300 UDP flows (memory must stay flat)+ dns 200 uncached DNS lookups through the DNS proxy+ idle 40 idle UDP flows must be reaped after ~2 minutes (slow)+ leaks `leaks` on the extension must report 0 (needs `sudo -v` first, or SUDO_ASKPASS)+Environment: PB_NTP_IP (default: time.apple.com resolved once), PB_EVENTS (event log path)."""+import atexit, concurrent.futures as cf, json, os, random, socket, subprocess, sys, threading, time++HERE = os.path.dirname(os.path.abspath(__file__))+WORK = os.path.join(HERE, "work")+os.makedirs(WORK, exist_ok=True)+LOG = os.environ.setdefault("PB_EVENTS", os.path.join(WORK, "events.log"))+PBUDP = os.path.join(WORK, "pbudp")+EXT = "com.interceptsuite.ProxyBridge.extension"+NTP_PAYLOAD = b"\x1b" + b"\0" * 47+results = []+_servers = None+++# ---------------------------------------------------------------- plumbing+def events(since):+ out = []+ try:+ for line in open(LOG):+ try:+ e = json.loads(line)+ except ValueError:+ continue+ if e["t"] >= since:+ out.append(e)+ except FileNotFoundError:+ pass+ return out+++def hits(evs, kind, proxy=None, port=None):+ return [e for e in evs if e["kind"] == kind and (proxy is None or e.get("proxy") == proxy)+ and (port is None or e.get("port") == port)]+++def ext_pid():+ r = subprocess.run(["pgrep", "-f", EXT], capture_output=True, text=True)+ pids = [int(p) for p in r.stdout.split() if p]+ return pids[0] if pids else None+++def snap():+ """(rss MB, %cpu) of the extension, or None."""+ pid = ext_pid()+ if not pid:+ return None+ r = subprocess.run(["ps", "-o", "rss=,%cpu=", "-p", str(pid)], capture_output=True, text=True).stdout.split()+ return (int(r[0]) / 1024.0, float(r[1])) if len(r) == 2 else None+++def run(cmd, timeout=30, inp=None):+ try:+ p = subprocess.run(cmd, capture_output=True, timeout=timeout, input=inp)+ return p.returncode, p.stdout, p.stderr+ except subprocess.TimeoutExpired:+ return 124, b"", b"timeout"+++def check(name, ok, detail=""):+ results.append((name, ok, detail))+ print(("PASS " if ok else "FAIL ") + name + (" - " + detail if detail else ""), flush=True)+++def port_open(port):+ try:+ socket.create_connection(("127.0.0.1", port), 0.5).close()+ return True+ except OSError:+ return False+++def start_servers():+ global _servers+ if port_open(1080):+ print("note: something already listens on 1080, assuming the test proxies are running "+ f"(their event log must be {LOG})")+ return+ # servers.py prints asyncio shutdown noise when it is stopped, keep that out of the test output+ _servers = subprocess.Popen([sys.executable, os.path.join(HERE, "servers.py")], stdout=subprocess.DEVNULL,+ stderr=open(os.path.join(WORK, "servers.err"), "w"), env=os.environ)+ atexit.register(lambda: _servers and _servers.terminate())+ for _ in range(50):+ if port_open(1080) and port_open(8081):+ return+ time.sleep(0.1)+ sys.exit("test proxies did not start")+++def build_pbudp():+ src = os.path.join(HERE, "pbudp.c")+ if not os.path.exists(PBUDP) or os.path.getmtime(PBUDP) < os.path.getmtime(src):+ subprocess.run(["cc", "-O2", "-o", PBUDP, src], check=True)+++def sudo_prefix():+ """['sudo','-n'] after `sudo -v` in this terminal, ['sudo','-A'] when SUDO_ASKPASS is set, else None.+ Nothing here reads or stores a password itself."""+ if subprocess.run(["sudo", "-n", "true"], capture_output=True).returncode == 0:+ return ["sudo", "-n"]+ if os.environ.get("SUDO_ASKPASS"):+ return ["sudo", "-A"]+ return None+++def flush_dns_cache():+ """Make the system resolver ask again, so the extension sees a fresh DNS answer for every name the+ hostname tests use. Without sudo the tests still run, but a name the resolver served from its cache+ (no DNS packet, so nothing for the extension to learn) is sent to the proxy as an IP."""+ sudo = sudo_prefix()+ if not sudo:+ print("note: no sudo, DNS cache not flushed (hostname checks can fall back to IPs if the resolver answers from cache)")+ return+ subprocess.run(sudo + ["dscacheutil", "-flushcache"], capture_output=True)+ subprocess.run(sudo + ["killall", "-HUP", "mDNSResponder"], capture_output=True)+ time.sleep(2)+++def ntp_ip():+ return os.environ.get("PB_NTP_IP") or socket.gethostbyname("time.apple.com")+++def preflight():+ """A request that the first test rule must send through SOCKS5 1080, so a missing setup is obvious."""+ t0 = time.time()+ run(["curl", "-s", "-o", "/dev/null", "-m", "15", "https://example.com"], 20)+ time.sleep(1)+ if ext_pid() is None:+ sys.exit("The ProxyBridge extension is not running. Start the app and approve the system extension.")+ if not hits(events(t0), "connect", "socks1080", 443):+ sys.exit("The test rules are not active: curl to example.com did not reach SOCKS5 1080.\n"+ "Import pbtest.pbprofile (Profiles menu, Import) and make it the active profile, see README.md.")+++def scenario(name, cmd, expect, timeout=30, inp=None, client_ok=None):+ """expect = (event kind, proxy, port): the proxy must have seen it, or proxy None = nothing proxied."""+ t0 = time.time()+ rc, out, err = run(cmd, timeout, inp)+ time.sleep(1.0)+ evs = events(t0)+ kind, proxy, port = expect+ if proxy is None:+ proxied = [e for e in evs if e["kind"] in ("connect", "udp_assoc_open")]+ ok, detail = not proxied, ("went direct" if not proxied else f"unexpectedly proxied: {proxied[0]}")+ else:+ seen = hits(evs, kind, proxy, port)+ ok = bool(seen)+ detail = f"{kind} on {proxy}" + (f":{port}" if port else "") + (" seen" if ok else " NOT seen")+ if client_ok is not None:+ good = client_ok(rc, out, err)+ detail += f"; client {'ok' if good else 'FAILED'} rc={rc}"+ ok = ok and good+ check(name, ok, detail)+++HTTP_OK = lambda rc, o, e: rc == 0 and o.strip() in (b"200", b"301", b"302", b"404")+CURL = ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "-m", "25"]+++# ---------------------------------------------------------------- suites+def functional():+ print("\n== functional ==")+ scenario("T1 curl example.com -> SOCKS5 1080 (domain rule)", CURL + ["https://example.com"], ("connect", "socks1080", 443), client_ok=HTTP_OK)+ scenario("T2 curl example.net -> HTTP+auth 8081", CURL + ["http://example.net"], ("connect", "http8081", 80), client_ok=HTTP_OK)+ scenario("T3 curl example.org -> HTTP 8080", CURL + ["http://example.org"], ("connect", "http8080", 80), client_ok=HTTP_OK)+ scenario("T4 curl www.iana.org -> DIRECT", CURL + ["https://www.iana.org"], ("connect", None, None), client_ok=HTTP_OK)+ scenario("T5 curl www.apple.com -> no rule, direct", CURL + ["https://www.apple.com"], ("connect", None, None), client_ok=HTTP_OK)+ # stdin is kept open: a client that half-closes after sending cannot get a reply through a+ # transparent proxy flow on macOS (the OS closes the flow), that is a platform limit+ scenario("T6 nc -> SOCKS5+auth 1081 (process rule)",+ ["bash", "-c", "(printf 'GET / HTTP/1.0\\r\\nHost: example.com\\r\\n\\r\\n'; sleep 3) | nc -w 6 example.com 80"],+ ("connect", "socks1081", 80), timeout=20, client_ok=lambda rc, o, e: b"HTTP/1." in o)+ scenario("T7 openssl -> BLOCK", ["openssl", "s_client", "-connect", "example.net:443"], ("connect", None, None),+ timeout=15, inp=b"", client_ok=lambda rc, o, e: b"BEGIN CERTIFICATE" not in o)+ ip = ntp_ip()+ scenario("T8 pbudp NTP -> SOCKS5 1080 UDP associate", [PBUDP, "ntp", ip], ("udp_assoc_open", "socks1080", None),+ client_ok=lambda rc, o, e: o.strip() == b"48")+ scenario("T9 nc -u NTP -> SOCKS5+auth 1081 UDP associate", ["nc", "-u", "-w", "4", ip, "123"], ("udp_assoc_open", "socks1081", None),+ inp=NTP_PAYLOAD, client_ok=lambda rc, o, e: len(o) == 48)+ t0 = time.time()+ run(["curl", "-s", "-o", "/dev/null", "-m", "45", "http://neverssl.com"], 60)+ evs = events(t0)+ acc = hits(evs, "accept", "socks1082")+ closed = [e for e in evs if e["kind"] in ("closed_by_peer", "tcp_closed") and e.get("proxy") == "socks1082"]+ if acc and closed:+ dt = closed[0]["t"] - acc[0]["t"]+ check("T10 stuck proxy handshake is cut after ~20s", 15 <= dt <= 30, f"dropped after {dt:.1f}s")+ else:+ check("T10 stuck proxy handshake is cut after ~20s", False, f"accept={bool(acc)} closed={bool(closed)}")+++def replies():+ print("\n== reply parsing ==")+ def banner(name, ip, port, proxy, want):+ t0 = time.time()+ p = subprocess.run(["bash", "-c", f"(sleep 2) | nc -w 4 {ip} {port}"], capture_output=True, timeout=20)+ seen = bool(hits(events(t0), "connect", proxy, port))+ check(name, seen and p.stdout == want, f"{proxy} connect={seen}; client got {p.stdout[:40]!r}")+ banner("B2 SOCKS5 reply in IPv6 form + immediate banner", "192.0.2.10", 80, "socks1081", b"SSH-2.0-pbtest\r\n")+ banner("B1 HTTP 200 with a banner glued to the headers", "192.0.2.20", 22, "http8080", b"SSH-2.0-pbtest\r\n")+ banner("B1 HTTP 407 with '200' in its headers is not success", "192.0.2.21", 22, "http8080", b"")+++def hostnames(mode="on"):+ print(f"\n== hostnames (mode={mode}) ==")+ flush_dns_cache()+ off = set(mode[3:].split(",")) if mode.startswith("off") else set()+ def dest_of(proxy, port, cmd):+ t0 = time.time()+ run(cmd, 40)+ time.sleep(1.0)+ h = hits(events(t0), "connect", proxy, port)+ return h[-1]["dest"] if h else None+ def expect(name, proxy, port, cmd, host, want_name):+ got = dest_of(proxy, port, cmd)+ if want_name:+ check(name, got == host, f"{proxy} received {got!r} (want the name {host!r})")+ else:+ check(name, bool(got) and got != host and got.replace(".", "").isdigit(), f"{proxy} received {got!r} (want an IP)")+ c = ["curl", "-s", "-o", "/dev/null", "-m", "25"]+ expect("D1 example.com via SOCKS5 1080", "socks1080", 443, c + ["https://example.com"], "example.com", "1080" not in off)+ expect("D2 example.org via HTTP 8080", "http8080", 80, c + ["http://example.org"], "example.org", "8080" not in off)+ expect("D3 example.net via HTTP+auth 8081", "http8081", 80, c + ["http://example.net"], "example.net", "8081" not in off)+ got = dest_of("socks1081", 80, ["bash", "-c", "(sleep 2) | nc -w 3 192.0.2.10 80"])+ check("D4 address with no DNS record is sent as an IP", got == "192.0.2.10", f"socks1081 received {got!r}")+++def stress():+ print("\n== stress ==")+ subprocess.run([PBUDP, "flood", "300", "2"], capture_output=True) # warm-up+ time.sleep(8)+ for i in (1, 2, 3):+ base = snap(); t0 = time.time()+ subprocess.run([PBUDP, "flood", "300", "3"], capture_output=True, timeout=120)+ time.sleep(8)+ evs = events(t0)+ opened, closed = len(hits(evs, "udp_assoc_open", "socks1080")), len(hits(evs, "udp_assoc_close", "socks1080"))+ after = snap()+ check(f"S2.{i} 300 UDP flows opened and closed, memory flat", opened >= 295 and closed >= 295 and after[0] - base[0] < 8,+ f"opened={opened} closed={closed} RSS {base[0]:.1f}->{after[0]:.1f}MB")+ base = snap(); peak = [0.0]; stop = threading.Event()+ def sampler():+ while not stop.is_set():+ s = snap(); peak[0] = max(peak[0], s[1] if s else 0); time.sleep(0.3)+ th = threading.Thread(target=sampler); th.start(); t0 = time.time()+ sc = "curl -s -o /dev/null -m 20 -w '%{http_code}\\n' https://example.com"+ p = subprocess.run(["bash", "-c", f"seq 300 | xargs -P 30 -I{{}} {sc}"], capture_output=True, text=True, timeout=400)+ stop.set(); th.join()+ n = sum(x.startswith(("2", "3")) for x in p.stdout.split()); time.sleep(8); after = snap()+ closed = [e for e in events(t0) if e["kind"] == "tcp_closed" and e["proxy"] == "socks1080"]+ check("S1 300 parallel TCP flows", n >= 295 and bool(closed) and closed[-1]["active"] == 0,+ f"{n}/300 ok, peak CPU {peak[0]:.0f}%, RSS {base[0]:.1f}->{after[0]:.1f}MB, proxy-side open at end={closed[-1]['active'] if closed else None}")+++def dns():+ print("\n== dns ==")+ def look(i):+ name = f"10-{random.randint(1, 250)}-{random.randint(1, 250)}-{i % 250 + 1}.sslip.io" # sslip.io answers any such name+ try:+ return socket.gethostbyname(name) == name.replace(".sslip.io", "").replace("-", ".")+ except OSError:+ return False+ base = snap()+ with cf.ThreadPoolExecutor(8) as ex:+ res = list(ex.map(look, range(200)))+ time.sleep(3)+ check("D5 200 uncached DNS lookups (8 parallel) all correct", sum(res) >= 198, f"{sum(res)}/200 correct, extension {base} -> {snap()}")+++def idle():+ print("\n== idle UDP reaper (about 2.5 minutes) ==")+ t0 = time.time()+ proc = subprocess.Popen([PBUDP, "flood", "40", "170"], stdout=subprocess.DEVNULL) # 40 flows held open and silent+ time.sleep(6)+ opened = len(hits(events(t0), "udp_assoc_open", "socks1080"))+ first = None+ while time.time() - t0 < 150:+ c = hits(events(t0), "udp_assoc_close", "socks1080")+ if len(c) >= opened - 1:+ first = c[0]["t"] - t0+ break+ time.sleep(2)+ proc.terminate()+ c = hits(events(t0), "udp_assoc_close", "socks1080")+ check("S3 idle UDP flows are reaped while the app still holds the sockets", opened >= 38 and len(c) >= opened - 1,+ f"opened={opened} reaped={len(c)}" + (f", first at ~{first:.0f}s" if first else ""))+++def leaks():+ print("\n== leaks ==")+ sudo = sudo_prefix()+ if not sudo:+ print("SKIP leaks: run `sudo -v` first (or set SUDO_ASKPASS) so sudo does not prompt")+ return+ # leaks freezes the extension for several seconds while it scans, so this suite runs last+ out = subprocess.run(sudo + ["leaks", str(ext_pid())], capture_output=True, text=True).stdout+ line = next((l for l in out.splitlines() if "leaks for" in l), "")+ check("L1 leaks reports 0 leaks in the extension", " 0 leaks for 0 total leaked bytes" in line, line.strip() or "no result")+++SUITES = {"functional": functional, "replies": replies, "hostnames": hostnames, "stress": stress, "dns": dns, "idle": idle, "leaks": leaks}+DEFAULT = ["functional", "replies", "hostnames", "stress", "dns", "leaks"]+++def main():+ args = [a for a in sys.argv[1:] if not a.startswith("--")]+ if "-h" in sys.argv or "--help" in sys.argv:+ print(__doc__); return 0+ wanted = args or DEFAULT[:]+ if "--slow" in sys.argv and "idle" not in wanted:+ wanted.append("idle")+ for w in wanted:+ if w.split(":")[0] not in SUITES:+ sys.exit(f"unknown suite {w!r}, see --help")+ build_pbudp()+ start_servers()+ preflight()+ print("extension:", ext_pid(), snap())+ for w in wanted:+ name, _, arg = w.partition(":")+ SUITES[name](arg) if arg else SUITES[name]()+ bad = [r for r in results if not r[1]]+ print(f"\n{len(results) - len(bad)}/{len(results)} passed")+ for n, _, d in bad:+ print(" FAILED:", n, "-", d)+ return 1 if bad else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/MacOS/tests/pbudp.c b/MacOS/tests/pbudp.cnew file mode 100644index 0000000..d8b5120--- /dev/null+++ b/MacOS/tests/pbudp.c@@ -0,0 +1,51 @@+// Small UDP client for the ProxyBridge macOS tests. The test rules match it by process name+// ("pbudp"), which keeps it apart from the Python test proxies (rules match on process only).+//+// pbudp ntp <ip> one NTP exchange, prints the reply size (48 = answered)+// pbudp flood <n> <hold_s> n UDP sockets, one packet each to 192.0.2.1:40000 (a documentation+// address, nothing answers), sockets held open for hold_s seconds+//+// build: cc -O2 -o pbudp pbudp.c+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <unistd.h>+#include <arpa/inet.h>+#include <sys/socket.h>+#include <sys/time.h>++int main(int argc, char **argv) {+ if (argc >= 3 && !strcmp(argv[1], "ntp")) {+ int s = socket(AF_INET, SOCK_DGRAM, 0);+ struct timeval tv = {6, 0};+ setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);+ struct sockaddr_in a = {0};+ a.sin_family = AF_INET;+ a.sin_port = htons(123);+ inet_pton(AF_INET, argv[2], &a.sin_addr);+ unsigned char q[48] = {0x1b};+ sendto(s, q, 48, 0, (struct sockaddr *)&a, sizeof a);+ unsigned char r[512];+ ssize_t n = recv(s, r, sizeof r, 0);+ printf("%zd\n", n);+ return n == 48 ? 0 : 1;+ }+ if (argc >= 4 && !strcmp(argv[1], "flood")) {+ int n = atoi(argv[2]), hold = atoi(argv[3]);+ struct sockaddr_in a = {0};+ a.sin_family = AF_INET;+ a.sin_port = htons(40000);+ inet_pton(AF_INET, "192.0.2.1", &a.sin_addr);+ for (int i = 0; i < n; i++) {+ int s = socket(AF_INET, SOCK_DGRAM, 0);+ sendto(s, "x", 1, 0, (struct sockaddr *)&a, sizeof a);+ usleep(10000);+ }+ printf("opened %d\n", n);+ fflush(stdout);+ sleep(hold);+ return 0;+ }+ fprintf(stderr, "usage: pbudp ntp <ip> | pbudp flood <n> <hold_seconds>\n");+ return 2;+}diff --git a/MacOS/tests/servers.py b/MacOS/tests/servers.pynew file mode 100644index 0000000..ef43b69--- /dev/null+++ b/MacOS/tests/servers.py@@ -0,0 +1,242 @@+#!/usr/bin/env python3+"""Local proxies the ProxyBridge macOS tests talk to. Loopback only, logs every event as+one JSON line to $PB_EVENTS (default: work/events.log next to this file).++ socks5 127.0.0.1:1080 no auth (TCP CONNECT + UDP ASSOCIATE)+ socks5 127.0.0.1:1081 user/pass (pbtest / pbpass)+ socks5 127.0.0.1:1082 black hole (accepts, never answers)+ http 127.0.0.1:8080 no auth (CONNECT)+ http 127.0.0.1:8081 user/pass (pbtest / pbpass)++Special destinations (documentation addresses, nothing is really contacted):+ 192.0.2.10:80 via socks5 1081 reply uses the 22 byte IPv6 address form and a banner right behind it+ 192.0.2.20:22 via http 8080 "200" reply with a banner glued to the headers+ 192.0.2.21:22 via http 8080 407 whose headers contain "200" (must not count as success)+"""+import asyncio, base64, json, os, socket, struct, time++HERE = os.path.dirname(os.path.abspath(__file__))+LOG = os.environ.get("PB_EVENTS", os.path.join(HERE, "work", "events.log"))+USER, PASS = "pbtest", "pbpass"+BANNER = b"SSH-2.0-pbtest\r\n"+active = {"tcp": 0, "udp_assoc": 0}+++def ev(kind, **kw):+ kw.update(t=round(time.time(), 3), kind=kind)+ with open(LOG, "a") as f:+ f.write(json.dumps(kw) + "\n")+++async def pipe(r, w):+ # on EOF only half-close the other side, both ends are closed once both directions end+ try:+ while True:+ d = await r.read(65536)+ if not d:+ break+ w.write(d)+ await w.drain()+ if w.can_write_eof():+ w.write_eof()+ except Exception:+ pass+++async def splice(cr, cw, ur, uw):+ try:+ await asyncio.gather(pipe(cr, uw), pipe(ur, cw))+ finally:+ for w in (cw, uw):+ try:+ w.close()+ except Exception:+ pass+++# ---------------- SOCKS5 ----------------+class UDPRelay(asyncio.DatagramProtocol):+ def __init__(self, name):+ self.name, self.client, self.transport = name, None, None+ self.up, self.down = 0, 0++ def connection_made(self, t):+ self.transport = t++ def datagram_received(self, data, addr):+ if addr[0] == "127.0.0.1" and (self.client is None or addr == self.client) and len(data) > 10 and data[2] == 0:+ self.client = addr+ atyp = data[3]+ if atyp == 1:+ host, port, off = socket.inet_ntoa(data[4:8]), struct.unpack("!H", data[8:10])[0], 10+ elif atyp == 3:+ n = data[4]+ host, port, off = data[5:5 + n].decode(), struct.unpack("!H", data[5 + n:7 + n])[0], 7 + n+ elif atyp == 4:+ host, port, off = socket.inet_ntop(socket.AF_INET6, data[4:20]), struct.unpack("!H", data[20:22])[0], 22+ else:+ return+ self.up += 1+ if self.up == 1:+ ev("udp_pkt", proxy=self.name, dest=host, port=port)+ try:+ self.transport.sendto(data[off:], (host, port))+ except Exception:+ pass+ elif self.client:+ # a reply from a remote peer, wrap it and hand it back to the client+ self.down += 1+ hdr = b"\x00\x00\x00\x01" + socket.inet_aton(addr[0]) + struct.pack("!H", addr[1])+ self.transport.sendto(hdr + data, self.client)+++async def socks_client(name, auth, blackhole, r, w):+ peer = w.get_extra_info("peername")+ ev("accept", proxy=name, src=peer[1])+ active["tcp"] += 1+ try:+ if blackhole:+ await r.read()+ ev("closed_by_peer", proxy=name, src=peer[1])+ return+ ver, n = await r.readexactly(2)+ methods = await r.readexactly(n)+ if auth:+ if 2 not in methods:+ w.write(b"\x05\xff")+ return+ w.write(b"\x05\x02")+ await w.drain()+ await r.readexactly(1)+ ul = (await r.readexactly(1))[0]; u = (await r.readexactly(ul)).decode()+ pl = (await r.readexactly(1))[0]; p = (await r.readexactly(pl)).decode()+ ok = (u, p) == (USER, PASS)+ w.write(b"\x01\x00" if ok else b"\x01\x01")+ await w.drain()+ ev("auth", proxy=name, ok=ok)+ if not ok:+ return+ else:+ w.write(b"\x05\x00")+ await w.drain()+ _, cmd, _, atyp = await r.readexactly(4)+ if atyp == 1:+ host = socket.inet_ntoa(await r.readexactly(4))+ elif atyp == 3:+ host = (await r.readexactly((await r.readexactly(1))[0])).decode()+ else:+ host = socket.inet_ntop(socket.AF_INET6, await r.readexactly(16))+ port = struct.unpack("!H", await r.readexactly(2))[0]+ if cmd == 1 and (host, port) == ("192.0.2.10", 80):+ ev("connect", proxy=name, dest=host, port=port, special="ipv6-bnd+banner")+ w.write(b"\x05\x00\x00\x04" + b"\x00" * 16 + struct.pack("!H", 1080) + BANNER)+ await w.drain()+ await r.read()+ return+ if cmd == 1:+ ev("connect", proxy=name, dest=host, port=port)+ try:+ ur, uw = await asyncio.wait_for(asyncio.open_connection(host, port), 10)+ except Exception as e:+ ev("connect_failed", proxy=name, dest=host, port=port, err=str(e))+ w.write(b"\x05\x05\x00\x01\x00\x00\x00\x00\x00\x00")+ return+ w.write(b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00")+ await w.drain()+ await splice(r, w, ur, uw)+ elif cmd == 3:+ relay = UDPRelay(name)+ # bound to all interfaces: a loopback-only socket can't send to the internet+ tr, _ = await asyncio.get_running_loop().create_datagram_endpoint(lambda: relay, local_addr=("0.0.0.0", 0))+ bport = tr.get_extra_info("sockname")[1]+ active["udp_assoc"] += 1+ ev("udp_assoc_open", proxy=name, relay_port=bport, active=active["udp_assoc"])+ w.write(b"\x05\x00\x00\x01" + socket.inet_aton("127.0.0.1") + struct.pack("!H", bport))+ await w.drain()+ await r.read() # the association lives as long as the control connection+ tr.close()+ active["udp_assoc"] -= 1+ ev("udp_assoc_close", proxy=name, up=relay.up, down=relay.down, active=active["udp_assoc"])+ else:+ w.write(b"\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00")+ except Exception as e:+ ev("error", proxy=name, err=repr(e))+ finally:+ active["tcp"] -= 1+ ev("tcp_closed", proxy=name, src=peer[1], active=active["tcp"])+ try:+ w.close()+ except Exception:+ pass+++# ---------------- HTTP CONNECT ----------------+async def http_client(name, auth, r, w):+ peer = w.get_extra_info("peername")+ ev("accept", proxy=name, src=peer[1])+ active["tcp"] += 1+ try:+ head = await asyncio.wait_for(r.readuntil(b"\r\n\r\n"), 10)+ lines = head.decode("latin1").split("\r\n")+ method, target, _ = lines[0].split(" ", 2)+ hdrs = {l.split(":", 1)[0].lower(): l.split(":", 1)[1].strip() for l in lines[1:] if ":" in l}+ if auth:+ exp = "Basic " + base64.b64encode(f"{USER}:{PASS}".encode()).decode()+ ok = hdrs.get("proxy-authorization") == exp+ ev("auth", proxy=name, ok=ok)+ if not ok:+ w.write(b"HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic\r\nContent-Length: 0\r\n\r\n")+ return+ if method != "CONNECT":+ w.write(b"HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n")+ return+ host, port = target.rsplit(":", 1)+ host = host.strip("[]")+ ev("connect", proxy=name, dest=host, port=int(port))+ if (host, int(port)) == ("192.0.2.20", 22):+ w.write(b"HTTP/1.1 200 Connection established\r\n\r\n" + BANNER)+ await w.drain()+ await r.read()+ return+ if (host, int(port)) == ("192.0.2.21", 22):+ w.write(b"HTTP/1.1 407 Proxy Authentication Required\r\nContent-Length: 200\r\n\r\nSSH-2.0-should-not-arrive\r\n")+ await w.drain()+ await r.read()+ return+ try:+ ur, uw = await asyncio.wait_for(asyncio.open_connection(host, int(port)), 10)+ except Exception as e:+ ev("connect_failed", proxy=name, dest=host, port=int(port), err=str(e))+ w.write(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n")+ return+ w.write(b"HTTP/1.1 200 Connection established\r\n\r\n")+ await w.drain()+ await splice(r, w, ur, uw)+ except Exception as e:+ ev("error", proxy=name, err=repr(e))+ finally:+ active["tcp"] -= 1+ ev("tcp_closed", proxy=name, src=peer[1], active=active["tcp"])+ try:+ w.close()+ except Exception:+ pass+++async def main():+ os.makedirs(os.path.dirname(LOG), exist_ok=True)+ open(LOG, "w").close()+ servers = [+ ("socks1080", 1080, lambda r, w: socks_client("socks1080", False, False, r, w)),+ ("socks1081", 1081, lambda r, w: socks_client("socks1081", True, False, r, w)),+ ("socks1082", 1082, lambda r, w: socks_client("socks1082", False, True, r, w)),+ ("http8080", 8080, lambda r, w: http_client("http8080", False, r, w)),+ ("http8081", 8081, lambda r, w: http_client("http8081", True, r, w)),+ ]+ started = [await asyncio.start_server(cb, "127.0.0.1", port) for _, port, cb in servers]+ print("proxies up:", ", ".join(f"{n}:{p}" for n, p, _ in servers), flush=True)+ await asyncio.gather(*(s.serve_forever() for s in started))+++if __name__ == "__main__":+ asyncio.run(main())