Compare commits

...
96 Commits
Author SHA1 Message Date
Zhiqiang Zhang fc8c5a24b1 feat: support comp-lzo for OpenVPN (#2841) 2026-05-30 09:14:40 +08:00
enfein 8f2d84f915 chore: update mieru version to v3.33.0 (#2840) 2026-05-29 08:37:53 +08:00
wwqgtxx 38cb06d3a5 fix: hysteria2 realm stun domain resolve 2026-05-27 22:32:31 +08:00
wwqgtxx 4065583ae4 fix: masque retry condition 2026-05-26 21:03:44 +08:00
wwqgtxx f30a64f93f feat: support hysteria2 gecko obfs 2026-05-25 15:35:22 +08:00
wwqgtxx f1c365611d feat: support AES-192-GCM/AES-192-CBC OpenVPN data ciphers 2026-05-25 13:53:36 +08:00
wwqgtxx 2dd7d59942 feat: support MD5/SHA384/SHA512 OpenVPN auth methods 2026-05-25 13:41:15 +08:00
wwqgtxx d610afef1b chore: clear parameter passing 2026-05-25 09:49:30 +08:00
saba-futai 5b28a0ee46 chore: optimize sudoku packed hot paths (#2833) 2026-05-25 07:52:43 +08:00
Romanov Caesar 5639e93f72 fix: improve OpenVPN transport reliability (#2824) 2026-05-23 21:54:22 +08:00
wwqgtxx 03e1f44921 fix: interface structs do not copy correctly 2026-05-23 11:58:21 +08:00
wwqgtxx f69331f45f fix: config struct not exported 2026-05-22 01:26:42 +08:00
xream 52edebd155 feat: add snell version 4/5 outbound and inbound (#2817) 2026-05-22 01:14:58 +08:00
Romanov Caesar 7a6a650902 feat: support OpenVPN CBC ciphers (#2818) 2026-05-21 23:41:08 +08:00
wwqgtxx 6e15299cab chore: remove AF_ALG in tailscale-wireguard-go 2026-05-21 20:52:19 +08:00
wwqgtxx 72f133f4bd chore: more logging for tailscale debug 2026-05-21 09:54:07 +08:00
wwqgtxx 301d580d8a fix: compile issue of tailscale-wireguard-go dependency 2026-05-20 23:40:06 +08:00
wwqgtxx 3809a03c9f fix: stack panic after dispatcher attach nil 2026-05-20 23:26:50 +08:00
wwqgtxx 0ddf4bbffd chore: update sing-tun 2026-05-20 11:07:10 +08:00
wwqgtxx d27f3201ab chore: use pre-go1.27 tls.QUICConfig.ClientHelloInfoConn API for quic-go to avoid cloning tls.Config 2026-05-20 10:13:55 +08:00
wwqgtxx a2aca027e4 fix: pinger in tailscale not under our control 2026-05-20 09:33:22 +08:00
wwqgtxx cb652ddb7d chore: make the handler-related SNAT key in NewPacket 2026-05-19 10:30:57 +08:00
wwqgtxx a52a27ed56 fix: errors.ErrUnsupported backport 2026-05-19 01:53:05 +08:00
wwqgtxx 060711fb7d chore: more netip.AddrPort using in tproxy 2026-05-18 22:48:45 +08:00
wwqgtxx 8c26d61ce3 fix: tproxy did not pass the additions correctly 2026-05-18 22:23:16 +08:00
wwqgtxx f2da5b7c27 chore: reduce internal circular dependencies 2026-05-18 21:31:08 +08:00
ayanamist d60b336dfc chore: use mihomo name & ver to tailscale reported ver to avoid update prompts (#2801) 2026-05-18 10:44:01 +08:00
wwqgtxx a531449b84 fix: missing param passing in vless listener config 2026-05-17 23:21:48 +08:00
wwqgtxx a05c94b4ad chore: make the proxydialer module no longer directly depend on the tunnel module 2026-05-17 21:55:16 +08:00
Lanlan13-14 ff98700df2 feat: support CHACHA20-POLY1305 data cipher for OpenVPN (#2798) 2026-05-17 17:45:26 +08:00
wwqgtxx 0dec35ed69 chore: always dial tcp on netstack for tailscale 2026-05-17 17:07:26 +08:00
wwqgtxx d2fcf71c4a fix: tailscale panic when working with dialer-proxy 2026-05-17 13:05:30 +08:00
wwqgtxx b230c90d13 fix: shadowtls v3 client HMAC handling for TLS 1.3 HelloRetryRequest 2026-05-17 10:16:53 +08:00
wwqgtxx b1a07d2006 chore: remove unnecessary member variables added by xsync/v3 2026-05-17 09:47:39 +08:00
wwqgtxx 31ece04ab0 chore: upgrade the embedded xsync.Map to v4.5.0 2026-05-17 08:49:48 +08:00
wwqgtxx e9e23c4e98 chore: tailscale must be compiled under the with_gvisor build tag 2026-05-16 23:45:08 +08:00
ztywyj 5e22035118 feat: add GOST relay outbound proxy type (#2795) 2026-05-16 22:37:07 +08:00
wwqgtxx 263d06d176 chore: allow passing tunnel when creating the proxy 2026-05-16 21:20:02 +08:00
wwqgtxx ac6f6d0482 chore: tailscale using ListenPacket for UDP 2026-05-16 20:44:04 +08:00
wwqgtxx 388d958a6e fix: remove unstable warning for tailscale 2026-05-16 20:03:33 +08:00
wwqgtxx 9e97dc05ef fix: tailscale not use configured dialer for netstack forwardTCP 2026-05-16 18:39:05 +08:00
wwqgtxx 2f6ce20f6e fix: tailscale not use configured dialer for captive detection 2026-05-16 16:09:48 +08:00
wwqgtxx d2acf450fd fix: hysteria2 realm server reaper loop 2026-05-15 23:58:47 +08:00
wwqgtxx 17bed79b41 fix: tsnet panic for tailscale 2026-05-15 18:13:04 +08:00
Aaron Chen fd3141919e fix: wrong function call in SetWriteDeadline (#2790) 2026-05-15 15:22:25 +08:00
wwqgtxx 802b0b2449 fix: netlink permission denied on android for tailscale 2026-05-15 14:46:03 +08:00
wwqgtxx 5df45b25e0 fix: typo in default alpn 2026-05-15 09:26:40 +08:00
xream 8a28dce512 fix: validate Linux process netlink matches 2026-05-15 08:41:02 +08:00
wwqgtxx e933ca82d9 fix: netlink permission denied on android for tailscale 2026-05-14 22:22:14 +08:00
wwqgtxx 3d3af1f44e chore: respect outbound dns prefer when resolve UDP 2026-05-14 16:53:11 +08:00
wwqgtxx 2f11d9635f chore: use our internal DNS resolution logic for tailscale 2026-05-14 16:21:31 +08:00
Ekko 6ea4373eba feat: support auth-user-pass and AES-256-GCM for OpenVPN (#2787) 2026-05-14 15:38:42 +08:00
汐殇 571925d2d2 feat: add Tailscale outbound support (#2786) 2026-05-14 12:47:05 +08:00
wwqgtxx 787dbfc5fd feat: support setting realm-opts.proxy for hysteria2 listener 2026-05-14 07:45:41 +08:00
wwqgtxx 44c94236b3 chore: code cleanup 2026-05-13 21:07:37 +08:00
Romanov Caesar 7af9eeb3f8 feat: add OpenVPN outbound support (#2785) 2026-05-13 18:31:42 +08:00
wwqgtxx 2ffd96288d feat: support hysteria2-realm listener 2026-05-13 16:20:37 +08:00
wwqgtxx 993d1b6456 chore: add stun retry and lazy server start for realm 2026-05-12 23:18:56 +08:00
wwqgtxx 0003e1432c fix: trusttunnel listener panic 2026-05-12 20:49:45 +08:00
wwqgtxx 00e6df5018 chore: close http2 connections when closing client in doh 2026-05-12 18:20:33 +08:00
wwqgtxx faa58f27fc chore: add some comments for using the new net/http API 2026-05-12 09:57:25 +08:00
wwqgtxx 98aa7e63c2 feat: support realm-opts for hysteria2 outbound and listener 2026-05-11 19:20:30 +08:00
wwqgtxx 8b8eae56d7 feat: support simple-obfs for shadowsocks listener 2026-05-11 11:52:28 +08:00
wwqgtxx cc376acc5b fix: skip TTL update for OPT records 2026-05-09 22:14:25 +08:00
wwqgtxx 95946a5fb2 fix: net/http.Transport's UnencryptedHTTP2 does not work TLS without ALPN 2026-05-09 11:50:15 +08:00
wwqgtxx aae5812004 fix: net/http.Server's UnencryptedHTTP2 does not work TLS without ALPN 2026-05-09 11:19:34 +08:00
wwqgtxx ffe6e42cfa fix: conn maybe not closed in error handling 2026-05-09 09:53:40 +08:00
wwqgtxx c98e67a1c0 chore: using new net/http api in trusttunnel client 2026-05-08 17:37:44 +08:00
wwqgtxx c27446a5e8 chore: using new net/http api in gun client 2026-05-08 17:37:24 +08:00
wwqgtxx bb2f57b0e4 chore: using new net/http api in xhttp client 2026-05-08 17:37:05 +08:00
wwqgtxx f333359c8a chore: move magic close http2 connections function to own fork 2026-05-08 17:26:30 +08:00
wwqgtxx 028b480ae6 chore: remove unused http server code 2026-05-08 15:47:39 +08:00
wwqgtxx 3fb93bd79e chore: using new net/http api in gun and xhttp listener 2026-05-08 15:40:20 +08:00
wwqgtxx b8b443942e chore: using new net/http api in trusttunnel listener 2026-05-08 15:23:09 +08:00
wwqgtxx 35d5d4e44d fix: CVE-2026-39825 for net/http 2026-05-08 00:36:37 +08:00
wwqgtxx 191830a7e7 action: remove already applied patch file for go1.26.3 2026-05-07 23:26:56 +08:00
wwqgtxx 81bea659dc chore: using new net/http api in vmess h2 client 2026-05-07 18:57:12 +08:00
wwqgtxx 8bc7d3e58f chore: using new net/http api in doh client 2026-05-07 18:47:55 +08:00
wwqgtxx a1c68a4346 chore: using new net/http api in reality client fallback 2026-05-07 18:47:54 +08:00
wwqgtxx 7a646e8d10 fix: correctly configure the HTTP/2 scheduled ping parameters in masque h2 mode 2026-05-07 18:27:25 +08:00
wwqgtxx b03aa5d570 chore: remove race code in wireguard implementation 2026-05-07 17:18:03 +08:00
wwqgtxx 2f51cb0330 fix: conn maybe not closed in error handling 2026-05-07 09:54:00 +08:00
wwqgtxx 163ce6abd4 chore: add mlkem768x25519-sha256 key exchange algorithm to ssh outbound 2026-05-05 20:47:16 +08:00
wwqgtxx 2a8da25d26 chore: handle the possibility of multiple ClientTrace.GotConn calls 2026-05-02 19:39:32 +08:00
wwqgtxx 2d94970cab chore: using new net/http api in masque h2 mode 2026-05-02 18:43:01 +08:00
saba-futai df1c5e54dd chore: relax sudoku user configuration (#2757) 2026-04-28 10:04:49 +08:00
wwqgtxx 82621cd1bf chore: always safe UUID generation 2026-04-26 09:46:16 +08:00
wwqgtxx f5f9e5999f chore: update sing-tun 2026-04-26 08:51:55 +08:00
wwqgtxx 1fea551513 chore: verify adapter can parse convert's result in its test 2026-04-22 20:36:25 +08:00
wangwei354 98aa42edfc fix: convert place disguise host in h2-opts.host for legacy base64-JSON VMess (#2739) 2026-04-22 20:10:42 +08:00
wangwei354 f5cfb8d26b fix: convert emit HTTP2Options-shaped h2-opts for share-link HTTP/2 transport (#2737) 2026-04-22 19:28:33 +08:00
wwqgtxx 8d5395283d chore: remove unused xhttp options in download-settings 2026-04-22 18:54:53 +08:00
wwqgtxx 8f69ad9ed1 chore: better uuid generation 2026-04-22 18:54:52 +08:00
wwqgtxx c59c99a051 chore: handle context cancellation in xhttp client dialing 2026-04-20 21:31:38 +08:00
beck b3104a527d fix: panic in vless xhttp h3 mode when quic dial fails (#2736) 2026-04-20 14:26:16 +08:00
wwqgtxx 80e23d5acd doc: add missing options 2026-04-20 10:20:39 +08:00
149 changed files with 11620 additions and 1641 deletions

No files matched your search

-344
View File
@@ -1,344 +0,0 @@
From f4de14a515221e27c0d79446b423849a6546e3a6 Mon Sep 17 00:00:00 2001
From: Brad Fitzpatrick <bradfitz@golang.org>
Date: Tue, 24 Mar 2026 23:02:09 +0000
Subject: [PATCH] runtime: use uname version check for 64-bit time on 32-bit
arch codepaths
The previous fallback-on-ENOSYS logic causes issues on forks of Linux.
Android: #77621 (CL 750040 added a workaround with a TODO,
this fixes that TODO)
Causes the OS to terminate the program when running on Android
versions <=10 since the seccomp jail does not know about the 64-bit
time syscall and is configured to terminate the program on any
unknown syscall.
Synology's Linux: #77930
On old versions of Synology's Linux they added custom vendor syscalls
without adding a gap in the syscall numbers, that means when we call
the newer Linux syscall which was added later, Synology's Linux
interprets it as a completely different vendor syscall.
Originally by Jorropo in CL 751340.
Fixes golang/go#77930
Updates tailscale/go#162
Originally https://go-review.googlesource.com/c/go/+/758902/2
Co-authored-by: Jorropo <jorropo.pgm@gmail.com>
Change-Id: I90e15495d9249fd7f6e112f9e3ae8ad1322f56e0
---
.../runtime/syscall/linux/defs_linux_386.go | 1 +
.../runtime/syscall/linux/defs_linux_amd64.go | 1 +
.../runtime/syscall/linux/defs_linux_arm.go | 1 +
.../runtime/syscall/linux/defs_linux_arm64.go | 1 +
.../syscall/linux/defs_linux_loong64.go | 1 +
.../syscall/linux/defs_linux_mips64x.go | 1 +
.../runtime/syscall/linux/defs_linux_mipsx.go | 1 +
.../syscall/linux/defs_linux_ppc64x.go | 1 +
.../syscall/linux/defs_linux_riscv64.go | 1 +
.../runtime/syscall/linux/defs_linux_s390x.go | 1 +
.../runtime/syscall/linux/syscall_linux.go | 14 +++++
src/runtime/os_linux.go | 62 +++++++++++++++++++
src/runtime/os_linux32.go | 28 +++------
src/runtime/os_linux64.go | 2 +
14 files changed, 97 insertions(+), 19 deletions(-)
diff --git a/src/internal/runtime/syscall/linux/defs_linux_386.go b/src/internal/runtime/syscall/linux/defs_linux_386.go
index 7fdf5d3f8062fa..4e8e645dc49a66 100644
--- a/src/internal/runtime/syscall/linux/defs_linux_386.go
+++ b/src/internal/runtime/syscall/linux/defs_linux_386.go
@@ -17,6 +17,7 @@ const (
SYS_OPENAT = 295
SYS_PREAD64 = 180
SYS_READ = 3
+ SYS_UNAME = 122
EFD_NONBLOCK = 0x800
diff --git a/src/internal/runtime/syscall/linux/defs_linux_amd64.go b/src/internal/runtime/syscall/linux/defs_linux_amd64.go
index 2c8676e6e9b4d9..fa764d9ccd9b8e 100644
--- a/src/internal/runtime/syscall/linux/defs_linux_amd64.go
+++ b/src/internal/runtime/syscall/linux/defs_linux_amd64.go
@@ -17,6 +17,7 @@ const (
SYS_OPENAT = 257
SYS_PREAD64 = 17
SYS_READ = 0
+ SYS_UNAME = 63
EFD_NONBLOCK = 0x800
diff --git a/src/internal/runtime/syscall/linux/defs_linux_arm.go b/src/internal/runtime/syscall/linux/defs_linux_arm.go
index a0b395d6762734..cef556d5f6f986 100644
--- a/src/internal/runtime/syscall/linux/defs_linux_arm.go
+++ b/src/internal/runtime/syscall/linux/defs_linux_arm.go
@@ -17,6 +17,7 @@ const (
SYS_OPENAT = 322
SYS_PREAD64 = 180
SYS_READ = 3
+ SYS_UNAME = 122
EFD_NONBLOCK = 0x800
diff --git a/src/internal/runtime/syscall/linux/defs_linux_arm64.go b/src/internal/runtime/syscall/linux/defs_linux_arm64.go
index 223dce0c5b4281..eabddbac1bc063 100644
--- a/src/internal/runtime/syscall/linux/defs_linux_arm64.go
+++ b/src/internal/runtime/syscall/linux/defs_linux_arm64.go
@@ -17,6 +17,7 @@ const (
SYS_OPENAT = 56
SYS_PREAD64 = 67
SYS_READ = 63
+ SYS_UNAME = 160
EFD_NONBLOCK = 0x800
diff --git a/src/internal/runtime/syscall/linux/defs_linux_loong64.go b/src/internal/runtime/syscall/linux/defs_linux_loong64.go
index 8aa61c391dcdcb..08e5d49b83c9bd 100644
--- a/src/internal/runtime/syscall/linux/defs_linux_loong64.go
+++ b/src/internal/runtime/syscall/linux/defs_linux_loong64.go
@@ -17,6 +17,7 @@ const (
SYS_OPENAT = 56
SYS_PREAD64 = 67
SYS_READ = 63
+ SYS_UNAME = 160
EFD_NONBLOCK = 0x800
diff --git a/src/internal/runtime/syscall/linux/defs_linux_mips64x.go b/src/internal/runtime/syscall/linux/defs_linux_mips64x.go
index 84b760dc1b5545..b5794e5002af5e 100644
--- a/src/internal/runtime/syscall/linux/defs_linux_mips64x.go
+++ b/src/internal/runtime/syscall/linux/defs_linux_mips64x.go
@@ -19,6 +19,7 @@ const (
SYS_OPENAT = 5247
SYS_PREAD64 = 5016
SYS_READ = 5000
+ SYS_UNAME = 5061
EFD_NONBLOCK = 0x80
diff --git a/src/internal/runtime/syscall/linux/defs_linux_mipsx.go b/src/internal/runtime/syscall/linux/defs_linux_mipsx.go
index a9be21414c26f9..1fb4d919d1a318 100644
--- a/src/internal/runtime/syscall/linux/defs_linux_mipsx.go
+++ b/src/internal/runtime/syscall/linux/defs_linux_mipsx.go
@@ -19,6 +19,7 @@ const (
SYS_OPENAT = 4288
SYS_PREAD64 = 4200
SYS_READ = 4003
+ SYS_UNAME = 4122
EFD_NONBLOCK = 0x80
diff --git a/src/internal/runtime/syscall/linux/defs_linux_ppc64x.go b/src/internal/runtime/syscall/linux/defs_linux_ppc64x.go
index 63f4e5d7864de4..ee93ad345b810f 100644
--- a/src/internal/runtime/syscall/linux/defs_linux_ppc64x.go
+++ b/src/internal/runtime/syscall/linux/defs_linux_ppc64x.go
@@ -19,6 +19,7 @@ const (
SYS_OPENAT = 286
SYS_PREAD64 = 179
SYS_READ = 3
+ SYS_UNAME = 122
EFD_NONBLOCK = 0x800
diff --git a/src/internal/runtime/syscall/linux/defs_linux_riscv64.go b/src/internal/runtime/syscall/linux/defs_linux_riscv64.go
index 8aa61c391dcdcb..08e5d49b83c9bd 100644
--- a/src/internal/runtime/syscall/linux/defs_linux_riscv64.go
+++ b/src/internal/runtime/syscall/linux/defs_linux_riscv64.go
@@ -17,6 +17,7 @@ const (
SYS_OPENAT = 56
SYS_PREAD64 = 67
SYS_READ = 63
+ SYS_UNAME = 160
EFD_NONBLOCK = 0x800
diff --git a/src/internal/runtime/syscall/linux/defs_linux_s390x.go b/src/internal/runtime/syscall/linux/defs_linux_s390x.go
index 52945db0e5b72f..da11c704081abc 100644
--- a/src/internal/runtime/syscall/linux/defs_linux_s390x.go
+++ b/src/internal/runtime/syscall/linux/defs_linux_s390x.go
@@ -17,6 +17,7 @@ const (
SYS_OPENAT = 288
SYS_PREAD64 = 180
SYS_READ = 3
+ SYS_UNAME = 122
EFD_NONBLOCK = 0x800
diff --git a/src/internal/runtime/syscall/linux/syscall_linux.go b/src/internal/runtime/syscall/linux/syscall_linux.go
index 8201e7d1907444..b64f511b03c947 100644
--- a/src/internal/runtime/syscall/linux/syscall_linux.go
+++ b/src/internal/runtime/syscall/linux/syscall_linux.go
@@ -86,3 +86,17 @@ func Pread(fd int, p []byte, offset int64) (n int, errno uintptr) {
}
return int(r1), e
}
+
+type Utsname struct {
+ Sysname [65]byte
+ Nodename [65]byte
+ Release [65]byte
+ Version [65]byte
+ Machine [65]byte
+ Domainname [65]byte
+}
+
+func Uname(buf *Utsname) (errno uintptr) {
+ _, _, e := Syscall6(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0, 0, 0, 0)
+ return e
+}
diff --git a/src/runtime/os_linux.go b/src/runtime/os_linux.go
index 7e6af22d48a764..493567b5303673 100644
--- a/src/runtime/os_linux.go
+++ b/src/runtime/os_linux.go
@@ -354,6 +354,7 @@ func osinit() {
numCPUStartup = getCPUCount()
physHugePageSize = getHugePageSize()
vgetrandomInit()
+ configure64bitsTimeOn32BitsArchitectures()
}
var urandom_dev = []byte("/dev/urandom\x00")
@@ -935,3 +936,64 @@ func mprotect(addr unsafe.Pointer, n uintptr, prot int32) (ret int32, errno int3
r, _, err := linux.Syscall6(linux.SYS_MPROTECT, uintptr(addr), n, uintptr(prot), 0, 0, 0)
return int32(r), int32(err)
}
+
+type kernelVersion struct {
+ major int
+ minor int
+}
+
+// getKernelVersion returns major and minor kernel version numbers
+// parsed from the uname release field.
+func getKernelVersion() kernelVersion {
+ var buf linux.Utsname
+ if e := linux.Uname(&buf); e != 0 {
+ throw("uname failed")
+ }
+
+ rel := gostringnocopy(&buf.Release[0])
+ major, minor, _, ok := parseRelease(rel)
+ if !ok {
+ throw("failed to parse kernel version from uname")
+ }
+ return kernelVersion{major: major, minor: minor}
+}
+
+// parseRelease parses a dot-separated version number. It follows the
+// semver syntax, but allows the minor and patch versions to be
+// elided.
+func parseRelease(rel string) (major, minor, patch int, ok bool) {
+ // Strip anything after a dash or plus.
+ for i := 0; i < len(rel); i++ {
+ if rel[i] == '-' || rel[i] == '+' {
+ rel = rel[:i]
+ break
+ }
+ }
+
+ next := func() (int, bool) {
+ for i := 0; i < len(rel); i++ {
+ if rel[i] == '.' {
+ ver, err := strconv.Atoi(rel[:i])
+ rel = rel[i+1:]
+ return ver, err == nil
+ }
+ }
+ ver, err := strconv.Atoi(rel)
+ rel = ""
+ return ver, err == nil
+ }
+ if major, ok = next(); !ok || rel == "" {
+ return
+ }
+ if minor, ok = next(); !ok || rel == "" {
+ return
+ }
+ patch, ok = next()
+ return
+}
+
+// GE checks if the running kernel version
+// is greater than or equal to the provided version.
+func (kv kernelVersion) GE(x, y int) bool {
+ return kv.major > x || (kv.major == x && kv.minor >= y)
+}
diff --git a/src/runtime/os_linux32.go b/src/runtime/os_linux32.go
index 16de6fb350f624..02cb18f32d57d2 100644
--- a/src/runtime/os_linux32.go
+++ b/src/runtime/os_linux32.go
@@ -7,27 +7,25 @@
package runtime
import (
- "internal/runtime/atomic"
"unsafe"
)
+func configure64bitsTimeOn32BitsArchitectures() {
+ use64bitsTimeOn32bits = getKernelVersion().GE(5, 1)
+}
+
//go:noescape
func futex_time32(addr unsafe.Pointer, op int32, val uint32, ts *timespec32, addr2 unsafe.Pointer, val3 uint32) int32
//go:noescape
func futex_time64(addr unsafe.Pointer, op int32, val uint32, ts *timespec, addr2 unsafe.Pointer, val3 uint32) int32
-var isFutexTime32bitOnly atomic.Bool
+var use64bitsTimeOn32bits bool
//go:nosplit
func futex(addr unsafe.Pointer, op int32, val uint32, ts *timespec, addr2 unsafe.Pointer, val3 uint32) int32 {
- if !isFutexTime32bitOnly.Load() {
- ret := futex_time64(addr, op, val, ts, addr2, val3)
- // futex_time64 is only supported on Linux 5.0+
- if ret != -_ENOSYS {
- return ret
- }
- isFutexTime32bitOnly.Store(true)
+ if use64bitsTimeOn32bits {
+ return futex_time64(addr, op, val, ts, addr2, val3)
}
// Downgrade ts.
var ts32 timespec32
@@ -45,17 +43,10 @@ func timer_settime32(timerid int32, flags int32, new, old *itimerspec32) int32
//go:noescape
func timer_settime64(timerid int32, flags int32, new, old *itimerspec) int32
-var isSetTime32bitOnly atomic.Bool
-
//go:nosplit
func timer_settime(timerid int32, flags int32, new, old *itimerspec) int32 {
- if !isSetTime32bitOnly.Load() {
- ret := timer_settime64(timerid, flags, new, old)
- // timer_settime64 is only supported on Linux 5.0+
- if ret != -_ENOSYS {
- return ret
- }
- isSetTime32bitOnly.Store(true)
+ if use64bitsTimeOn32bits {
+ return timer_settime64(timerid, flags, new, old)
}
var newts, oldts itimerspec32
@@ -73,6 +64,5 @@ func timer_settime(timerid int32, flags int32, new, old *itimerspec) int32 {
old32 = &oldts
}
- // Fall back to 32-bit timer
return timer_settime32(timerid, flags, new32, old32)
}
diff --git a/src/runtime/os_linux64.go b/src/runtime/os_linux64.go
index 7b70d80fbe5a89..f9571dd7586614 100644
--- a/src/runtime/os_linux64.go
+++ b/src/runtime/os_linux64.go
@@ -10,6 +10,8 @@ import (
"unsafe"
)
+func configure64bitsTimeOn32BitsArchitectures() {}
+
//go:noescape
func futex(addr unsafe.Pointer, op int32, val uint32, ts *timespec, addr2 unsafe.Pointer, val3 uint32) int32
-7
View File
@@ -186,13 +186,6 @@ jobs:
- name: Verify Go env
run: go env
# TODO: remove after issue77930 fixed, see: https://github.com/golang/go/issues/77930
- name: Fix issue77930 for Golang1.26
if: ${{ matrix.jobs.goversion == '' }}
run: |
cd $(go env GOROOT)
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/issue77930.patch
- name: Set variables
run: |
VERSION="${GITHUB_REF_NAME,,}-$(git rev-parse --short HEAD)"
+8 -3
View File
@@ -69,7 +69,7 @@ func NewBase(opt BaseOption) *Base {
iface: opt.Interface,
rmark: opt.RoutingMark,
prefer: opt.Prefer,
id: utils.NewUUIDV6(),
id: utils.NewUUIDV4(),
}
}
@@ -177,7 +177,7 @@ func (b *Base) DialOptions() (opts []dialer.Option) {
func (b *Base) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
if !metadata.Resolved() {
ip, err := resolver.ResolveIP(ctx, metadata.Host)
ip, err := resolveIPWithResolver(ctx, metadata.Host, b.prefer, resolver.DefaultResolver)
if err != nil {
return fmt.Errorf("can't resolve ip: %w", err)
}
@@ -202,6 +202,7 @@ type BasicOption struct {
// The following parameters are used internally, assign value by the structure decoder are disallowed
//
DialerForAPI C.Dialer `proxy:"-"` // the dialer used for API usage has higher priority than all the above configurations.
TunnelForAPI C.Tunnel `proxy:"-"`
ProviderName string `proxy:"-"`
}
@@ -209,7 +210,7 @@ func (b *BasicOption) NewDialer(opts []dialer.Option) C.Dialer {
cDialer := b.DialerForAPI
if cDialer == nil {
if b.DialerProxy != "" {
cDialer = proxydialer.NewByName(b.DialerProxy)
cDialer = proxydialer.NewByName(b.DialerProxy, b.NewTunnel())
} else {
cDialer = dialer.NewDialer(opts...)
}
@@ -217,6 +218,10 @@ func (b *BasicOption) NewDialer(opts []dialer.Option) C.Dialer {
return cDialer
}
func (b *BasicOption) NewTunnel() C.Tunnel {
return b.TunnelForAPI
}
type conn struct {
N.ExtendedConn
chain C.Chain
+1 -1
View File
@@ -51,7 +51,7 @@ func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
func (d *Direct) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
if (!metadata.Resolved() || resolver.DirectHostResolver != resolver.DefaultResolver) && metadata.Host != "" {
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, resolver.DirectHostResolver)
ip, err := resolveIPWithResolver(ctx, metadata.Host, d.prefer, resolver.DirectHostResolver)
if err != nil {
return fmt.Errorf("can't resolve ip: %w", err)
}
+109
View File
@@ -0,0 +1,109 @@
package outbound
import (
"context"
"fmt"
"net"
"strconv"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/gost"
)
type GostRelay struct {
*Base
dialer C.Dialer
option *GostRelayOption
}
type GostRelayOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Forward bool `proxy:"forward,omitempty"`
UDP bool `proxy:"udp,omitempty"`
TLS bool `proxy:"tls,omitempty"`
Mux bool `proxy:"mux,omitempty"`
SNI string `proxy:"sni,omitempty"`
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
}
func (g *GostRelay) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
c, err := g.dialer.DialContext(ctx, "tcp", metadata.RemoteAddress())
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", g.addr, err)
}
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
return NewConn(c, g), nil
}
func (g *GostRelay) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
if err = g.ResolveUDP(ctx, metadata); err != nil {
return nil, err
}
pc, err := g.dialer.ListenPacket(ctx, "udp", "", metadata.AddrPort())
if err != nil {
return nil, fmt.Errorf("%s udp connect error: %w", g.addr, err)
}
return newPacketConn(pc, g), nil
}
func (g *GostRelay) ProxyInfo() C.ProxyInfo {
info := g.Base.ProxyInfo()
info.DialerProxy = g.option.DialerProxy
info.SMUX = g.option.Mux
return info
}
func NewGostRelay(option GostRelayOption) (*GostRelay, error) {
if option.Server == "" || option.Port <= 0 || option.Port > 0xffff {
return nil, fmt.Errorf("gost-relay %s requires a valid server and port", option.Name)
}
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
relay := &GostRelay{
Base: NewBase(BaseOption{
Name: option.Name,
Addr: addr,
Type: C.GostRelay,
ProviderName: option.ProviderName,
UDP: option.UDP,
TFO: option.TFO,
MPTCP: option.MPTCP,
Interface: option.Interface,
RoutingMark: option.RoutingMark,
Prefer: option.IPVersion,
}),
option: &option,
}
relay.dialer = gost.NewRelayDialer(option.NewDialer(relay.DialOptions()), &gost.RelayOption{
Server: option.Server,
Port: option.Port,
Forward: option.Forward,
TLS: option.TLS,
Mux: option.Mux,
SNI: option.SNI,
Username: option.Username,
Password: option.Password,
SkipCertVerify: option.SkipCertVerify,
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
})
return relay, nil
}
+5 -4
View File
@@ -9,6 +9,7 @@ import (
"strconv"
"time"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/ech"
@@ -19,7 +20,7 @@ import (
"github.com/metacubex/mihomo/transport/hysteria/obfs"
"github.com/metacubex/mihomo/transport/hysteria/pmtud_fix"
"github.com/metacubex/mihomo/transport/hysteria/transport"
"github.com/metacubex/mihomo/transport/hysteria/utils"
hyUtils "github.com/metacubex/mihomo/transport/hysteria/utils"
"github.com/metacubex/tls"
@@ -69,7 +70,7 @@ func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata
return newPacketConn(&hyPacketConn{udpConn}, h), nil
}
func (h *Hysteria) genHdc(ctx context.Context) utils.PacketDialer {
func (h *Hysteria) genHdc(ctx context.Context) hyUtils.PacketDialer {
return &hyDialerWithContext{
ctx: context.Background(),
hyDialer: func(network string, rAddr net.Addr) (net.PacketConn, error) {
@@ -128,12 +129,12 @@ type HysteriaOption struct {
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
var up, down uint64
up = StringToBps(c.Up)
up = utils.StringToBps(c.Up)
if up == 0 {
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
}
down = StringToBps(c.Down)
down = utils.StringToBps(c.Down)
if down == 0 {
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
}
+98 -22
View File
@@ -5,19 +5,23 @@ import (
"errors"
"fmt"
"net"
"net/netip"
"strconv"
"time"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/transport/tuic/common"
"github.com/metacubex/http"
"github.com/metacubex/quic-go"
qtls "github.com/metacubex/sing-quic"
"github.com/metacubex/sing-quic/hysteria2"
"github.com/metacubex/sing-quic/hysteria2/realm"
M "github.com/metacubex/sing/common/metadata"
"github.com/metacubex/tls"
)
@@ -34,26 +38,30 @@ type Hysteria2 struct {
type Hysteria2Option struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port,omitempty"`
Ports string `proxy:"ports,omitempty"`
HopInterval string `proxy:"hop-interval,omitempty"`
Up string `proxy:"up,omitempty"`
Down string `proxy:"down,omitempty"`
Password string `proxy:"password,omitempty"`
Obfs string `proxy:"obfs,omitempty"`
ObfsPassword string `proxy:"obfs-password,omitempty"`
SNI string `proxy:"sni,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
ALPN []string `proxy:"alpn,omitempty"`
CWND int `proxy:"cwnd,omitempty"`
BBRProfile string `proxy:"bbr-profile,omitempty"`
UdpMTU int `proxy:"udp-mtu,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port,omitempty"`
Ports string `proxy:"ports,omitempty"`
HopInterval string `proxy:"hop-interval,omitempty"`
Up string `proxy:"up,omitempty"`
Down string `proxy:"down,omitempty"`
Password string `proxy:"password,omitempty"`
Obfs string `proxy:"obfs,omitempty"`
ObfsPassword string `proxy:"obfs-password,omitempty"`
ObfsMinPacketSize int `proxy:"obfs-min-packet-size,omitempty"`
ObfsMaxPacketSize int `proxy:"obfs-max-packet-size,omitempty"`
SNI string `proxy:"sni,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
ALPN []string `proxy:"alpn,omitempty"`
CWND int `proxy:"cwnd,omitempty"`
BBRProfile string `proxy:"bbr-profile,omitempty"`
UdpMTU int `proxy:"udp-mtu,omitempty"`
RealmOpts Hysteria2RealmOption `proxy:"realm-opts,omitempty"`
// quic-go special config
InitialStreamReceiveWindow uint64 `proxy:"initial-stream-receive-window,omitempty"`
@@ -62,6 +70,22 @@ type Hysteria2Option struct {
MaxConnectionReceiveWindow uint64 `proxy:"max-connection-receive-window,omitempty"`
}
type Hysteria2RealmOption struct {
Enable bool `proxy:"enable,omitempty"`
ServerURL string `proxy:"server-url,omitempty"`
Token string `proxy:"token,omitempty"`
RealmID string `proxy:"realm-id,omitempty"`
STUNServers []string `proxy:"stun-servers,omitempty"`
// for ServerURL
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
ALPN []string `proxy:"alpn,omitempty"`
}
func (h *Hysteria2) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
c, err := h.client.DialConn(ctx, M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
if err != nil {
@@ -117,6 +141,8 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
outbound.dialer = option.NewDialer(outbound.DialOptions())
var salamanderPassword string
var geckoPassword string
var geckoMinPacketSize, geckoMaxPacketSize int
if len(option.Obfs) > 0 {
if option.ObfsPassword == "" {
return nil, errors.New("missing obfs password")
@@ -124,6 +150,10 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
switch option.Obfs {
case hysteria2.ObfsTypeSalamander:
salamanderPassword = option.ObfsPassword
case hysteria2.ObfsTypeGecko:
geckoPassword = option.ObfsPassword
geckoMinPacketSize = option.ObfsMinPacketSize
geckoMaxPacketSize = option.ObfsMaxPacketSize
default:
return nil, fmt.Errorf("unknown obfs type: %s", option.Obfs)
}
@@ -174,9 +204,12 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
clientOptions := hysteria2.ClientOptions{
Context: context.TODO(),
Logger: log.SingLogger,
SendBPS: StringToBps(option.Up),
ReceiveBPS: StringToBps(option.Down),
SendBPS: utils.StringToBps(option.Up),
ReceiveBPS: utils.StringToBps(option.Down),
SalamanderPassword: salamanderPassword,
GeckoPassword: geckoPassword,
GeckoMinPacketSize: geckoMinPacketSize,
GeckoMaxPacketSize: geckoMaxPacketSize,
Password: option.Password,
TLSConfig: tlsClientConfig,
QUICConfig: quicConfig,
@@ -229,6 +262,49 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
return nil, errors.New("invalid port")
}
if option.RealmOpts.Enable {
httpTLSClientConfig, err := ca.GetTLSConfig(ca.Option{
TLSConfig: &tls.Config{
ServerName: option.RealmOpts.SNI,
InsecureSkipVerify: option.RealmOpts.SkipCertVerify,
NextProtos: option.RealmOpts.ALPN,
},
Fingerprint: option.RealmOpts.Fingerprint,
Certificate: option.RealmOpts.Certificate,
PrivateKey: option.RealmOpts.PrivateKey,
})
if err != nil {
return nil, err
}
clientOptions.RealmOptions = &realm.Options{
ServerURL: option.RealmOpts.ServerURL,
Token: option.RealmOpts.Token,
RealmID: option.RealmOpts.RealmID,
STUNServers: option.RealmOpts.STUNServers,
HTTPClient: &http.Client{
Transport: &http.Transport{
DialContext: outbound.dialer.DialContext,
TLSClientConfig: httpTLSClientConfig,
// from http.DefaultTransport
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
},
Resolver: func(ctx context.Context, host string, ipv4, ipv6 bool) ([]netip.Addr, error) {
if ipv4 && !ipv6 {
return resolver.LookupIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
} else if ipv6 && !ipv4 {
return resolver.LookupIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
}
return resolver.LookupIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
},
Logger: log.SingLogger,
}
}
client, err := hysteria2.NewClient(clientOptions)
if err != nil {
return nil, err
+24 -8
View File
@@ -40,7 +40,7 @@ type Masque struct {
tunDevice wireguard.Device
resolver resolver.Resolver
uri string
h2Transport *http.Http2Transport
h2Transport *http.Transport
runCtx context.Context
runCancel context.CancelFunc
@@ -163,15 +163,31 @@ func NewMasque(option MasqueOption) (*Masque, error) {
if option.Network == "h2" {
tlsConfig.NextProtos = []string{"h2"}
outbound.h2Transport = &http.Http2Transport{
DialTLSContext: func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) {
// use h2c mode to disallow the net/http fallback to http1.1 when the server returns a not h2 ALPN
//
// Note that this usage is only applicable to our own net/http fork.
// The standard library also needs to mask the tls.Conn type for the conn returned by DialTLSContext
// see: https://github.com/golang/go/issues/79293#issuecomment-4426393534
protocols := new(http.Protocols)
protocols.SetUnencryptedHTTP2(true)
outbound.h2Transport = &http.Transport{
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
c, err := outbound.dialer.DialContext(ctx, "tcp", outbound.addr)
if err != nil {
return nil, err
}
return tls.Client(c, tlsConfig), nil
tlsConn := tls.Client(c, tlsConfig)
err = tlsConn.HandshakeContext(ctx)
if err != nil {
_ = c.Close()
return nil, err
}
return tlsConn, nil
},
Protocols: protocols,
HTTP2: &http.HTTP2Config{
SendPingTimeout: 30 * time.Second,
},
ReadIdleTimeout: 30 * time.Second,
}
}
@@ -298,7 +314,7 @@ func (w *Masque) run(ctx context.Context) error {
}
icmp, err := ipConn.WritePacket(buf[:sizes[0]])
if err != nil {
if errors.Is(err, net.ErrClosed) {
if errors.Is(err, net.ErrClosed) || errors.Is(err, io.ErrClosedPipe) {
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
return
}
@@ -319,7 +335,7 @@ func (w *Masque) run(ctx context.Context) error {
for runCtx.Err() == nil {
buf, err := ipConn.ReadPacket()
if err != nil {
if errors.Is(err, net.ErrClosed) {
if errors.Is(err, net.ErrClosed) || errors.Is(err, io.ErrClosedPipe) {
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
return
}
@@ -395,7 +411,7 @@ func (w *Masque) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
if w.resolver != nil {
r = w.resolver
}
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, r)
ip, err := resolveIPWithResolver(ctx, metadata.Host, w.prefer, r)
if err != nil {
return fmt.Errorf("can't resolve ip: %w", err)
}
+1 -11
View File
@@ -63,17 +63,7 @@ type mieruDNSResolver struct {
var _ mierucommon.DNSResolver = (*mieruDNSResolver)(nil)
func (dr mieruDNSResolver) LookupIP(ctx context.Context, network, host string) (_ []net.IP, err error) {
var ip netip.Addr
switch dr.prefer {
case C.IPv4Only:
ip, err = resolver.ResolveIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
case C.IPv6Only:
ip, err = resolver.ResolveIPv6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
case C.IPv6Prefer:
ip, err = resolver.ResolveIPPrefer6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
default:
ip, err = resolver.ResolveIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
}
ip, err := resolveIPWithResolver(ctx, host, dr.prefer, resolver.ProxyServerHostResolver)
if err != nil {
return nil, fmt.Errorf("can't resolve ip: %w", err)
}
+404
View File
@@ -0,0 +1,404 @@
package outbound
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"os"
"sync"
"github.com/metacubex/mihomo/common/contextutils"
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/dns"
"github.com/metacubex/mihomo/log"
ovpn "github.com/metacubex/mihomo/transport/openvpn"
wireguard "github.com/metacubex/sing-wireguard"
E "github.com/metacubex/sing/common/exceptions"
M "github.com/metacubex/sing/common/metadata"
"golang.org/x/sync/semaphore"
)
type OpenVPN struct {
*Base
option *OpenVPNOption
config *ovpn.ClientConfig
tunDevice wireguard.Device
client *ovpn.Client
resolver resolver.Resolver
dns []dns.NameServer
runCtx context.Context
runCancel context.CancelFunc
runLock *semaphore.Weighted
running bool
}
type OpenVPNOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Proto string `proxy:"proto,omitempty"`
Dev string `proxy:"dev,omitempty"`
Cipher string `proxy:"cipher,omitempty"`
Auth string `proxy:"auth,omitempty"`
CompLZO string `proxy:"comp-lzo,omitempty"`
CA string `proxy:"ca"`
Cert string `proxy:"cert,omitempty"`
Key string `proxy:"key,omitempty"`
TLSCrypt string `proxy:"tls-crypt,omitempty"`
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
Dns []string `proxy:"dns,omitempty"`
}
func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
cfg := &ovpn.ClientConfig{
RemoteHost: option.Server,
RemotePort: uint16(option.Port),
Proto: option.Proto,
Dev: option.Dev,
Cipher: option.Cipher,
Auth: option.Auth,
CompLZO: option.CompLZO,
CA: []byte(option.CA),
Cert: []byte(option.Cert),
Key: []byte(option.Key),
TLSCrypt: []byte(option.TLSCrypt),
Username: option.Username,
Password: option.Password,
}
if err := cfg.Prepare(); err != nil {
return nil, err
}
outbound := &OpenVPN{
Base: NewBase(BaseOption{
Name: option.Name,
Addr: cfg.RemoteAddress(),
Type: C.OpenVPN,
ProviderName: option.ProviderName,
UDP: true,
TFO: option.TFO,
MPTCP: option.MPTCP,
Interface: option.Interface,
RoutingMark: option.RoutingMark,
Prefer: option.IPVersion,
}),
option: &option,
config: cfg,
runLock: semaphore.NewWeighted(1),
}
if option.RemoteDnsResolve && len(option.Dns) > 0 {
nss, err := dns.ParseNameServer(option.Dns)
if err != nil {
return nil, err
}
outbound.dns = nss
}
outbound.dialer = option.NewDialer(outbound.DialOptions())
outbound.runCtx, outbound.runCancel = context.WithCancel(context.Background())
return outbound, nil
}
func (o *OpenVPN) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
tunDevice, r, err := o.run(ctx)
if err != nil {
return nil, err
}
var conn net.Conn
if !metadata.Resolved() || r != nil {
if r == nil {
r = resolver.DefaultResolver
}
options := o.DialOptions()
options = append(options, dialer.WithResolver(r))
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: tunDevice}))
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
} else {
conn, err = tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
}
if err != nil {
return nil, err
}
if conn == nil {
return nil, E.New("conn is nil")
}
return NewConn(conn, o), nil
}
func (o *OpenVPN) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
var pc net.PacketConn
tunDevice, r, err := o.run(ctx)
if err != nil {
return nil, err
}
if err = o.resolveUDP(ctx, metadata, r); err != nil {
return nil, err
}
pc, err = tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
if err != nil {
return nil, err
}
if pc == nil {
return nil, errors.New("packetConn is nil")
}
return newPacketConn(pc, o), nil
}
func (o *OpenVPN) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
_, r, err := o.run(ctx)
if err != nil {
return err
}
return o.resolveUDP(ctx, metadata, r)
}
func (o *OpenVPN) resolveUDP(ctx context.Context, metadata *C.Metadata, r resolver.Resolver) error {
if (!metadata.Resolved() || r != nil) && metadata.Host != "" {
if r == nil {
r = resolver.DefaultResolver
}
ip, err := resolveIPWithResolver(ctx, metadata.Host, o.prefer, r)
if err != nil {
return fmt.Errorf("can't resolve ip: %w", err)
}
metadata.DstIP = ip
}
return nil
}
func (o *OpenVPN) ProxyInfo() C.ProxyInfo {
info := o.Base.ProxyInfo()
info.DialerProxy = o.option.DialerProxy
return info
}
func (o *OpenVPN) IsL3Protocol(metadata *C.Metadata) bool {
return true
}
func (o *OpenVPN) Close() error {
if o.runCancel != nil {
o.runCancel()
}
_ = o.runLock.Acquire(context.Background(), 1)
client := o.client
tunDevice := o.tunDevice
o.client = nil
o.tunDevice = nil
o.running = false
o.runLock.Release(1)
if client != nil {
_ = client.Close()
}
if tunDevice != nil {
return tunDevice.Close()
}
return nil
}
func (o *OpenVPN) run(ctx context.Context) (wireguard.Device, resolver.Resolver, error) {
if err := o.lockRun(ctx); err != nil {
return nil, nil, err
}
defer o.runLock.Release(1)
if o.running {
if o.tunDevice == nil {
return nil, nil, net.ErrClosed
}
return o.tunDevice, o.resolver, nil
}
if o.runCtx.Err() != nil {
return nil, nil, o.runCtx.Err()
}
handshakeCtx, cancel := o.handshakeContext(ctx)
defer cancel()
packetIO, err := o.openPacketIO(handshakeCtx)
if err != nil {
if ctxErr := o.contextErr(ctx); ctxErr != nil {
return nil, nil, ctxErr
}
return nil, nil, E.Cause(err, "connect OpenVPN server")
}
client, err := ovpn.NewClient(o.config, packetIO)
if err != nil {
_ = packetIO.Close()
return nil, nil, err
}
push, err := client.Handshake(handshakeCtx)
if err != nil {
_ = client.Close()
if ctxErr := o.contextErr(ctx); ctxErr != nil {
return nil, nil, ctxErr
}
return nil, nil, E.Cause(err, "OpenVPN handshake")
}
log.Debugln("[OpenVPN](%s) handshake complete: prefixes=%v routes=%v peer-id=%d dns=%v redirect=%t block-ipv6=%t", o.name, push.Prefixes, push.Routes, push.PeerID, push.DNS, push.Redirect, push.BlockIPv6)
mtu := o.option.MTU
if mtu == 0 {
mtu = 1500
}
tunDevice, err := wireguard.NewStackDevice(push.Prefixes, uint32(mtu))
if err != nil {
_ = client.Close()
return nil, nil, E.Cause(err, "create OpenVPN stack device")
}
if err := tunDevice.Start(); err != nil {
_ = client.Close()
_ = tunDevice.Close()
return nil, nil, err
}
o.client = client
o.tunDevice = tunDevice
o.running = true
if o.option.RemoteDnsResolve && len(o.dns) > 0 && o.resolver == nil {
nss := append([]dns.NameServer(nil), o.dns...)
for i := range nss {
nss[i].ProxyAdapter = o
}
o.resolver = dns.NewResolver(dns.Config{
Main: nss,
IPv6: openVPNPrefixesHas6(push.Prefixes),
})
}
o.startPacketLoops()
return o.tunDevice, o.resolver, nil
}
func (o *OpenVPN) lockRun(ctx context.Context) error {
lockCtx, cancel := context.WithCancel(ctx)
stop := contextutils.AfterFunc(o.runCtx, cancel)
defer func() {
stop()
cancel()
}()
if err := o.runLock.Acquire(lockCtx, 1); err != nil {
if ctxErr := o.contextErr(ctx); ctxErr != nil {
return ctxErr
}
return err
}
return nil
}
func (o *OpenVPN) handshakeContext(ctx context.Context) (context.Context, context.CancelFunc) {
handshakeCtx, handshakeCancel := context.WithTimeout(ctx, ovpn.DefaultHandshakeTimeout)
stop := contextutils.AfterFunc(o.runCtx, handshakeCancel)
return handshakeCtx, func() {
stop()
handshakeCancel()
}
}
func (o *OpenVPN) contextErr(ctx context.Context) error {
if err := ctx.Err(); err != nil {
return err
}
return o.runCtx.Err()
}
func openVPNPrefixesHas6(prefixes []netip.Prefix) bool {
for _, prefix := range prefixes {
if !prefix.Addr().Unmap().Is4() {
return true
}
}
return false
}
func (o *OpenVPN) openPacketIO(ctx context.Context) (ovpn.PacketIO, error) {
switch o.config.Proto {
case ovpn.ProtoUDP:
conn, err := o.dialer.DialContext(ctx, "udp", o.addr)
if err != nil {
return nil, err
}
return ovpn.NewDatagramPacketIO(conn), nil
case ovpn.ProtoTCP:
conn, err := o.dialer.DialContext(ctx, "tcp", o.addr)
if err != nil {
return nil, err
}
return ovpn.NewTCPPacketIO(conn), nil
default:
return nil, fmt.Errorf("unsupported openvpn proto %q", o.config.Proto)
}
}
func (o *OpenVPN) startPacketLoops() {
runCtx, runCancel := context.WithCancel(o.runCtx)
client := o.client
tunDevice := o.tunDevice
var stopOnce sync.Once
stop := func() {
stopOnce.Do(func() {
runCancel()
_ = client.Close()
_ = tunDevice.Close()
_ = o.runLock.Acquire(context.Background(), 1)
if o.client == client {
o.client = nil
o.tunDevice = nil
o.running = false
}
o.runLock.Release(1)
})
}
go func() {
defer stop()
buf := make([]byte, 64*1024)
bufs := [][]byte{buf}
sizes := []int{0}
for runCtx.Err() == nil {
_, err := tunDevice.Read(bufs, sizes, 0)
if err != nil {
if runCtx.Err() == nil && !errors.Is(err, net.ErrClosed) && !errors.Is(err, os.ErrClosed) {
log.Errorln("[OpenVPN](%s) error reading from stack device: %v", o.name, err)
}
return
}
if err := client.WriteIPPacket(runCtx, buf[:sizes[0]]); err != nil {
if !errors.Is(err, context.Canceled) && !errors.Is(err, net.ErrClosed) {
log.Warnln("[OpenVPN](%s) error writing packet to OpenVPN link: %v", o.name, err)
}
return
}
}
}()
go func() {
defer stop()
for runCtx.Err() == nil {
packet, err := client.ReadIPPacket(runCtx)
if err != nil {
if runCtx.Err() == nil && (errors.Is(err, net.ErrClosed) || errors.Is(err, os.ErrClosed)) {
log.Warnln("[OpenVPN](%s) OpenVPN link closed while reading packet: %v", o.name, err)
} else if !errors.Is(err, context.Canceled) && !errors.Is(err, net.ErrClosed) && !errors.Is(err, os.ErrClosed) {
log.Warnln("[OpenVPN](%s) error reading packet from OpenVPN link: %v", o.name, err)
}
return
}
if _, err := tunDevice.Write([][]byte{packet}, 0); err != nil {
if !errors.Is(err, net.ErrClosed) {
log.Errorln("[OpenVPN](%s) error writing to stack device: %v", o.name, err)
}
return
}
}
}()
}
+7 -3
View File
@@ -10,7 +10,7 @@ import (
"github.com/metacubex/mihomo/common/structure"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/ntp"
gost "github.com/metacubex/mihomo/transport/gost-plugin"
gost "github.com/metacubex/mihomo/transport/gost"
"github.com/metacubex/mihomo/transport/kcptun"
"github.com/metacubex/mihomo/transport/restls"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
@@ -225,12 +225,16 @@ func (ss *ShadowSocks) listenPacketContext(ctx context.Context) (net.PacketConn,
}
// ListenPacketContext implements C.ProxyAdapter
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
if ss.option.UDPOverTCP {
c, err := ss.DialContext(ctx, metadata)
var c net.Conn
c, err = ss.DialContext(ctx, metadata)
if err != nil {
return nil, err
}
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
if err = ss.ResolveUDP(ctx, metadata); err != nil {
return nil, err
}
+3 -2
View File
@@ -4,6 +4,7 @@ import (
"context"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/proxydialer"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"
@@ -106,8 +107,8 @@ func NewSingMux(option SingMuxOption, proxy ProxyAdapter) (ProxyAdapter, error)
TCPTimeout: C.DefaultTCPTimeout,
Brutal: mux.BrutalOptions{
Enabled: option.BrutalOpts.Enabled,
SendBPS: StringToBps(option.BrutalOpts.Up),
ReceiveBPS: StringToBps(option.BrutalOpts.Down),
SendBPS: utils.StringToBps(option.BrutalOpts.Up),
ReceiveBPS: utils.StringToBps(option.BrutalOpts.Down),
},
})
if err != nil {
+25 -6
View File
@@ -20,6 +20,7 @@ type Snell struct {
pool *snell.Pool
obfsOption *simpleObfsOption
version int
reuse bool
}
type SnellOption struct {
@@ -30,6 +31,7 @@ type SnellOption struct {
Psk string `proxy:"psk"`
UDP bool `proxy:"udp,omitempty"`
Version int `proxy:"version,omitempty"`
Reuse bool `proxy:"reuse,omitempty"`
ObfsOpts map[string]any `proxy:"obfs-opts,omitempty"`
}
@@ -66,15 +68,20 @@ func (s *Snell) writeHeaderContext(ctx context.Context, c net.Conn, metadata *C.
if metadata.NetWork == C.UDP {
err = snell.WriteUDPHeader(c, s.version)
if err == nil && s.version >= snell.Version4 {
if sc, ok := c.(*snell.Snell); ok {
err = sc.ReadReply()
}
}
return
}
err = snell.WriteHeader(c, metadata.String(), uint(metadata.DstPort), s.version)
err = snell.WriteHeaderWithReuse(c, metadata.String(), uint(metadata.DstPort), s.version, s.reuse)
return
}
// DialContext implements C.ProxyAdapter
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
if s.version == snell.Version2 {
if s.reuse {
c, err := s.pool.Get()
if err != nil {
return nil, err
@@ -101,8 +108,7 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn
}
// ListenPacketContext implements C.ProxyAdapter
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
var err error
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
if err = s.ResolveUDP(ctx, metadata); err != nil {
return nil, err
}
@@ -111,7 +117,14 @@ func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (
return nil, err
}
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
c, err = s.StreamConnContext(ctx, c, metadata)
if err != nil {
return nil, err
}
pc := snell.PacketConn(c)
return newPacketConn(pc, s), nil
@@ -150,12 +163,17 @@ func NewSnell(option SnellOption) (*Snell, error) {
if option.Version == 0 {
option.Version = snell.DefaultSnellVersion
}
if option.Version == snell.Version5 {
// Snell v5 servers are backward-compatible with v4 clients.
option.Version = snell.Version4
}
reuse := option.Version == snell.Version2 || (option.Version == snell.Version4 && option.Reuse)
switch option.Version {
case snell.Version1, snell.Version2:
if option.UDP {
return nil, fmt.Errorf("snell version %d not support UDP", option.Version)
}
case snell.Version3:
case snell.Version3, snell.Version4:
default:
return nil, fmt.Errorf("snell version error: %d", option.Version)
}
@@ -177,10 +195,11 @@ func NewSnell(option SnellOption) (*Snell, error) {
psk: psk,
obfsOption: obfsOption,
version: option.Version,
reuse: reuse,
}
s.dialer = option.NewDialer(s.DialOptions())
if option.Version == snell.Version2 {
if s.reuse {
s.pool = snell.NewPool(func(ctx context.Context) (*snell.Snell, error) {
c, err := s.dialer.DialContext(ctx, "tcp", addr)
if err != nil {
+9 -6
View File
@@ -96,16 +96,19 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
return
}
if ss.tls {
cc := tls.Client(c, ss.tlsConfig)
err = cc.HandshakeContext(ctx)
c = cc
}
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
if ss.tls {
cc := tls.Client(c, ss.tlsConfig)
err = cc.HandshakeContext(ctx)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
}
c = cc
}
var user *socks5.User
if ss.user != "" {
user = &socks5.User{
+1 -1
View File
@@ -15,7 +15,7 @@ import (
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/randv2"
"golang.org/x/crypto/ssh"
"github.com/metacubex/ssh"
)
type Ssh struct {
+476
View File
@@ -0,0 +1,476 @@
//go:build with_gvisor && !no_tailscale
package outbound
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"runtime"
"sync"
"time"
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/iface/anet"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/dns"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/tailscale/envknob"
"github.com/metacubex/tailscale/hostinfo"
"github.com/metacubex/tailscale/ipn"
"github.com/metacubex/tailscale/net/netmon"
"github.com/metacubex/tailscale/tailcfg"
"github.com/metacubex/tailscale/tsnet"
D "github.com/miekg/dns"
"github.com/samber/lo"
)
type Tailscale struct {
*Base
server *tsnet.Server
dnsResolver *dns.Resolver
option TailscaleOption
ctx context.Context
cancel context.CancelFunc
startOnce sync.Once
startErr error
backendInitOnce sync.Once
backendInitCh chan struct{}
backendInitErr error
serverStarted bool
unregisterDNSResolver func()
}
type TailscaleOption struct {
BasicOption
Name string `proxy:"name"`
Hostname string `proxy:"hostname,omitempty"`
AuthKey string `proxy:"auth-key,omitempty"`
ControlURL string `proxy:"control-url,omitempty"`
StateDir string `proxy:"state-dir,omitempty"`
Ephemeral bool `proxy:"ephemeral,omitempty"`
UDP bool `proxy:"udp,omitempty"`
AcceptRoutes *bool `proxy:"accept-routes,omitempty"`
ExitNode string `proxy:"exit-node,omitempty"`
ExitNodeAllowLANAccess *bool `proxy:"exit-node-allow-lan-access,omitempty"`
}
func init() {
hostinfo.RegisterHostinfoNewHook(func(hi *tailcfg.Hostinfo) {
hi.IPNVersion = C.MihomoName + " " + C.Version
})
envknob.SetNoLogsNoSupport()
if runtime.GOOS == "android" { // Android SDK 30 no longer permits Go's net.Interfaces to work (Issue 2293)
netmon.RegisterInterfaceGetter(func() (nif []netmon.Interface, err error) {
log.Debugln("[Tailscale] InterfaceGetter: start, IsForceAnet: %v", anet.IsForceAnet())
ifaces, err := anet.Interfaces()
if err != nil {
log.Warnln("[Tailscale] anet.Interfaces failed: %v", err)
return nil, err
}
for _, iff := range ifaces {
addrs, err := anet.InterfaceAddrsByInterface(&iff)
if err != nil {
log.Warnln("[Tailscale] anet.InterfaceAddrsByInterface(%v) failed: %v", iff.Name, err)
continue
}
nif = append(nif, netmon.Interface{
Interface: &net.Interface{
Index: iff.Index,
MTU: iff.MTU,
Name: iff.Name,
HardwareAddr: iff.HardwareAddr,
Flags: iff.Flags,
},
AltAddrs: addrs,
})
}
log.Debugln("[Tailscale] InterfaceGetter: %v", lo.Map(nif, func(item netmon.Interface, index int) string {
var addrs any
addrs, err := item.Addrs()
if err != nil {
addrs = err
}
return fmt.Sprintf("{Name: %s, Addrs: %v, IsUp: %v, IsLoopback: %v}", item.Name, addrs, item.IsUp(), item.IsLoopback())
}))
return
})
}
}
func NewTailscale(option TailscaleOption) (*Tailscale, error) {
if _, err := buildTailscaleMaskedPrefs(option); err != nil {
return nil, err
}
if option.StateDir == "" {
option.StateDir = "tailscale"
}
option.StateDir = C.Path.Resolve(option.StateDir)
if !C.Path.IsSafePath(option.StateDir) {
return nil, C.Path.ErrNotSafePath(option.StateDir)
}
addr := option.ControlURL
if addr == "" {
addr = "tailscale"
}
ctx, cancel := context.WithCancel(context.Background())
outbound := &Tailscale{
Base: NewBase(BaseOption{
Name: option.Name,
Addr: addr,
Type: C.Tailscale,
ProviderName: option.ProviderName,
UDP: option.UDP,
Interface: option.Interface,
RoutingMark: option.RoutingMark,
Prefer: option.IPVersion,
}),
option: option,
ctx: ctx,
cancel: cancel,
backendInitCh: make(chan struct{}),
}
outbound.dialer = option.NewDialer(outbound.DialOptions())
outbound.server = &tsnet.Server{
Dir: option.StateDir,
Hostname: option.Hostname,
AuthKey: option.AuthKey,
ControlURL: option.ControlURL,
Ephemeral: option.Ephemeral,
SystemDialer: func(ctx context.Context, network, address string) (net.Conn, error) {
log.Debugln("[Tailscale](%s) SystemDialer: start dial %s %s", option.Name, network, address)
conn, err := outbound.dialer.DialContext(ctx, network, address)
log.Debugln("[Tailscale](%s) SystemDialer: finish dial %s %s, err: %v", option.Name, network, address, err)
return conn, err
},
SystemPacketListener: func(ctx context.Context, network, address string) (net.PacketConn, error) {
log.Debugln("[Tailscale](%s) SystemPacketListener: start listen %s %s", option.Name, network, address)
pc, err := outbound.dialer.ListenPacket(ctx, network, address, netip.AddrPort{})
log.Debugln("[Tailscale](%s) SystemPacketListener: finish listen %s %s, err: %v", option.Name, network, address, err)
return pc, err
},
ExtraRootCAs: ca.GetCertPool(),
LookupHook: func(ctx context.Context, host string) ([]netip.Addr, error) {
log.Debugln("[Tailscale](%s) LookupHook: start lookup %s", option.Name, host)
ips, err := resolver.LookupIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
log.Debugln("[Tailscale](%s) LookupHook: finish lookup %s, ips: %v, err: %v", option.Name, host, ips, err)
return ips, err
},
UserLogf: func(format string, args ...any) {
log.Infoln("[Tailscale](%s) %s", option.Name, fmt.Sprintf(format, args...))
},
Logf: func(format string, args ...any) {
log.Debugln("[Tailscale](%s) %s", option.Name, fmt.Sprintf(format, args...))
},
}
dnsTransport := tailscaleDNSTransport{tailscale: outbound}
outbound.dnsResolver = dns.NewResolverFromClient(dnsTransport)
outbound.unregisterDNSResolver = dns.RegisterTailscaleDnsClient(option.Name, dnsTransport)
return outbound, nil
}
func (t *Tailscale) start() error {
t.startOnce.Do(func() {
if err := t.server.Start(); err != nil {
t.startErr = err
t.setBackendInitialized(err)
return
}
t.serverStarted = true
ctx, cancel := context.WithTimeout(t.ctx, 30*time.Second)
defer cancel()
if err := t.applyPrefs(ctx); err != nil {
t.startErr = err
t.setBackendInitialized(err)
return
}
go t.watchBackendState()
})
return t.startErr
}
func (t *Tailscale) ensureStarted(ctx context.Context) error {
if err := t.start(); err != nil {
return err
}
return t.waitBackendInitialized(ctx)
}
func (t *Tailscale) watchBackendState() {
lc, err := t.server.LocalClient()
if err != nil {
t.setBackendInitialized(err)
return
}
watcher, err := lc.WatchIPNBus(t.ctx, ipn.NotifyInitialState)
if err != nil {
t.setBackendInitialized(err)
return
}
defer watcher.Close()
backendInitialized := false
exitNodeNeedsStatus := tailscaleExitNodeNeedsStatus(t.option)
for {
n, err := watcher.Next()
if err != nil {
t.setBackendInitialized(err)
return
}
if n.State == nil {
continue
}
if *n.State != ipn.NoState && !backendInitialized {
t.setBackendInitialized(nil)
backendInitialized = true
if !exitNodeNeedsStatus {
return
}
}
if exitNodeNeedsStatus && *n.State == ipn.Running {
if err := t.applyExitNodePrefs(t.ctx); err != nil {
log.Warnln("[Tailscale](%s) set exit node failed: %v", t.Name(), err)
}
return
}
}
}
func (t *Tailscale) setBackendInitialized(err error) {
t.backendInitOnce.Do(func() {
t.backendInitErr = err
close(t.backendInitCh)
})
}
func (t *Tailscale) waitBackendInitialized(ctx context.Context) error {
select {
case <-t.backendInitCh:
return t.backendInitErr
case <-ctx.Done():
return ctx.Err()
case <-t.ctx.Done():
return t.ctx.Err()
}
}
func (t *Tailscale) applyPrefs(ctx context.Context) error {
mp, err := buildTailscaleMaskedPrefs(t.option)
if err != nil {
return err
}
if mp == nil {
return nil
}
lc, err := t.server.LocalClient()
if err != nil {
return err
}
_, err = lc.EditPrefs(ctx, mp)
return err
}
func (t *Tailscale) applyExitNodePrefs(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
lc, err := t.server.LocalClient()
if err != nil {
return err
}
status, err := lc.Status(ctx)
if err != nil {
return err
}
mp := &ipn.MaskedPrefs{
ExitNodeIPSet: true,
}
if t.option.ExitNodeAllowLANAccess != nil {
mp.ExitNodeAllowLANAccess = *t.option.ExitNodeAllowLANAccess
mp.ExitNodeAllowLANAccessSet = true
}
if err = mp.SetExitNodeIP(t.option.ExitNode, status); err != nil {
return err
}
_, err = lc.EditPrefs(ctx, mp)
return err
}
func buildTailscaleMaskedPrefs(option TailscaleOption) (*ipn.MaskedPrefs, error) {
var mp ipn.MaskedPrefs
changed := false
if option.AcceptRoutes != nil {
mp.RouteAll = *option.AcceptRoutes
mp.RouteAllSet = true
changed = true
}
if option.ExitNode != "" {
if autoExitNode, ok := ipn.ParseAutoExitNodeString(option.ExitNode); ok {
mp.AutoExitNode = autoExitNode
mp.AutoExitNodeSet = true
changed = true
}
}
if option.ExitNodeAllowLANAccess != nil && !tailscaleExitNodeNeedsStatus(option) {
mp.ExitNodeAllowLANAccess = *option.ExitNodeAllowLANAccess
mp.ExitNodeAllowLANAccessSet = true
changed = true
}
if !changed {
return nil, nil
}
return &mp, nil
}
func tailscaleExitNodeNeedsStatus(option TailscaleOption) bool {
if option.ExitNode == "" {
return false
}
_, ok := ipn.ParseAutoExitNodeString(option.ExitNode)
return !ok
}
func (t *Tailscale) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
if err = t.ensureStarted(ctx); err != nil {
return nil, err
}
netStack, err := t.server.Netstack(ctx)
if err != nil {
return nil, err
}
v4, v6 := t.server.TailscaleIPs()
options := t.DialOptions()
options = append(options, dialer.WithResolver(t.dnsResolver))
options = append(options, dialer.WithNetDialer(dialer.NetDialerFunc(func(ctx context.Context, network, address string) (net.Conn, error) {
dst, err := netip.ParseAddrPort(address) // the dialer will resolve the domain to ip
if err != nil {
return nil, err
}
src := v4
if dst.Addr().Is6() {
src = v6
}
tcpConn, err := netStack.DialContextTCPWithBind(ctx, src, dst)
if err != nil {
return nil, err
}
return tcpConn, nil
})))
var conn net.Conn
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
if err != nil {
return nil, err
}
if conn == nil {
return nil, errors.New("conn is nil")
}
return NewConn(conn, t), nil
}
func (t *Tailscale) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
if err = t.ensureStarted(ctx); err != nil {
return nil, err
}
if err = t.ResolveUDP(ctx, metadata); err != nil {
return nil, err
}
v4, v6 := t.server.TailscaleIPs()
src := v4
if metadata.DstIP.Is6() {
src = v6
}
pc, err := t.server.ListenPacket("udp", net.JoinHostPort(src.String(), "0"))
if err != nil {
return nil, err
}
if pc == nil {
return nil, errors.New("packetConn is nil")
}
return newPacketConn(pc, t), nil
}
func (t *Tailscale) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
if metadata.Host != "" {
ip, err := resolveIPWithResolver(ctx, metadata.Host, t.prefer, t.dnsResolver)
if err != nil {
return fmt.Errorf("can't resolve ip: %w", err)
}
metadata.DstIP = ip
}
return nil
}
type tailscaleDNSTransport struct {
tailscale *Tailscale
}
func (t tailscaleDNSTransport) Address() string {
return "tailscale://" + t.tailscale.Name()
}
func (t tailscaleDNSTransport) ResetConnection() {}
func (t tailscaleDNSTransport) ExchangeContext(ctx context.Context, msg *D.Msg) (*D.Msg, error) {
if len(msg.Question) == 0 {
return nil, errors.New("should have one question at least")
}
if err := t.tailscale.ensureStarted(ctx); err != nil {
return nil, err
}
q := msg.Question[0]
qtypeName, ok := D.TypeToString[q.Qtype]
if !ok {
return nil, fmt.Errorf("unsupported query type: %d", q.Qtype)
}
lc, err := t.tailscale.server.LocalClient()
if err != nil {
return nil, err
}
response, _, err := lc.QueryDNS(ctx, q.Name, qtypeName)
if err != nil {
return nil, err
}
var responseMsg D.Msg
if err = responseMsg.Unpack(response); err != nil {
return nil, err
}
responseMsg.Id = msg.Id
return &responseMsg, nil
}
func (t *Tailscale) ProxyInfo() C.ProxyInfo {
info := t.Base.ProxyInfo()
info.DialerProxy = t.option.DialerProxy
return info
}
func (t *Tailscale) IsL3Protocol(metadata *C.Metadata) bool {
return true
}
func (t *Tailscale) Close() error {
t.cancel()
if t.unregisterDNSResolver != nil {
t.unregisterDNSResolver()
}
t.startOnce.Do(func() {
t.startErr = errors.New("tailscale outbound closed")
})
if t.server != nil && t.serverStarted { // tsnet.Server.Close() must not be called before or concurrently with Start.
return t.server.Close()
}
return nil
}
+28
View File
@@ -0,0 +1,28 @@
//go:build !with_gvisor || no_tailscale
package outbound
import "fmt"
type Tailscale struct {
*Base
}
type TailscaleOption struct {
BasicOption
Name string `proxy:"name"`
Hostname string `proxy:"hostname,omitempty"`
AuthKey string `proxy:"auth-key,omitempty"`
ControlURL string `proxy:"control-url,omitempty"`
StateDir string `proxy:"state-dir,omitempty"`
Ephemeral bool `proxy:"ephemeral,omitempty"`
UDP bool `proxy:"udp,omitempty"`
AcceptRoutes *bool `proxy:"accept-routes,omitempty"`
ExitNode string `proxy:"exit-node,omitempty"`
ExitNodeAllowLANAccess *bool `proxy:"exit-node-allow-lan-access,omitempty"`
}
func NewTailscale(option TailscaleOption) (*Tailscale, error) {
return nil, fmt.Errorf("tailscale support is disabled by \"no_tailscale\" build tag or not include \"with_gvisor\" build tag")
}
+14 -52
View File
@@ -3,10 +3,8 @@ package outbound
import (
"bytes"
"context"
"fmt"
"net"
"net/netip"
"regexp"
"strconv"
"github.com/metacubex/mihomo/component/resolver"
@@ -34,23 +32,26 @@ func serializesSocksAddr(metadata *C.Metadata) []byte {
return bytes.Join(buf, nil)
}
func resolveIPWithResolver(ctx context.Context, host string, prefer C.DNSPrefer, r resolver.Resolver) (netip.Addr, error) {
switch prefer {
case C.IPv4Only:
return resolver.ResolveIPv4WithResolver(ctx, host, r)
case C.IPv6Only:
return resolver.ResolveIPv6WithResolver(ctx, host, r)
case C.IPv6Prefer:
return resolver.ResolveIPPrefer6WithResolver(ctx, host, r)
default:
return resolver.ResolveIPWithResolver(ctx, host, r)
}
}
func resolveUDPAddr(ctx context.Context, network, address string, prefer C.DNSPrefer) (*net.UDPAddr, error) {
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
var ip netip.Addr
switch prefer {
case C.IPv4Only:
ip, err = resolver.ResolveIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
case C.IPv6Only:
ip, err = resolver.ResolveIPv6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
case C.IPv6Prefer:
ip, err = resolver.ResolveIPPrefer6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
default:
ip, err = resolver.ResolveIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
}
ip, err := resolveIPWithResolver(ctx, host, prefer, resolver.ProxyServerHostResolver)
if err != nil {
return nil, err
@@ -75,42 +76,3 @@ func safeConnClose(c net.Conn, err error) {
_ = c.Close()
}
}
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
func StringToBps(s string) uint64 {
if s == "" {
return 0
}
// when have not unit, use Mbps
if v, err := strconv.Atoi(s); err == nil {
return StringToBps(fmt.Sprintf("%d Mbps", v))
}
m := rateStringRegexp.FindStringSubmatch(s)
if m == nil {
return 0
}
var n uint64 = 1
switch m[2] {
case "T":
n *= 1000
fallthrough
case "G":
n *= 1000
fallthrough
case "M":
n *= 1000
fallthrough
case "K":
n *= 1000
}
v, _ := strconv.ParseUint(m[1], 10, 64)
n *= v
if m[3] == "b" {
// Bits, need to convert to bytes
n /= 8
}
return n
}
+18 -48
View File
@@ -115,27 +115,10 @@ type XHTTPReuseSettings struct {
type XHTTPDownloadSettings struct {
// xhttp part
Path *string `proxy:"path,omitempty"`
Host *string `proxy:"host,omitempty"`
Headers *map[string]string `proxy:"headers,omitempty"`
NoGRPCHeader *bool `proxy:"no-grpc-header,omitempty"`
XPaddingBytes *string `proxy:"x-padding-bytes,omitempty"`
XPaddingObfsMode *bool `proxy:"x-padding-obfs-mode,omitempty"`
XPaddingKey *string `proxy:"x-padding-key,omitempty"`
XPaddingHeader *string `proxy:"x-padding-header,omitempty"`
XPaddingPlacement *string `proxy:"x-padding-placement,omitempty"`
XPaddingMethod *string `proxy:"x-padding-method,omitempty"`
UplinkHTTPMethod *string `proxy:"uplink-http-method,omitempty"`
SessionPlacement *string `proxy:"session-placement,omitempty"`
SessionKey *string `proxy:"session-key,omitempty"`
SeqPlacement *string `proxy:"seq-placement,omitempty"`
SeqKey *string `proxy:"seq-key,omitempty"`
UplinkDataPlacement *string `proxy:"uplink-data-placement,omitempty"`
UplinkDataKey *string `proxy:"uplink-data-key,omitempty"`
UplinkChunkSize *string `proxy:"uplink-chunk-size,omitempty"`
ScMaxEachPostBytes *string `proxy:"sc-max-each-post-bytes,omitempty"`
ScMinPostsIntervalMs *string `proxy:"sc-min-posts-interval-ms,omitempty"`
ReuseSettings *XHTTPReuseSettings `proxy:"reuse-settings,omitempty"` // aka XMUX
Path *string `proxy:"path,omitempty"`
Host *string `proxy:"host,omitempty"`
Headers *map[string]string `proxy:"headers,omitempty"`
ReuseSettings *XHTTPReuseSettings `proxy:"reuse-settings,omitempty"` // aka XMUX
// proxy part
Server *string `proxy:"server,omitempty"`
Port *int `proxy:"port,omitempty"`
@@ -316,7 +299,7 @@ func (v *Vless) dialContext(ctx context.Context) (c net.Conn, err error) {
case "grpc": // gun transport
return v.gunClient.Dial()
case "xhttp":
return v.xhttpClient.Dial()
return v.xhttpClient.Dial(ctx)
default:
}
return v.dialer.DialContext(ctx, "tcp", v.addr)
@@ -636,6 +619,9 @@ func NewVless(option VlessOption) (*Vless, error) {
return nil, err
}
_, quicConn, err := common.DialQuic(ctx, v.addr, v.DialOptions(), v.dialer, tlsConfig, cfg, true)
if err != nil {
return nil, err
}
return quicConn, nil
},
v.option.ALPN,
@@ -687,9 +673,13 @@ func NewVless(option VlessOption) (*Vless, error) {
downloadHKeepAlivePeriod := hKeepAlivePeriod
downloadReuseCfg := reuseCfg
downloadCfg := *cfg // make a copy
downloadCfg.Host = downloadHost
downloadCfg.Path = lo.FromPtrOr(ds.Path, v.option.XHTTPOpts.Path)
downloadCfg.Headers = lo.FromPtrOr(ds.Headers, v.option.XHTTPOpts.Headers)
if ds.ReuseSettings != nil {
downloadReuseCfg = &xhttp.ReuseConfig{
downloadCfg.ReuseConfig = &xhttp.ReuseConfig{
MaxConcurrency: ds.ReuseSettings.MaxConcurrency,
MaxConnections: ds.ReuseSettings.MaxConnections,
CMaxReuseTimes: ds.ReuseSettings.CMaxReuseTimes,
@@ -699,30 +689,7 @@ func NewVless(option VlessOption) (*Vless, error) {
downloadHKeepAlivePeriod = time.Duration(ds.ReuseSettings.HKeepAlivePeriod) * time.Second
}
cfg.DownloadConfig = &xhttp.Config{
Host: downloadHost,
Path: lo.FromPtrOr(ds.Path, v.option.XHTTPOpts.Path),
Mode: v.option.XHTTPOpts.Mode,
Headers: lo.FromPtrOr(ds.Headers, v.option.XHTTPOpts.Headers),
NoGRPCHeader: lo.FromPtrOr(ds.NoGRPCHeader, v.option.XHTTPOpts.NoGRPCHeader),
XPaddingBytes: lo.FromPtrOr(ds.XPaddingBytes, v.option.XHTTPOpts.XPaddingBytes),
XPaddingObfsMode: lo.FromPtrOr(ds.XPaddingObfsMode, v.option.XHTTPOpts.XPaddingObfsMode),
XPaddingKey: lo.FromPtrOr(ds.XPaddingKey, v.option.XHTTPOpts.XPaddingKey),
XPaddingHeader: lo.FromPtrOr(ds.XPaddingHeader, v.option.XHTTPOpts.XPaddingHeader),
XPaddingPlacement: lo.FromPtrOr(ds.XPaddingPlacement, v.option.XHTTPOpts.XPaddingPlacement),
XPaddingMethod: lo.FromPtrOr(ds.XPaddingMethod, v.option.XHTTPOpts.XPaddingMethod),
UplinkHTTPMethod: lo.FromPtrOr(ds.UplinkHTTPMethod, v.option.XHTTPOpts.UplinkHTTPMethod),
SessionPlacement: lo.FromPtrOr(ds.SessionPlacement, v.option.XHTTPOpts.SessionPlacement),
SessionKey: lo.FromPtrOr(ds.SessionKey, v.option.XHTTPOpts.SessionKey),
SeqPlacement: lo.FromPtrOr(ds.SeqPlacement, v.option.XHTTPOpts.SeqPlacement),
SeqKey: lo.FromPtrOr(ds.SeqKey, v.option.XHTTPOpts.SeqKey),
UplinkDataPlacement: lo.FromPtrOr(ds.UplinkDataPlacement, v.option.XHTTPOpts.UplinkDataPlacement),
UplinkDataKey: lo.FromPtrOr(ds.UplinkDataKey, v.option.XHTTPOpts.UplinkDataKey),
UplinkChunkSize: lo.FromPtrOr(ds.UplinkChunkSize, v.option.XHTTPOpts.UplinkChunkSize),
ScMaxEachPostBytes: lo.FromPtrOr(ds.ScMaxEachPostBytes, v.option.XHTTPOpts.ScMaxEachPostBytes),
ScMinPostsIntervalMs: lo.FromPtrOr(ds.ScMinPostsIntervalMs, v.option.XHTTPOpts.ScMinPostsIntervalMs),
ReuseConfig: downloadReuseCfg,
}
cfg.DownloadConfig = &downloadCfg
makeDownloadTransport = func() http.RoundTripper {
return xhttp.NewTransport(
@@ -790,6 +757,9 @@ func NewVless(option VlessOption) (*Vless, error) {
return nil, err
}
_, quicConn, err := common.DialQuic(ctx, downloadAddr, v.DialOptions(), v.dialer, tlsConfig, cfg, true)
if err != nil {
return nil, err
}
return quicConn, nil
},
downloadALPN,
+1 -1
View File
@@ -600,7 +600,7 @@ func (w *WireGuard) ResolveUDP(ctx context.Context, metadata *C.Metadata) error
if w.resolver != nil {
r = w.resolver
}
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, r)
ip, err := resolveIPWithResolver(ctx, metadata.Host, w.prefer, r)
if err != nil {
return fmt.Errorf("can't resolve ip: %w", err)
}
+29
View File
@@ -18,6 +18,7 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error)
opt := applyProxyOptions(options...)
basicOption := outbound.BasicOption{
DialerForAPI: opt.DialerForAPI,
TunnelForAPI: opt.TunnelForAPI,
ProviderName: opt.ProviderName,
}
@@ -110,6 +111,13 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error)
break
}
proxy, err = outbound.NewTuic(*tuicOption)
case "gost-relay":
relayOption := &outbound.GostRelayOption{BasicOption: basicOption}
err = decoder.Decode(mapping, relayOption)
if err != nil {
break
}
proxy, err = outbound.NewGostRelay(*relayOption)
case "direct":
directOption := &outbound.DirectOption{BasicOption: basicOption}
err = decoder.Decode(mapping, directOption)
@@ -173,6 +181,20 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error)
break
}
proxy, err = outbound.NewTrustTunnel(*trustTunnelOption)
case "openvpn":
openVPNOption := &outbound.OpenVPNOption{BasicOption: basicOption}
err = decoder.Decode(mapping, openVPNOption)
if err != nil {
break
}
proxy, err = outbound.NewOpenVPN(*openVPNOption)
case "tailscale":
tailscaleOption := &outbound.TailscaleOption{BasicOption: basicOption}
err = decoder.Decode(mapping, tailscaleOption)
if err != nil {
break
}
proxy, err = outbound.NewTailscale(*tailscaleOption)
default:
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
}
@@ -201,6 +223,7 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error)
type proxyOption struct {
DialerForAPI C.Dialer
TunnelForAPI C.Tunnel
ProviderName string
}
@@ -220,6 +243,12 @@ func WithDialerForAPI(dialer C.Dialer) ProxyOption {
}
}
func WithTunnelForAPI(tunnel C.Tunnel) ProxyOption {
return func(opt *proxyOption) {
opt.TunnelForAPI = tunnel
}
}
func WithProviderName(name string) ProxyOption {
return func(opt *proxyOption) {
opt.ProviderName = name
+2 -2
View File
@@ -43,7 +43,7 @@ type proxyProviderSchema struct {
Header map[string][]string `provider:"header,omitempty"`
}
func ParseProxyProvider(name string, mapping map[string]any) (P.ProxyProvider, error) {
func ParseProxyProvider(name string, mapping map[string]any, tunnel C.Tunnel) (P.ProxyProvider, error) {
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
schema := &proxyProviderSchema{
@@ -69,7 +69,7 @@ func ParseProxyProvider(name string, mapping map[string]any) (P.ProxyProvider, e
}
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, uint(schema.HealthCheck.TestTimeout), hcInterval, schema.HealthCheck.Lazy, expectedStatus)
parser, err := NewProxiesParser(name, schema.Filter, schema.ExcludeFilter, schema.ExcludeType, schema.DialerProxy, schema.Override)
parser, err := NewProxiesParser(name, tunnel, schema.Filter, schema.ExcludeFilter, schema.ExcludeType, schema.DialerProxy, schema.Override)
if err != nil {
return nil, err
}
+2 -2
View File
@@ -339,7 +339,7 @@ func (cp *CompatibleProvider) Close() error {
return cp.compatibleProvider.Close()
}
func NewProxiesParser(pdName string, filter string, excludeFilter string, excludeType string, dialerProxy string, override overrideSchema) (resource.Parser[[]C.Proxy], error) {
func NewProxiesParser(pdName string, tunnel C.Tunnel, filter string, excludeFilter string, excludeType string, dialerProxy string, override overrideSchema) (resource.Parser[[]C.Proxy], error) {
var excludeTypeArray []string
if excludeType != "" {
excludeTypeArray = strings.Split(excludeType, "|")
@@ -433,7 +433,7 @@ func NewProxiesParser(pdName string, filter string, excludeFilter string, exclud
return nil, fmt.Errorf("proxy %d override error: %w", idx, err)
}
proxy, err := adapter.ParseProxy(mapping, adapter.WithProviderName(pdName))
proxy, err := adapter.ParseProxy(mapping, adapter.WithTunnelForAPI(tunnel), adapter.WithProviderName(pdName))
if err != nil {
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
}
+5 -6
View File
@@ -331,15 +331,14 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
vmess["http-opts"] = httpOpts
case "h2":
headers := make(map[string]any)
h2Opts := make(map[string]any)
h2Opts["path"] = "/"
if path, ok := values["path"].(string); ok && path != "" {
h2Opts["path"] = path
}
if host, ok := values["host"].(string); ok && host != "" {
headers["Host"] = []string{host}
h2Opts["host"] = []string{host}
}
h2Opts["path"] = values["path"]
h2Opts["headers"] = headers
vmess["h2-opts"] = h2Opts
case "ws", "httpupgrade":
+86 -12
View File
@@ -1,14 +1,17 @@
package convert
package convert_test
import (
"testing"
"github.com/metacubex/mihomo/adapter"
. "github.com/metacubex/mihomo/common/convert"
"github.com/stretchr/testify/assert"
)
// https://v2.hysteria.network/zh/docs/developers/URI-Scheme/
func TestConvertsV2Ray_normal(t *testing.T) {
hy2test := "hysteria2://letmein@example.com:8443/?insecure=1&obfs=salamander&obfs-password=gawrgura&pinSHA256=deadbeef&sni=real.example.com&up=114&down=514&alpn=h3,h4#hy2test"
hy2test := "hysteria2://letmein@example.com:8443/?insecure=1&obfs=salamander&obfs-password=gawrgura&pinSHA256=65b3acd7db555768304a16abb6f4366c1a0c0bb5cec81429617f0150d7d66726&sni=real.example.com&up=114&down=514&alpn=h3,h4#hy2test"
expected := []map[string]interface{}{
{
@@ -24,7 +27,7 @@ func TestConvertsV2Ray_normal(t *testing.T) {
"up": "114",
"down": "514",
"skip-cert-verify": true,
"fingerprint": "deadbeef",
"fingerprint": "65b3acd7db555768304a16abb6f4366c1a0c0bb5cec81429617f0150d7d66726",
},
}
@@ -32,10 +35,13 @@ func TestConvertsV2Ray_normal(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, expected, proxies)
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
func TestConvertsV2RayMieru(t *testing.T) {
mierusTest := "mierus://user:pass@1.2.3.4?handshake-mode=HANDSHAKE_NO_WAIT&mtu=1400&multiplexing=MULTIPLEXING_HIGH&port=6666&port=9998-9999&port=6489&port=4896&profile=default&protocol=TCP&protocol=TCP&protocol=UDP&protocol=UDP&traffic-pattern=CCoQAQ"
mierusTest := "mierus://user:pass@1.2.3.4?handshake-mode=HANDSHAKE_NO_WAIT&mtu=1400&multiplexing=MULTIPLEXING_HIGH&port=6666&port=9998-9999&port=6489&port=4896&profile=default&protocol=TCP&protocol=TCP&protocol=UDP&protocol=UDP&traffic-pattern=CCoQARoECAEQCiIYCAMQASoIMDAwMTAyMDMqCDA0MDUwNjA3"
expected := []map[string]any{
{
@@ -49,7 +55,7 @@ func TestConvertsV2RayMieru(t *testing.T) {
"password": "pass",
"multiplexing": "MULTIPLEXING_HIGH",
"handshake-mode": "HANDSHAKE_NO_WAIT",
"traffic-pattern": "CCoQAQ",
"traffic-pattern": "CCoQARoECAEQCiIYCAMQASoIMDAwMTAyMDMqCDA0MDUwNjA3",
},
{
"name": "default:9998-9999/TCP",
@@ -62,7 +68,7 @@ func TestConvertsV2RayMieru(t *testing.T) {
"password": "pass",
"multiplexing": "MULTIPLEXING_HIGH",
"handshake-mode": "HANDSHAKE_NO_WAIT",
"traffic-pattern": "CCoQAQ",
"traffic-pattern": "CCoQARoECAEQCiIYCAMQASoIMDAwMTAyMDMqCDA0MDUwNjA3",
},
{
"name": "default:6489/UDP",
@@ -75,7 +81,7 @@ func TestConvertsV2RayMieru(t *testing.T) {
"password": "pass",
"multiplexing": "MULTIPLEXING_HIGH",
"handshake-mode": "HANDSHAKE_NO_WAIT",
"traffic-pattern": "CCoQAQ",
"traffic-pattern": "CCoQARoECAEQCiIYCAMQASoIMDAwMTAyMDMqCDA0MDUwNjA3",
},
{
"name": "default:4896/UDP",
@@ -88,7 +94,7 @@ func TestConvertsV2RayMieru(t *testing.T) {
"password": "pass",
"multiplexing": "MULTIPLEXING_HIGH",
"handshake-mode": "HANDSHAKE_NO_WAIT",
"traffic-pattern": "CCoQAQ",
"traffic-pattern": "CCoQARoECAEQCiIYCAMQASoIMDAwMTAyMDMqCDA0MDUwNjA3",
},
}
@@ -96,6 +102,9 @@ func TestConvertsV2RayMieru(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, expected, proxies)
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
func TestConvertsV2RayMieruMinimal(t *testing.T) {
@@ -118,6 +127,9 @@ func TestConvertsV2RayMieruMinimal(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, expected, proxies)
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
func TestConvertsV2RayMieruFragment(t *testing.T) {
@@ -128,10 +140,13 @@ func TestConvertsV2RayMieruFragment(t *testing.T) {
assert.Nil(t, err)
assert.Len(t, proxies, 1)
assert.Equal(t, "myproxy:443/TCP", proxies[0]["name"])
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
func TestConvertsV2RayVlessRealityVisionTCPWithoutHeaderType(t *testing.T) {
vlessTest := "vless://a1b2c3d4-eacc-4433-981b-7e5f9a8b@142.98.76.54:34888?encryption=none&security=reality&type=tcp&sni=github.io&fp=chrome&pbk=TifX9kL2mPqRsTuVwXyZ_JdUWw&sid=6ba85179f3a2b4c5&flow=xtls-rprx-vision#My-VLESS-Reality-Vision"
vlessTest := "vless://a1b2c3d4-eacc-4433-981b-7e5f9a8b@142.98.76.54:34888?encryption=none&security=reality&type=tcp&sni=github.io&fp=chrome&pbk=ppQ9FwLrLIa0AOrp1WvcyiaQ37vg2WSy_CD4bIdiTUw&sid=6ba85179f3a2b4c5&flow=xtls-rprx-vision#My-VLESS-Reality-Vision"
proxies, err := ConvertsV2Ray([]byte(vlessTest))
@@ -143,6 +158,9 @@ func TestConvertsV2RayVlessRealityVisionTCPWithoutHeaderType(t *testing.T) {
assert.Equal(t, "github.io", proxies[0]["servername"])
assert.NotContains(t, proxies[0], "http-opts")
assert.NotContains(t, proxies[0], "h2-opts")
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
func TestConvertsV2RayVlessTCPHTTPHeaderType(t *testing.T) {
@@ -161,6 +179,9 @@ func TestConvertsV2RayVlessTCPHTTPHeaderType(t *testing.T) {
},
}, proxies[0]["http-opts"])
assert.NotContains(t, proxies[0], "h2-opts")
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
func TestConvertsV2RayVlessHTTPTransportUsesH2Opts(t *testing.T) {
@@ -172,9 +193,62 @@ func TestConvertsV2RayVlessHTTPTransportUsesH2Opts(t *testing.T) {
assert.Len(t, proxies, 1)
assert.Equal(t, "h2", proxies[0]["network"])
assert.Equal(t, map[string]any{
"host": []string{"cdn.example.com"},
"path": []string{"/grpc"},
"headers": map[string]any{},
"host": []string{"cdn.example.com"},
"path": "/grpc",
}, proxies[0]["h2-opts"])
assert.NotContains(t, proxies[0], "http-opts")
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
// Regression test for MetaCubeX/mihomo#2738: the legacy v2rayN-style
// base64-JSON VMess parser must place `host` under h2-opts.host instead
// of stranding it inside a non-existent h2-opts.headers.Host key.
func TestConvertsV2RayVmessBase64H2Transport(t *testing.T) {
// base64 payload decodes to:
// {"v":"2","ps":"demo","add":"server.example.com","port":"443",
// "id":"b831381d-6324-4d53-ad4f-8cda48b30811","aid":"0","scy":"auto",
// "net":"h2","type":"none","host":"cdn.example.com","path":"/grpc","tls":"tls"}
vmessTest := "vmess://eyJ2IjoiMiIsInBzIjoiZGVtbyIsImFkZCI6InNlcnZlci5leGFtcGxlLmNvbSIsInBvcnQiOiI0NDMiLCJpZCI6ImI4MzEzODFkLTYzMjQtNGQ1My1hZDRmLThjZGE0OGIzMDgxMSIsImFpZCI6IjAiLCJzY3kiOiJhdXRvIiwibmV0IjoiaDIiLCJ0eXBlIjoibm9uZSIsImhvc3QiOiJjZG4uZXhhbXBsZS5jb20iLCJwYXRoIjoiL2dycGMiLCJ0bHMiOiJ0bHMifQ=="
proxies, err := ConvertsV2Ray([]byte(vmessTest))
assert.Nil(t, err)
assert.Len(t, proxies, 1)
assert.Equal(t, "h2", proxies[0]["network"])
assert.Equal(t, map[string]any{
"host": []string{"cdn.example.com"},
"path": "/grpc",
}, proxies[0]["h2-opts"])
assert.NotContains(t, proxies[0], "http-opts")
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
// `net: http` with `type != "http"` is remapped to h2 transport
// at converter.go's network-resolution step, so it must produce the
// same h2-opts shape as `net: h2`. Guards against regression if the
// remap rule is changed later.
func TestConvertsV2RayVmessBase64HTTPRemappedToH2Transport(t *testing.T) {
// base64 payload decodes to:
// {"v":"2","ps":"demo-http-remapped","add":"server.example.com","port":"443",
// "id":"b831381d-6324-4d53-ad4f-8cda48b30811","aid":"0","scy":"auto",
// "net":"http","type":"none","host":"cdn.example.com","path":"/grpc","tls":"tls"}
vmessTest := "vmess://eyJ2IjoiMiIsInBzIjoiZGVtby1odHRwLXJlbWFwcGVkIiwiYWRkIjoic2VydmVyLmV4YW1wbGUuY29tIiwicG9ydCI6IjQ0MyIsImlkIjoiYjgzMTM4MWQtNjMyNC00ZDUzLWFkNGYtOGNkYTQ4YjMwODExIiwiYWlkIjoiMCIsInNjeSI6ImF1dG8iLCJuZXQiOiJodHRwIiwidHlwZSI6Im5vbmUiLCJob3N0IjoiY2RuLmV4YW1wbGUuY29tIiwicGF0aCI6Ii9ncnBjIiwidGxzIjoidGxzIn0="
proxies, err := ConvertsV2Ray([]byte(vmessTest))
assert.Nil(t, err)
assert.Len(t, proxies, 1)
assert.Equal(t, "h2", proxies[0]["network"])
assert.Equal(t, map[string]any{
"host": []string{"cdn.example.com"},
"path": "/grpc",
}, proxies[0]["h2-opts"])
assert.NotContains(t, proxies[0], "http-opts")
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
+22 -75
View File
@@ -91,16 +91,14 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
proxy["http-opts"] = httpOpts
case "h2":
headers := make(map[string]any)
h2Opts := make(map[string]any)
h2Opts["path"] = []string{"/"}
h2Opts["path"] = "/"
if path := query.Get("path"); path != "" {
h2Opts["path"] = []string{path}
h2Opts["path"] = path
}
if host := query.Get("host"); host != "" {
h2Opts["host"] = []string{host}
}
h2Opts["headers"] = headers
proxy["h2-opts"] = h2Opts
case "ws", "httpupgrade":
@@ -199,74 +197,74 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
if v, ok := extra["xPaddingBytes"].(string); ok && v != "" {
opts["x-padding-bytes"] = v
}
if v, ok := extra["xPaddingObfsMode"].(bool); ok {
opts["x-padding-obfs-mode"] = v
}
if v, ok := extra["xPaddingKey"].(string); ok && v != "" {
opts["x-padding-key"] = v
}
if v, ok := extra["xPaddingHeader"].(string); ok && v != "" {
opts["x-padding-header"] = v
}
if v, ok := extra["xPaddingPlacement"].(string); ok && v != "" {
opts["x-padding-placement"] = v
}
if v, ok := extra["xPaddingMethod"].(string); ok && v != "" {
opts["x-padding-method"] = v
}
if v, ok := extra["uplinkHttpMethod"].(string); ok && v != "" {
opts["uplink-http-method"] = v
}
if v, ok := extra["sessionPlacement"].(string); ok && v != "" {
opts["session-placement"] = v
}
if v, ok := extra["sessionKey"].(string); ok && v != "" {
opts["session-key"] = v
}
if v, ok := extra["seqPlacement"].(string); ok && v != "" {
opts["seq-placement"] = v
}
if v, ok := extra["seqKey"].(string); ok && v != "" {
opts["seq-key"] = v
}
if v, ok := extra["uplinkDataPlacement"].(string); ok && v != "" {
opts["uplink-data-placement"] = v
}
if v, ok := extra["uplinkDataKey"].(string); ok && v != "" {
opts["uplink-data-key"] = v
}
if v, ok := extra["uplinkChunkSize"].(float64); ok {
opts["uplink-chunk-size"] = int(v)
}
if v, ok := extra["scMaxEachPostBytes"].(float64); ok {
opts["sc-max-each-post-bytes"] = int(v)
}
if v, ok := extra["scMinPostsIntervalMs"].(float64); ok {
opts["sc-min-posts-interval-ms"] = int(v)
}
// xmux in root extra → reuse-settings
if xmuxAny, ok := extra["xmux"].(map[string]any); ok && len(xmuxAny) > 0 {
if reuse := xmuxToReuse(xmuxAny); len(reuse) > 0 {
opts["reuse-settings"] = reuse
}
}
if dsAny, ok := extra["downloadSettings"].(map[string]any); ok {
ds := make(map[string]any)
@@ -285,7 +283,7 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
if sec == "tls" || sec == "reality" {
ds["tls"] = true
if tlsAny, ok := dsAny["tlsSettings"].(map[string]any); ok {
if sn, ok := tlsAny["serverName"].(string); ok && sn != "" {
ds["servername"] = sn
@@ -308,7 +306,7 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
ds["skip-cert-verify"] = true
}
}
if sec == "reality" {
if realityAny, ok := dsAny["realitySettings"].(map[string]any); ok {
realityOpts := make(map[string]any)
@@ -335,57 +333,6 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
if headers, ok := xhttpAny["headers"].(map[string]any); ok && len(headers) > 0 {
ds["headers"] = headers
}
if v, ok := xhttpAny["noGRPCHeader"].(bool); ok && v {
ds["no-grpc-header"] = true
}
if v, ok := xhttpAny["xPaddingBytes"].(string); ok && v != "" {
ds["x-padding-bytes"] = v
}
if v, ok := xhttpAny["xPaddingObfsMode"].(bool); ok {
ds["x-padding-obfs-mode"] = v
}
if v, ok := xhttpAny["xPaddingKey"].(string); ok && v != "" {
ds["x-padding-key"] = v
}
if v, ok := xhttpAny["xPaddingHeader"].(string); ok && v != "" {
ds["x-padding-header"] = v
}
if v, ok := xhttpAny["xPaddingPlacement"].(string); ok && v != "" {
ds["x-padding-placement"] = v
}
if v, ok := xhttpAny["xPaddingMethod"].(string); ok && v != "" {
ds["x-padding-method"] = v
}
if v, ok := xhttpAny["uplinkHttpMethod"].(string); ok && v != "" {
ds["uplink-http-method"] = v
}
if v, ok := xhttpAny["sessionPlacement"].(string); ok && v != "" {
ds["session-placement"] = v
}
if v, ok := xhttpAny["sessionKey"].(string); ok && v != "" {
ds["session-key"] = v
}
if v, ok := xhttpAny["seqPlacement"].(string); ok && v != "" {
ds["seq-placement"] = v
}
if v, ok := xhttpAny["seqKey"].(string); ok && v != "" {
ds["seq-key"] = v
}
if v, ok := xhttpAny["uplinkDataPlacement"].(string); ok && v != "" {
ds["uplink-data-placement"] = v
}
if v, ok := xhttpAny["uplinkDataKey"].(string); ok && v != "" {
ds["uplink-data-key"] = v
}
if v, ok := xhttpAny["uplinkChunkSize"].(float64); ok {
ds["uplink-chunk-size"] = int(v)
}
if v, ok := xhttpAny["scMaxEachPostBytes"].(float64); ok {
ds["sc-max-each-post-bytes"] = int(v)
}
if v, ok := xhttpAny["scMinPostsIntervalMs"].(float64); ok {
ds["sc-min-posts-interval-ms"] = int(v)
}
// xmux inside downloadSettings.xhttpSettings.extra → download-settings.reuse-settings
if dsExtraAny, ok := xhttpAny["extra"].(map[string]any); ok {
@@ -401,4 +348,4 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
opts["download-settings"] = ds
}
}
}
}
+6 -2
View File
@@ -10,12 +10,16 @@ type closeIdleTransport interface {
CloseIdleConnections()
}
type closeHttp2Connections interface {
CloseHttp2Connections()
}
func CloseTransport(roundTripper http.RoundTripper) {
if tr, ok := roundTripper.(closeIdleTransport); ok {
tr.CloseIdleConnections() // for *http.Transport
}
if tr, ok := roundTripper.(*http.Http2Transport); ok {
closeHttp2Transport(tr) // for *http2.Transport
if tr, ok := roundTripper.(closeHttp2Connections); ok {
tr.CloseHttp2Connections() // for *http.Transport in our own fork
}
if tr, ok := roundTripper.(io.Closer); ok {
_ = tr.Close() // for *http3.Transport
-63
View File
@@ -1,63 +0,0 @@
package httputils
import (
"net"
"sync"
"time"
"unsafe"
"github.com/metacubex/http"
)
type clientConnPool struct {
t *http.Http2Transport
mu sync.Mutex
conns map[string][]*http.Http2ClientConn // key is host:port
dialing map[string]unsafe.Pointer // currently in-flight dials
keys map[*http.Http2ClientConn][]string
addConnCalls map[string]unsafe.Pointer // in-flight addConnIfNeeded calls
}
type clientConn struct {
t *http.Transport
tconn net.Conn // usually *tls.Conn, except specialized impls
}
type efaceWords struct {
typ unsafe.Pointer
data unsafe.Pointer
}
type tlsConn interface {
net.Conn
NetConn() net.Conn
}
func closeClientConn(cc *http.Http2ClientConn) { // like forceCloseConn() in http.Http2ClientConn but also apply for tls-like conn
if conn, ok := (*clientConn)(unsafe.Pointer(cc)).tconn.(tlsConn); ok {
t := time.AfterFunc(time.Second, func() {
_ = conn.NetConn().Close()
})
defer t.Stop()
}
_ = cc.Close()
}
func closeHttp2Transport(tr *http.Http2Transport) {
connPool := transportConnPool(tr)
p := (*clientConnPool)((*efaceWords)(unsafe.Pointer(&connPool)).data)
p.mu.Lock()
defer p.mu.Unlock()
for _, vv := range p.conns {
for _, cc := range vv {
closeClientConn(cc)
}
}
// cleanup
p.conns = make(map[string][]*http.Http2ClientConn)
p.keys = make(map[*http.Http2ClientConn][]string)
}
//go:linkname transportConnPool github.com/metacubex/http.(*http2Transport).connPool
func transportConnPool(t *http.Http2Transport) http.Http2ClientConnPool
+46
View File
@@ -0,0 +1,46 @@
package utils
import (
"fmt"
"regexp"
"strconv"
)
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
func StringToBps(s string) uint64 {
if s == "" {
return 0
}
// when have not unit, use Mbps
if v, err := strconv.Atoi(s); err == nil {
return StringToBps(fmt.Sprintf("%d Mbps", v))
}
m := rateStringRegexp.FindStringSubmatch(s)
if m == nil {
return 0
}
var n uint64 = 1
switch m[2] {
case "T":
n *= 1000
fallthrough
case "G":
n *= 1000
fallthrough
case "M":
n *= 1000
fallthrough
case "K":
n *= 1000
}
v, _ := strconv.ParseUint(m[1], 10, 64)
n *= v
if m[3] == "b" {
// Bits, need to convert to bytes
n /= 8
}
return n
}
+30 -49
View File
@@ -1,71 +1,52 @@
package utils
import (
"crypto/md5"
"crypto/rand"
"crypto/sha1"
"github.com/gofrs/uuid/v5"
"github.com/metacubex/randv2"
)
type unsafeRandReader struct{}
// NewUUIDV3 returns a UUID based on the MD5 hash of the namespace UUID and name.
func NewUUIDV3(ns uuid.UUID, name string) (u uuid.UUID) {
h := md5.New()
h.Write(ns[:])
h.Write([]byte(name))
copy(u[:], h.Sum(make([]byte, 0, md5.Size)))
func (r unsafeRandReader) Read(p []byte) (n int, err error) {
// modify from https://github.com/golang/go/blob/587c3847da81aa7cfc3b3db2677c8586c94df13a/src/runtime/rand.go#L70-L89
// Inspired by wyrand.
n = len(p)
v := randv2.Uint64()
for len(p) > 0 {
v ^= 0xa0761d6478bd642f
v *= 0xe7037ed1a0b428db
size := 8
if len(p) < 8 {
size = len(p)
}
for i := 0; i < size; i++ {
p[i] ^= byte(v >> (8 * i))
}
p = p[size:]
v = v>>32 | v<<32
}
return
}
var UnsafeRandReader = unsafeRandReader{}
var UnsafeUUIDGenerator = uuid.NewGenWithOptions(uuid.WithRandomReader(UnsafeRandReader))
func NewUUIDV1() uuid.UUID {
u, _ := UnsafeUUIDGenerator.NewV1() // unsafeRandReader wouldn't cause error, so ignore err is safe
u.SetVersion(uuid.V3)
u.SetVariant(uuid.VariantRFC9562)
return u
}
func NewUUIDV3(ns uuid.UUID, name string) uuid.UUID {
return UnsafeUUIDGenerator.NewV3(ns, name)
}
func NewUUIDV4() uuid.UUID {
u, _ := UnsafeUUIDGenerator.NewV4() // unsafeRandReader wouldn't cause error, so ignore err is safe
// NewUUIDV4 returns a new version 4 UUID.
//
// Version 4 UUIDs contain 122 bits of random data.
func NewUUIDV4() (u uuid.UUID) {
rand.Read(u[:])
u.SetVersion(uuid.V4)
u.SetVariant(uuid.VariantRFC9562)
return u
}
func NewUUIDV5(ns uuid.UUID, name string) uuid.UUID {
return UnsafeUUIDGenerator.NewV5(ns, name)
}
// NewUUIDV5 returns a UUID based on SHA-1 hash of the namespace UUID and name.
func NewUUIDV5(ns uuid.UUID, name string) (u uuid.UUID) {
h := sha1.New()
h.Write(ns[:])
h.Write([]byte(name))
copy(u[:], h.Sum(make([]byte, 0, sha1.Size)))
func NewUUIDV6() uuid.UUID {
u, _ := UnsafeUUIDGenerator.NewV6() // unsafeRandReader wouldn't cause error, so ignore err is safe
return u
}
func NewUUIDV7() uuid.UUID {
u, _ := UnsafeUUIDGenerator.NewV7() // unsafeRandReader wouldn't cause error, so ignore err is safe
u.SetVersion(uuid.V5)
u.SetVariant(uuid.VariantRFC9562)
return u
}
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
func UUIDMap(str string) (uuid.UUID, error) {
func UUIDMap(str string) uuid.UUID {
u, err := uuid.FromString(str)
if err != nil {
return NewUUIDV5(uuid.Nil, str), nil
return NewUUIDV5(uuid.Nil, str)
}
return u, nil
return u
}
+8 -16
View File
@@ -1,9 +1,10 @@
package utils
import (
"github.com/gofrs/uuid/v5"
"reflect"
"testing"
"github.com/gofrs/uuid/v5"
)
func TestUUIDMap(t *testing.T) {
@@ -22,24 +23,21 @@ func TestUUIDMap(t *testing.T) {
args: args{
str: "82410302-039e-41b6-98b0-d964084b4170",
},
want: uuid.FromStringOrNil("82410302-039e-41b6-98b0-d964084b4170"),
wantErr: false,
want: uuid.FromStringOrNil("82410302-039e-41b6-98b0-d964084b4170"),
},
{
name: "uuid-test-2",
args: args{
str: "88c502e6-d7eb-4c8e-8259-94cb13d83c77",
},
want: uuid.FromStringOrNil("88c502e6-d7eb-4c8e-8259-94cb13d83c77"),
wantErr: false,
want: uuid.FromStringOrNil("88c502e6-d7eb-4c8e-8259-94cb13d83c77"),
},
{
name: "uuid-map-1",
args: args{
str: "123456",
},
want: uuid.FromStringOrNil("f8598425-92f2-5508-a071-4fc67f9040ac"),
wantErr: false,
want: uuid.FromStringOrNil("f8598425-92f2-5508-a071-4fc67f9040ac"),
},
// GENERATED BY 'xray uuid -i'
{
@@ -47,25 +45,19 @@ func TestUUIDMap(t *testing.T) {
args: args{
str: "a9dk23bz0",
},
want: uuid.FromStringOrNil("c91481b6-fc0f-5d9e-b166-5ddf07b9c3c5"),
wantErr: false,
want: uuid.FromStringOrNil("c91481b6-fc0f-5d9e-b166-5ddf07b9c3c5"),
},
{
name: "uuid-map-2",
args: args{
str: "中文123",
},
want: uuid.FromStringOrNil("145c544c-2229-59e5-8dbb-3f33b7610d26"),
wantErr: false,
want: uuid.FromStringOrNil("145c544c-2229-59e5-8dbb-3f33b7610d26"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := UUIDMap(tt.args.str)
if (err != nil) != tt.wantErr {
t.Errorf("UUIDMap() error = %v, wantErr %v", err, tt.wantErr)
return
}
got := UUIDMap(tt.args.str)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("UUIDMap() got = %v, want %v", got, tt.want)
}
+380 -88
View File
@@ -1,11 +1,12 @@
package xsync
// copy and modified from https://github.com/puzpuzpuz/xsync/blob/v4.2.0/map.go
// copy and modified from https://github.com/puzpuzpuz/xsync/blob/v4.5.0/map.go
// which is licensed under Apache v2.
//
// mihomo modified:
// 1. restore xsync/v3's LoadOrCompute api and rename to LoadOrStoreFn.
// 2. the zero Map is ready for use.
// 3. remove unnecessary member variables added by xsync/v3's "optimize Map for integer keys"
import (
"fmt"
@@ -37,11 +38,10 @@ const (
// minimum counter stripes to use
minMapCounterLen = 8
// maximum counter stripes to use; stands for around 4KB of memory
maxMapCounterLen = 32
defaultMeta uint64 = 0x8080808080808080
metaMask uint64 = 0xffffffffff
defaultMetaMasked uint64 = defaultMeta & metaMask
emptyMetaSlot uint8 = 0x80
maxMapCounterLen = 32
metaMask = 0xffffffffff
occupiedMeta = 0x8080808080808080
occupiedMetaMasked = occupiedMeta & metaMask
// minimal number of buckets to transfer when participating in cooperative
// resize; should be at least defaultMinMapTableLen
minResizeTransferStride = 64
@@ -212,7 +212,7 @@ func NewMap[K comparable, V any](options ...func(*MapConfig)) *Map[K, V] {
m := &Map[K, V]{}
if c.sizeHint > defaultMinMapTableLen*entriesPerMapBucket {
tableLen := nextPowOf2(uint32((float64(c.sizeHint) / entriesPerMapBucket) / mapLoadFactor))
tableLen := nextPowOf2(uint64((float64(c.sizeHint) / entriesPerMapBucket) / mapLoadFactor))
m.minTableLen = int(tableLen)
}
m.growOnly = c.growOnly
@@ -229,11 +229,46 @@ func (m *Map[K, V]) init() {
m.table.Store(table)
}
// detectIntKey returns true if the key type is an integer type.
func detectIntKey[K comparable]() bool {
var zero K
switch any(zero).(type) {
case int, uint, uintptr, int64, uint64, int32, uint32, int16, uint16, int8, uint8:
return true
default:
return false
}
}
// hashUint64 computes a hash for integer keys using two rounds of
// multiply-xorshift mixing (wyhash-style).
// This is significantly faster than maphash.Comparable for integer types.
func hashUint64(seed maphash.Seed, v uint64) uint64 {
// maphash.Seed is just a uint64, so we can convert it directly
hi, lo := bits.Mul64(v^(*(*uint64)(unsafe.Pointer(&seed))), 0x2d358dccaa6c78a5)
hi2, lo2 := bits.Mul64(hi^lo, 0x8bb84b93962eacc9)
return hi2 ^ lo2
}
// toUint64 reinterprets integer-like keys as uint64 for hashUint64.
// The size switch is folded per instantiated K by the compiler.
func toUint64[K any](k K) uint64 {
switch unsafe.Sizeof(k) {
case 8:
return *(*uint64)(unsafe.Pointer(&k))
case 4:
return uint64(*(*uint32)(unsafe.Pointer(&k)))
case 2:
return uint64(*(*uint16)(unsafe.Pointer(&k)))
case 1:
return uint64(*(*uint8)(unsafe.Pointer(&k)))
default:
panic("unreachable")
}
}
func newMapTable[K comparable, V any](minTableLen int, seed maphash.Seed) *mapTable[K, V] {
buckets := make([]bucketPadded, minTableLen)
for i := range buckets {
buckets[i].meta = defaultMeta
}
counterLen := minTableLen >> 10
if counterLen < minMapCounterLen {
counterLen = minMapCounterLen
@@ -270,17 +305,33 @@ func ToPlainMap[K comparable, V any](m *Map[K, V]) map[K]V {
func (m *Map[K, V]) Load(key K) (value V, ok bool) {
m.initOnce.Do(m.init)
table := m.table.Load()
hash := maphash.Comparable(table.seed, key)
var hash uint64
if detectIntKey[K]() {
hash = hashUint64(table.seed, toUint64(key))
} else {
hash = maphash.Comparable(table.seed, key)
}
h1 := h1(hash)
h2w := broadcast(h2(hash))
bidx := uint64(len(table.buckets)-1) & h1
b := &table.buckets[bidx]
// Same as: b := &table.buckets[bidx]
// Inline bounds check elimination via unsafe pointer arithmetic.
// Safety: bidx is always < len(table.buckets) since it's masked with (len-1).
b := (*bucketPadded)(unsafe.Add(unsafe.Pointer(&table.buckets[0]),
uintptr(bidx)*unsafe.Sizeof(bucketPadded{})))
for {
metaw := atomic.LoadUint64(&b.meta)
markedw := markZeroBytes(metaw^h2w) & metaMask
for markedw != 0 {
idx := firstMarkedByteIndex(markedw)
eptr := atomic.LoadPointer(&b.entries[idx])
// Same as: eptr := atomic.LoadPointer(&b.entries[idx])
// Inline bounds check elimination via unsafe pointer arithmetic.
// Safety: idx is always < entriesPerMapBucket (5) since it comes from
// firstMarkedByteIndex which returns index of a marked byte in the
// 5-byte metadata mask (metaMask).
eptr := atomic.LoadPointer((*unsafe.Pointer)(unsafe.Add(
unsafe.Pointer(&b.entries[0]),
uintptr(idx)*unsafe.Sizeof(b.entries[0]))))
if eptr != nil {
e := (*entry[K, V])(eptr)
if e.key == key {
@@ -299,14 +350,109 @@ func (m *Map[K, V]) Load(key K) (value V, ok bool) {
// Store sets the value for a key.
func (m *Map[K, V]) Store(key K, value V) {
m.doCompute(
key,
func(V, bool) (V, ComputeOp) {
return value, UpdateOp
},
noLoadOp,
false,
)
m.initOnce.Do(m.init)
// Store is a popular operation, hence instead of using doCompute,
// it uses a simplified and slightly faster version of it.
for {
store_attempt:
var (
emptyb *bucketPadded
emptyidx int
)
table := m.table.Load()
tableLen := len(table.buckets)
var hash uint64
if detectIntKey[K]() {
hash = hashUint64(table.seed, toUint64(key))
} else {
hash = maphash.Comparable(table.seed, key)
}
h1 := h1(hash)
h2 := h2(hash)
h2w := broadcast(h2)
bidx := uint64(len(table.buckets)-1) & h1
rootb := &table.buckets[bidx]
rootb.mu.Lock()
// The following two checks must go in reverse to what's
// in the resize method.
if seq := resizeSeq(m.resizeCtl.Load()); seq&1 == 1 {
// Resize is in progress. Help with the transfer, then go for another attempt.
rootb.mu.Unlock()
m.helpResize(seq)
goto store_attempt
}
if m.newerTableExists(table) {
// Someone resized the table. Go for another attempt.
rootb.mu.Unlock()
goto store_attempt
}
b := rootb
for {
metaw := b.meta
markedw := markZeroBytes(metaw^h2w) & metaMask
for markedw != 0 {
idx := firstMarkedByteIndex(markedw)
eptr := b.entries[idx]
if eptr != nil {
e := (*entry[K, V])(eptr)
if e.key == key {
// In-place update.
newe := new(entry[K, V])
newe.key = key
newe.value = value
atomic.StorePointer(&b.entries[idx], unsafe.Pointer(newe))
rootb.mu.Unlock()
return
}
}
markedw &= markedw - 1
}
if emptyb == nil {
// Search for empty entries (up to 5 per bucket).
emptyw := ^metaw & occupiedMetaMasked
if emptyw != 0 {
idx := firstMarkedByteIndex(emptyw)
emptyb = b
emptyidx = idx
}
}
if b.next == nil {
if emptyb != nil {
// Insertion into an existing bucket.
newe := new(entry[K, V])
newe.key = key
newe.value = value
// First we update meta, then the entry.
atomic.StoreUint64(&emptyb.meta, setByte(emptyb.meta, h2, emptyidx))
atomic.StorePointer(&emptyb.entries[emptyidx], unsafe.Pointer(newe))
rootb.mu.Unlock()
table.addSize(bidx, 1)
return
}
growThreshold := float64(tableLen) * entriesPerMapBucket * mapLoadFactor
if table.sumSize() > int64(growThreshold) {
// Need to grow the table. Then go for another attempt.
rootb.mu.Unlock()
m.resize(table, mapGrowHint)
goto store_attempt
}
// Insertion into a new bucket.
// Create and append a bucket.
newb := new(bucketPadded)
newb.meta = setByte(0, h2, 0)
newe := new(entry[K, V])
newe.key = key
newe.value = value
newb.entries[0] = unsafe.Pointer(newe)
atomic.StorePointer(&b.next, unsafe.Pointer(newb))
rootb.mu.Unlock()
table.addSize(bidx, 1)
return
}
b = (*bucketPadded)(b.next)
}
}
}
// LoadOrStore returns the existing value for the key if present.
@@ -436,7 +582,12 @@ func (m *Map[K, V]) doCompute(
)
table := m.table.Load()
tableLen := len(table.buckets)
hash := maphash.Comparable(table.seed, key)
var hash uint64
if detectIntKey[K]() {
hash = hashUint64(table.seed, toUint64(key))
} else {
hash = maphash.Comparable(table.seed, key)
}
h1 := h1(hash)
h2 := h2(hash)
h2w := broadcast(h2)
@@ -509,13 +660,13 @@ func (m *Map[K, V]) doCompute(
case DeleteOp:
// Deletion.
// First we update the hash, then the entry.
newmetaw := setByte(metaw, emptyMetaSlot, idx)
newmetaw := setByte(metaw, 0, idx)
atomic.StoreUint64(&b.meta, newmetaw)
atomic.StorePointer(&b.entries[idx], nil)
rootb.mu.Unlock()
table.addSize(bidx, -1)
// Might need to shrink the table if we left bucket empty.
if newmetaw == defaultMeta {
if newmetaw == 0 {
m.resize(table, mapShrinkHint)
}
return oldv, !computeOnly
@@ -540,7 +691,7 @@ func (m *Map[K, V]) doCompute(
}
if emptyb == nil {
// Search for empty entries (up to 5 per bucket).
emptyw := metaw & defaultMetaMasked
emptyw := ^metaw & occupiedMetaMasked
if emptyw != 0 {
idx := firstMarkedByteIndex(emptyw)
emptyb = b
@@ -581,11 +732,11 @@ func (m *Map[K, V]) doCompute(
switch op {
case DeleteOp, CancelOp:
rootb.mu.Unlock()
return newValue, false
return zeroV, false
default:
// Create and append a bucket.
newb := new(bucketPadded)
newb.meta = setByte(defaultMeta, h2, 0)
newb.meta = setByte(0, h2, 0)
newe := new(entry[K, V])
newe.key = key
newe.value = newValue
@@ -655,10 +806,10 @@ func (m *Map[K, V]) resize(knownTable *mapTable[K, V], hint mapResizeHint) {
shrinkThreshold := int64((tableLen * entriesPerMapBucket) / mapShrinkFraction)
if tableLen > m.minTableLen && table.sumSize() <= shrinkThreshold {
// Shrink the table with factor of 2.
// It's fine to generate a new seed since full locking
// is required anyway.
// Analogous to growth, we must preserve the seed to ensure stable
// hash mapping, enabling lock-free writes to destination buckets.
m.totalShrinks.Add(1)
newTable = newMapTable[K, V](tableLen>>1, maphash.MakeSeed())
newTable = newMapTable[K, V](tableLen>>1, table.seed)
} else {
// No need to shrink. Wake up all waiters and give up.
m.resizeMu.Lock()
@@ -740,6 +891,20 @@ func (m *Map[K, V]) helpResize(seq uint64) {
func (m *Map[K, V]) transfer(table, newTable *mapTable[K, V]) {
tableLen := len(table.buckets)
newTableLen := len(newTable.buckets)
// Determines the concurrent task range for destination buckets.
// We iterate based on these properties to avoid locking destination
// buckets:
// - Grow (Pow2): baseLen == tableLen
// Entries from source bucket i move to dest buckets i and i+baseLen
// - Shrink (Pow2): baseLen == newTableLen
// Entries from source buckets i and i+baseLen move to dest bucket i
// By iterating 0..baseLen and processing all possible source buckets
// (srcIdx += baseLen) in the inner loop, a single goroutine exclusively
// owns the write operations for its assigned destination buckets.
baseLen := tableLen
if baseLen > newTableLen {
baseLen = newTableLen
}
stride := (tableLen >> 3) / int(maxResizeHelpers)
if stride < minResizeTransferStride {
stride = minResizeTransferStride
@@ -751,27 +916,20 @@ func (m *Map[K, V]) transfer(table, newTable *mapTable[K, V]) {
if start < 0 {
start = 0
}
if start > tableLen {
if start >= baseLen {
break
}
end := int(nextIdx)
if end > tableLen {
end = tableLen
if end > baseLen {
end = baseLen
}
// Transfer buckets in this range.
total := 0
if newTableLen > tableLen {
// We're growing the table with 2x multiplier, so entries from a N bucket can
// only be transferred to N and 2*N buckets in the new table. Thus, destination
// buckets written by the resize helpers don't intersect, so we don't need to
// acquire locks in the destination buckets.
for i := start; i < end; i++ {
total += transferBucketUnsafe(&table.buckets[i], newTable)
}
} else {
// We're shrinking the table, so all locks must be acquired.
for i := start; i < end; i++ {
total += transferBucket(&table.buckets[i], newTable)
for i := start; i < end; i++ {
// Visit all source buckets that map to this destination bucket.
// When growing, runs once. When shrinking, runs twice.
for srcIdx := i; srcIdx < tableLen; srcIdx += baseLen {
total += transferBucketUnsafe(&table.buckets[srcIdx], newTable)
}
}
// The exact counter stripe doesn't matter here, so pick up the one
@@ -791,7 +949,12 @@ func transferBucketUnsafe[K comparable, V any](
for i := 0; i < entriesPerMapBucket; i++ {
if eptr := b.entries[i]; eptr != nil {
e := (*entry[K, V])(eptr)
hash := maphash.Comparable(destTable.seed, e.key)
var hash uint64
if detectIntKey[K]() {
hash = hashUint64(destTable.seed, toUint64(e.key))
} else {
hash = maphash.Comparable(destTable.seed, e.key)
}
bidx := uint64(len(destTable.buckets)-1) & h1(hash)
destb := &destTable.buckets[bidx]
appendToBucket(h2(hash), e, destb)
@@ -806,33 +969,6 @@ func transferBucketUnsafe[K comparable, V any](
}
}
func transferBucket[K comparable, V any](
b *bucketPadded,
destTable *mapTable[K, V],
) (copied int) {
rootb := b
rootb.mu.Lock()
for {
for i := 0; i < entriesPerMapBucket; i++ {
if eptr := b.entries[i]; eptr != nil {
e := (*entry[K, V])(eptr)
hash := maphash.Comparable(destTable.seed, e.key)
bidx := uint64(len(destTable.buckets)-1) & h1(hash)
destb := &destTable.buckets[bidx]
destb.mu.Lock()
appendToBucket(h2(hash), e, destb)
destb.mu.Unlock()
copied++
}
}
if b.next == nil {
rootb.mu.Unlock()
return
}
b = (*bucketPadded)(b.next)
}
}
// Range calls f sequentially for each key and value present in the
// map. If f returns false, range stops the iteration.
//
@@ -846,6 +982,9 @@ func transferBucket[K comparable, V any](
// creation, modification and deletion. However, the concurrent
// modification rule apply, i.e. the changes may be not reflected
// in the subsequently iterated entries.
//
// For a faster, lock-free alternative with relaxed consistency
// guarantees, see [RangeRelaxed].
func (m *Map[K, V]) Range(f func(key K, value V) bool) {
m.initOnce.Do(m.init)
// Pre-allocate array big enough to fit entries for most hash tables.
@@ -882,6 +1021,167 @@ func (m *Map[K, V]) Range(f func(key K, value V) bool) {
}
}
// All is similar to [Range], but returns an [iter.Seq2], so is compatible with
// Go 1.23+ iterators. All of the same caveats and behaviour from [Range] apply
// to All.
//
// For a faster, lock-free alternative with relaxed consistency
// guarantees, see [AllRelaxed].
func (m *Map[K, V]) All() func(func(key K, value V) bool) {
return m.Range
}
// RangeRelaxed calls f sequentially for each key and value present
// in the map. If f returns false, range stops the iteration.
//
// RangeRelaxed is a faster, lock-free alternative to [Range]. Unlike
// Range, it does not acquire bucket locks and does not allocate memory
// for entry snapshots. Instead, it reads entries directly using atomic
// loads.
//
// RangeRelaxed does not necessarily correspond to any consistent
// snapshot of the Map's contents: if the value for any key is stored
// or deleted concurrently, RangeRelaxed may reflect any mapping for
// that key from any point during the RangeRelaxed call. Unlike [Range],
// the same key may be visited more than once if it is concurrently
// deleted and re-inserted during the iteration.
//
// It is safe to modify the map while iterating it, including entry
// creation, modification and deletion. However, the concurrent
// modification rule apply, i.e. the changes may be not reflected
// in the subsequently iterated entries.
//
// For stronger consistency guarantees where each key is visited at
// most once, see [Range].
func (m *Map[K, V]) RangeRelaxed(f func(key K, value V) bool) {
m.initOnce.Do(m.init)
table := m.table.Load()
for i := range table.buckets {
b := &table.buckets[i]
for {
metaw := atomic.LoadUint64(&b.meta)
markedw := metaw & occupiedMeta
for markedw != 0 {
idx := firstMarkedByteIndex(markedw)
eptr := atomic.LoadPointer(&b.entries[idx])
if eptr != nil {
e := (*entry[K, V])(eptr)
if !f(e.key, e.value) {
return
}
}
markedw &= markedw - 1
}
bptr := atomic.LoadPointer(&b.next)
if bptr == nil {
break
}
b = (*bucketPadded)(bptr)
}
}
}
// AllRelaxed is similar to [RangeRelaxed], but returns an [iter.Seq2],
// so is compatible with Go 1.23+ iterators. All of the same caveats
// and behaviour from [RangeRelaxed] apply to AllRelaxed.
//
// For stronger consistency guarantees where each key is visited at
// most once, see [All].
func (m *Map[K, V]) AllRelaxed() func(func(key K, value V) bool) {
return m.RangeRelaxed
}
// DeleteMatching deletes all entries for which the delete return
// value of f is true. If the stop return value is true, the
// iteration stops immediately. The function returns the number
// of deleted entries.
//
// DeleteMatching does not necessarily correspond to any consistent
// snapshot of the Map's contents: if the value for any key is stored
// or deleted concurrently (including by a concurrent DeleteMatching
// call), DeleteMatching may reflect any mapping for that key from
// any point during the call. In particular, if the map is resized
// during the call (for example, due to concurrent modifications),
// the iteration restarts internally with the new table, which may
// result in calling f with the same key more than once.
//
// This call locks a hash table bucket for the duration of
// evaluating f for all entries in the bucket and performing
// deletions. It means that modifications on other entries in
// the bucket will be blocked until f executes. Consider this when
// the function includes long-running operations.
func (m *Map[K, V]) DeleteMatching(f func(key K, value V) (delete, stop bool)) int {
m.initOnce.Do(m.init)
var totalDeleted int
var anyBucketEmptied bool
delete_loop_attempt:
table := m.table.Load()
for bidx := range table.buckets {
rootb := &table.buckets[bidx]
rootb.mu.Lock()
// The following two checks must go in reverse to what's
// in the resize method.
if seq := resizeSeq(m.resizeCtl.Load()); seq&1 == 1 {
// Resize is in progress. Help with the transfer, then go for another attempt.
rootb.mu.Unlock()
m.helpResize(seq)
goto delete_loop_attempt
}
if m.newerTableExists(table) {
// Someone resized the table. Go for another attempt.
rootb.mu.Unlock()
goto delete_loop_attempt
}
var bucketDeleted int
b := rootb
for {
for i := 0; i < entriesPerMapBucket; i++ {
eptr := b.entries[i]
if eptr != nil {
e := (*entry[K, V])(eptr)
del, stop := f(e.key, e.value)
if del {
// Deletion.
// First we update the meta, then the entry.
newmetaw := setByte(b.meta, 0, i)
atomic.StoreUint64(&b.meta, newmetaw)
atomic.StorePointer(&b.entries[i], nil)
bucketDeleted++
if newmetaw == 0 {
anyBucketEmptied = true
}
}
if stop {
rootb.mu.Unlock()
totalDeleted += bucketDeleted
if bucketDeleted > 0 {
table.addSize(uint64(bidx), -bucketDeleted)
}
if anyBucketEmptied {
m.resize(table, mapShrinkHint)
}
return totalDeleted
}
}
}
if b.next == nil {
break
}
b = (*bucketPadded)(b.next)
}
rootb.mu.Unlock()
if bucketDeleted > 0 {
totalDeleted += bucketDeleted
table.addSize(uint64(bidx), -bucketDeleted)
}
}
if anyBucketEmptied {
m.resize(table, mapShrinkHint)
}
return totalDeleted
}
// Clear deletes all keys and values currently stored in the map.
func (m *Map[K, V]) Clear() {
m.initOnce.Do(m.init)
@@ -907,7 +1207,7 @@ func appendToBucket[K comparable, V any](h2 uint8, e *entry[K, V], b *bucketPadd
}
if b.next == nil {
newb := new(bucketPadded)
newb.meta = setByte(defaultMeta, h2, 0)
newb.meta = setByte(0, h2, 0)
newb.entries[0] = unsafe.Pointer(e)
b.next = unsafe.Pointer(newb)
return
@@ -917,7 +1217,7 @@ func appendToBucket[K comparable, V any](h2 uint8, e *entry[K, V], b *bucketPadd
}
func (table *mapTable[K, V]) addSize(bucketIdx uint64, delta int) {
cidx := uint64(len(table.size)-1) & bucketIdx
cidx := bucketIdx & uint64(len(table.size)-1)
atomic.AddInt64(&table.size[cidx].c, int64(delta))
}
@@ -934,7 +1234,7 @@ func h1(h uint64) uint64 {
}
func h2(h uint64) uint8 {
return uint8(h & 0x7f)
return 0x80 | uint8(h&0x7f)
}
// MapStats is Map statistics.
@@ -1052,20 +1352,12 @@ const (
cacheLineSize = 64
)
// nextPowOf2 computes the next highest power of 2 of 32-bit v.
// Source: https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
func nextPowOf2(v uint32) uint32 {
if v == 0 {
// nextPowOf2 computes the next highest power of 2 of 64-bit v.
func nextPowOf2(v uint64) uint64 {
if v <= 1 {
return 1
}
v--
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v++
return v
return 1 << bits.Len64(v-1)
}
func parallelism() uint32 {
+845 -341
View File
File diff suppressed because it is too large. Load diff
+11
View File
@@ -0,0 +1,11 @@
package anet
import (
"os"
"strconv"
)
func IsForceAnet() bool {
force, _ := strconv.ParseBool(os.Getenv("FORCE_ANET"))
return force
}
+3
View File
@@ -0,0 +1,3 @@
// Package anet fix "route ip+net: netlinkrib: permission denied" on android
// copy and modify from https://github.com/wlynxg/anet/tree/5501d401a269290292909e6cc75f105571f97cfa
package anet
+27
View File
@@ -0,0 +1,27 @@
//go:build !android
package anet
import (
"net"
)
// Interfaces returns a list of the system's network interfaces.
func Interfaces() ([]net.Interface, error) {
return net.Interfaces()
}
// InterfaceAddrs returns a list of the system's unicast interface
// addresses.
//
// The returned list does not identify the associated interface; use
// Interfaces and Interface.Addrs for more detail.
func InterfaceAddrs() ([]net.Addr, error) {
return net.InterfaceAddrs()
}
// InterfaceAddrsByInterface returns a list of the system's unicast
// interface addresses by specific interface.
func InterfaceAddrsByInterface(ifi *net.Interface) ([]net.Addr, error) {
return ifi.Addrs()
}
+367
View File
@@ -0,0 +1,367 @@
package anet
import (
"bytes"
"errors"
"net"
"os"
"syscall"
"unsafe"
)
var (
errInvalidInterface = errors.New("invalid network interface")
errInvalidInterfaceIndex = errors.New("invalid network interface index")
errInvalidInterfaceName = errors.New("invalid network interface name")
errNoSuchInterface = errors.New("no such network interface")
errNoSuchMulticastInterface = errors.New("no such multicast network interface")
)
type ifReq [40]byte
// Interfaces returns a list of the system's network interfaces.
func Interfaces() ([]net.Interface, error) {
if !IsForceAnet() {
ift, err := net.Interfaces()
if err == nil {
return ift, nil
}
}
ift, err := interfaceTable(0)
if err != nil {
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
}
return ift, nil
}
// InterfaceAddrs returns a list of the system's unicast interface
// addresses.
//
// The returned list does not identify the associated interface; use
// Interfaces and Interface.Addrs for more detail.
func InterfaceAddrs() ([]net.Addr, error) {
if !IsForceAnet() {
ifat, err := net.InterfaceAddrs()
if err == nil {
return ifat, nil
}
}
ifat, err := interfaceAddrTable(nil)
if err != nil {
err = &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
}
return ifat, err
}
// InterfaceByIndex returns the interface specified by index.
//
// On Solaris, it returns one of the logical network interfaces
// sharing the logical data link; for more precision use
// InterfaceByName.
func InterfaceByIndex(index int) (*net.Interface, error) {
if !IsForceAnet() {
ifi, err := net.InterfaceByIndex(index)
if err == nil {
return ifi, nil
}
}
if index <= 0 {
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: errInvalidInterfaceIndex}
}
ift, err := interfaceTable(index)
if err != nil {
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
}
ifi, err := interfaceByIndex(ift, index)
if err != nil {
err = &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
}
return ifi, err
}
// InterfaceByName returns the interface specified by name.
func InterfaceByName(name string) (*net.Interface, error) {
if !IsForceAnet() {
ifi, err := net.InterfaceByName(name)
if err == nil {
return ifi, nil
}
}
if name == "" {
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: errInvalidInterfaceName}
}
ift, err := interfaceTable(0)
if err != nil {
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
}
for _, ifi := range ift {
if name == ifi.Name {
return &ifi, nil
}
}
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: errNoSuchInterface}
}
// InterfaceAddrsByInterface returns a list of the system's unicast
// interface addresses by specific interface.
func InterfaceAddrsByInterface(ifi *net.Interface) ([]net.Addr, error) {
ifat, err := ifi.Addrs()
if err == nil {
return ifat, nil
}
if ifi == nil {
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: errInvalidInterface}
}
ifat, err = interfaceAddrTable(ifi)
if err != nil {
err = &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
}
return ifat, err
}
// If the ifindex is zero, interfaceTable returns mappings of all
// network interfaces. Otherwise it returns a mapping of a specific
// interface.
func interfaceTable(ifindex int) ([]net.Interface, error) {
tab, err := NetlinkRIB(syscall.RTM_GETADDR, syscall.AF_UNSPEC)
if err != nil {
return nil, os.NewSyscallError("netlinkrib", err)
}
msgs, err := syscall.ParseNetlinkMessage(tab)
if err != nil {
return nil, os.NewSyscallError("parsenetlinkmessage", err)
}
var ift []net.Interface
im := make(map[uint32]struct{})
loop:
for _, m := range msgs {
switch m.Header.Type {
case syscall.NLMSG_DONE:
break loop
case syscall.RTM_NEWADDR:
ifam := (*syscall.IfAddrmsg)(unsafe.Pointer(&m.Data[0]))
if _, ok := im[ifam.Index]; ok {
continue
} else {
im[ifam.Index] = struct{}{}
}
if ifindex == 0 || ifindex == int(ifam.Index) {
ifi := newLink(ifam)
if ifi != nil {
ift = append(ift, *ifi)
}
if ifindex == int(ifam.Index) {
break loop
}
}
}
}
return ift, nil
}
func newLink(ifam *syscall.IfAddrmsg) *net.Interface {
ift := &net.Interface{Index: int(ifam.Index)}
name, err := indexToName(ifam.Index)
if err != nil {
return nil
}
ift.Name = name
mtu, err := nameToMTU(name)
if err != nil {
return nil
}
ift.MTU = mtu
flags, err := nameToFlags(name)
if err != nil {
return nil
}
ift.Flags = flags
return ift
}
func linkFlags(rawFlags uint32) net.Flags {
var f net.Flags
if rawFlags&syscall.IFF_UP != 0 {
f |= net.FlagUp
}
if rawFlags&syscall.IFF_RUNNING != 0 {
f |= net.FlagRunning
}
if rawFlags&syscall.IFF_BROADCAST != 0 {
f |= net.FlagBroadcast
}
if rawFlags&syscall.IFF_LOOPBACK != 0 {
f |= net.FlagLoopback
}
if rawFlags&syscall.IFF_POINTOPOINT != 0 {
f |= net.FlagPointToPoint
}
if rawFlags&syscall.IFF_MULTICAST != 0 {
f |= net.FlagMulticast
}
return f
}
// If the ifi is nil, interfaceAddrTable returns addresses for all
// network interfaces. Otherwise it returns addresses for a specific
// interface.
func interfaceAddrTable(ifi *net.Interface) ([]net.Addr, error) {
tab, err := NetlinkRIB(syscall.RTM_GETADDR, syscall.AF_UNSPEC)
if err != nil {
return nil, os.NewSyscallError("netlinkrib", err)
}
msgs, err := syscall.ParseNetlinkMessage(tab)
if err != nil {
return nil, os.NewSyscallError("parsenetlinkmessage", err)
}
var ift []net.Interface
if ifi == nil {
var err error
ift, err = interfaceTable(0)
if err != nil {
return nil, err
}
}
ifat, err := addrTable(ift, ifi, msgs)
if err != nil {
return nil, err
}
return ifat, nil
}
func addrTable(ift []net.Interface, ifi *net.Interface, msgs []syscall.NetlinkMessage) ([]net.Addr, error) {
var ifat []net.Addr
loop:
for _, m := range msgs {
switch m.Header.Type {
case syscall.NLMSG_DONE:
break loop
case syscall.RTM_NEWADDR:
ifam := (*syscall.IfAddrmsg)(unsafe.Pointer(&m.Data[0]))
if len(ift) != 0 || ifi.Index == int(ifam.Index) {
attrs, err := syscall.ParseNetlinkRouteAttr(&m)
if err != nil {
return nil, os.NewSyscallError("parsenetlinkrouteattr", err)
}
ifa := newAddr(ifam, attrs)
if ifa != nil {
ifat = append(ifat, ifa)
}
}
}
}
return ifat, nil
}
func newAddr(ifam *syscall.IfAddrmsg, attrs []syscall.NetlinkRouteAttr) net.Addr {
var ipPointToPoint bool
// Seems like we need to make sure whether the IP interface
// stack consists of IP point-to-point numbered or unnumbered
// addressing.
for _, a := range attrs {
if a.Attr.Type == syscall.IFA_LOCAL {
ipPointToPoint = true
break
}
}
for _, a := range attrs {
if ipPointToPoint && a.Attr.Type == syscall.IFA_ADDRESS {
continue
}
switch ifam.Family {
case syscall.AF_INET:
return &net.IPNet{IP: net.IPv4(a.Value[0], a.Value[1], a.Value[2], a.Value[3]), Mask: net.CIDRMask(int(ifam.Prefixlen), 8*net.IPv4len)}
case syscall.AF_INET6:
ifa := &net.IPNet{IP: make(net.IP, net.IPv6len), Mask: net.CIDRMask(int(ifam.Prefixlen), 8*net.IPv6len)}
copy(ifa.IP, a.Value[:])
return ifa
}
}
return nil
}
func interfaceByIndex(ift []net.Interface, index int) (*net.Interface, error) {
for _, ifi := range ift {
if index == ifi.Index {
return &ifi, nil
}
}
return nil, errNoSuchInterface
}
func ioctl(fd int, req uint, arg unsafe.Pointer) error {
_, _, e1 := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
if e1 != 0 {
return e1
}
return nil
}
func indexToName(index uint32) (string, error) {
fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM|syscall.SOCK_CLOEXEC, 0)
if err != nil {
return "", err
}
defer syscall.Close(fd)
var ifr ifReq
*(*uint32)(unsafe.Pointer(&ifr[syscall.IFNAMSIZ])) = index
err = ioctl(fd, syscall.SIOCGIFNAME, unsafe.Pointer(&ifr[0]))
if err != nil {
return "", err
}
return string(bytes.Trim(ifr[:syscall.IFNAMSIZ], "\x00")), nil
}
func nameToMTU(name string) (int, error) {
// Leave room for terminating NULL byte.
if len(name) >= syscall.IFNAMSIZ {
return -1, syscall.EINVAL
}
fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM|syscall.SOCK_CLOEXEC, 0)
if err != nil {
return -1, err
}
defer syscall.Close(fd)
var ifr ifReq
copy(ifr[:], name)
err = ioctl(fd, syscall.SIOCGIFMTU, unsafe.Pointer(&ifr[0]))
if err != nil {
return -1, err
}
return int(*(*int32)(unsafe.Pointer(&ifr[syscall.IFNAMSIZ]))), nil
}
func nameToFlags(name string) (net.Flags, error) {
// Leave room for terminating NULL byte.
if len(name) >= syscall.IFNAMSIZ {
return 0, syscall.EINVAL
}
fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM|syscall.SOCK_CLOEXEC, 0)
if err != nil {
return 0, err
}
defer syscall.Close(fd)
var ifr ifReq
copy(ifr[:], name)
err = ioctl(fd, syscall.SIOCGIFFLAGS, unsafe.Pointer(&ifr[0]))
if err != nil {
return 0, err
}
return linkFlags(*(*uint32)(unsafe.Pointer(&ifr[syscall.IFNAMSIZ]))), nil
}
+179
View File
@@ -0,0 +1,179 @@
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Netlink sockets and messages
package anet
import (
"syscall"
"unsafe"
)
// Round the length of a netlink message up to align it properly.
func nlmAlignOf(msglen int) int {
return (msglen + syscall.NLMSG_ALIGNTO - 1) & ^(syscall.NLMSG_ALIGNTO - 1)
}
// Round the length of a netlink route attribute up to align it
// properly.
func rtaAlignOf(attrlen int) int {
return (attrlen + syscall.RTA_ALIGNTO - 1) & ^(syscall.RTA_ALIGNTO - 1)
}
// NetlinkRouteRequest represents a request message to receive routing
// and link states from the kernel.
type NetlinkRouteRequest struct {
Header syscall.NlMsghdr
Data syscall.RtGenmsg
}
func (rr *NetlinkRouteRequest) toWireFormat() []byte {
b := make([]byte, rr.Header.Len)
*(*uint32)(unsafe.Pointer(&b[0:4][0])) = rr.Header.Len
*(*uint16)(unsafe.Pointer(&b[4:6][0])) = rr.Header.Type
*(*uint16)(unsafe.Pointer(&b[6:8][0])) = rr.Header.Flags
*(*uint32)(unsafe.Pointer(&b[8:12][0])) = rr.Header.Seq
*(*uint32)(unsafe.Pointer(&b[12:16][0])) = rr.Header.Pid
b[16] = byte(rr.Data.Family)
return b
}
func newNetlinkRouteRequest(proto, seq, family int) []byte {
rr := &NetlinkRouteRequest{}
rr.Header.Len = uint32(syscall.NLMSG_HDRLEN + syscall.SizeofRtGenmsg)
rr.Header.Type = uint16(proto)
rr.Header.Flags = syscall.NLM_F_DUMP | syscall.NLM_F_REQUEST
rr.Header.Seq = uint32(seq)
rr.Data.Family = uint8(family)
return rr.toWireFormat()
}
// NetlinkRIB returns routing information base, as known as RIB, which
// consists of network facility information, states and parameters.
func NetlinkRIB(proto, family int) ([]byte, error) {
s, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW|syscall.SOCK_CLOEXEC, syscall.NETLINK_ROUTE)
if err != nil {
return nil, err
}
defer syscall.Close(s)
sa := &syscall.SockaddrNetlink{Family: syscall.AF_NETLINK}
wb := newNetlinkRouteRequest(proto, 1, family)
if err := syscall.Sendto(s, wb, 0, sa); err != nil {
return nil, err
}
lsa, err := syscall.Getsockname(s)
if err != nil {
return nil, err
}
lsanl, ok := lsa.(*syscall.SockaddrNetlink)
if !ok {
return nil, syscall.EINVAL
}
var tab []byte
rbNew := make([]byte, syscall.Getpagesize())
done:
for {
rb := rbNew
nr, _, err := syscall.Recvfrom(s, rb, 0)
if err != nil {
return nil, err
}
if nr < syscall.NLMSG_HDRLEN {
return nil, syscall.EINVAL
}
rb = rb[:nr]
tab = append(tab, rb...)
msgs, err := ParseNetlinkMessage(rb)
if err != nil {
return nil, err
}
for _, m := range msgs {
if m.Header.Seq != 1 || m.Header.Pid != lsanl.Pid {
return nil, syscall.EINVAL
}
if m.Header.Type == syscall.NLMSG_DONE {
break done
}
if m.Header.Type == syscall.NLMSG_ERROR {
return nil, syscall.EINVAL
}
}
}
return tab, nil
}
// NetlinkMessage represents a netlink message.
type NetlinkMessage struct {
Header syscall.NlMsghdr
Data []byte
}
// ParseNetlinkMessage parses b as an array of netlink messages and
// returns the slice containing the NetlinkMessage structures.
func ParseNetlinkMessage(b []byte) ([]NetlinkMessage, error) {
var msgs []NetlinkMessage
for len(b) >= syscall.NLMSG_HDRLEN {
h, dbuf, dlen, err := netlinkMessageHeaderAndData(b)
if err != nil {
return nil, err
}
m := NetlinkMessage{Header: *h, Data: dbuf[:int(h.Len)-syscall.NLMSG_HDRLEN]}
msgs = append(msgs, m)
b = b[dlen:]
}
return msgs, nil
}
func netlinkMessageHeaderAndData(b []byte) (*syscall.NlMsghdr, []byte, int, error) {
h := (*syscall.NlMsghdr)(unsafe.Pointer(&b[0]))
l := nlmAlignOf(int(h.Len))
if int(h.Len) < syscall.NLMSG_HDRLEN || l > len(b) {
return nil, nil, 0, syscall.EINVAL
}
return h, b[syscall.NLMSG_HDRLEN:], l, nil
}
// NetlinkRouteAttr represents a netlink route attribute.
type NetlinkRouteAttr struct {
Attr syscall.RtAttr
Value []byte
}
// ParseNetlinkRouteAttr parses m's payload as an array of netlink
// route attributes and returns the slice containing the
// NetlinkRouteAttr structures.
func ParseNetlinkRouteAttr(m *NetlinkMessage) ([]NetlinkRouteAttr, error) {
var b []byte
switch m.Header.Type {
case syscall.RTM_NEWLINK, syscall.RTM_DELLINK:
b = m.Data[syscall.SizeofIfInfomsg:]
case syscall.RTM_NEWADDR, syscall.RTM_DELADDR:
b = m.Data[syscall.SizeofIfAddrmsg:]
case syscall.RTM_NEWROUTE, syscall.RTM_DELROUTE:
b = m.Data[syscall.SizeofRtMsg:]
default:
return nil, syscall.EINVAL
}
var attrs []NetlinkRouteAttr
for len(b) >= syscall.SizeofRtAttr {
a, vbuf, alen, err := netlinkRouteAttrAndValue(b)
if err != nil {
return nil, err
}
ra := NetlinkRouteAttr{Attr: *a, Value: vbuf[:int(a.Len)-syscall.SizeofRtAttr]}
attrs = append(attrs, ra)
b = b[alen:]
}
return attrs, nil
}
func netlinkRouteAttrAndValue(b []byte) (*syscall.RtAttr, []byte, int, error) {
a := (*syscall.RtAttr)(unsafe.Pointer(&b[0]))
if int(a.Len) < syscall.SizeofRtAttr || int(a.Len) > len(b) {
return nil, nil, 0, syscall.EINVAL
}
return a, b[syscall.SizeofRtAttr:], rtaAlignOf(int(a.Len)), nil
}
+3 -2
View File
@@ -7,6 +7,7 @@ import (
"time"
"github.com/metacubex/mihomo/common/singledo"
"github.com/metacubex/mihomo/component/iface/anet"
"github.com/metacubex/bart"
)
@@ -35,7 +36,7 @@ var caches = singledo.NewSingle[*ifaceCache](time.Second * 20)
func getCache() (*ifaceCache, error) {
value, err, _ := caches.Do(func() (*ifaceCache, error) {
ifaces, err := net.Interfaces()
ifaces, err := anet.Interfaces()
if err != nil {
return nil, err
}
@@ -46,7 +47,7 @@ func getCache() (*ifaceCache, error) {
}
for _, iface := range ifaces {
addrs, err := iface.Addrs()
addrs, err := anet.InterfaceAddrsByInterface(&iface)
if err != nil {
continue
}
+31 -3
View File
@@ -90,7 +90,7 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (uint32, string
return uid, pp, err
}
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32, uint32, error) {
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uid uint32, inode uint32, err error) {
request := &inetDiagRequest{
States: 0xffffffff,
Cookie: [2]uint32{0xffffffff, 0xffffffff},
@@ -133,6 +133,7 @@ func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32,
return 0, 0, err
}
err = ErrNotFound
for _, msg := range messages {
if len(msg.Data) < inetDiagResponseSize {
continue
@@ -140,10 +141,37 @@ func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32,
response := (*inetDiagResponse)(unsafe.Pointer(&msg.Data[0]))
return response.UID, response.INode, nil
// always set to allow fallback when check fails
uid, inode, err = response.UID, response.INode, nil
// check src port
if binary.BigEndian.Uint16(response.SrcPort[:]) != uint16(srcPort) {
continue
}
// check src IP
var src netip.Addr
switch response.Family {
case unix.AF_INET:
var a [4]byte
copy(a[:], response.Src[:4])
src = netip.AddrFrom4(a)
case unix.AF_INET6:
var a [16]byte
copy(a[:], response.Src[:])
src = netip.AddrFrom16(a).Unmap()
default:
continue
}
if src != ip.Unmap() {
continue
}
// this is the one we want
break
}
return 0, 0, ErrNotFound
return
}
func resolveProcessNameByProcSearch(inode, uid uint32) (string, error) {
+16 -3
View File
@@ -7,14 +7,23 @@ import (
"net/netip"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/tunnel"
)
type Tunnel interface {
C.Tunnel
Proxies() map[string]C.Proxy
}
type byNameProxyDialer struct {
proxyName string
tunnel C.Tunnel
}
func (d byNameProxyDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
tunnel, _ := d.tunnel.(Tunnel)
if tunnel == nil {
return nil, fmt.Errorf("tunnel is invalid, must be proxydialer.Tunnel, but got: %T", d.tunnel)
}
proxies := tunnel.Proxies()
proxy, ok := proxies[d.proxyName]
if !ok {
@@ -24,6 +33,10 @@ func (d byNameProxyDialer) DialContext(ctx context.Context, network, address str
}
func (d byNameProxyDialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
tunnel, _ := d.tunnel.(Tunnel)
if tunnel == nil {
return nil, fmt.Errorf("tunnel is invalid, must be proxydialer.Tunnel, but got: %T", d.tunnel)
}
proxies := tunnel.Proxies()
proxy, ok := proxies[d.proxyName]
if !ok {
@@ -32,6 +45,6 @@ func (d byNameProxyDialer) ListenPacket(ctx context.Context, network, address st
return New(proxy, true).ListenPacket(ctx, network, address, rAddrPort)
}
func NewByName(proxyName string) C.Dialer {
return byNameProxyDialer{proxyName: proxyName}
func NewByName(proxyName string, tunnel C.Tunnel) C.Dialer {
return byNameProxyDialer{proxyName: proxyName, tunnel: tunnel}
}
+5
View File
@@ -2,6 +2,7 @@ package proxydialer
import (
"context"
"fmt"
"net"
"net/netip"
"strings"
@@ -33,6 +34,7 @@ func (p proxyDialer) DialContext(ctx context.Context, network, address string) (
if !currentMeta.Resolved() { // should not happen, maybe by a wrongly implemented proxy, but we can handle this (:
err = pc.ResolveUDP(ctx, currentMeta)
if err != nil {
_ = pc.Close()
return nil, err
}
}
@@ -49,6 +51,9 @@ func (p proxyDialer) DialContext(ctx context.Context, network, address string) (
}
func (p proxyDialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
if !strings.HasPrefix(network, "udp") {
return nil, fmt.Errorf("proxyDialer only support udp network, but got: %s", network)
}
currentMeta := &C.Metadata{Type: C.INNER, DstIP: rAddrPort.Addr(), DstPort: rAddrPort.Port()}
return p.listenPacket(ctx, currentMeta)
}
-69
View File
@@ -1,69 +0,0 @@
package tls
import (
"context"
"net"
"runtime/debug"
"time"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/http"
)
func extractTlsHandshakeTimeoutFromServer(s *http.Server) time.Duration {
var ret time.Duration
for _, v := range [...]time.Duration{
s.ReadHeaderTimeout,
s.ReadTimeout,
s.WriteTimeout,
} {
if v <= 0 {
continue
}
if ret == 0 || v < ret {
ret = v
}
}
return ret
}
// NewListenerForHttps returns a net.Listener for (*http.Server).Serve()
// the "func (c *conn) serve(ctx context.Context)" in http\server.go
// only do tls handshake and check NegotiatedProtocol with std's *tls.Conn
// so we do the same logic to let http2 (not h2c) work fine
func NewListenerForHttps(l net.Listener, httpServer *http.Server, tlsConfig *Config) net.Listener {
http2Server := &http.Http2Server{}
_ = http.Http2ConfigureServer(httpServer, http2Server)
return N.NewHandleContextListener(context.Background(), l, func(ctx context.Context, conn net.Conn) (net.Conn, error) {
c := Server(conn, tlsConfig)
tlsTO := extractTlsHandshakeTimeoutFromServer(httpServer)
if tlsTO > 0 {
dl := time.Now().Add(tlsTO)
_ = conn.SetReadDeadline(dl)
_ = conn.SetWriteDeadline(dl)
}
err := c.HandshakeContext(ctx)
if err != nil {
return nil, err
}
// Restore Conn-level deadlines.
if tlsTO > 0 {
_ = conn.SetReadDeadline(time.Time{})
_ = conn.SetWriteDeadline(time.Time{})
}
if c.ConnectionState().NegotiatedProtocol == http.Http2NextProtoTLS {
http2Server.ServeConn(c, &http.Http2ServeConnOpts{BaseConfig: httpServer})
return nil, net.ErrClosed
}
return c, nil
}, func(a any) {
stack := debug.Stack()
log.Errorln("https server panic: %s\n%s", a, stack)
})
}
+10 -3
View File
@@ -22,7 +22,6 @@ import (
"github.com/metacubex/http"
"github.com/metacubex/randv2"
"github.com/metacubex/tls"
utls "github.com/metacubex/utls"
"golang.org/x/crypto/hkdf"
)
@@ -134,11 +133,19 @@ func GetRealityConn(ctx context.Context, conn net.Conn, fingerprint UClientHello
func realityClientFallback(uConn net.Conn, serverName string, fingerprint utls.ClientHelloID) {
defer uConn.Close()
// use h2c mode to disallow the net/http fallback to http1.1
//
// Note that this usage is only applicable to our own net/http fork.
// The standard library also needs to mask the tls.Conn type for the conn returned by DialTLSContext
// see: https://github.com/golang/go/issues/79293#issuecomment-4426393534
protocols := new(http.Protocols)
protocols.SetUnencryptedHTTP2(true)
client := http.Client{
Transport: &http.Http2Transport{
DialTLSContext: func(ctx context.Context, network, addr string, config *tls.Config) (net.Conn, error) {
Transport: &http.Transport{
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return uConn, nil
},
Protocols: protocols,
},
}
request, err := http.NewRequest("GET", "https://"+serverName, nil)
+8 -2
View File
@@ -876,7 +876,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
// parse proxy
for idx, mapping := range proxiesConfig {
proxy, err := adapter.ParseProxy(mapping)
proxy, err := adapter.ParseProxy(mapping, adapter.WithTunnelForAPI(T.Tunnel))
if err != nil {
return nil, nil, fmt.Errorf("proxy %d: %w", idx, err)
}
@@ -913,7 +913,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
return nil, nil, fmt.Errorf("can not defined a provider called `%s`", provider.ReservedName)
}
pd, err := provider.ParseProxyProvider(name, mapping)
pd, err := provider.ParseProxyProvider(name, mapping, T.Tunnel)
if err != nil {
return nil, nil, fmt.Errorf("parse proxy provider %s error: %w", name, err)
}
@@ -1217,6 +1217,12 @@ func parseNameServer(servers []string, respectRules bool, preferH3 bool) ([]dns.
dnsNetType = "quic" // DNS over QUIC
case "system":
dnsNetType = "system" // System DNS
case "ts", "tailscale":
addr = u.Host
dnsNetType = "tailscale" // Tailscale DNS via proxy name
if addr == "" {
err = errors.New("missing Tailscale proxy name")
}
case "dhcp":
addr = server[len("dhcp://"):] // some special notation cannot be parsed by url
dnsNetType = "dhcp" // UDP from DHCP
+9
View File
@@ -47,6 +47,9 @@ const (
Sudoku
Masque
TrustTunnel
OpenVPN
Tailscale
GostRelay
)
const (
@@ -218,6 +221,12 @@ func (at AdapterType) String() string {
return "Masque"
case TrustTunnel:
return "TrustTunnel"
case OpenVPN:
return "OpenVPN"
case Tailscale:
return "Tailscale"
case GostRelay:
return "GostRelay"
case Relay:
return "Relay"
case Selector:
+5
View File
@@ -0,0 +1,5 @@
//go:build no_tailscale
package features
const NoTailscale = true
+5
View File
@@ -0,0 +1,5 @@
//go:build !no_tailscale
package features
const NoTailscale = false
+3
View File
@@ -10,6 +10,9 @@ func Tags() (tags []string) {
if NoFakeTCP {
tags = append(tags, "no_fake_tcp")
}
if NoTailscale {
tags = append(tags, "no_tailscale")
}
if WithGVisor {
tags = append(tags, "with_gvisor")
}
+5
View File
@@ -28,6 +28,7 @@ const (
SOCKS4
SOCKS5
SHADOWSOCKS
SNELL
VMESS
VLESS
REDIR
@@ -92,6 +93,8 @@ func (t Type) String() string {
return "Socks5"
case SHADOWSOCKS:
return "ShadowSocks"
case SNELL:
return "Snell"
case VMESS:
return "Vmess"
case VLESS:
@@ -138,6 +141,8 @@ func ParseType(t string) (*Type, error) {
res = SOCKS5
case "SHADOWSOCKS":
res = SHADOWSOCKS
case "SNELL":
res = SNELL
case "VMESS":
res = VMESS
case "VLESS":
+10 -13
View File
@@ -27,9 +27,9 @@ import (
// Values to configure HTTP and HTTP/2 transport.
const (
// transportDefaultReadIdleTimeout is the default timeout for pinging
// transportDefaultSendPingTimeout is the default timeout for pinging
// idle connections in HTTP/2 transport.
transportDefaultReadIdleTimeout = 30 * time.Second
transportDefaultSendPingTimeout = 30 * time.Second
// transportDefaultIdleConnTimeout is the default timeout for idle
// connections in HTTP transport.
@@ -191,6 +191,10 @@ func (doh *dnsOverHTTPS) ResetConnection() {
func (doh *dnsOverHTTPS) closeClient(client *http.Client) (err error) {
client.CloseIdleConnections()
if tr, ok := client.Transport.(*http.Transport); ok { // HTTP/2 may leak due to keep-alive connections.
tr.CloseHttp2Connections()
}
if isHTTP3(client) { // HTTP/3 may leak due to keep-alive connections.
return client.Transport.(io.Closer).Close()
}
@@ -434,17 +438,10 @@ func (doh *dnsOverHTTPS) createTransport(ctx context.Context) (t http.RoundTripp
// only be used when negotiated on the TLS level.
transport.ForceAttemptHTTP2 = true
// Explicitly configure transport to use HTTP/2.
//
// See https://github.com/AdguardTeam/dnsproxy/issues/11.
var transportH2 *http.Http2Transport
transportH2, err = http.Http2ConfigureTransports(transport)
if err != nil {
return nil, err
}
// Enable HTTP/2 pings on idle connections.
transportH2.ReadIdleTimeout = transportDefaultReadIdleTimeout
transport.HTTP2 = &http.HTTP2Config{
SendPingTimeout: transportDefaultSendPingTimeout,
}
return transport, nil
}
@@ -735,7 +732,7 @@ func (doh *dnsOverHTTPS) tlsDial(ctx context.Context, network string, config *tl
err = conn.HandshakeContext(ctx)
if err != nil {
defer conn.Close()
_ = rawConn.Close()
return nil, err
}
+2
View File
@@ -129,10 +129,12 @@ func (t *dnsOverTLS) dialContext(ctx context.Context) (net.Conn, error) {
},
})
if err != nil {
_ = conn.Close()
return nil, err
}
tlsConn := tls.Client(conn, tlsConfig)
if err = tlsConn.HandshakeContext(ctx); err != nil {
_ = conn.Close()
return nil, err
}
conn = tlsConn
+2
View File
@@ -10,6 +10,7 @@ import (
)
type ResolverEnhancer struct {
ipv6 bool
mode C.DNSMode
fakeIPPool *fakeip.Pool
fakeIPPool6 *fakeip.Pool
@@ -169,6 +170,7 @@ type EnhancerConfig struct {
func NewEnhancer(cfg EnhancerConfig) *ResolverEnhancer {
e := &ResolverEnhancer{
ipv6: cfg.IPv6,
mode: cfg.EnhancedMode,
useHosts: cfg.UseHosts,
}
+4 -4
View File
@@ -196,14 +196,14 @@ func withFakeIP(skipper *fakeip.Skipper, fakePool *fakeip.Pool, fakePool6 *fakei
}
}
func withResolver(resolver *Resolver) handler {
func withResolver(resolver resolver.Resolver, ipv6 bool) handler {
return func(ctx *icontext.DNSContext, r *D.Msg) (*D.Msg, error) {
ctx.SetType(icontext.DNSTypeRaw)
q := r.Question[0]
// return a empty AAAA msg when ipv6 disabled
if !resolver.ipv6 && q.Qtype == D.TypeAAAA {
if !ipv6 && q.Qtype == D.TypeAAAA {
return handleMsgWithEmptyAnswer(r), nil
}
@@ -230,7 +230,7 @@ func compose(middlewares []middleware, endpoint handler) handler {
return h
}
func newHandler(resolver *Resolver, mapper *ResolverEnhancer) handler {
func newHandler(resolver resolver.Resolver, mapper *ResolverEnhancer) handler {
var middlewares []middleware
if mapper.useHosts {
@@ -245,5 +245,5 @@ func newHandler(resolver *Resolver, mapper *ResolverEnhancer) handler {
middlewares = append(middlewares, withMapping(mapper.mapping))
}
return compose(middlewares, withResolver(resolver))
return compose(middlewares, withResolver(resolver, mapper.ipv6))
}
+8
View File
@@ -479,6 +479,14 @@ func (rs Resolvers) ResetConnection() {
rs.DirectResolver.ResetConnection()
}
func NewResolverFromClient(client dnsClient) *Resolver {
return &Resolver{
ipv6: true,
main: []dnsClient{client},
cache: Config{}.newCache(),
}
}
func NewResolver(config Config) (rs Resolvers) {
defaultResolver := &Resolver{
main: transform(config.Default, nil),
+1 -1
View File
@@ -24,6 +24,6 @@ func (s *Service) ServeMsg(ctx context.Context, msg *D.Msg) (*D.Msg, error) {
var _ resolver.Service = (*Service)(nil)
func NewService(resolver *Resolver, mapper *ResolverEnhancer) *Service {
func NewService(resolver resolver.Resolver, mapper *ResolverEnhancer) *Service {
return &Service{handler: newHandler(resolver, mapper)}
}
+65
View File
@@ -0,0 +1,65 @@
package dns
import (
"context"
"fmt"
"sync"
"sync/atomic"
D "github.com/miekg/dns"
)
type tailscaleDNSClient struct {
name string
}
type tailscaleResolverEntry struct {
id uint64
client dnsClient
}
var (
tailscaleResolverID atomic.Uint64
tailscaleResolverMu sync.RWMutex
tailscaleResolvers = map[string]tailscaleResolverEntry{}
)
var _ dnsClient = (*tailscaleDNSClient)(nil)
func RegisterTailscaleDnsClient(name string, client dnsClient) func() {
id := tailscaleResolverID.Add(1)
tailscaleResolverMu.Lock()
tailscaleResolvers[name] = tailscaleResolverEntry{
id: id,
client: client,
}
tailscaleResolverMu.Unlock()
return func() {
tailscaleResolverMu.Lock()
if entry, ok := tailscaleResolvers[name]; ok && entry.id == id {
delete(tailscaleResolvers, name)
}
tailscaleResolverMu.Unlock()
}
}
func newTailscaleClient(name string) *tailscaleDNSClient {
return &tailscaleDNSClient{name: name}
}
func (c *tailscaleDNSClient) Address() string {
return "tailscale://" + c.name
}
func (c *tailscaleDNSClient) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error) {
tailscaleResolverMu.RLock()
entry, ok := tailscaleResolvers[c.name]
tailscaleResolverMu.RUnlock()
if !ok || entry.client == nil {
return nil, fmt.Errorf("proxy %q does not provide Tailscale DNS", c.name)
}
return entry.client.ExchangeContext(ctx, m)
}
func (c *tailscaleDNSClient) ResetConnection() {}
+5
View File
@@ -96,6 +96,9 @@ func setMsgTTL(msg *D.Msg, ttl uint32) {
}
for _, extra := range msg.Extra {
if extra.Header().Rrtype == D.TypeOPT { // TTL section in OPT is the extended RCODE and flags (RFC 6891), not real TTL value
continue
}
extra.Header().Ttl = ttl
}
}
@@ -123,6 +126,8 @@ func transform(servers []NameServer, resolver *Resolver) []dnsClient {
c = newDHCPClient(s.Addr)
case "system":
c = newSystemClient()
case "tailscale":
c = newTailscaleClient(s.Addr)
case "rcode":
c = newRCodeClient(s.Addr)
case "quic":
+196 -25
View File
@@ -310,6 +310,7 @@ dns:
- https://mozilla.cloudflare-dns.com/dns-query#DNS&h3=true # 指定策略组和使用 HTTP/3
- dhcp://en0 # dns from dhcp
- quic://dns.adguard.com:784 # DNS over QUIC
# - ts://tailscale # 使用指定 Tailscale 出站的 DNS 配置查询
# - '8.8.8.8#RULES' # 效果同respect-rules,但仅对该服务器生效
# - '8.8.8.8#en0' # 兼容指定 DNS 出口网卡
@@ -393,13 +394,14 @@ proxies: # socks5
# ip-version: dual
# Snell
# Beware that there's currently no UDP support yet
- name: "snell"
type: snell
server: server
port: 44046
psk: yourpsk
# version: 2
# version: 4 # support 1/2/3/4/5
# udp: true # support UDP on version 3/4/5
# reuse: false # v4/5 only
# obfs-opts:
# mode: http # or tls
# host: bing.com
@@ -510,6 +512,60 @@ proxies: # socks5
# headers:
# custom: value
- name: "gost-relay-hop"
type: gost-relay
# Dynamic mode: relay connects to the target address requested by the upper proxy.
# Use this proxy through dialer-proxy to carry ss/vmess/vless/trojan/etc.
server: relay.example.com
port: 443
udp: true
tls: true
# mux: true # relay+mtls when tls is also true
# sni: relay.example.com
# username: user
# password: pass
# client-fingerprint: chrome
# fingerprint: xxxx
# certificate: ./client.crt
# private-key: ./client.key
# skip-cert-verify: true
- name: "ss6-gost-relay"
type: ss
# This address is dialed from the remote GOST relay server side.
# If the remote SS listens on 127.0.0.1:12345 on the relay server, write it here.
server: 127.0.0.1
port: 12345
cipher: chacha20-ietf-poly1305
password: "password"
udp: true
# udp-over-tcp: true # use this instead if your SS server expects UoT over TCP
dialer-proxy: gost-relay-hop
# - name: "gost-relay-forward-hop"
# type: gost-relay
# # Forward mode: relay server chooses its configured forwarding target.
# server: relay.example.com
# port: 443
# udp: true
# forward: true
# tls: true
# # mux: true
# # sni: relay.example.com
# # username: user
# # password: pass
#
# - name: "ss6-gost-relay-forward"
# type: ss
# # In forward mode this address is only used to ask dialer-proxy for a stream.
# # The GOST relay server forwards the stream to its configured target.
# server: relay.example.com
# port: 443
# cipher: chacha20-ietf-poly1305
# password: "password"
# udp: true
# dialer-proxy: gost-relay-forward-hop
- name: "ss-restls-tls13"
type: ss
server: [YOUR_SERVER_IP]
@@ -853,23 +909,6 @@ proxies: # socks5
# host: xxx.com
# headers:
# X-Forwarded-For: ""
# no-grpc-header: false
# x-padding-bytes: "100-1000"
# x-padding-obfs-mode: false
# x-padding-key: x_padding
# x-padding-header: Referer
# x-padding-placement: queryInHeader # Available: queryInHeader, cookie, header, query
# x-padding-method: repeat-x # Available: repeat-x, tokenish
# uplink-http-method: POST # Available: POST, PUT, PATCH, DELETE
# session-placement: path # Available: path, query, cookie, header
# session-key: ""
# seq-placement: path # Available: path, query, cookie, header
# seq-key: ""
# uplink-data-placement: body # Available: body, cookie, header
# uplink-data-key: ""
# uplink-chunk-size: 0 # only applicable when uplink-data-placement is not body
# sc-max-each-post-bytes: 1000000
# sc-min-posts-interval-ms: 30
# reuse-settings: # aka XMUX
# max-concurrency: "16-32"
# max-connections: "0"
@@ -1016,8 +1055,10 @@ proxies: # socks5
# down: "200 Mbps" # 若不写单位,默认为 Mbps
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
password: yourpassword
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前仅支持 salamander
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前支持 salamander 和 gecko
# obfs-password: yourpassword
# obfs-min-packet-size: 512 # 最小线上数据包大小(字节)。仅限 Gecko。
# obfs-max-packet-size: 1200 # 最大线上数据包大小(字节)。仅限 Gecko。
# sni: server.com
# ech-opts:
# enable: true # 必须手动开启
@@ -1031,6 +1072,18 @@ proxies: # socks5
# private-key: ./client.key # 证书对应的私钥 PEM 格式,或者私钥路径
# alpn:
# - h3
# realm-opts:
# enable: true # 必须手动开启
# server-url: https://realm.hy2.io
# token: public
# realm-id: my-cabin-1f3a8c2e9b
# stun-servers:
# - stun.nextcloud.com:3478
# - stun.sip.us:3478
# - global.stun.twilio.com:3478
# # 下面支持填写针对server-url的TLS配置(sni, skip-cert-verify, fingerprint, certificate, private-key, alpn)
# # skip-cert-verify: false
# # ......
###quic-go特殊配置项,不要随意修改除非你知道你在干什么###
# initial-stream-receive-window: 8388608
# max-stream-receive-window: 8388608
@@ -1092,6 +1145,67 @@ proxies: # socks5
# j3: <t><b 0xf6ab><c><r 10> # AmneziaWG v1.5 only (removed in v2)
# itime: 60 # AmneziaWG v1.5 only (removed in v2)
# tailscale
- name: "tailscale"
type: tailscale
# hostname: mihomo # Tailscale 设备名,默认由 tsnet 处理
# auth-key: tskey-auth-xxxx # 可选;不填写时首次启动会输出交互式登录 URL
# control-url: https://controlplane.tailscale.com # 可选;自定义 Headscale/Tailscale control server
# state-dir: ./tailscale # tsnet 状态目录,默认 tailscale
# ephemeral: false # 是否作为 ephemeral node 登录,默认 false
udp: true # 是否启用 UDP,默认 false
# accept-routes: true # 是否接受 Tailnet 中发布的 subnet routes
# exit-node: 100.64.0.1 # 使用指定 exit node,可填写节点 IP;也支持 auto:any
# exit-node-allow-lan-access: true # 使用 exit node 时是否允许访问本地 LAN
# 当目标不在 Tailscale 路由内时,连接会直接报错,不会回退到直连;
# 访问公网需要配置可用的 exit-node,或接受覆盖目标网段的 subnet routes。
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出 Tailscale 控制面和 DERP/STUN 等连接
# dialer-proxy: "ss1"
# interface-name: "WLAN" # 指定出站网卡
# routing-mark: 6666 # Linux 下配置 fwmark
# ip-version: ipv4-prefer # 可选:dual/ipv4/ipv6/ipv4-prefer/ipv6-prefer
# openvpn
- name: "openvpn"
type: openvpn
server: vpn.example.com
port: 1194
proto: udp # udp/tcp,默认 udp
# dev: tun # 目前仅支持 tun,默认 tun
# cipher: AES-128-GCM # 支持 AES-128-GCM / AES-192-GCM / AES-256-GCM / AES-128-CBC / AES-192-CBC / AES-256-CBC / CHACHA20-POLY1305,默认 AES-128-GCM;AES-CBC 会按 AES-128-CBC 处理
# auth: SHA256 # 支持 MD5 / SHA1 / SHA256 / SHA384 / SHA512,默认 SHA256;AEAD cipher 会忽略 auth
# comp-lzo: "no" # 可选值:"yes", "no", "adaptive"
# username / password: auth-user-pass 模式(与下方 cert+key 二选一,不能都不填)
# username: "user"
# password: "pass"
# 从 .ovpn 中复制 <ca></ca> 内的内容,不需要保留 <ca> 标签
ca: |
-----BEGIN CERTIFICATE-----
MIIB...example
-----END CERTIFICATE-----
# 从 .ovpn 中复制 <cert></cert> 内的内容(auth-user-pass 时可省略 cert / key)
cert: |
-----BEGIN CERTIFICATE-----
MIIB...example
-----END CERTIFICATE-----
# 从 .ovpn 中复制 <key></key> 内的内容
key: |
-----BEGIN PRIVATE KEY-----
MIIE...example
-----END PRIVATE KEY-----
# 从 .ovpn 中复制 <tls-crypt></tls-crypt> 内的内容,不需要保留 <tls-crypt> 标签;没有 tls-crypt 的配置可省略
# tls-crypt: |
# -----BEGIN OpenVPN Static key V1-----
# 00000000000000000000000000000000
# ...
# -----END OpenVPN Static key V1-----
# mtu: 1500
udp: true
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
# dialer-proxy: "ss1"
# remote-dns-resolve: true # 强制 dns 远程解析,默认值为 false
# dns: [ 1.1.1.1, 8.8.8.8 ] # 仅在 remote-dns-resolve 为 true 时生效
# masque
- name: "masque"
type: masque
@@ -1214,7 +1328,7 @@ proxies: # socks5
server: server_ip/domain # 1.2.3.4 or domain
port: 443
key: "<client_key>" # 如果你使用sudoku生成的ED25519密钥对,请填写密钥对中的私钥,否则填入和服务端相同的uuid
aead-method: chacha20-poly1305 # 可选:chacha20-poly1305、aes-128-gcm、none(不建议;且 enable-pure-downlink=false 时不可用)
aead-method: chacha20-poly1305 # 可选:chacha20-poly1305、aes-128-gcm、none(不建议;none 不提供 AEAD 保护)
padding-min: 2 # 最小填充率(0-100)
padding-max: 7 # 最大填充率(0-100,必须 >= padding-min)
table-type: prefer_ascii # 可选值:prefer_ascii、prefer_entropy、up_ascii_down_entropy、up_entropy_down_ascii
@@ -1228,7 +1342,7 @@ proxies: # socks5
# host: "" # 可选:覆盖 Host/SNI(支持 example.com 或 example.com:443);仅在 mode 为 stream/poll/auto/ws 时生效
# path-root: "" # 可选:HTTP 隧道端点一级路径前缀(双方需一致),例如 "aabbcc" 或 "/aabbcc/" => /aabbcc/session、/aabbcc/stream、/aabbcc/api/v1/upload、/aabbcc/ws
# multiplex: "off" # 可选字符串:off(默认)、auto(复用底层 HTTP 连接,减少建链 RTT)、on(Sudoku mux 单隧道多目标;仅在 mode=stream/poll/auto 生效;ws 强制 off)
enable-pure-downlink: false # 可选:false=带宽优化下行(更快,要求 aead-method != none);true=纯 Sudoku 下行
enable-pure-downlink: false # 可选:false=带宽优化下行;true=纯 Sudoku 下行
# anytls
- name: anytls
@@ -1576,6 +1690,9 @@ listeners:
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
password: vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg=
cipher: 2022-blake3-aes-256-gcm
# simple-obfs:
# enable: false # 设置为true时开启
# mode: http # Available: http, tls
# shadow-tls:
# enable: false # 设置为true时开启
# version: 3 # 支持v1/v2/v3
@@ -1612,6 +1729,19 @@ listeners:
# streambuf: 2097152 # per stream receive buffer in bytes, smux v2+
# keepalive: 10 # seconds between heartbeats
- name: snell-in-1
type: snell
port: 10815 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
psk: your-password
version: 4 # 仅支持 4/5
udp: true # UDP over TCP tunnel,默认 true
# obfs-opts:
# mode: http # 可选:http / tls
# host: bing.com
# rule: sub-rule-name1
# proxy: proxy
- name: vmess-in-1
type: vmess
port: 10814 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
@@ -1816,14 +1946,14 @@ listeners:
port: 8443 # 仅支持单端口
listen: 0.0.0.0
key: "<server_key>" # 如果你使用sudoku生成的ED25519密钥对,此处是密钥对中的公钥,当然,你也可以仅仅使用任意uuid充当key
aead-method: chacha20-poly1305 # 可选:chacha20-poly1305、aes-128-gcm、none(不建议;且 enable-pure-downlink=false 时不可用)
aead-method: chacha20-poly1305 # 可选:chacha20-poly1305、aes-128-gcm、none(不建议;none 不提供 AEAD 保护)
padding-min: 1 # 最小填充率(0-100)
padding-max: 15 # 最大填充率(0-100,必须 >= padding-min)
table-type: prefer_ascii # 可选值:prefer_ascii、prefer_entropy、up_ascii_down_entropy、up_entropy_down_ascii
# custom-table: xpxvvpvv # 可选,自定义字节布局,必须包含2个x、2个p、4个v,可随意组合;只对 entropy 方向生效
# custom-tables: ["xpxvvpvv", "vxpvxvvp"] # 可选,自定义字节布局列表(x/v/p),用于多表轮换;非空时覆盖 custom-table
handshake-timeout: 5 # 可选(秒)
enable-pure-downlink: false # 可选:false=带宽优化下行(更快,要求 aead-method != none);true=纯 Sudoku 下行
enable-pure-downlink: false # 可选:false=带宽优化下行;true=纯 Sudoku 下行
# 推荐:使用 httpmask 对象统一管理 HTTPMask 相关字段:
httpmask:
disable: false # true 禁用所有 HTTP 伪装/隧道
@@ -1906,8 +2036,11 @@ listeners:
## up 和 down 均不写或为 0 则使用 BBR 流控
# up: "30 Mbps" # 若不写单位,默认为 Mbps
# down: "200 Mbps" # 若不写单位,默认为 Mbps
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前仅支持 salamander
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前支持 salamander 和 gecko
# obfs-password: yourpassword
# obfs-min-packet-size: 512 # 最小线上数据包大小(字节)。仅限 Gecko。
# obfs-max-packet-size: 1200 # 最大线上数据包大小(字节)。仅限 Gecko。
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
# max-idle-time: 15000
# alpn:
# - h3
@@ -1916,6 +2049,44 @@ listeners:
# masquerade: file:///var/www # 作为文件服务器
# masquerade: http://127.0.0.1:8080 #作为反向代理
# masquerade: https://127.0.0.1:8080 #作为反向代理
# realm-opts:
# enable: true # 必须手动开启
# server-url: https://realm.hy2.io
# token: public
# realm-id: my-cabin-1f3a8c2e9b
# stun-servers:
# - stun.nextcloud.com:3478
# - stun.sip.us:3478
# - global.stun.twilio.com:3478
# # proxy: DIRECT # 设置server-url通过哪个代理进行连接
# # 下面支持填写针对server-url的TLS配置(sni, skip-cert-verify, fingerprint, certificate, private-key, alpn)
# # skip-cert-verify: false
# # ......
# 注意,这是用于自建hysteria2入站和出站中realm-opts中server-url的HTTP/HTTPS服务器,请勿混淆
- name: hysteria2-realm-in-1
type: hysteria2-realm
port: 10820 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
token: public # hysteria2入站和出站通过 `Authorization: Bearer <token>` 出示的 Bearer 令牌。
max-realms: 65536 # maximum total realms (0 = unlimited)
max-realms-per-ip: 4 # maximum realms per client IP (0 = unlimited)
trusted-proxy-header: "" # header to read real client IP from (e.g. X-Forwarded-For)
realm-name-pattern: "^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$" # regex realm names must match
# # 下面内容如果配置, realm 将通过 TLS 提供 HTTPS 服务;否则提供明文 HTTP
# certificate: ./server.crt # 证书 PEM 格式,或者 证书的路径
# private-key: ./server.key # 证书对应的私钥 PEM 格式,或者私钥路径
# 下面两项为mTLS配置项,如果client-auth-type设置为 "verify-if-given" 或 "require-and-verify" 则client-auth-cert必须不为空
# client-auth-type: "" # 可选值:""、"request"、"require-any"、"verify-if-given"、"require-and-verify"
# client-auth-cert: string # 证书 PEM 格式,或者 证书的路径
# 如果填写则开启ech(可由 mihomo generate ech-keypair <明文域名> 生成)
# ech-key: |
# -----BEGIN ECH KEYS-----
# ACATwY30o/RKgD6hgeQxwrSiApLaCgU+HKh7B6SUrAHaDwBD/g0APwAAIAAgHjzK
# madSJjYQIf9o1N5GXjkW4DEEeb17qMxHdwMdNnwADAABAAEAAQACAAEAAwAIdGVz
# dC5jb20AAA==
# -----END ECH KEYS-----
# alpn: ["h2", "http/1.1"]
- name: trusttunnel-in-1
type: trusttunnel
+35 -11
View File
@@ -6,7 +6,7 @@ require (
github.com/bahlo/generic-list-go v0.2.0
github.com/coreos/go-iptables v0.8.0
github.com/dlclark/regexp2 v1.12.0
github.com/enfein/mieru/v3 v3.31.0
github.com/enfein/mieru/v3 v3.33.0
github.com/gobwas/ws v1.4.0
github.com/gofrs/uuid/v5 v5.4.0
github.com/golang/snappy v1.0.0
@@ -21,29 +21,32 @@ require (
github.com/metacubex/edwards25519 v1.2.0
github.com/metacubex/fswatch v0.1.1
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759
github.com/metacubex/http v0.1.2
github.com/metacubex/http v0.1.6
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604
github.com/metacubex/mhurl v0.1.0
github.com/metacubex/mlkem v0.1.0
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306
github.com/metacubex/quic-go v0.59.1-0.20260520020949-fcd18c7b6ace
github.com/metacubex/randv2 v0.2.0
github.com/metacubex/restls-client-go v0.1.7
github.com/metacubex/sing v0.5.7
github.com/metacubex/sing-mux v0.3.9
github.com/metacubex/sing-quic v0.0.0-20260414034501-3ea3410d197a
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3
github.com/metacubex/sing-shadowsocks v0.2.12
github.com/metacubex/sing-shadowsocks2 v0.2.7
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2
github.com/metacubex/sing-tun v0.4.17
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc
github.com/metacubex/sing-tun v0.4.20
github.com/metacubex/sing-vmess v0.2.5
github.com/metacubex/sing-wireguard v0.0.0-20250503063753-2dc62acc626f
github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141
github.com/metacubex/ssh v0.1.0
github.com/metacubex/tailscale v0.0.0-20260520011538-f23132fac4b7
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443
github.com/metacubex/tls v0.1.5
github.com/metacubex/tls v0.1.6
github.com/metacubex/utls v1.8.4
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f
github.com/mroth/weightedrand/v2 v2.1.0
github.com/openacid/low v0.1.21
github.com/rasky/go-lzo v0.0.0-20200203143853-96a758eda86e
github.com/samber/lo v1.53.0
github.com/sirupsen/logrus v1.9.4
github.com/stretchr/testify v1.11.1
@@ -74,7 +77,10 @@ require (
github.com/RyuaNerin/go-krypto v1.3.0 // indirect
github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344 // indirect
github.com/ajg/form v1.5.1 // indirect
github.com/akutz/memconn v0.1.0 // indirect
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa // indirect
github.com/andybalholm/brotli v1.0.6 // indirect
github.com/coder/websocket v1.8.12 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dunglas/httpsfv v1.0.2 // indirect
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 // indirect
@@ -82,37 +88,55 @@ require (
github.com/ericlagergren/siv v0.0.0-20220507050439-0b757b3aa5f1 // indirect
github.com/ericlagergren/subtle v0.0.0-20220507045147-890d697da010 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/fxamacker/cbor/v2 v2.9.0 // indirect
github.com/gaukas/godicttls v0.0.4 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/godbus/dbus/v5 v5.1.1-0.20230522191255-76236955d466 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/google/btree v1.1.3 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8 // indirect
github.com/huin/goupnp v1.3.0 // indirect
github.com/josharian/native v1.1.0 // indirect
github.com/jsimonetti/rtnetlink v1.4.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.6 // indirect
github.com/klauspost/reedsolomon v1.12.3 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/mdlayher/socket v0.4.1 // indirect
github.com/mdlayher/socket v0.5.1 // indirect
github.com/metacubex/ascon v0.1.0 // indirect
github.com/metacubex/gvisor v0.0.0-20251227095601-261ec1326fe8 // indirect
github.com/metacubex/hkdf v0.1.0 // indirect
github.com/metacubex/hpke v0.1.0 // indirect
github.com/metacubex/nftables v0.0.0-20250503052935-30a69ab87793 // indirect
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df // indirect
github.com/metacubex/nftables v0.0.0-20260426003805-208c2c1ba2cb // indirect
github.com/metacubex/qpack v0.6.0 // indirect
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260521124654-e1bf77ef79af // indirect
github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49 // indirect
github.com/mitchellh/go-ps v1.0.0 // indirect
github.com/oasisprotocol/deoxysii v0.0.0-20220228165953-2091330c22b7 // indirect
github.com/pierrec/lz4/v4 v4.1.14 // indirect
github.com/pires/go-proxyproto v0.8.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/safchain/ethtool v0.3.0 // indirect
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a // indirect
github.com/sina-ghaderi/poly1305 v0.0.0-20220724002748-c5926b03988b // indirect
github.com/sina-ghaderi/rabaead v0.0.0-20220730151906-ab6e06b96e8c // indirect
github.com/sina-ghaderi/rabbitio v0.0.0-20220730151941-9ce26f4f872e // indirect
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d // indirect
github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 // indirect
github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a // indirect
github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc // indirect
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 // indirect
github.com/vishvananda/netns v0.0.4 // indirect
github.com/vishvananda/netns v0.0.5 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
github.com/x448/float16 v0.8.4 // indirect
gitlab.com/yawning/bsaes.git v0.0.0-20190805113838-0a714cd429ec // indirect
go4.org/mem v0.0.0-20240501181205-ae6ca9944745 // indirect
golang.org/x/mod v0.20.0 // indirect
golang.org/x/oauth2 v0.24.0 // indirect
golang.org/x/term v0.29.0 // indirect
golang.org/x/text v0.22.0 // indirect
golang.org/x/time v0.10.0 // indirect
golang.org/x/tools v0.24.0 // indirect
+74 -22
View File
@@ -5,11 +5,18 @@ github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344 h1:cDVUiFo+npB0ZASqnw4
github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344/go.mod h1:9pIqrY6SXNL8vjRQE5Hd/OL5GyK/9MrGUWs87z/eFfk=
github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=
github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=
github.com/akutz/memconn v0.1.0 h1:NawI0TORU4hcOMsMr11g7vwlCdkYeLKXBcxWu2W/P8A=
github.com/akutz/memconn v0.1.0/go.mod h1:Jo8rI7m0NieZyLI5e2CDlRdRqRRB4S7Xp77ukDjH+Fw=
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI=
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI=
github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk=
github.com/cilium/ebpf v0.12.3 h1:8ht6F9MquybnY97at+VDZb3eQQr8ev79RueWeVaEcG4=
github.com/coder/websocket v1.8.12 h1:5bUXkEPPIbewrnkU8LTCLVaxi4N4J8ahufH2vlo4NAo=
github.com/coder/websocket v1.8.12/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
github.com/coreos/go-iptables v0.8.0 h1:MPc2P89IhuVpLI7ETL/2tx3XZ61VeICZjYqDEgNsPRc=
github.com/coreos/go-iptables v0.8.0/go.mod h1:Qe8Bv2Xik5FyTXwgIbLAnv2sWSBmvWdFETJConOQ//Q=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
@@ -20,8 +27,8 @@ github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz
github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dunglas/httpsfv v1.0.2 h1:iERDp/YAfnojSDJ7PW3dj1AReJz4MrwbECSSE59JWL0=
github.com/dunglas/httpsfv v1.0.2/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg=
github.com/enfein/mieru/v3 v3.31.0 h1:Fl2ocRCRXJzMygzdRjBHgqI996ZuIDHUmyQyovSf9sA=
github.com/enfein/mieru/v3 v3.31.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
github.com/enfein/mieru/v3 v3.33.0 h1:hv2jK8nqYHwpSG86U2rpZR2I8Aff1/J3ifRmd9NBbFc=
github.com/enfein/mieru/v3 v3.33.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 h1:kXYqH/sL8dS/FdoFjr12ePjnLPorPo2FsnrHNuXSDyo=
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358/go.mod h1:hkIFzoiIPZYxdFOOLyDho59b7SrDfo+w3h+yWdlg45I=
github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 h1:8j2RH289RJplhA6WfdaPqzg1MjH2K8wX5e0uhAxrw2g=
@@ -33,8 +40,11 @@ github.com/ericlagergren/subtle v0.0.0-20220507045147-890d697da010 h1:fuGucgPk5d
github.com/ericlagergren/subtle v0.0.0-20220507045147-890d697da010/go.mod h1:JtBcj7sBuTTRupn7c2bFspMDIObMJsVK8TeUvpShPok=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM=
github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
github.com/gaukas/godicttls v0.0.4 h1:NlRaXb3J6hAnTmWdsEKb9bcSBD6BvcIjdGdeb0zfXbk=
github.com/gaukas/godicttls v0.0.4/go.mod h1:l6EenT4TLWgTdwslVb4sEMOCf7Bv0JAK67deKr9/NCI=
github.com/github/fakeca v0.1.0 h1:Km/MVOFvclqxPM9dZBC4+QE564nU4gz4iZ0D9pMw28I=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
@@ -43,8 +53,12 @@ github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
github.com/godbus/dbus/v5 v5.1.1-0.20230522191255-76236955d466 h1:sQspH8M4niEijh3PFscJRLDnkL547IeP7kpPe3uUhEg=
github.com/godbus/dbus/v5 v5.1.1-0.20230522191255-76236955d466/go.mod h1:ZiQxhyQ+bbbfxUKVvjfO498oPYvtYhZzycal3G/NHmU=
github.com/gofrs/uuid/v5 v5.4.0 h1:EfbpCTjqMuGyq5ZJwxqzn3Cbr2d0rUZU7v5ycAk/e/0=
github.com/gofrs/uuid/v5 v5.4.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=
github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
@@ -55,11 +69,15 @@ github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN
github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8 h1:FKHo8hFI3A+7w0aUQuYXQ+6EN5stWmeY/AZqtM8xk9k=
github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo=
github.com/google/tink/go v1.6.1 h1:t7JHqO8Ath2w2ig5vjwQYJzhGEZymedQc90lQXUBa4I=
github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc=
github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8=
github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905 h1:q3OEI9RaN/wwcx+qgGo6ZaoJkCiDYe/gjDLfq7lQQF4=
github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905/go.mod h1:VvGYjkZoJyKqlmT1yzakUs4mfKMNB0XdODP0+rdml6k=
github.com/josharian/native v1.0.1-0.20221213033349-c1e37c09b531/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
github.com/josharian/native v1.1.0 h1:uuaP0hAbW7Y4l0ZRQ6C9zfb7Mg1mbFKry/xzDAfmtLA=
github.com/josharian/native v1.1.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
github.com/jsimonetti/rtnetlink v1.4.0 h1:Z1BF0fRgcETPEa0Kt0MRk3yV5+kF1FWTni6KUFKrq2I=
github.com/jsimonetti/rtnetlink v1.4.0/go.mod h1:5W1jDvWdnthFJ7fxYX1GMK07BUpI4oskfOqvPteYS6E=
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc=
@@ -71,8 +89,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/g=
github.com/mdlayher/netlink v1.7.2/go.mod h1:xraEF7uJbxLhc5fpHL4cPe221LI2bdttWlU+ZGLfQSw=
github.com/mdlayher/socket v0.4.1 h1:eM9y2/jlbs1M615oshPQOHZzj6R6wMT7bX5NPiQvn2U=
github.com/mdlayher/socket v0.4.1/go.mod h1:cAqeGjoufqdxWkD7DkpyS+wcefOtmu5OQ8KuoJGIReA=
github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d h1:vAJ0ZT4aO803F1uw2roIA9yH7Sxzox34tVVyye1bz6c=
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d/go.mod h1:MsM/5czONyXMJ3PRr5DbQ4O/BxzAnJWOIcJdLzW6qHY=
github.com/metacubex/ascon v0.1.0 h1:6ZWxmXYszT1XXtwkf6nxfFhc/OTtQ9R3Vyj1jN32lGM=
@@ -103,22 +121,24 @@ github.com/metacubex/hkdf v0.1.0 h1:fPA6VzXK8cU1foc/TOmGCDmSa7pZbxlnqhl3RNsthaA=
github.com/metacubex/hkdf v0.1.0/go.mod h1:3seEfds3smgTAXqUGn+tgEJH3uXdsUjOiduG/2EtvZ4=
github.com/metacubex/hpke v0.1.0 h1:gu2jUNhraehWi0P/z5HX2md3d7L1FhPQE6/Q0E9r9xQ=
github.com/metacubex/hpke v0.1.0/go.mod h1:vfDm6gfgrwlXUxKDkWbcE44hXtmc1uxLDm2BcR11b3U=
github.com/metacubex/http v0.1.2 h1:XxW+pMaGAvVveRqREbyWJJDDl9dRZQGJoyKBiPPPKs8=
github.com/metacubex/http v0.1.2/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
github.com/metacubex/http v0.1.6 h1:xvXuvXMCMxCWMF5nEJF4yiKvXL+p2atWMzs37e80m1I=
github.com/metacubex/http v0.1.6/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df h1:S0vBzqjXok24VopstOgPd1JdgglW9tXehrqvwpQWbQ8=
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df/go.mod h1:F4sVXat6QjPXkNsKRDyyG3BhSkxPFFnRPEIwmmyCgbg=
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604 h1:hJwCVlE3ojViC35MGHB+FBr8TuIf3BUFn2EQ1VIamsI=
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604/go.mod h1:lpmN3m269b3V5jFCWtffqBLS4U3QQoIid9ugtO+OhVc=
github.com/metacubex/mhurl v0.1.0 h1:ZdW4Zxe3j3uJ89gNytOazHu6kbHn5owutN/VfXOI8GE=
github.com/metacubex/mhurl v0.1.0/go.mod h1:2qpQImCbXoUs6GwJrjuEXKelPyoimsIXr07eNKZdS00=
github.com/metacubex/mlkem v0.1.0 h1:wFClitonSFcmipzzQvax75beLQU+D7JuC+VK1RzSL8I=
github.com/metacubex/mlkem v0.1.0/go.mod h1:amhaXZVeYNShuy9BILcR7P0gbeo/QLZsnqCdL8U2PDQ=
github.com/metacubex/nftables v0.0.0-20250503052935-30a69ab87793 h1:1Qpuy+sU3DmyX9HwI+CrBT/oLNJngvBorR2RbajJcqo=
github.com/metacubex/nftables v0.0.0-20250503052935-30a69ab87793/go.mod h1:RjRNb4G52yAgfR+Oe/kp9G4PJJ97Fnj89eY1BFO3YyA=
github.com/metacubex/nftables v0.0.0-20260426003805-208c2c1ba2cb h1:wk6mHYPURSUvWcUv72gNP79oiylFsscBSDPJ6ieV6Iw=
github.com/metacubex/nftables v0.0.0-20260426003805-208c2c1ba2cb/go.mod h1:73ZrCfhdkW4F2E2GAlta3km/S2RHhFNogCMtWZV2anQ=
github.com/metacubex/protobuf-go v0.0.0-20260306035419-7ceee0674686 h1:PIXmYT2anQt9V8vdmwixtbIJxOpoPXJfIACHPjXEgnE=
github.com/metacubex/protobuf-go v0.0.0-20260306035419-7ceee0674686/go.mod h1:eQV7juxFZIdRgjMxtVqP+6BssKoTZQ1RM0fc58BsCZY=
github.com/metacubex/qpack v0.6.0 h1:YqClGIMOpiRYLjV1qOs483Od08MdPgRnHjt90FuaAKw=
github.com/metacubex/qpack v0.6.0/go.mod h1:lKGSi7Xk94IMvHGOmxS9eIei3bvIqpOAImEBsaOwTkA=
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306 h1:HlGLmLsWJMLSu0CMI9z/BmEnithB4oXM5Rom6/0Qxtg=
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306/go.mod h1:oNzMrmylS897M3zSMuapIdwSwfq6F2qW01Z3NhVRJhk=
github.com/metacubex/quic-go v0.59.1-0.20260520020949-fcd18c7b6ace h1:KXacx7dp1GYVMgxezwXRt5BMsEbvAYuA6rPFUmdAvcQ=
github.com/metacubex/quic-go v0.59.1-0.20260520020949-fcd18c7b6ace/go.mod h1:2YEQEvFrZ5V76oynMBDTlN+4fdnSHCa2uNJxv3cm1HU=
github.com/metacubex/randv2 v0.2.0 h1:uP38uBvV2SxYfLj53kuvAjbND4RUDfFJjwr4UigMiLs=
github.com/metacubex/randv2 v0.2.0/go.mod h1:kFi2SzrQ5WuneuoLLCMkABtiBu6VRrMrWFqSPyj2cxY=
github.com/metacubex/restls-client-go v0.1.7 h1:eCwiXCTQb5WJu9IlgYvDBA1OgrINv58dEe7hcN5H15k=
@@ -127,26 +147,32 @@ github.com/metacubex/sing v0.5.7 h1:8OC+fhKFSv/l9ehEhJRaZZAOuthfZo68SteBVLe8QqM=
github.com/metacubex/sing v0.5.7/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w=
github.com/metacubex/sing-mux v0.3.9 h1:/aoBD2+sK2qsXDlNDe3hkR0GZuFDtwIZhOeGUx9W0Yk=
github.com/metacubex/sing-mux v0.3.9/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
github.com/metacubex/sing-quic v0.0.0-20260414034501-3ea3410d197a h1:977o0ZYYbiQAGuOxql7Q6UN3rEy59OyAE0tELq4gZfI=
github.com/metacubex/sing-quic v0.0.0-20260414034501-3ea3410d197a/go.mod h1:6ayFGfzzBE85csgQkM3gf4neFq6s0losHlPRSxY+nuk=
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3 h1:PnMby5+kZXTl/CFDHfxMbMTaSRD+uMKMsrDYVQyAmX8=
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3/go.mod h1:6ayFGfzzBE85csgQkM3gf4neFq6s0losHlPRSxY+nuk=
github.com/metacubex/sing-shadowsocks v0.2.12 h1:Wqzo8bYXrK5aWqxu/TjlTnYZzAKtKsaFQBdr6IHFaBE=
github.com/metacubex/sing-shadowsocks v0.2.12/go.mod h1:2e5EIaw0rxKrm1YTRmiMnDulwbGxH9hAFlrwQLQMQkU=
github.com/metacubex/sing-shadowsocks2 v0.2.7 h1:hSuuc0YpsfiqYqt1o+fP4m34BQz4e6wVj3PPBVhor3A=
github.com/metacubex/sing-shadowsocks2 v0.2.7/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE=
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2 h1:gXU+MYPm7Wme3/OAY2FFzVq9d9GxPHOqu5AQfg/ddhI=
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2/go.mod h1:mbfboaXauKJNIHJYxQRa+NJs4JU9NZfkA+I33dS2+9E=
github.com/metacubex/sing-tun v0.4.17 h1:ehzvPLyxG1vmjaKVeB0aEK1eqhR3reEzdbqQfM3+5XA=
github.com/metacubex/sing-tun v0.4.17/go.mod h1:L/TjQY5JEGy8nvsuYmy/XgMFMCPiF0+AWSFCYfS6r9w=
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc h1:8wLoFfYQ88iGPL+krQ5tJsI8IAmkFjKpQL2q+y3pvss=
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc/go.mod h1:mbfboaXauKJNIHJYxQRa+NJs4JU9NZfkA+I33dS2+9E=
github.com/metacubex/sing-tun v0.4.20 h1:xdupzizRoZKyDzP0l68WAx5Sk4ooiuT1GiWsiJyOGPw=
github.com/metacubex/sing-tun v0.4.20/go.mod h1:g4I/JNplDBhXLF+aQWgFbhNeJPSXQOWS9HvLeNvkgeA=
github.com/metacubex/sing-vmess v0.2.5 h1:m9Zt5I27lB9fmLMZfism9sH2LcnAfShZfwSkf6/KJoE=
github.com/metacubex/sing-vmess v0.2.5/go.mod h1:AwtlzUgf8COe9tRYAKqWZ+leDH7p5U98a0ZUpYehl8Q=
github.com/metacubex/sing-wireguard v0.0.0-20250503063753-2dc62acc626f h1:Sr/DYKYofKHKc4GF3qkRGNuj6XA6c0eqPgEDN+VAsYU=
github.com/metacubex/sing-wireguard v0.0.0-20250503063753-2dc62acc626f/go.mod h1:jpAkVLPnCpGSfNyVmj6Cq4YbuZsFepm/Dc+9BAOcR80=
github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c h1:tH9FuQW357zp2xAGzkoZTGpNGMVmEFZov0iV5M2S5ew=
github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c/go.mod h1:eQZDJTx+IH3k4mXqaOJ3VJ9h9ZqOl60F7TLi5wAU51Q=
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141 h1:DK2l6m2Fc85H2BhiAPgbJygiWhesPlfGmF+9Vw6ARdk=
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141/go.mod h1:/yI4OiGOSn0SURhZdJF3CbtPg3nwK700bG8TZLMBvAg=
github.com/metacubex/ssh v0.1.0 h1:iGfr99qk/eMHzUnQ/0bTxXT8+8SWqLSHBWDHoAhngzw=
github.com/metacubex/ssh v0.1.0/go.mod h1:NUtl0d+/f2cG9ECEpMM8iCVOpmggQlC13oLeDUONDlU=
github.com/metacubex/tailscale v0.0.0-20260520011538-f23132fac4b7 h1:LoJR4NMyNKHeEJoeGDtcsao7sV0NRkzMeV5H/0J0MIE=
github.com/metacubex/tailscale v0.0.0-20260520011538-f23132fac4b7/go.mod h1:MAo3HhE7968rIwmDvYTYE8xCsV4x+hLnkChdXeP3X4c=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260521124654-e1bf77ef79af h1:c60IbBMUq2h1M2m7+grMJJmBmrObxL8SwvNtm6Ozbwk=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260521124654-e1bf77ef79af/go.mod h1:i3zLKytWkOnyT1i9OmiLevWvrN5J5HE1+yjE7UYNfcQ=
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443 h1:H6TnfM12tOoTizYE/qBHH3nEuibIelmHI+BVSxVJr8o=
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443/go.mod h1:l9oLnLoEXyGZ5RVLsh7QCC5XsouTUyKk4F2nLm2DHLw=
github.com/metacubex/tls v0.1.5 h1:ECcB83dj+zadnhlKcLnUUf1Sq6+vU0f/zoyU0+9oPTc=
github.com/metacubex/tls v0.1.5/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
github.com/metacubex/tls v0.1.6 h1:t2ubLneYa4ceyIC++54a57BLqZFA/QYUrhdjLk2GPwo=
github.com/metacubex/tls v0.1.6/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
github.com/metacubex/utls v1.8.4 h1:HmL9nUApDdWSkgUyodfwF6hSjtiwCGGdyhaSpEejKpg=
github.com/metacubex/utls v1.8.4/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f h1:FGBPRb1zUabhPhDrlKEjQ9lgIwQ6cHL4x8M9lrERhbk=
@@ -155,6 +181,8 @@ github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49 h1:lhlqpYHopuTLx9x
github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49/go.mod h1:MBeEa9IVBphH7vc3LNtW6ZujVXFizotPo3OEiHQ+TNU=
github.com/miekg/dns v1.1.63 h1:8M5aAw6OMZfFXTT7K5V0Eu5YiiL8l7nUAkyN6C9YwaY=
github.com/miekg/dns v1.1.63/go.mod h1:6NGHfjhpmr5lt3XPLuyfDJi5AXbNIPM9PY6H6sF1Nfs=
github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc=
github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=
github.com/mroth/weightedrand/v2 v2.1.0 h1:o1ascnB1CIVzsqlfArQQjeMy1U0NcIbBO5rfd5E/OeU=
github.com/mroth/weightedrand/v2 v2.1.0/go.mod h1:f2faGsfOGOwc1p94wzHKKZyTpcJUW7OJ/9U4yfiNAOU=
github.com/oasisprotocol/deoxysii v0.0.0-20220228165953-2091330c22b7 h1:1102pQc2SEPp5+xrS26wEaeb26sZy6k9/ZXlZN+eXE4=
@@ -168,10 +196,16 @@ github.com/oschwald/maxminddb-golang v1.12.0 h1:9FnTOD0YOhP7DGxGsq4glzpGy5+w7pq5
github.com/oschwald/maxminddb-golang v1.12.0/go.mod h1:q0Nob5lTCqyQ8WT6FYgS1L7PXKVVbgiymefNwIjPzgY=
github.com/pierrec/lz4/v4 v4.1.14 h1:+fL8AQEZtz/ijeNnpduH0bROTu0O3NZAlPjQxGn8LwE=
github.com/pierrec/lz4/v4 v4.1.14/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
github.com/pires/go-proxyproto v0.8.0 h1:5unRmEAPbHXHuLjDg01CxJWf91cw3lKHc/0xzKpXEe0=
github.com/pires/go-proxyproto v0.8.0/go.mod h1:iknsfgnH8EkjrMeMyvfKByp9TiBZCKZM0jx2xmKqnVY=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g=
github.com/rasky/go-lzo v0.0.0-20200203143853-96a758eda86e h1:dCWirM5F3wMY+cmRda/B1BiPsFtmzXqV9b0hLWtVBMs=
github.com/rasky/go-lzo v0.0.0-20200203143853-96a758eda86e/go.mod h1:9leZcVcItj6m9/CfHY5Em/iBrCz7js8LcRQGTKEEv2M=
github.com/safchain/ethtool v0.3.0 h1:gimQJpsI6sc1yIqP/y8GYgiXn/NjgvpM0RNoWLVVmP0=
github.com/safchain/ethtool v0.3.0/go.mod h1:SA9BwrgyAqNo7M+uaL6IYbxpm5wk3L7Mm6ocLW+CJUs=
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a h1:ObwtHN2VpqE0ZNjr6sGeT00J8uU7JF4cNUdb44/Duis=
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a/go.mod h1:xLnfdiJbSp8rNqYEdIW/6eDO4mVoogml14Bh2hSiFpM=
github.com/samber/lo v1.53.0 h1:t975lj2py4kJPQ6haz1QMgtId2gtmfktACxIXArw3HM=
@@ -190,17 +224,27 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d h1:JcGKBZAL7ePLwOhUdN8qGQZlP5GueEiIZwY7R62pejE=
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d/go.mod h1:XrBNfAFN+pwoWuksbFS9Ccxnopa15zJGgXRFN90l3K4=
github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 h1:Gzfnfk2TWrk8Jj4P4c1a3CtQyMaTVCznlkLZI++hok4=
github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55/go.mod h1:4k4QO+dQ3R5FofL+SanAUZe+/QfeK0+OIuwDIRu2vSg=
github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a h1:SJy1Pu0eH1C29XwJucQo73FrleVK6t4kYz4NVhp34Yw=
github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a/go.mod h1:DFSS3NAGHthKo1gTlmEcSBiZrRJXi28rLNd/1udP1c8=
github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc h1:24heQPtnFR+yfntqhI3oAu9i27nEojcQ4NuBQOo5ZFA=
github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc/go.mod h1:f93CXfllFsO9ZQVq+Zocb1Gp4G5Fz0b0rXHLOzt/Djc=
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 h1:tHNk7XK9GkmKUR6Gh8gVBKXc2MVSZ4G/NnWLtzw4gNA=
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923/go.mod h1:eLL9Nub3yfAho7qB0MzZizFhTU2QkLeoVsWdHtDW264=
github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE=
github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU=
github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0=
github.com/vishvananda/netns v0.0.4 h1:Oeaw1EM2JMxD51g9uhtC0D7erkIjgmj8+JZc26m1YX8=
github.com/vishvananda/netns v0.0.4/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8=
github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
@@ -211,6 +255,8 @@ gitlab.com/yawning/bsaes.git v0.0.0-20190805113838-0a714cd429ec/go.mod h1:BZ1RAo
go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs=
go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8=
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
go4.org/mem v0.0.0-20240501181205-ae6ca9944745 h1:Tl++JLUCe4sxGu8cTpDzRLd3tN7US4hOxG5YpKCzkek=
go4.org/mem v0.0.0-20240501181205-ae6ca9944745/go.mod h1:reUoABIJ9ikfM5sgtSF3Wushcza7+WeD01VB9Lirh3g=
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M=
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
@@ -227,7 +273,10 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
golang.org/x/oauth2 v0.24.0 h1:KTBBxWqUa0ykRPLtV69rRto9TLXcqYkeswu48x/gvNE=
golang.org/x/oauth2 v0.24.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -236,12 +285,14 @@ golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220817070843-5a390386f1f2/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU=
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
@@ -256,3 +307,4 @@ gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
software.sslmate.com/src/go-pkcs12 v0.2.1 h1:tbT1jjaeFOF230tzOIRJ6U5S1jNqpsSyNjzDd58H3J8=
+3 -2
View File
@@ -229,10 +229,11 @@ func updateNTP(c *config.NTP) {
net.JoinHostPort(c.Server, strconv.Itoa(c.Port)),
time.Duration(c.Interval),
c.DialerProxy,
tunnel.Tunnel,
c.WriteToSystem,
)
} else {
ntp.ReCreateNTPService("", 0, "", false)
ntp.ReCreateNTPService("", 0, "", nil, false)
}
}
@@ -279,7 +280,7 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
m.PatchFrom(old.(*dns.ResolverEnhancer))
}
s := dns.NewService(r.Resolver, m)
s := dns.NewService(r, m)
resolver.DefaultResolver = r
resolver.DefaultHostMapper = m
+21
View File
@@ -12,6 +12,8 @@ type Hysteria2Server struct {
Users map[string]string `yaml:"users" json:"users,omitempty"`
Obfs string `yaml:"obfs" json:"obfs,omitempty"`
ObfsPassword string `yaml:"obfs-password" json:"obfs-password,omitempty"`
ObfsMinPacketSize int `yaml:"obfs-min-packet-size" json:"obfs-min-packet-size,omitempty"`
ObfsMaxPacketSize int `yaml:"obfs-max-packet-size" json:"obfs-max-packet-size,omitempty"`
Certificate string `yaml:"certificate" json:"certificate"`
PrivateKey string `yaml:"private-key" json:"private-key"`
ClientAuthType string `yaml:"client-auth-type" json:"client-auth-type,omitempty"`
@@ -28,6 +30,8 @@ type Hysteria2Server struct {
UdpMTU int `yaml:"udp-mtu" json:"udp-mtu,omitempty"`
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
RealmOpts Hysteria2RealmOption `yaml:"realm-opts" json:"realm-opts,omitempty"`
// quic-go special config
InitialStreamReceiveWindow uint64 `yaml:"initial-stream-receive-window" json:"initial-stream-receive-window,omitempty"`
MaxStreamReceiveWindow uint64 `yaml:"max-stream-receive-window" json:"max-stream-receive-window,omitempty"`
@@ -35,6 +39,23 @@ type Hysteria2Server struct {
MaxConnectionReceiveWindow uint64 `yaml:"max-connection-receive-window" json:"max-connection-receive-window,omitempty"`
}
type Hysteria2RealmOption struct {
Enable bool `yaml:"enable" json:"enable,omitempty"`
ServerURL string `yaml:"server-url" json:"server-url,omitempty"`
Token string `yaml:"token" json:"token,omitempty"`
RealmID string `yaml:"realm-id" json:"realm-id,omitempty"`
STUNServers []string `yaml:"stun-servers" json:"stun-servers,omitempty"`
// for ServerURL
SNI string `yaml:"sni" json:"sni,omitempty"`
SkipCertVerify bool `yaml:"skip-cert-verify" json:"skip-cert-verify,omitempty"`
Fingerprint string `yaml:"fingerprint" json:"fingerprint,omitempty"`
Certificate string `yaml:"certificate" json:"certificate,omitempty"`
PrivateKey string `yaml:"private-key" json:"private-key,omitempty"`
ALPN []string `yaml:"alpn" json:"alpn,omitempty"`
Proxy string `yaml:"proxy" json:"proxy,omitempty"`
}
func (h Hysteria2Server) String() string {
b, _ := json.Marshal(h)
return string(b)
+24
View File
@@ -0,0 +1,24 @@
package config
import "encoding/json"
type Hysteria2RealmServer struct {
Enable bool `yaml:"enable" json:"enable"`
Listen string `yaml:"listen" json:"listen"`
Token string `yaml:"token" json:"token"`
MaxRealms int `yaml:"max-realms" json:"max-realms,omitempty"`
MaxRealmsPerIP int `yaml:"max-realms-per-ip" json:"max-realms-per-ip,omitempty"`
TrustedProxyHeader string `yaml:"trusted-proxy-header" json:"trusted-proxy-header,omitempty"`
RealmNamePattern string `yaml:"realm-name-pattern" json:"realm-name-pattern,omitempty"`
Certificate string `yaml:"certificate" json:"certificate"`
PrivateKey string `yaml:"private-key" json:"private-key"`
ClientAuthType string `yaml:"client-auth-type" json:"client-auth-type,omitempty"`
ClientAuthCert string `yaml:"client-auth-cert" json:"client-auth-cert,omitempty"`
EchKey string `yaml:"ech-key" json:"ech-key,omitempty"`
ALPN []string `yaml:"alpn" json:"alpn,omitempty"`
}
func (h Hysteria2RealmServer) String() string {
b, _ := json.Marshal(h)
return string(b)
}
+14 -8
View File
@@ -7,14 +7,20 @@ import (
)
type ShadowsocksServer struct {
Enable bool
Listen string
Password string
Cipher string
Udp bool
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
KcpTun KcpTun `yaml:"kcp-tun" json:"kcp-tun,omitempty"`
Enable bool
Listen string
Password string
Cipher string
Udp bool
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
KcpTun KcpTun `yaml:"kcp-tun" json:"kcp-tun,omitempty"`
SimpleObfs SimpleObfs `yaml:"simple-obfs" json:"simple-obfs,omitempty"`
}
type SimpleObfs struct {
Enable bool
Mode string
}
func (t ShadowsocksServer) String() string {
+368
View File
@@ -0,0 +1,368 @@
package hysteria2_realm
import (
"encoding/json"
"fmt"
"io"
"time"
"github.com/metacubex/chi"
"github.com/metacubex/http"
)
type punchEvent struct {
Addresses []string `json:"addresses"`
Nonce string `json:"nonce"`
Obfs string `json:"obfs"`
}
const maxRequestBodyBytes = 4 << 10
var connectResponseTimeout = 10 * time.Second
func limitBody(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
next.ServeHTTP(w, r)
})
}
func (s *server) routes() http.Handler {
r := chi.NewRouter()
r.Use(limitBody)
r.Post("/v1/{id}", s.register)
r.Delete("/v1/{id}", s.deregister)
r.Get("/v1/{id}/events", s.events)
r.Post("/v1/{id}/heartbeat", s.heartbeat)
r.Post("/v1/{id}/connect", s.connect)
r.Post("/v1/{id}/connects/{nonce}", s.connectResponse)
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusNotFound, errNotFound, "unknown path")
})
r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusMethodNotAllowed, errBadRequest, "method not allowed")
})
return r
}
func (s *server) handle(w http.ResponseWriter, r *http.Request) {
s.routes().ServeHTTP(w, r)
}
func (s *server) checkRealmToken(r *http.Request) bool {
expected := s.realmToken
return expected != "" && bearer(r) == expected
}
func (s *server) requestIP(r *http.Request) string {
return clientIP(r, s.proxyHeader)
}
func (s *server) realmID(w http.ResponseWriter, r *http.Request) (string, bool) {
id := chi.URLParam(r, "id")
if !s.realmIDPattern.MatchString(id) {
writeErr(w, http.StatusBadRequest, errBadRequest, "invalid realm name")
return "", false
}
return id, true
}
func (s *server) register(w http.ResponseWriter, r *http.Request) {
id, ok := s.realmID(w, r)
if !ok {
return
}
remote := s.requestIP(r)
if !s.checkRealmToken(r) {
debugf("register unauthorized realm=%s remote=%s", id, remote)
writeErr(w, http.StatusUnauthorized, errInvalidToken, "invalid realm token")
return
}
var req struct {
Addresses []string `json:"addresses"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, errBadRequest, "invalid json")
return
}
if err := validateAddresses(req.Addresses); err != nil {
writeErr(w, http.StatusBadRequest, errBadRequest, err.Error())
return
}
ip := remote
s.mu.Lock()
if _, exists := s.realms[id]; exists {
s.mu.Unlock()
debugf("register conflict realm=%s remote=%s", id, ip)
writeErr(w, http.StatusConflict, errRealmTaken, "realm already registered")
return
}
if s.maxRealms > 0 && len(s.realms) >= s.maxRealms {
s.mu.Unlock()
debugf("register rejected (global limit) realm=%s remote=%s", id, ip)
writeErr(w, http.StatusTooManyRequests, errRealmLimit, "global realm limit reached")
return
}
if s.maxRealmsPerIP > 0 && s.ipCounts[ip] >= s.maxRealmsPerIP {
s.mu.Unlock()
debugf("register rejected (per-ip limit) realm=%s remote=%s", id, remote)
writeErr(w, http.StatusTooManyRequests, errIPLimit, "per-ip realm limit reached")
return
}
sess := &session{
id: randToken(),
realmID: id,
addresses: req.Addresses,
expires: time.Now().Add(sessionTTL),
events: make(chan sessionEvent, eventsBufferSize),
done: make(chan struct{}),
clientIP: ip,
pending: make(map[string]chan punchResponsePayload),
}
s.realms[id] = sess
s.sessions[sess.id] = sess
s.ipCounts[ip]++
s.mu.Unlock()
debugf("registered realm=%s session=%s addresses=%d remote=%s", id, sess.id, len(req.Addresses), ip)
writeJSON(w, http.StatusOK, map[string]any{
"session_id": sess.id,
"ttl": int(sessionTTL.Seconds()),
})
}
func (s *server) deregister(w http.ResponseWriter, r *http.Request) {
id, ok := s.realmID(w, r)
if !ok {
return
}
remote := s.requestIP(r)
sess := s.getSessionByToken(bearer(r))
if sess == nil || sess.realmID != id {
debugf("deregister unauthorized realm=%s remote=%s", id, remote)
writeErr(w, http.StatusUnauthorized, errInvalidToken, "invalid session token")
return
}
debugf("deregistered realm=%s session=%s remote=%s", id, sess.id, remote)
s.removeSession(sess)
w.WriteHeader(http.StatusNoContent)
}
func (s *server) heartbeat(w http.ResponseWriter, r *http.Request) {
id, ok := s.realmID(w, r)
if !ok {
return
}
remote := s.requestIP(r)
sess := s.getSessionByToken(bearer(r))
if sess == nil || sess.realmID != id {
debugf("heartbeat unauthorized realm=%s remote=%s", id, remote)
writeErr(w, http.StatusUnauthorized, errInvalidToken, "invalid session token")
return
}
var req struct {
Addresses []string `json:"addresses"`
}
if r.Body != nil {
if err := json.NewDecoder(r.Body).Decode(&req); err != nil && err != io.EOF {
writeErr(w, http.StatusBadRequest, errBadRequest, "invalid json")
return
}
}
if req.Addresses != nil {
if err := validateAddresses(req.Addresses); err != nil {
writeErr(w, http.StatusBadRequest, errBadRequest, err.Error())
return
}
}
s.mu.Lock()
if sess.closed {
s.mu.Unlock()
debugf("heartbeat closed realm=%s session=%s remote=%s", id, sess.id, remote)
writeErr(w, http.StatusUnauthorized, errInvalidToken, "invalid session token")
return
}
sess.expires = time.Now().Add(sessionTTL)
if req.Addresses != nil {
sess.addresses = append([]string(nil), req.Addresses...)
}
s.mu.Unlock()
debugf("heartbeat realm=%s session=%s addressesUpdated=%t remote=%s", id, sess.id, req.Addresses != nil, remote)
if !s.sendEvent(sess, sessionEvent{kind: "heartbeat_ack", data: map[string]any{"ttl": int(sessionTTL.Seconds())}}) {
debugf("heartbeat ack dropped realm=%s session=%s remote=%s", id, sess.id, remote)
}
writeJSON(w, http.StatusOK, map[string]any{"ttl": int(sessionTTL.Seconds())})
}
func (s *server) events(w http.ResponseWriter, r *http.Request) {
id, ok := s.realmID(w, r)
if !ok {
return
}
remote := s.requestIP(r)
sess := s.getSessionByToken(bearer(r))
if sess == nil || sess.realmID != id {
debugf("events unauthorized realm=%s remote=%s", id, remote)
writeErr(w, http.StatusUnauthorized, errInvalidToken, "invalid session token")
return
}
debugf("events connected realm=%s session=%s remote=%s", id, sess.id, remote)
flusher, ok := w.(http.Flusher)
if !ok {
writeErr(w, http.StatusInternalServerError, errBadRequest, "streaming not supported")
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(http.StatusOK)
flusher.Flush()
ctx := r.Context()
for {
select {
case <-ctx.Done():
debugf("events disconnected realm=%s session=%s remote=%s", id, sess.id, remote)
return
case <-sess.done:
debugf("events closed realm=%s session=%s remote=%s", id, sess.id, remote)
return
case ev := <-sess.events:
data, _ := json.Marshal(ev.data)
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", ev.kind, data)
flusher.Flush()
}
}
}
func (s *server) connect(w http.ResponseWriter, r *http.Request) {
id, ok := s.realmID(w, r)
if !ok {
return
}
remote := s.requestIP(r)
if !s.checkRealmToken(r) {
debugf("connect unauthorized realm=%s remote=%s", id, remote)
writeErr(w, http.StatusUnauthorized, errInvalidToken, "invalid realm token")
return
}
var req struct {
Addresses []string `json:"addresses"`
Nonce string `json:"nonce"`
Obfs string `json:"obfs"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, errBadRequest, "invalid json")
return
}
if err := validateAddresses(req.Addresses); err != nil {
writeErr(w, http.StatusBadRequest, errBadRequest, err.Error())
return
}
if err := validateHexField("nonce", req.Nonce, nonceHexLength); err != nil {
writeErr(w, http.StatusBadRequest, errBadRequest, err.Error())
return
}
if err := validateHexField("obfs", req.Obfs, obfsHexLength); err != nil {
writeErr(w, http.StatusBadRequest, errBadRequest, err.Error())
return
}
s.mu.Lock()
sess := s.realms[id]
if sess == nil || sess.closed || time.Now().After(sess.expires) {
s.mu.Unlock()
debugf("connect realm not found realm=%s remote=%s", id, remote)
writeErr(w, http.StatusNotFound, errRealmNotFound, "realm not registered")
return
}
serverAddrs := append([]string(nil), sess.addresses...)
s.mu.Unlock()
// Register the pending entry BEFORE pushing the punch event,
// so a fast Hysteria server can never deliver before we're ready.
respCh, ok := s.registerPending(sess, req.Nonce)
if !ok {
debugf("connect rate limited (pending) realm=%s session=%s remote=%s", id, sess.id, remote)
writeErr(w, http.StatusServiceUnavailable, errRateLimited, "too many in-flight connect attempts")
return
}
defer s.cancelPending(sess, req.Nonce)
if s.sendEvent(sess, sessionEvent{kind: "punch", data: punchEvent{Addresses: req.Addresses, Nonce: req.Nonce, Obfs: req.Obfs}}) {
debugf("connect notified realm=%s session=%s clientAddresses=%d serverAddresses=%d remote=%s", id, sess.id, len(req.Addresses), len(serverAddrs), remote)
} else {
debugf("connect rate limited realm=%s session=%s remote=%s", id, sess.id, remote)
writeErr(w, http.StatusServiceUnavailable, errRateLimited, "server event buffer full")
return
}
// Now we wait for the fresh addresses to arrive.
timer := time.NewTimer(connectResponseTimeout)
defer timer.Stop()
select {
case payload, ok := <-respCh:
if !ok {
debugf("connect canceled realm=%s session=%s remote=%s", id, sess.id, remote)
writeErr(w, http.StatusNotFound, errRealmNotFound, "realm not registered")
return
}
if len(payload.addresses) > 0 {
serverAddrs = payload.addresses
debugf("connect fresh addresses realm=%s session=%s addresses=%d remote=%s", id, sess.id, len(serverAddrs), remote)
}
case <-timer.C:
debugf("connect response timed out realm=%s session=%s remote=%s", id, sess.id, remote)
case <-sess.done:
debugf("connect canceled realm=%s session=%s remote=%s", id, sess.id, remote)
writeErr(w, http.StatusNotFound, errRealmNotFound, "realm not registered")
return
case <-r.Context().Done():
// Client gave up
return
}
writeJSON(w, http.StatusOK, map[string]any{
"addresses": serverAddrs,
"nonce": req.Nonce,
"obfs": req.Obfs,
})
}
func (s *server) connectResponse(w http.ResponseWriter, r *http.Request) {
id, ok := s.realmID(w, r)
if !ok {
return
}
remote := s.requestIP(r)
nonce := chi.URLParam(r, "nonce")
if err := validateHexField("nonce", nonce, nonceHexLength); err != nil {
writeErr(w, http.StatusBadRequest, errBadRequest, err.Error())
return
}
sess := s.getSessionByToken(bearer(r))
if sess == nil || sess.realmID != id {
debugf("connect-response unauthorized realm=%s remote=%s", id, remote)
writeErr(w, http.StatusUnauthorized, errInvalidToken, "invalid session token")
return
}
var req struct {
Addresses []string `json:"addresses"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, errBadRequest, "invalid json")
return
}
if err := validateAddresses(req.Addresses); err != nil {
writeErr(w, http.StatusBadRequest, errBadRequest, err.Error())
return
}
if !s.deliverPending(sess, nonce, punchResponsePayload{addresses: req.Addresses}) {
debugf("connect-response no pending realm=%s session=%s nonce=%s remote=%s", id, sess.id, nonce, remote)
writeErr(w, http.StatusNotFound, errAttemptNotFound, "no pending attempt for nonce")
return
}
debugf("connect-response delivered realm=%s session=%s addresses=%d remote=%s", id, sess.id, len(req.Addresses), remote)
w.WriteHeader(http.StatusNoContent)
}
+3
View File
@@ -0,0 +1,3 @@
// Package hysteria2_realm copy and modify from:
// https://github.com/apernet/hysteria-realm-server/tree/1ec22609705b5896df17d4ae4bfb2a1675cdb606
package hysteria2_realm
+147
View File
@@ -0,0 +1,147 @@
package hysteria2_realm
import (
"context"
"fmt"
"net"
"regexp"
"strings"
"time"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/mihomo/component/ech"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/http"
"github.com/metacubex/tls"
)
type Listener struct {
closed bool
config LC.Hysteria2RealmServer
listeners []net.Listener
server *server
cancel func()
}
const (
DefaultMaxRealms = 65536
DefaultMaxRealmsPerIP = 4
DefaultRealmNamePattern = defaultRealmNamePattern
)
func DefaultALPN() []string { return []string{"h2", "http/1.1"} }
func New(config LC.Hysteria2RealmServer, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
if len(additions) == 0 {
additions = []inbound.Addition{
inbound.WithInName("DEFAULT-HYSTERIA2-REALM"),
inbound.WithSpecialRules(""),
}
}
pat, err := regexp.Compile(config.RealmNamePattern)
if err != nil {
return nil, fmt.Errorf("invalid realm name pattern %q: %v", config.RealmNamePattern, err)
}
s := newServer(serverConfig{
realmToken: config.Token,
maxRealms: config.MaxRealms,
maxRealmsPerIP: config.MaxRealmsPerIP,
proxyHeader: config.TrustedProxyHeader,
realmIDPattern: pat,
})
tlsConfig := &tls.Config{Time: ntp.Now}
if config.Certificate != "" && config.PrivateKey != "" {
certLoader, err := ca.NewTLSKeyPairLoader(config.Certificate, config.PrivateKey)
if err != nil {
return nil, err
}
tlsConfig.GetCertificate = func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
return certLoader()
}
if config.EchKey != "" {
err = ech.LoadECHKey(config.EchKey, tlsConfig)
if err != nil {
return nil, err
}
}
}
tlsConfig.ClientAuth = ca.ClientAuthTypeFromString(config.ClientAuthType)
if len(config.ClientAuthCert) > 0 {
if tlsConfig.ClientAuth == tls.NoClientCert {
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
}
if tlsConfig.ClientAuth == tls.VerifyClientCertIfGiven || tlsConfig.ClientAuth == tls.RequireAndVerifyClientCert {
pool, err := ca.LoadCertificates(config.ClientAuthCert)
if err != nil {
return nil, err
}
tlsConfig.ClientCAs = pool
}
sl := &Listener{config: config, server: s}
for _, addr := range strings.Split(config.Listen, ",") {
addr := addr
//TCP
l, err := inbound.Listen("tcp", addr)
if err != nil {
return nil, err
}
if tlsConfig.GetCertificate != nil {
l = tls.NewListener(l, tlsConfig)
}
sl.listeners = append(sl.listeners, l)
srv := &http.Server{
Handler: s.routes(),
ReadHeaderTimeout: 10 * time.Second,
}
go srv.Serve(l)
}
ctx, cancel := context.WithCancel(context.Background())
sl.cancel = cancel
go s.reaper(ctx)
return sl, nil
}
func (l *Listener) Close() error {
l.closed = true
var retErr error
for _, lis := range l.listeners {
err := lis.Close()
if err != nil {
retErr = err
}
}
if l.cancel != nil {
l.cancel()
}
return retErr
}
func (l *Listener) Config() string {
return l.config.String()
}
func (l *Listener) AddrList() (addrList []net.Addr) {
for _, lis := range l.listeners {
addrList = append(addrList, lis.Addr())
}
return
}
func debugf(format string, v ...any) {
log.Debugln("[RealmServer] "+format, v...)
}
+213
View File
@@ -0,0 +1,213 @@
package hysteria2_realm
import (
"context"
"crypto/rand"
"encoding/hex"
"regexp"
"sync"
"time"
)
const (
sessionTTL = time.Minute
reaperInterval = time.Second
defaultRealmNamePattern = `^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`
)
const (
eventsBufferSize = 16
maxPendingAttempts = eventsBufferSize
)
type session struct {
id string
realmID string
addresses []string
expires time.Time
events chan sessionEvent
done chan struct{}
closed bool
clientIP string
pending map[string]chan punchResponsePayload
}
type sessionEvent struct {
kind string
data any
}
type punchResponsePayload struct {
addresses []string
}
type serverConfig struct {
realmToken string
maxRealms int
maxRealmsPerIP int
proxyHeader string
realmIDPattern *regexp.Regexp
}
type server struct {
mu sync.Mutex
realms map[string]*session // realmID -> session
sessions map[string]*session // sessionID -> session
ipCounts map[string]int // clientIP -> realm count
realmToken string
maxRealms int
maxRealmsPerIP int
proxyHeader string
realmIDPattern *regexp.Regexp
}
func newServer(cfg serverConfig) *server {
pat := cfg.realmIDPattern
if pat == nil {
pat = regexp.MustCompile(defaultRealmNamePattern)
}
return &server{
realms: make(map[string]*session),
sessions: make(map[string]*session),
ipCounts: make(map[string]int),
realmToken: cfg.realmToken,
maxRealms: cfg.maxRealms,
maxRealmsPerIP: cfg.maxRealmsPerIP,
proxyHeader: cfg.proxyHeader,
realmIDPattern: pat,
}
}
func randToken() string {
var b [16]byte
_, _ = rand.Read(b[:])
return hex.EncodeToString(b[:])
}
func (s *server) getSessionByToken(token string) *session {
s.mu.Lock()
defer s.mu.Unlock()
sess := s.sessions[token]
if sess == nil || sess.closed || time.Now().After(sess.expires) {
return nil
}
return sess
}
func (s *server) removeSession(sess *session) {
s.mu.Lock()
defer s.mu.Unlock()
s.removeSessionLocked(sess)
}
func (s *server) removeSessionLocked(sess *session) {
if sess.closed {
return
}
sess.closed = true
close(sess.done)
if s.realms[sess.realmID] == sess {
delete(s.realms, sess.realmID)
}
if _, ok := s.sessions[sess.id]; ok {
s.ipCounts[sess.clientIP]--
if s.ipCounts[sess.clientIP] <= 0 {
delete(s.ipCounts, sess.clientIP)
}
}
delete(s.sessions, sess.id)
for nonce, ch := range sess.pending {
close(ch)
delete(sess.pending, nonce)
}
}
func (s *server) removeExpiredSession(sess *session, now time.Time) bool {
s.mu.Lock()
defer s.mu.Unlock()
if sess.closed || !now.After(sess.expires) {
return false
}
s.removeSessionLocked(sess)
return true
}
func (s *server) registerPending(sess *session, nonce string) (chan punchResponsePayload, bool) {
s.mu.Lock()
defer s.mu.Unlock()
if sess.closed || len(sess.pending) >= maxPendingAttempts {
return nil, false
}
if _, exists := sess.pending[nonce]; exists {
// Nonce collision? Silently drop the attempt.
return nil, false
}
ch := make(chan punchResponsePayload, 1)
sess.pending[nonce] = ch
return ch, true
}
func (s *server) deliverPending(sess *session, nonce string, payload punchResponsePayload) bool {
s.mu.Lock()
defer s.mu.Unlock()
if sess.closed {
return false
}
ch, ok := sess.pending[nonce]
if !ok {
return false
}
delete(sess.pending, nonce)
select {
case ch <- payload:
default:
}
return true
}
func (s *server) cancelPending(sess *session, nonce string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(sess.pending, nonce)
}
func (s *server) sendEvent(sess *session, ev sessionEvent) bool {
s.mu.Lock()
defer s.mu.Unlock()
if sess.closed {
return false
}
select {
case sess.events <- ev:
return true
default:
return false
}
}
func (s *server) reaper(ctx context.Context) {
t := time.NewTicker(reaperInterval)
defer t.Stop()
for {
select {
case <-ctx.Done():
break
case <-t.C:
s.mu.Lock()
now := time.Now()
var expired []*session
for _, sess := range s.sessions {
if now.After(sess.expires) {
expired = append(expired, sess)
}
}
s.mu.Unlock()
for _, sess := range expired {
if s.removeExpiredSession(sess, now) {
debugf("session expired realm=%s session=%s", sess.realmID, sess.id)
}
}
}
}
}
+101
View File
@@ -0,0 +1,101 @@
package hysteria2_realm
import (
"encoding/hex"
"encoding/json"
"fmt"
"net"
"net/netip"
"strings"
"github.com/metacubex/http"
)
const (
maxAddresses = 8
nonceHexLength = 32 // 16 bytes
obfsHexLength = 64 // 32 bytes
)
const (
errBadRequest = "bad_request"
errInvalidToken = "invalid_token"
errRealmTaken = "realm_taken"
errRealmLimit = "realm_limit_reached"
errIPLimit = "ip_limit_reached"
errRealmNotFound = "realm_not_found"
errAttemptNotFound = "attempt_not_found"
errRateLimited = "rate_limited"
errNotFound = "not_found"
)
func writeErr(w http.ResponseWriter, status int, code, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": code, "message": msg})
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func clientIP(r *http.Request, header string) string {
if header != "" {
if v := r.Header.Get(header); v != "" {
if i := strings.Index(v, ","); i >= 0 {
v = v[:i]
}
v = strings.TrimSpace(v)
if h, _, err := net.SplitHostPort(v); err == nil {
v = h
}
if addr, err := netip.ParseAddr(v); err == nil {
return addr.Unmap().String()
}
}
}
host := r.RemoteAddr
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
if addr, err := netip.ParseAddr(host); err == nil {
return addr.Unmap().String()
}
return host
}
func bearer(r *http.Request) string {
h := r.Header.Get("Authorization")
if !strings.HasPrefix(h, "Bearer ") {
return ""
}
return strings.TrimPrefix(h, "Bearer ")
}
func validateAddresses(addrs []string) error {
if len(addrs) == 0 {
return fmt.Errorf("at least one address required")
}
if len(addrs) > maxAddresses {
return fmt.Errorf("too many addresses (max %d)", maxAddresses)
}
for _, a := range addrs {
ap, err := netip.ParseAddrPort(a)
if err != nil || !ap.IsValid() {
return fmt.Errorf("invalid address: %s", a)
}
}
return nil
}
func validateHexField(name, value string, length int) error {
if len(value) != length {
return fmt.Errorf("%s must be %d hex characters", name, length)
}
if _, err := hex.DecodeString(value); err != nil {
return fmt.Errorf("%s must be valid hex", name)
}
return nil
}
+1
View File
@@ -42,6 +42,7 @@ func testInboundAnyTLS(t *testing.T, inboundOptions inbound.AnyTLSOption, outbou
outboundOptions.Port = int(addrPort.Port())
outboundOptions.Password = userUUID
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewAnyTLS(outboundOptions)
if !assert.NoError(t, err) {
+3
View File
@@ -354,6 +354,9 @@ func NewHttpTestTunnel() *TestTunnel {
}
<-c.ch
},
HandleUDPPacketFn: func(packet C.UDPPacket, metadata *C.Metadata) {
// TODO
},
CloseFn: ln.Close,
DoSequentialTestFn: sequentialTestFn,
DoConcurrentTestFn: concurrentTestFn,
+41
View File
@@ -14,6 +14,8 @@ type Hysteria2Option struct {
Users map[string]string `inbound:"users,omitempty"`
Obfs string `inbound:"obfs,omitempty"`
ObfsPassword string `inbound:"obfs-password,omitempty"`
ObfsMinPacketSize int `inbound:"obfs-min-packet-size,omitempty"`
ObfsMaxPacketSize int `inbound:"obfs-max-packet-size,omitempty"`
Certificate string `inbound:"certificate"`
PrivateKey string `inbound:"private-key"`
ClientAuthType string `inbound:"client-auth-type,omitempty"`
@@ -30,6 +32,8 @@ type Hysteria2Option struct {
UdpMTU int `inbound:"udp-mtu,omitempty"`
MuxOption MuxOption `inbound:"mux-option,omitempty"`
RealmOpts Hysteria2RealmOption `inbound:"realm-opts,omitempty"`
// quic-go special config
InitialStreamReceiveWindow uint64 `inbound:"initial-stream-receive-window,omitempty"`
MaxStreamReceiveWindow uint64 `inbound:"max-stream-receive-window,omitempty"`
@@ -37,6 +41,40 @@ type Hysteria2Option struct {
MaxConnectionReceiveWindow uint64 `inbound:"max-connection-receive-window,omitempty"`
}
type Hysteria2RealmOption struct {
Enable bool `inbound:"enable,omitempty"`
ServerURL string `inbound:"server-url,omitempty"`
Token string `inbound:"token,omitempty"`
RealmID string `inbound:"realm-id,omitempty"`
STUNServers []string `inbound:"stun-servers,omitempty"`
// for ServerURL
SNI string `inbound:"sni,omitempty"`
SkipCertVerify bool `inbound:"skip-cert-verify,omitempty"`
Fingerprint string `inbound:"fingerprint,omitempty"`
Certificate string `inbound:"certificate,omitempty"`
PrivateKey string `inbound:"private-key,omitempty"`
ALPN []string `inbound:"alpn,omitempty"`
Proxy string `inbound:"proxy,omitempty"`
}
func (o Hysteria2RealmOption) Build() LC.Hysteria2RealmOption {
return LC.Hysteria2RealmOption{
Enable: o.Enable,
ServerURL: o.ServerURL,
Token: o.Token,
RealmID: o.RealmID,
STUNServers: o.STUNServers,
SNI: o.SNI,
SkipCertVerify: o.SkipCertVerify,
Fingerprint: o.Fingerprint,
Certificate: o.Certificate,
PrivateKey: o.PrivateKey,
ALPN: o.ALPN,
Proxy: o.Proxy,
}
}
func (o Hysteria2Option) Equal(config C.InboundConfig) bool {
return optionToString(o) == optionToString(config)
}
@@ -62,6 +100,8 @@ func NewHysteria2(options *Hysteria2Option) (*Hysteria2, error) {
Users: options.Users,
Obfs: options.Obfs,
ObfsPassword: options.ObfsPassword,
ObfsMinPacketSize: options.ObfsMinPacketSize,
ObfsMaxPacketSize: options.ObfsMaxPacketSize,
Certificate: options.Certificate,
PrivateKey: options.PrivateKey,
ClientAuthType: options.ClientAuthType,
@@ -77,6 +117,7 @@ func NewHysteria2(options *Hysteria2Option) (*Hysteria2, error) {
BBRProfile: options.BBRProfile,
UdpMTU: options.UdpMTU,
MuxOption: options.MuxOption.Build(),
RealmOpts: options.RealmOpts.Build(),
// quic-go special config
InitialStreamReceiveWindow: options.InitialStreamReceiveWindow,
MaxStreamReceiveWindow: options.MaxStreamReceiveWindow,
+105
View File
@@ -0,0 +1,105 @@
package inbound
import (
"strings"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/hysteria2_realm"
"github.com/metacubex/mihomo/log"
)
type Hysteria2RealmServerOption struct {
BaseOption
Token string `inbound:"token"`
MaxRealms int `inbound:"max-realms,omitempty"`
MaxRealmsPerIP int `inbound:"max-realms-per-ip,omitempty"`
TrustedProxyHeader string `inbound:"trusted-proxy-header,omitempty"`
RealmNamePattern string `inbound:"realm-name-pattern,omitempty"`
Certificate string `inbound:"certificate,omitempty"`
PrivateKey string `inbound:"private-key,omitempty"`
ClientAuthType string `inbound:"client-auth-type,omitempty"`
ClientAuthCert string `inbound:"client-auth-cert,omitempty"`
EchKey string `inbound:"ech-key,omitempty"`
ALPN []string `inbound:"alpn,omitempty"`
}
func (o Hysteria2RealmServerOption) Equal(config C.InboundConfig) bool {
return optionToString(o) == optionToString(config)
}
func DefaultHysteria2RealmServerOption() *Hysteria2RealmServerOption {
return &Hysteria2RealmServerOption{
MaxRealms: hysteria2_realm.DefaultMaxRealms,
MaxRealmsPerIP: hysteria2_realm.DefaultMaxRealmsPerIP,
RealmNamePattern: hysteria2_realm.DefaultRealmNamePattern,
ALPN: hysteria2_realm.DefaultALPN(),
}
}
type Hysteria2RealmServer struct {
*Base
config *Hysteria2RealmServerOption
l *hysteria2_realm.Listener
ts LC.Hysteria2RealmServer
}
func NewHysteria2RealmServer(options *Hysteria2RealmServerOption) (*Hysteria2RealmServer, error) {
base, err := NewBase(&options.BaseOption)
if err != nil {
return nil, err
}
return &Hysteria2RealmServer{
Base: base,
config: options,
ts: LC.Hysteria2RealmServer{
Enable: true,
Listen: base.RawAddress(),
Token: options.Token,
MaxRealms: options.MaxRealms,
MaxRealmsPerIP: options.MaxRealmsPerIP,
TrustedProxyHeader: options.TrustedProxyHeader,
RealmNamePattern: options.RealmNamePattern,
Certificate: options.Certificate,
PrivateKey: options.PrivateKey,
ClientAuthType: options.ClientAuthType,
ClientAuthCert: options.ClientAuthCert,
EchKey: options.EchKey,
ALPN: options.ALPN,
},
}, nil
}
// Config implements constant.InboundListener
func (t *Hysteria2RealmServer) Config() C.InboundConfig {
return t.config
}
// Address implements constant.InboundListener
func (t *Hysteria2RealmServer) Address() string {
var addrList []string
if t.l != nil {
for _, addr := range t.l.AddrList() {
addrList = append(addrList, addr.String())
}
}
return strings.Join(addrList, ",")
}
// Listen implements constant.InboundListener
func (t *Hysteria2RealmServer) Listen(tunnel C.Tunnel) error {
var err error
t.l, err = hysteria2_realm.New(t.ts, tunnel, t.Additions()...)
if err != nil {
return err
}
log.Infoln("Hysteria2_Realm[%s] proxy listening at: %s", t.Name(), t.Address())
return nil
}
// Close implements constant.InboundListener
func (t *Hysteria2RealmServer) Close() error {
return t.l.Close()
}
var _ C.InboundListener = (*Hysteria2)(nil)
+16
View File
@@ -42,6 +42,7 @@ func testInboundHysteria2(t *testing.T, inboundOptions inbound.Hysteria2Option,
outboundOptions.Port = int(addrPort.Port())
outboundOptions.Password = userUUID
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewHysteria2(outboundOptions)
if !assert.NoError(t, err) {
@@ -113,6 +114,21 @@ func TestInboundHysteria2_Salamander(t *testing.T) {
testInboundHysteria2TLS(t, inboundOptions, outboundOptions)
}
func TestInboundHysteria2_Gecko(t *testing.T) {
inboundOptions := inbound.Hysteria2Option{
Certificate: tlsCertificate,
PrivateKey: tlsPrivateKey,
Obfs: "gecko",
ObfsPassword: userUUID,
}
outboundOptions := outbound.Hysteria2Option{
Fingerprint: tlsFingerprint,
Obfs: "gecko",
ObfsPassword: userUUID,
}
testInboundHysteria2TLS(t, inboundOptions, outboundOptions)
}
func TestInboundHysteria2_Brutal(t *testing.T) {
inboundOptions := inbound.Hysteria2Option{
Certificate: tlsCertificate,
+1
View File
@@ -238,6 +238,7 @@ func testInboundMieruTCP(t *testing.T, handshakeMode string) {
HandshakeMode: handshakeMode,
}
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewMieru(outboundOptions)
if !assert.NoError(t, err) {
return
+28 -14
View File
@@ -11,12 +11,25 @@ import (
type ShadowSocksOption struct {
BaseOption
Password string `inbound:"password"`
Cipher string `inbound:"cipher"`
UDP bool `inbound:"udp,omitempty"`
MuxOption MuxOption `inbound:"mux-option,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
KcpTun KcpTun `inbound:"kcp-tun,omitempty"`
Password string `inbound:"password"`
Cipher string `inbound:"cipher"`
UDP bool `inbound:"udp,omitempty"`
MuxOption MuxOption `inbound:"mux-option,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
KcpTun KcpTun `inbound:"kcp-tun,omitempty"`
SimpleObfs SimpleObfs `inbound:"simple-obfs,omitempty"`
}
type SimpleObfs struct {
Enable bool `inbound:"enable,omitempty"`
Mode string `inbound:"mode,omitempty"`
}
func (o SimpleObfs) Build() LC.SimpleObfs {
return LC.SimpleObfs{
Enable: o.Enable,
Mode: o.Mode,
}
}
func (o ShadowSocksOption) Equal(config C.InboundConfig) bool {
@@ -39,14 +52,15 @@ func NewShadowSocks(options *ShadowSocksOption) (*ShadowSocks, error) {
Base: base,
config: options,
ss: LC.ShadowsocksServer{
Enable: true,
Listen: base.RawAddress(),
Password: options.Password,
Cipher: options.Cipher,
Udp: options.UDP,
MuxOption: options.MuxOption.Build(),
ShadowTLS: options.ShadowTLS.Build(),
KcpTun: options.KcpTun.Build(),
Enable: true,
Listen: base.RawAddress(),
Password: options.Password,
Cipher: options.Cipher,
Udp: options.UDP,
MuxOption: options.MuxOption.Build(),
ShadowTLS: options.ShadowTLS.Build(),
KcpTun: options.KcpTun.Build(),
SimpleObfs: options.SimpleObfs.Build(),
},
}, nil
}
+29
View File
@@ -86,6 +86,7 @@ func testInboundShadowSocks0(t *testing.T, inboundOptions inbound.ShadowSocksOpt
outboundOptions.Port = int(addrPort.Port())
outboundOptions.Password = password
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewShadowSocks(outboundOptions)
if !assert.NoError(t, err) {
@@ -167,6 +168,34 @@ func TestInboundShadowSocks_ShadowTlsv3(t *testing.T) {
testInboundShadowSocksShadowTls(t, inboundOptions, outboundOptions)
}
func TestInboundShadowSocks_SimpleObfs_Http(t *testing.T) {
inboundOptions := inbound.ShadowSocksOption{
SimpleObfs: inbound.SimpleObfs{
Enable: true,
Mode: "http",
},
}
outboundOptions := outbound.ShadowSocksOption{
Plugin: "obfs",
PluginOpts: map[string]any{"mode": "http", "host": realityDest},
}
testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherShortLists, false)
}
func TestInboundShadowSocks_SimpleObfs_Tls(t *testing.T) {
inboundOptions := inbound.ShadowSocksOption{
SimpleObfs: inbound.SimpleObfs{
Enable: true,
Mode: "tls",
},
}
outboundOptions := outbound.ShadowSocksOption{
Plugin: "obfs",
PluginOpts: map[string]any{"mode": "tls", "host": realityDest},
}
testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherShortLists, false)
}
func TestInboundShadowSocks_KcpTun(t *testing.T) {
if runtime.GOOS == "windows" && strings.HasPrefix(runtime.Version(), "go1.20") {
t.Skip("skip kcptun test on windows go1.20")
+90
View File
@@ -0,0 +1,90 @@
package inbound
import (
"fmt"
"strings"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/listener/snell"
"github.com/metacubex/mihomo/log"
)
type SnellOption struct {
BaseOption
Psk string `inbound:"psk"`
Version int `inbound:"version,omitempty"`
UDP bool `inbound:"udp,omitempty"`
ObfsOpts SnellObfsOption `inbound:"obfs-opts,omitempty"`
}
func (o SnellOption) Equal(config C.InboundConfig) bool {
return optionToString(o) == optionToString(config)
}
type SnellObfsOption struct {
Mode string `obfs:"mode,omitempty"`
Host string `obfs:"host,omitempty"`
}
type Snell struct {
*Base
config *SnellOption
l C.MultiAddrListener
snell snell.Config
}
func NewSnell(options *SnellOption) (*Snell, error) {
base, err := NewBase(&options.BaseOption)
if err != nil {
return nil, err
}
if options.Version == 0 {
options.Version = 4
}
if options.Version != 4 && options.Version != 5 {
return nil, fmt.Errorf("snell inbound version %d is not supported", options.Version)
}
return &Snell{
Base: base,
config: options,
snell: snell.Config{
Listen: base.RawAddress(),
Psk: options.Psk,
Version: options.Version,
UDP: options.UDP,
ObfsMode: options.ObfsOpts.Mode,
ObfsHost: options.ObfsOpts.Host,
},
}, nil
}
func (s *Snell) Config() C.InboundConfig {
return s.config
}
func (s *Snell) Address() string {
var addrList []string
if s.l != nil {
for _, addr := range s.l.AddrList() {
addrList = append(addrList, addr.String())
}
}
return strings.Join(addrList, ",")
}
func (s *Snell) Listen(tunnel C.Tunnel) error {
var err error
s.l, err = snell.New(s.snell, tunnel, s.Additions()...)
if err != nil {
return err
}
log.Infoln("Snell[%s] inbound listening at: %s", s.Name(), s.Address())
return nil
}
func (s *Snell) Close() error {
return s.l.Close()
}
var _ C.InboundListener = (*Snell)(nil)
+72
View File
@@ -0,0 +1,72 @@
package inbound_test
import (
"net/netip"
"testing"
"github.com/metacubex/mihomo/adapter/outbound"
"github.com/metacubex/mihomo/listener/inbound"
"github.com/stretchr/testify/assert"
)
func testInboundSnell(t *testing.T, inboundOptions inbound.SnellOption, outboundOptions outbound.SnellOption) {
t.Parallel()
inboundOptions.BaseOption = inbound.BaseOption{
NameStr: "snell_inbound",
Listen: "127.0.0.1",
Port: "0",
}
inboundOptions.Psk = userUUID
in, err := inbound.NewSnell(&inboundOptions)
if !assert.NoError(t, err) {
return
}
tunnel := NewHttpTestTunnel()
defer tunnel.Close()
err = in.Listen(tunnel)
if !assert.NoError(t, err) {
return
}
defer in.Close()
addrPort, err := netip.ParseAddrPort(in.Address())
if !assert.NoError(t, err) {
return
}
outboundOptions.Name = "snell_outbound"
outboundOptions.Server = addrPort.Addr().String()
outboundOptions.Port = int(addrPort.Port())
outboundOptions.Psk = userUUID
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewSnell(outboundOptions)
if !assert.NoError(t, err) {
return
}
defer out.Close()
tunnel.DoTest(t, out)
}
func TestInboundSnell(t *testing.T) {
testCase := []struct {
name string
version int
}{
{"v4", 4},
{"v5", 5},
}
for _, tc := range testCase {
tc := tc
t.Run(tc.name, func(t *testing.T) {
inboundOptions := inbound.SnellOption{Version: tc.version}
outboundOptions := outbound.SnellOption{Version: tc.version}
testInboundSnell(t, inboundOptions, outboundOptions)
})
}
}
+1
View File
@@ -44,6 +44,7 @@ func testInboundSudoku(t *testing.T, inboundOptions inbound.SudokuOption, outbou
outboundOptions.Server = addrPort.Addr().String()
outboundOptions.Port = int(addrPort.Port())
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewSudoku(outboundOptions)
if !assert.NoError(t, err) {
+1
View File
@@ -44,6 +44,7 @@ func testInboundTrojan(t *testing.T, inboundOptions inbound.TrojanOption, outbou
outboundOptions.Port = int(addrPort.Port())
outboundOptions.Password = userUUID
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewTrojan(outboundOptions)
if !assert.NoError(t, err) {
+2 -1
View File
@@ -43,6 +43,7 @@ func testInboundTrustTunnel(t *testing.T, inboundOptions inbound.TrustTunnelOpti
outboundOptions.UserName = "test"
outboundOptions.Password = userUUID
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewTrustTunnel(outboundOptions)
if !assert.NoError(t, err) {
@@ -102,7 +103,7 @@ func testInboundTrustTunnelTLS(t *testing.T, quic bool) {
}
func TestInboundTrustTunnel_H2(t *testing.T) {
testInboundTrustTunnelTLS(t, true)
testInboundTrustTunnelTLS(t, false)
}
func TestInboundTrustTunnel_QUIC(t *testing.T) {
+1
View File
@@ -70,6 +70,7 @@ func testInboundTuic0(t *testing.T, inboundOptions inbound.TuicOption, outboundO
outboundOptions.Server = addrPort.Addr().String()
outboundOptions.Port = int(addrPort.Port())
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewTuic(outboundOptions)
if !assert.NoError(t, err) {
+1
View File
@@ -66,6 +66,7 @@ func (o XHTTPConfig) Build() LC.XHTTPConfig {
XPaddingKey: o.XPaddingKey,
XPaddingHeader: o.XPaddingHeader,
XPaddingPlacement: o.XPaddingPlacement,
XPaddingMethod: o.XPaddingMethod,
UplinkHTTPMethod: o.UplinkHTTPMethod,
SessionPlacement: o.SessionPlacement,
SessionKey: o.SessionKey,
+1
View File
@@ -45,6 +45,7 @@ func testInboundVless(t *testing.T, inboundOptions inbound.VlessOption, outbound
outboundOptions.Port = int(addrPort.Port())
outboundOptions.UUID = userUUID
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewVless(outboundOptions)
if !assert.NoError(t, err) {
+1
View File
@@ -46,6 +46,7 @@ func testInboundVMess(t *testing.T, inboundOptions inbound.VmessOption, outbound
outboundOptions.AlterID = 0
outboundOptions.Cipher = "auto"
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewVmess(outboundOptions)
if !assert.NoError(t, err) {
+14
View File
@@ -79,6 +79,13 @@ func ParseListener(mapping map[string]any) (C.InboundListener, error) {
return nil, err
}
listener, err = IN.NewShadowSocks(shadowsocksOption)
case "snell":
snellOption := &IN.SnellOption{UDP: true}
err = decoder.Decode(mapping, snellOption)
if err != nil {
return nil, err
}
listener, err = IN.NewSnell(snellOption)
case "vmess":
vmessOption := &IN.VmessOption{}
err = decoder.Decode(mapping, vmessOption)
@@ -107,6 +114,13 @@ func ParseListener(mapping map[string]any) (C.InboundListener, error) {
return nil, err
}
listener, err = IN.NewHysteria2(hysteria2Option)
case "hysteria2-realm":
hysteria2RealmOption := IN.DefaultHysteria2RealmServerOption()
err = decoder.Decode(mapping, hysteria2RealmOption)
if err != nil {
return nil, err
}
listener, err = IN.NewHysteria2RealmServer(hysteria2RealmOption)
case "tuic":
tuicOption := &IN.TuicOption{
MaxIdleTime: 15000,
+18 -1
View File
@@ -1,6 +1,7 @@
package shadowsocks
import (
"fmt"
"net"
"strings"
@@ -10,6 +11,7 @@ import (
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/sing"
"github.com/metacubex/mihomo/transport/shadowsocks/core"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
"github.com/metacubex/mihomo/transport/socks5"
)
@@ -20,6 +22,7 @@ type Listener struct {
udpListeners []*UDPListener
pickCipher core.Cipher
handler *sing.ListenerHandler
simpleObfs func(net.Conn) net.Conn
}
var _listener *Listener
@@ -40,9 +43,20 @@ func New(config LC.ShadowsocksServer, tunnel C.Tunnel, additions ...inbound.Addi
return nil, err
}
sl := &Listener{false, config, nil, nil, pickCipher, h}
sl := &Listener{config: config, pickCipher: pickCipher, handler: h}
_listener = sl
if config.SimpleObfs.Enable {
switch config.SimpleObfs.Mode {
case "http":
sl.simpleObfs = obfs.NewHTTPObfsServer
case "tls":
sl.simpleObfs = obfs.NewTLSObfsServer
default:
return nil, fmt.Errorf("unsupported simple obfs mode: %s", config.SimpleObfs.Mode)
}
}
for _, addr := range strings.Split(config.Listen, ",") {
addr := addr
@@ -111,6 +125,9 @@ func (l *Listener) AddrList() (addrList []net.Addr) {
}
func (l *Listener) HandleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
if l.simpleObfs != nil {
conn = l.simpleObfs(conn)
}
conn = l.pickCipher.StreamConn(conn)
conn = N.NewDeadlineConn(conn) // embed ss can't handle readDeadline correctly
+11 -4
View File
@@ -3,18 +3,19 @@ package sing
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"sync"
"time"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/adapter/outbound"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"
"github.com/gofrs/uuid/v5"
mux "github.com/metacubex/sing-mux"
vmess "github.com/metacubex/sing-vmess"
"github.com/metacubex/sing-vmess/packetaddr"
@@ -51,6 +52,7 @@ type BrutalOptions struct {
type ListenerHandler struct {
ListenerConfig
handlerId uuid.UUID
muxService *mux.Service
}
@@ -71,6 +73,7 @@ func ConvertMetadata(metadata *C.Metadata) M.Metadata {
func NewListenerHandler(lc ListenerConfig) (h *ListenerHandler, err error) {
h = &ListenerHandler{ListenerConfig: lc}
h.handlerId = utils.NewUUIDV4()
h.muxService, err = mux.NewService(mux.ServiceOptions{
NewStreamContext: func(ctx context.Context, conn net.Conn) context.Context {
return ctx
@@ -80,8 +83,8 @@ func NewListenerHandler(lc ListenerConfig) (h *ListenerHandler, err error) {
Padding: lc.MuxOption.Padding,
Brutal: mux.BrutalOptions{
Enabled: lc.MuxOption.Brutal.Enabled,
SendBPS: outbound.StringToBps(lc.MuxOption.Brutal.Up),
ReceiveBPS: outbound.StringToBps(lc.MuxOption.Brutal.Down),
SendBPS: utils.StringToBps(lc.MuxOption.Brutal.Up),
ReceiveBPS: utils.StringToBps(lc.MuxOption.Brutal.Down),
},
})
return
@@ -214,9 +217,13 @@ func (h *ListenerHandler) NewPacket(ctx context.Context, key netip.AddrPort, buf
cPacket := &packet{
writer: &writer,
mutex: &mutex,
rAddr: metadata.Source.UDPAddr(), // TODO: using key argument to make a SNAT key
rAddr: metadata.Source.UDPAddr(),
buff: buffer,
}
if h.Type != C.TUN { // make the handler-related SNAT key for not TUN listener
connID := fmt.Sprintf("%s:%s", h.handlerId, key)
cPacket.rAddr = N.NewCustomAddr(h.Type.String(), connID, cPacket.rAddr) // for tunnel's handleUDPConn
}
if conn, ok := common.Cast[localAddr](writer); ok { // tun does not have real inAddr
cPacket.lAddr = conn.LocalAddr()
}
+59 -3
View File
@@ -5,15 +5,17 @@ import (
"errors"
"fmt"
"net"
"net/netip"
"net/url"
"strings"
"time"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/adapter/outbound"
"github.com/metacubex/mihomo/common/sockopt"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/mihomo/component/ech"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/inner"
@@ -26,6 +28,7 @@ import (
"github.com/metacubex/http/httputil"
"github.com/metacubex/quic-go"
"github.com/metacubex/sing-quic/hysteria2"
"github.com/metacubex/sing-quic/hysteria2/realm"
E "github.com/metacubex/sing/common/exceptions"
"github.com/metacubex/tls"
)
@@ -97,6 +100,8 @@ func New(config LC.Hysteria2Server, tunnel C.Tunnel, additions ...inbound.Additi
}
var salamanderPassword string
var geckoPassword string
var geckoMinPacketSize, geckoMaxPacketSize int
if len(config.Obfs) > 0 {
if config.ObfsPassword == "" {
return nil, errors.New("missing obfs password")
@@ -104,6 +109,10 @@ func New(config LC.Hysteria2Server, tunnel C.Tunnel, additions ...inbound.Additi
switch config.Obfs {
case hysteria2.ObfsTypeSalamander:
salamanderPassword = config.ObfsPassword
case hysteria2.ObfsTypeGecko:
geckoPassword = config.ObfsPassword
geckoMinPacketSize = config.ObfsMinPacketSize
geckoMaxPacketSize = config.ObfsMaxPacketSize
default:
return nil, fmt.Errorf("unknown obfs type: %s", config.Obfs)
}
@@ -146,6 +155,49 @@ func New(config LC.Hysteria2Server, tunnel C.Tunnel, additions ...inbound.Additi
return nil, E.New("unknown masquerade URL scheme: ", masqueradeURL.Scheme)
}
}
var realmOptions *realm.Options
if config.RealmOpts.Enable {
httpTLSClientConfig, err := ca.GetTLSConfig(ca.Option{
TLSConfig: &tls.Config{
ServerName: config.RealmOpts.SNI,
InsecureSkipVerify: config.RealmOpts.SkipCertVerify,
NextProtos: config.RealmOpts.ALPN,
},
Fingerprint: config.RealmOpts.Fingerprint,
Certificate: config.RealmOpts.Certificate,
PrivateKey: config.RealmOpts.PrivateKey,
})
if err != nil {
return nil, err
}
realmOptions = &realm.Options{
ServerURL: config.RealmOpts.ServerURL,
Token: config.RealmOpts.Token,
RealmID: config.RealmOpts.RealmID,
STUNServers: config.RealmOpts.STUNServers,
HTTPClient: &http.Client{Transport: &http.Transport{
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
return inner.HandleTcp(tunnel, address, config.RealmOpts.Proxy)
},
TLSClientConfig: httpTLSClientConfig,
// from http.DefaultTransport
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}},
Resolver: func(ctx context.Context, host string, ipv4, ipv6 bool) ([]netip.Addr, error) {
if ipv4 && !ipv6 {
return resolver.LookupIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
} else if ipv6 && !ipv4 {
return resolver.LookupIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
}
return resolver.LookupIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
},
Logger: log.SingLogger,
}
}
if config.UdpMTU == 0 {
// "1200" from quic-go's MaxDatagramSize
@@ -163,9 +215,12 @@ func New(config LC.Hysteria2Server, tunnel C.Tunnel, additions ...inbound.Additi
service, err := hysteria2.NewService[string](hysteria2.ServiceOptions{
Context: context.Background(),
Logger: log.SingLogger,
SendBPS: outbound.StringToBps(config.Up),
ReceiveBPS: outbound.StringToBps(config.Down),
SendBPS: utils.StringToBps(config.Up),
ReceiveBPS: utils.StringToBps(config.Down),
SalamanderPassword: salamanderPassword,
GeckoPassword: geckoPassword,
GeckoMinPacketSize: geckoMinPacketSize,
GeckoMaxPacketSize: geckoMaxPacketSize,
TLSConfig: tlsConfig,
QUICConfig: quicConfig,
IgnoreClientBandwidth: config.IgnoreClientBandwidth,
@@ -173,6 +228,7 @@ func New(config LC.Hysteria2Server, tunnel C.Tunnel, additions ...inbound.Additi
Handler: h,
MasqueradeHandler: masqueradeHandler,
UdpMTU: config.UdpMTU,
RealmOptions: realmOptions,
SetBBRCongestion: func(quicConn *quic.Conn) {
common.SetCongestionController(quicConn, "bbr", config.CWND, config.BBRProfile)
},
+16
View File
@@ -15,6 +15,7 @@ import (
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/mihomo/transport/kcptun"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
shadowsocks "github.com/metacubex/sing-shadowsocks"
"github.com/metacubex/sing-shadowsocks/shadowaead"
@@ -34,6 +35,7 @@ type Listener struct {
udpListeners []net.PacketConn
service shadowsocks.Service
shadowTLS *shadowtls.Service
simpleObfs func(net.Conn) net.Conn
}
var _listener *Listener
@@ -139,6 +141,17 @@ func New(config LC.ShadowsocksServer, tunnel C.Tunnel, additions ...inbound.Addi
}
}
if config.SimpleObfs.Enable {
switch config.SimpleObfs.Mode {
case "http":
sl.simpleObfs = obfs.NewHTTPObfsServer
case "tls":
sl.simpleObfs = obfs.NewTLSObfsServer
default:
return nil, fmt.Errorf("unsupported simple obfs mode: %s", config.SimpleObfs.Mode)
}
}
var kcptunServer *kcptun.Server
if config.KcpTun.Enable {
kcptunServer = kcptun.NewServer(config.KcpTun.Config)
@@ -268,6 +281,9 @@ func (l *Listener) AddrList() (addrList []net.Addr) {
func (l *Listener) HandleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
ctx := sing.WithAdditions(context.TODO(), additions...)
if l.simpleObfs != nil {
conn = l.simpleObfs(conn)
}
err := l.service.NewConnection(ctx, conn, M.Metadata{
Protocol: "shadowsocks",
Source: M.SocksaddrFromNet(conn.RemoteAddr()),
+25 -1
View File
@@ -5,6 +5,7 @@ import (
"errors"
"net"
"strings"
"time"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/component/ca"
@@ -78,9 +79,12 @@ func New(config LC.VlessServer, tunnel C.Tunnel, additions ...inbound.Addition)
}()
}
httpServer := http.Server{
IdleTimeout: 30 * time.Second,
Protocols: new(http.Protocols),
}
tlsConfig := &tls.Config{Time: ntp.Now}
var realityBuilder *reality.Builder
var httpServer http.Server
if config.Certificate != "" && config.PrivateKey != "" {
certLoader, err := ca.NewTLSKeyPairLoader(config.Certificate, config.PrivateKey)
@@ -134,6 +138,7 @@ func New(config LC.VlessServer, tunnel C.Tunnel, additions ...inbound.Addition)
sl.HandleConn(conn, tunnel, additions...)
})
httpServer.Handler = httpMux
httpServer.Protocols.SetHTTP1(true)
tlsConfig.NextProtos = append(tlsConfig.NextProtos, "http/1.1")
}
if config.GrpcServiceName != "" {
@@ -144,6 +149,15 @@ func New(config LC.VlessServer, tunnel C.Tunnel, additions ...inbound.Addition)
},
HttpHandler: httpServer.Handler,
})
httpServer.Protocols.SetHTTP2(true)
// SetUnencryptedHTTP2 to ensure we can work in plain http2 and some tls conn is not *tls.Conn (like *reality.Conn)
//
// Enable HTTP/2 support unconditionally on the server.
//
// Note that this usage is limited to our own net/http fork
// The standard library also needs to mask the tls.Conn type for the conn returned by the Listener.
// see: https://github.com/golang/go/issues/79293#issuecomment-4426393534
httpServer.Protocols.SetUnencryptedHTTP2(true)
tlsConfig.NextProtos = append([]string{"h2"}, tlsConfig.NextProtos...) // h2 must before http/1.1
}
if config.XHTTPConfig.Mode != "" {
@@ -186,6 +200,16 @@ func New(config LC.VlessServer, tunnel C.Tunnel, additions ...inbound.Addition)
if err != nil {
return nil, err
}
httpServer.Protocols.SetHTTP1(true)
httpServer.Protocols.SetHTTP2(true)
// SetUnencryptedHTTP2 to ensure we can work in plain http2 and some tls conn is not *tls.Conn (like *reality.Conn)
//
// Enable HTTP/2 support unconditionally on the server.
//
// Note that this usage is limited to our own net/http fork
// The standard library also needs to mask the tls.Conn type for the conn returned by the Listener.
// see: https://github.com/golang/go/issues/79293#issuecomment-4426393534
httpServer.Protocols.SetUnencryptedHTTP2(true)
if !slices.Contains(tlsConfig.NextProtos, "http/1.1") {
tlsConfig.NextProtos = append([]string{"http/1.1"}, tlsConfig.NextProtos...)
}
+2 -4
View File
@@ -8,6 +8,7 @@ import (
"io"
"net"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/transport/vless"
"github.com/metacubex/mihomo/transport/vless/vision"
@@ -44,10 +45,7 @@ func (s *Service[T]) UpdateUsers(userList []T, userUUIDList []string, userFlowLi
userMap := make(map[[16]byte]T)
userFlowMap := make(map[T]string)
for i, userName := range userList {
userID, err := uuid.FromString(userUUIDList[i])
if err != nil {
userID = uuid.NewV5(uuid.Nil, userUUIDList[i])
}
userID := utils.UUIDMap(userUUIDList[i])
userMap[userID] = userName
userFlowMap[userName] = userFlowList[i]
}
+15 -1
View File
@@ -5,6 +5,7 @@ import (
"errors"
"net"
"strings"
"time"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/component/ca"
@@ -76,9 +77,12 @@ func New(config LC.VmessServer, tunnel C.Tunnel, additions ...inbound.Addition)
sl = &Listener{false, config, nil, service}
httpServer := http.Server{
IdleTimeout: 30 * time.Second,
Protocols: new(http.Protocols),
}
tlsConfig := &tls.Config{Time: ntp.Now}
var realityBuilder *reality.Builder
var httpServer http.Server
if config.Certificate != "" && config.PrivateKey != "" {
certLoader, err := ca.NewTLSKeyPairLoader(config.Certificate, config.PrivateKey)
@@ -132,6 +136,7 @@ func New(config LC.VmessServer, tunnel C.Tunnel, additions ...inbound.Addition)
sl.HandleConn(conn, tunnel, additions...)
})
httpServer.Handler = httpMux
httpServer.Protocols.SetHTTP1(true)
tlsConfig.NextProtos = append(tlsConfig.NextProtos, "http/1.1")
}
if config.GrpcServiceName != "" {
@@ -142,6 +147,15 @@ func New(config LC.VmessServer, tunnel C.Tunnel, additions ...inbound.Addition)
},
HttpHandler: httpServer.Handler,
})
httpServer.Protocols.SetHTTP2(true)
// SetUnencryptedHTTP2 to ensure we can work in plain http2 and some tls conn is not *tls.Conn (like *reality.Conn)
//
// Enable HTTP/2 support unconditionally on the server.
//
// Note that this usage is limited to our own net/http fork
// The standard library also needs to mask the tls.Conn type for the conn returned by the Listener.
// see: https://github.com/golang/go/issues/79293#issuecomment-4426393534
httpServer.Protocols.SetUnencryptedHTTP2(true)
tlsConfig.NextProtos = append([]string{"h2"}, tlsConfig.NextProtos...) // h2 must before http/1.1
}
+377
View File
@@ -0,0 +1,377 @@
package snell
import (
"bufio"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/netip"
"strings"
"sync"
"github.com/metacubex/mihomo/adapter/inbound"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/shadowsocks/shadowaead"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
"github.com/metacubex/mihomo/transport/snell"
)
const maxPacketLength = 0x3fff
type Config struct {
Listen string
Psk string
Version int
UDP bool
ObfsMode string
ObfsHost string
}
func (c Config) String() string {
b, _ := json.Marshal(c)
return string(b)
}
type Listener struct {
closed bool
config Config
listeners []net.Listener
}
func New(config Config, tunnel C.Tunnel, additions ...inbound.Addition) (C.MultiAddrListener, error) {
if config.Version == 0 {
config.Version = snell.Version4
}
if config.Version != snell.Version4 && config.Version != snell.Version5 {
return nil, fmt.Errorf("snell inbound version %d is not supported", config.Version)
}
if config.Psk == "" {
return nil, errors.New("snell inbound requires psk")
}
switch config.ObfsMode {
case "", "http", "tls":
default:
return nil, fmt.Errorf("snell inbound obfs mode error: %s", config.ObfsMode)
}
l := &Listener{config: config}
for _, addr := range strings.Split(config.Listen, ",") {
addr = strings.TrimSpace(addr)
if addr == "" {
continue
}
ln, err := inbound.Listen("tcp", addr)
if err != nil {
_ = l.Close()
return nil, err
}
l.listeners = append(l.listeners, ln)
go func(ln net.Listener) {
for {
conn, err := ln.Accept()
if err != nil {
if l.closed {
return
}
continue
}
go l.HandleConn(conn, tunnel, additions...)
}
}(ln)
}
return l, nil
}
func (l *Listener) Close() error {
l.closed = true
var retErr error
for _, ln := range l.listeners {
if err := ln.Close(); err != nil {
retErr = err
}
}
return retErr
}
func (l *Listener) Config() string {
return l.config.String()
}
func (l *Listener) AddrList() (addrList []net.Addr) {
for _, ln := range l.listeners {
addrList = append(addrList, ln.Addr())
}
return
}
func (l *Listener) HandleConn(rawConn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
defer rawConn.Close()
conn := rawConn
switch l.config.ObfsMode {
case "http":
conn = obfs.NewHTTPObfsServer(conn)
case "tls":
conn = obfs.NewTLSObfsServer(conn)
case "":
default:
return
}
stream := snell.ServerStreamConn(conn, []byte(l.config.Psk), l.config.Version)
for {
reuse, err := l.handleRequest(stream, tunnel, additions...)
if err != nil || !reuse {
return
}
}
}
func (l *Listener) handleRequest(stream *snell.Snell, tunnel C.Tunnel, additions ...inbound.Addition) (bool, error) {
br := bufio.NewReader(stream)
version, err := br.ReadByte()
if err != nil {
return false, err
}
if version != snell.Version {
return false, fmt.Errorf("snell invalid protocol version: %d", version)
}
command, err := br.ReadByte()
if err != nil {
return false, err
}
if command == snell.CommandPing {
_, _ = stream.Write([]byte{snell.CommandPong})
return false, nil
}
clientID, err := readClientID(br)
if err != nil {
return false, err
}
switch command {
case snell.CommandConnect, snell.CommandConnectV2:
return l.handleTCP(stream, br, command == snell.CommandConnectV2, clientID, tunnel, additions...)
case snell.CommandUDP:
if !l.config.UDP {
return false, errors.New("snell UDP is disabled")
}
return false, l.handleUDP(stream, clientID, tunnel, additions...)
default:
return false, fmt.Errorf("snell unknown command: %d", command)
}
}
func readClientID(r *bufio.Reader) (string, error) {
length, err := r.ReadByte()
if err != nil {
return "", err
}
if length == 0 {
return "", nil
}
id := make([]byte, int(length))
if _, err := io.ReadFull(r, id); err != nil {
return "", err
}
return string(id), nil
}
func (l *Listener) handleTCP(stream *snell.Snell, br *bufio.Reader, reuse bool, clientID string, tunnel C.Tunnel, additions ...inbound.Addition) (bool, error) {
hostLen, err := br.ReadByte()
if err != nil {
return false, err
}
if hostLen == 0 {
return false, errors.New("snell connect host is empty")
}
hostBytes := make([]byte, int(hostLen))
if _, err := io.ReadFull(br, hostBytes); err != nil {
return false, err
}
var portBytes [2]byte
if _, err := io.ReadFull(br, portBytes[:]); err != nil {
return false, err
}
metadata := l.metadata(C.TCP, string(hostBytes), binary.BigEndian.Uint16(portBytes[:]), stream, clientID, additions...)
conn := &tcpRequestConn{
Conn: stream,
reader: br,
reuse: reuse,
}
tunnel.HandleTCPConn(conn, metadata)
if !reuse {
return false, nil
}
return true, nil
}
func (l *Listener) handleUDP(stream *snell.Snell, clientID string, tunnel C.Tunnel, additions ...inbound.Addition) error {
if _, err := stream.Write([]byte{snell.CommandTunnel}); err != nil {
return err
}
connID := utils.NewUUIDV4().String()
localAddr := N.NewCustomAddr(C.SNELL.String(), connID, stream.RemoteAddr())
writeMu := &sync.Mutex{}
buf := make([]byte, maxPacketLength)
for {
n, err := stream.Read(buf)
if err != nil {
if errors.Is(err, io.EOF) || errors.Is(err, shadowaead.ErrZeroChunk) {
return nil
}
return err
}
request, err := snell.ParseUDPRequest(buf[:n])
if err != nil {
return err
}
metadata := l.metadata(C.UDP, request.Host, request.Port, stream, clientID, additions...)
if request.Ip.IsValid() {
metadata.Host = ""
metadata.DstIP = request.Ip
}
payload := append([]byte(nil), request.Payload...)
packet := &udpPacket{
data: payload,
conn: stream,
writeMu: writeMu,
localAddr: localAddr,
dstAddr: metadata.UDPAddr(),
}
tunnel.HandleUDPPacket(packet, metadata)
}
}
func (l *Listener) metadata(network C.NetWork, host string, port uint16, conn net.Conn, clientID string, additions ...inbound.Addition) *C.Metadata {
metadata := &C.Metadata{
NetWork: network,
Type: C.SNELL,
DstPort: port,
}
if ip, err := netip.ParseAddr(host); err == nil {
metadata.DstIP = ip.Unmap()
} else {
metadata.Host = host
}
inbound.ApplyAdditions(metadata, inbound.WithSrcAddr(conn.RemoteAddr()), inbound.WithInAddr(conn.LocalAddr()))
inbound.ApplyAdditions(metadata, additions...)
if clientID != "" {
inbound.ApplyAdditions(metadata, inbound.WithInUser(clientID))
}
return metadata
}
func writeCommandError(w io.Writer, code byte, message string) error {
msg := []byte(message)
if len(msg) > 255 {
msg = msg[:255]
}
buf := make([]byte, 0, 3+len(msg))
buf = append(buf, snell.CommandError, code, byte(len(msg)))
buf = append(buf, msg...)
_, err := w.Write(buf)
return err
}
type tcpRequestConn struct {
net.Conn
reader *bufio.Reader
reuse bool
writeMu sync.Mutex
closeOnce sync.Once
replyWritten bool
}
func (c *tcpRequestConn) Read(p []byte) (int, error) {
n, err := c.reader.Read(p)
if errors.Is(err, shadowaead.ErrZeroChunk) {
err = io.EOF
}
return n, err
}
func (c *tcpRequestConn) Write(p []byte) (int, error) {
c.writeMu.Lock()
defer c.writeMu.Unlock()
if !c.replyWritten {
payload := make([]byte, 1+len(p))
payload[0] = snell.CommandTunnel
copy(payload[1:], p)
if _, err := c.Conn.Write(payload); err != nil {
return 0, err
}
c.replyWritten = true
return len(p), nil
}
return c.Conn.Write(p)
}
func (c *tcpRequestConn) CloseWrite() error {
return c.Close()
}
func (c *tcpRequestConn) Close() error {
var err error
c.closeOnce.Do(func() {
c.writeMu.Lock()
defer c.writeMu.Unlock()
if !c.replyWritten {
err = writeCommandError(c.Conn, 0x65, "Remote EOF")
if !c.reuse {
err = errors.Join(err, c.Conn.Close())
}
return
}
if c.reuse {
_, err = c.Conn.Write(nil)
return
}
err = c.Conn.Close()
})
return err
}
type udpPacket struct {
data []byte
conn *snell.Snell
writeMu *sync.Mutex
localAddr net.Addr
dstAddr net.Addr
}
func (p *udpPacket) Data() []byte {
return p.data
}
func (p *udpPacket) WriteBack(b []byte, addr net.Addr) (int, error) {
if addr == nil {
addr = p.dstAddr
}
p.writeMu.Lock()
defer p.writeMu.Unlock()
return snell.WritePacketResponse(p.conn, addr, b)
}
func (p *udpPacket) Drop() {
p.data = nil
}
func (p *udpPacket) LocalAddr() net.Addr {
return p.localAddr
}
var _ C.MultiAddrListener = (*Listener)(nil)
var _ C.UDPPacket = (*udpPacket)(nil)
+15 -18
View File
@@ -13,10 +13,11 @@ import (
)
type packet struct {
pc net.PacketConn
lAddr netip.AddrPort
buf []byte
tunnel C.Tunnel
pc net.PacketConn
lAddr netip.AddrPort
buf []byte
tunnel C.Tunnel
additions []inbound.Addition
}
func (c *packet) Data() []byte {
@@ -25,9 +26,9 @@ func (c *packet) Data() []byte {
// WriteBack opens a new socket binding `addr` to write UDP packet back
func (c *packet) WriteBack(b []byte, addr net.Addr) (n int, err error) {
tc, err := createOrGetLocalConn(addr, c.LocalAddr(), c.tunnel)
rAddr := addr.(*net.UDPAddr).AddrPort() // tunnel's handleUDPToLocal will ensure addr is *net.UDPAddr
tc, err := createOrGetLocalConn(rAddr, c.lAddr, c.tunnel, c.additions...)
if err != nil {
n = 0
return
}
n, err = tc.Write(b)
@@ -36,7 +37,7 @@ func (c *packet) WriteBack(b []byte, addr net.Addr) (n int, err error) {
// LocalAddr returns the source IP/Port of UDP Packet
func (c *packet) LocalAddr() net.Addr {
return &net.UDPAddr{IP: c.lAddr.Addr().AsSlice(), Port: int(c.lAddr.Port()), Zone: c.lAddr.Addr().Zone()}
return net.UDPAddrFromAddrPort(c.lAddr)
}
func (c *packet) Drop() {
@@ -51,7 +52,7 @@ func (c *packet) InAddr() net.Addr {
// this function listen at rAddr and write to lAddr
// for here, rAddr is the ip/port client want to access
// lAddr is the ip/port client opened
func createOrGetLocalConn(rAddr, lAddr net.Addr, tunnel C.Tunnel) (*net.UDPConn, error) {
func createOrGetLocalConn(rAddr, lAddr netip.AddrPort, tunnel C.Tunnel, additions ...inbound.Addition) (*net.UDPConn, error) {
remote := rAddr.String()
local := lAddr.String()
natTable := tunnel.NatTable()
@@ -76,7 +77,7 @@ func createOrGetLocalConn(rAddr, lAddr net.Addr, tunnel C.Tunnel) (*net.UDPConn,
natTable.DeleteLockForLocalConn(local, remote)
cond.Broadcast()
}()
conn, err := listenLocalConn(rAddr, lAddr, tunnel)
conn, err := listenLocalConn(rAddr, lAddr, tunnel, additions...)
if err != nil {
log.Errorln("listenLocalConn failed with error: %s, packet loss (rAddr[%T]=%s lAddr[%T]=%s)", err.Error(), rAddr, remote, lAddr, local)
return nil, err
@@ -90,30 +91,26 @@ func createOrGetLocalConn(rAddr, lAddr net.Addr, tunnel C.Tunnel) (*net.UDPConn,
// this function listen at rAddr
// and send what received to program itself, then send to real remote
func listenLocalConn(rAddr, lAddr net.Addr, tunnel C.Tunnel) (*net.UDPConn, error) {
additions := []inbound.Addition{
inbound.WithInName("DEFAULT-TPROXY"),
inbound.WithSpecialRules(""),
}
lc, err := dialUDP("udp", rAddr.(*net.UDPAddr).AddrPort(), lAddr.(*net.UDPAddr).AddrPort())
func listenLocalConn(rAddr, lAddr netip.AddrPort, tunnel C.Tunnel, additions ...inbound.Addition) (*net.UDPConn, error) {
lc, err := dialUDP("udp", rAddr, lAddr)
if err != nil {
return nil, err
}
go func() {
log.Debugln("TProxy listenLocalConn rAddr=%s lAddr=%s", rAddr.String(), lAddr.String())
log.Debugln("TProxy listenLocalConn rAddr=%s lAddr=%s", rAddr, lAddr)
for {
buf := pool.Get(pool.UDPBufferSize)
br, err := lc.Read(buf)
if err != nil {
if errors.Is(err, net.ErrClosed) {
log.Debugln("TProxy local conn listener exit.. rAddr=%s lAddr=%s", rAddr.String(), lAddr.String())
log.Debugln("TProxy local conn listener exit.. rAddr=%s lAddr=%s", rAddr, lAddr)
pool.Put(buf)
return
}
}
// since following localPackets are pass through this socket which listen rAddr
// I choose current listener as packet's packet conn
handlePacketConn(lc, tunnel, buf[:br], lAddr.(*net.UDPAddr).AddrPort(), rAddr.(*net.UDPAddr).AddrPort(), additions...)
handlePacketConn(lc, tunnel, buf[:br], lAddr, rAddr, additions...)
}
}()
return lc, nil
+8 -5
View File
@@ -8,6 +8,8 @@ import (
"github.com/metacubex/mihomo/common/pool"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/socks5"
"golang.org/x/exp/slices"
)
type UDPListener struct {
@@ -81,7 +83,7 @@ func NewUDP(addr string, tunnel C.Tunnel, additions ...inbound.Addition) (*UDPLi
}
dscp, _ := getDSCP(oob[:oobn])
additions := append(additions, inbound.WithDSCP(dscp)) // don't change outside additions
additions := append(slices.Clip(additions), inbound.WithDSCP(dscp)) // don't change outside additions
if rAddr.Addr().Is4() {
// try to unmap 4in6 address
@@ -97,10 +99,11 @@ func NewUDP(addr string, tunnel C.Tunnel, additions ...inbound.Addition) (*UDPLi
func handlePacketConn(pc net.PacketConn, tunnel C.Tunnel, buf []byte, lAddr, rAddr netip.AddrPort, additions ...inbound.Addition) {
target := socks5.AddrFromStdAddrPort(rAddr)
pkt := &packet{
pc: pc,
lAddr: lAddr,
buf: buf,
tunnel: tunnel,
pc: pc,
lAddr: lAddr,
buf: buf,
tunnel: tunnel,
additions: additions,
}
tunnel.HandleUDPPacket(inbound.NewPacket(target, pkt, C.TPROXY, additions...))
}
+15 -1
View File
@@ -5,6 +5,7 @@ import (
"io"
"net"
"strings"
"time"
"github.com/metacubex/mihomo/adapter/inbound"
N "github.com/metacubex/mihomo/common/net"
@@ -73,9 +74,12 @@ func New(config LC.TrojanServer, tunnel C.Tunnel, additions ...inbound.Addition)
}
sl = &Listener{false, config, nil, keys, pickCipher, h}
httpServer := http.Server{
IdleTimeout: 30 * time.Second,
Protocols: new(http.Protocols),
}
tlsConfig := &tls.Config{Time: ntp.Now}
var realityBuilder *reality.Builder
var httpServer http.Server
if config.Certificate != "" && config.PrivateKey != "" {
certLoader, err := ca.NewTLSKeyPairLoader(config.Certificate, config.PrivateKey)
@@ -129,6 +133,7 @@ func New(config LC.TrojanServer, tunnel C.Tunnel, additions ...inbound.Addition)
sl.HandleConn(conn, tunnel, additions...)
})
httpServer.Handler = httpMux
httpServer.Protocols.SetHTTP1(true)
tlsConfig.NextProtos = append(tlsConfig.NextProtos, "http/1.1")
}
if config.GrpcServiceName != "" {
@@ -139,6 +144,15 @@ func New(config LC.TrojanServer, tunnel C.Tunnel, additions ...inbound.Addition)
},
HttpHandler: httpServer.Handler,
})
httpServer.Protocols.SetHTTP2(true)
// SetUnencryptedHTTP2 to ensure we can work in plain http2 and some tls conn is not *tls.Conn (like *reality.Conn)
//
// Enable HTTP/2 support unconditionally on the server.
//
// Note that this usage is limited to our own net/http fork
// The standard library also needs to mask the tls.Conn type for the conn returned by the Listener.
// see: https://github.com/golang/go/issues/79293#issuecomment-4426393534
httpServer.Protocols.SetUnencryptedHTTP2(true)
tlsConfig.NextProtos = append([]string{"h2"}, tlsConfig.NextProtos...) // h2 must before http/1.1
}
+2 -2
View File
@@ -27,7 +27,7 @@ type Service struct {
syncSystemTime bool
}
func ReCreateNTPService(server string, interval time.Duration, dialerProxy string, syncSystemTime bool) {
func ReCreateNTPService(server string, interval time.Duration, dialerProxy string, tunnel C.Tunnel, syncSystemTime bool) {
globalMu.Lock()
defer globalMu.Unlock()
if globalSrv != nil {
@@ -39,7 +39,7 @@ func ReCreateNTPService(server string, interval time.Duration, dialerProxy strin
ctx, cancel := context.WithCancel(context.Background())
var cDialer C.Dialer = dialer.NewDialer()
if dialerProxy != "" {
cDialer = proxydialer.NewByName(dialerProxy)
cDialer = proxydialer.NewByName(dialerProxy, tunnel)
}
globalSrv = &Service{
server: M.ParseSocksaddr(server),
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more