mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-11-28 06:38:32 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e22035118 | ||
|
|
263d06d176 | ||
|
|
ac6f6d0482 | ||
|
|
388d958a6e | ||
|
|
9e97dc05ef | ||
|
|
2f6ce20f6e | ||
|
|
d2acf450fd | ||
|
|
17bed79b41 | ||
|
|
fd3141919e | ||
|
|
802b0b2449 | ||
|
|
5df45b25e0 | ||
|
|
8a28dce512 | ||
|
|
e933ca82d9 | ||
|
|
3d3af1f44e | ||
|
|
2f11d9635f | ||
|
|
6ea4373eba | ||
|
|
571925d2d2 | ||
|
|
787dbfc5fd | ||
|
|
44c94236b3 | ||
|
|
7af9eeb3f8 | ||
|
|
2ffd96288d | ||
|
|
993d1b6456 | ||
|
|
0003e1432c | ||
|
|
00e6df5018 | ||
|
|
faa58f27fc | ||
|
|
98aa7e63c2 | ||
|
|
8b8eae56d7 | ||
|
|
cc376acc5b | ||
|
|
95946a5fb2 | ||
|
|
aae5812004 | ||
|
|
ffe6e42cfa | ||
|
|
c98e67a1c0 | ||
|
|
c27446a5e8 | ||
|
|
bb2f57b0e4 | ||
|
|
f333359c8a | ||
|
|
028b480ae6 | ||
|
|
3fb93bd79e | ||
|
|
b8b443942e | ||
|
|
35d5d4e44d | ||
|
|
191830a7e7 | ||
|
|
81bea659dc | ||
|
|
8bc7d3e58f | ||
|
|
a1c68a4346 | ||
|
|
7a646e8d10 | ||
|
|
b03aa5d570 | ||
|
|
2f51cb0330 | ||
|
|
163ce6abd4 | ||
|
|
2a8da25d26 | ||
|
|
2d94970cab | ||
|
|
df1c5e54dd | ||
|
|
82621cd1bf | ||
|
|
f5f9e5999f | ||
|
|
1fea551513 | ||
|
|
98aa42edfc | ||
|
|
f5cfb8d26b | ||
|
|
8d5395283d | ||
|
|
8f69ad9ed1 | ||
|
|
c59c99a051 | ||
|
|
b3104a527d | ||
|
|
80e23d5acd | ||
|
|
a84724665e | ||
|
|
e1bdfba0fb | ||
|
|
4f927ca12e | ||
|
|
8a029da50b | ||
|
|
ec664a511f | ||
|
|
d701d1c0e3 | ||
|
|
2cfff83e85 | ||
|
|
3f2b0ba631 | ||
|
|
4d83fb861c | ||
|
|
4814c727f5 | ||
|
|
03253614c5 | ||
|
|
7e83399a3f | ||
|
|
df6a5d3fe3 | ||
|
|
c39b680c52 | ||
|
|
ebc41ea8fd | ||
|
|
dfc888d060 | ||
|
|
2337d70d86 | ||
|
|
0e0265fdd6 | ||
|
|
3d6add33d5 | ||
|
|
2247c0ebb4 | ||
|
|
f425c81a85 | ||
|
|
e4099f0fa1 | ||
|
|
37942ce9d8 | ||
|
|
49858024ef | ||
|
|
7ab4eed838 | ||
|
|
d4c4b2851f | ||
|
|
b0b28ef002 | ||
|
|
e38aa82a23 | ||
|
|
e0a42d4e07 | ||
|
|
83ac220f54 | ||
|
|
6c407f0f93 | ||
|
|
a450080ed1 | ||
|
|
700e25fd2f | ||
|
|
ad91303f99 | ||
|
|
cac48917f1 | ||
|
|
db25932646 | ||
|
|
7abf290477 | ||
|
|
f0ad835df1 | ||
|
|
4ee2251c37 | ||
|
|
fe7f3d61db | ||
|
|
5b013f25cf | ||
|
|
fcbcd10bb0 | ||
|
|
d4b3d236da | ||
|
|
299fd33795 | ||
|
|
b00c985728 | ||
|
|
4387c674ca | ||
|
|
20cb280c9d | ||
|
|
9613f02a05 | ||
|
|
6fb9d9e433 | ||
|
|
0495d295e0 | ||
|
|
1bee5901de | ||
|
|
2fbed16d9a | ||
|
|
80072ebb6f | ||
|
|
d8cb32b856 | ||
|
|
fdafea36ce | ||
|
|
808c0d6251 | ||
|
|
6b076839c6 | ||
|
|
1b2ea14596 | ||
|
|
7b73775591 | ||
|
|
96a6962b3f | ||
|
|
299a63f8f6 | ||
|
|
acc4f626ad | ||
|
|
db63ffbbf6 | ||
|
|
b0ea75bd21 | ||
|
|
fa081fb16c | ||
|
|
0f71808cbe | ||
|
|
885244a9a0 | ||
|
|
ab3746a1d8 | ||
|
|
d9c447a816 | ||
|
|
6791df12e0 | ||
|
|
f5183da5a9 | ||
|
|
61dc7b1038 | ||
|
|
cacd01a3b3 | ||
|
|
d801e6b67b | ||
|
|
8c1b1a3ee2 | ||
|
|
f109b8b095 | ||
|
|
97c526f4cd | ||
|
|
49e5854143 | ||
|
|
8e1787cc35 | ||
|
|
5e8bd85f18 | ||
|
|
e5f05aa7a9 | ||
|
|
9f38a26683 | ||
|
|
979305d2dc | ||
|
|
4730f675d0 | ||
|
|
caacf7a9cd | ||
|
|
8b37e99f35 | ||
|
|
0cb51414ec | ||
|
|
871e6d1454 | ||
|
|
6a2b0dbd52 | ||
|
|
77095546ae | ||
|
|
78e4b844c2 | ||
|
|
4f5ad974ca | ||
|
|
3ef8a0ff7e | ||
|
|
b901d44999 | ||
|
|
3b45444f03 | ||
|
|
428b7ad941 | ||
|
|
5d8e2d2b87 | ||
|
|
5f7e78a193 | ||
|
|
7923f1abd0 | ||
|
|
7f6ac1db35 | ||
|
|
6687ae1332 | ||
|
|
c48f592db3 | ||
|
|
3db64d039f | ||
|
|
0d85eaa34d | ||
|
|
d131991232 | ||
|
|
f3b0581865 | ||
|
|
98b24999d1 | ||
|
|
aa2f313c75 |
No files matched your search
@@ -1,36 +0,0 @@
|
||||
From b8f897a9da7a82ad8584a22284ceac61262fcb7e Mon Sep 17 00:00:00 2001
|
||||
From: Jorropo <jorropo.pgm@gmail.com>
|
||||
Date: Sun, 22 Feb 2026 01:47:45 +0100
|
||||
Subject: [PATCH] runtime: fix value of ENOSYS on mips from 38 to 89
|
||||
|
||||
Fixes #77731
|
||||
|
||||
Change-Id: Iaca444e2d5f9e19fd2de38414b357b41471a668c
|
||||
---
|
||||
|
||||
diff --git a/src/runtime/defs_linux_mips64x.go b/src/runtime/defs_linux_mips64x.go
|
||||
index 7449d2c..4d0f103 100644
|
||||
--- a/src/runtime/defs_linux_mips64x.go
|
||||
+++ b/src/runtime/defs_linux_mips64x.go
|
||||
@@ -12,7 +12,7 @@
|
||||
_EINTR = 0x4
|
||||
_EAGAIN = 0xb
|
||||
_ENOMEM = 0xc
|
||||
- _ENOSYS = 0x26
|
||||
+ _ENOSYS = 0x59
|
||||
|
||||
_PROT_NONE = 0x0
|
||||
_PROT_READ = 0x1
|
||||
diff --git a/src/runtime/defs_linux_mipsx.go b/src/runtime/defs_linux_mipsx.go
|
||||
index 5a446e0..b8da4d0 100644
|
||||
--- a/src/runtime/defs_linux_mipsx.go
|
||||
+++ b/src/runtime/defs_linux_mipsx.go
|
||||
@@ -12,7 +12,7 @@
|
||||
_EINTR = 0x4
|
||||
_EAGAIN = 0xb
|
||||
_ENOMEM = 0xc
|
||||
- _ENOSYS = 0x26
|
||||
+ _ENOSYS = 0x59
|
||||
|
||||
_PROT_NONE = 0x0
|
||||
_PROT_READ = 0x1
|
||||
@@ -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
|
||||
|
||||
@@ -1,265 +0,0 @@
|
||||
From 1a44be4cecdc742ac6cce9825f9ffc19857c99f3 Mon Sep 17 00:00:00 2001
|
||||
From: database64128 <free122448@hotmail.com>
|
||||
Date: Mon, 9 Mar 2026 16:25:16 +0800
|
||||
Subject: [PATCH] [release-branch.go1.26] internal/poll: move rsan to heap on
|
||||
windows
|
||||
|
||||
According to https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsarecvfrom,
|
||||
the memory pointed to by lpFromlen must remain available during the
|
||||
overlapped I/O, and therefore cannot be allocated on the stack.
|
||||
|
||||
CL 685417 moved the rsan field out of the operation struct and placed
|
||||
it on stack, which violates the above requirement and causes stack
|
||||
corruption.
|
||||
|
||||
Unfortunately, it is no longer possible to cleanly revert CL 685417.
|
||||
Instead of attempting to revert it, this CL bundles rsan together
|
||||
with rsa in the same sync.Pool. The new wsaRsa struct is still in the
|
||||
same size class, so no additional overhead is introduced by this
|
||||
change.
|
||||
|
||||
Fixes #78041.
|
||||
|
||||
Change-Id: I5ffbccb332515116ddc03fb7c40ffc9293cad2ab
|
||||
Reviewed-on: https://go-review.googlesource.com/c/go/+/753040
|
||||
Reviewed-by: Quim Muntal <quimmuntal@gmail.com>
|
||||
Reviewed-by: Cherry Mui <cherryyz@google.com>
|
||||
Commit-Queue: Cherry Mui <cherryyz@google.com>
|
||||
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
|
||||
Reviewed-by: Damien Neil <dneil@google.com>
|
||||
Reviewed-on: https://go-review.googlesource.com/c/go/+/753480
|
||||
Reviewed-by: Mark Freeman <markfreeman@google.com>
|
||||
---
|
||||
src/internal/poll/fd_windows.go | 94 +++++++++++++++++++++------------
|
||||
1 file changed, 59 insertions(+), 35 deletions(-)
|
||||
|
||||
diff --git a/src/internal/poll/fd_windows.go b/src/internal/poll/fd_windows.go
|
||||
index 2ba967f990982f..26319548e3c310 100644
|
||||
--- a/src/internal/poll/fd_windows.go
|
||||
+++ b/src/internal/poll/fd_windows.go
|
||||
@@ -149,7 +149,7 @@ var wsaMsgPool = sync.Pool{
|
||||
|
||||
// newWSAMsg creates a new WSAMsg with the provided parameters.
|
||||
// Use [freeWSAMsg] to free it.
|
||||
-func newWSAMsg(p []byte, oob []byte, flags int, unconnected bool) *windows.WSAMsg {
|
||||
+func newWSAMsg(p []byte, oob []byte, flags int, rsa *wsaRsa) *windows.WSAMsg {
|
||||
// The returned object can't be allocated in the stack because it is accessed asynchronously
|
||||
// by Windows in between several system calls. If the stack frame is moved while that happens,
|
||||
// then Windows may access invalid memory.
|
||||
@@ -166,34 +166,46 @@ func newWSAMsg(p []byte, oob []byte, flags int, unconnected bool) *windows.WSAMs
|
||||
}
|
||||
}
|
||||
msg.Flags = uint32(flags)
|
||||
- if unconnected {
|
||||
- msg.Name = wsaRsaPool.Get().(*syscall.RawSockaddrAny)
|
||||
- msg.Namelen = int32(unsafe.Sizeof(syscall.RawSockaddrAny{}))
|
||||
+ if rsa != nil {
|
||||
+ msg.Name = &rsa.name
|
||||
+ msg.Namelen = rsa.namelen
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
func freeWSAMsg(msg *windows.WSAMsg) {
|
||||
// Clear pointers to buffers so they can be released by garbage collector.
|
||||
+ msg.Name = nil
|
||||
+ msg.Namelen = 0
|
||||
msg.Buffers.Len = 0
|
||||
msg.Buffers.Buf = nil
|
||||
msg.Control.Len = 0
|
||||
msg.Control.Buf = nil
|
||||
- if msg.Name != nil {
|
||||
- *msg.Name = syscall.RawSockaddrAny{}
|
||||
- wsaRsaPool.Put(msg.Name)
|
||||
- msg.Name = nil
|
||||
- msg.Namelen = 0
|
||||
- }
|
||||
wsaMsgPool.Put(msg)
|
||||
}
|
||||
|
||||
+// wsaRsa bundles a [syscall.RawSockaddrAny] with its length for efficient caching.
|
||||
+//
|
||||
+// When used by WSARecvFrom, wsaRsa must be on the heap. See
|
||||
+// https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsarecvfrom.
|
||||
+type wsaRsa struct {
|
||||
+ name syscall.RawSockaddrAny
|
||||
+ namelen int32
|
||||
+}
|
||||
+
|
||||
var wsaRsaPool = sync.Pool{
|
||||
New: func() any {
|
||||
- return new(syscall.RawSockaddrAny)
|
||||
+ return new(wsaRsa)
|
||||
},
|
||||
}
|
||||
|
||||
+func newWSARsa() *wsaRsa {
|
||||
+ rsa := wsaRsaPool.Get().(*wsaRsa)
|
||||
+ rsa.name = syscall.RawSockaddrAny{}
|
||||
+ rsa.namelen = int32(unsafe.Sizeof(syscall.RawSockaddrAny{}))
|
||||
+ return rsa
|
||||
+}
|
||||
+
|
||||
var operationPool = sync.Pool{
|
||||
New: func() any {
|
||||
return new(operation)
|
||||
@@ -739,19 +751,18 @@ func (fd *FD) ReadFrom(buf []byte) (int, syscall.Sockaddr, error) {
|
||||
|
||||
fd.pin('r', &buf[0])
|
||||
|
||||
- rsa := wsaRsaPool.Get().(*syscall.RawSockaddrAny)
|
||||
+ rsa := newWSARsa()
|
||||
defer wsaRsaPool.Put(rsa)
|
||||
n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) {
|
||||
- rsan := int32(unsafe.Sizeof(*rsa))
|
||||
var flags uint32
|
||||
- err = syscall.WSARecvFrom(fd.Sysfd, newWsaBuf(buf), 1, &qty, &flags, rsa, &rsan, &o.o, nil)
|
||||
+ err = syscall.WSARecvFrom(fd.Sysfd, newWsaBuf(buf), 1, &qty, &flags, &rsa.name, &rsa.namelen, &o.o, nil)
|
||||
return qty, err
|
||||
})
|
||||
err = fd.eofError(n, err)
|
||||
if err != nil {
|
||||
return n, nil, err
|
||||
}
|
||||
- sa, _ := rsa.Sockaddr()
|
||||
+ sa, _ := rsa.name.Sockaddr()
|
||||
return n, sa, nil
|
||||
}
|
||||
|
||||
@@ -770,19 +781,18 @@ func (fd *FD) ReadFromInet4(buf []byte, sa4 *syscall.SockaddrInet4) (int, error)
|
||||
|
||||
fd.pin('r', &buf[0])
|
||||
|
||||
- rsa := wsaRsaPool.Get().(*syscall.RawSockaddrAny)
|
||||
+ rsa := newWSARsa()
|
||||
defer wsaRsaPool.Put(rsa)
|
||||
n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) {
|
||||
- rsan := int32(unsafe.Sizeof(*rsa))
|
||||
var flags uint32
|
||||
- err = syscall.WSARecvFrom(fd.Sysfd, newWsaBuf(buf), 1, &qty, &flags, rsa, &rsan, &o.o, nil)
|
||||
+ err = syscall.WSARecvFrom(fd.Sysfd, newWsaBuf(buf), 1, &qty, &flags, &rsa.name, &rsa.namelen, &o.o, nil)
|
||||
return qty, err
|
||||
})
|
||||
err = fd.eofError(n, err)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
- rawToSockaddrInet4(rsa, sa4)
|
||||
+ rawToSockaddrInet4(&rsa.name, sa4)
|
||||
return n, err
|
||||
}
|
||||
|
||||
@@ -801,19 +811,18 @@ func (fd *FD) ReadFromInet6(buf []byte, sa6 *syscall.SockaddrInet6) (int, error)
|
||||
|
||||
fd.pin('r', &buf[0])
|
||||
|
||||
- rsa := wsaRsaPool.Get().(*syscall.RawSockaddrAny)
|
||||
+ rsa := newWSARsa()
|
||||
defer wsaRsaPool.Put(rsa)
|
||||
n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) {
|
||||
- rsan := int32(unsafe.Sizeof(*rsa))
|
||||
var flags uint32
|
||||
- err = syscall.WSARecvFrom(fd.Sysfd, newWsaBuf(buf), 1, &qty, &flags, rsa, &rsan, &o.o, nil)
|
||||
+ err = syscall.WSARecvFrom(fd.Sysfd, newWsaBuf(buf), 1, &qty, &flags, &rsa.name, &rsa.namelen, &o.o, nil)
|
||||
return qty, err
|
||||
})
|
||||
err = fd.eofError(n, err)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
- rawToSockaddrInet6(rsa, sa6)
|
||||
+ rawToSockaddrInet6(&rsa.name, sa6)
|
||||
return n, err
|
||||
}
|
||||
|
||||
@@ -1373,7 +1382,9 @@ func (fd *FD) ReadMsg(p []byte, oob []byte, flags int) (int, int, int, syscall.S
|
||||
p = p[:maxRW]
|
||||
}
|
||||
|
||||
- msg := newWSAMsg(p, oob, flags, true)
|
||||
+ rsa := newWSARsa()
|
||||
+ defer wsaRsaPool.Put(rsa)
|
||||
+ msg := newWSAMsg(p, oob, flags, rsa)
|
||||
defer freeWSAMsg(msg)
|
||||
n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) {
|
||||
err = windows.WSARecvMsg(fd.Sysfd, msg, &qty, &o.o, nil)
|
||||
@@ -1398,7 +1409,9 @@ func (fd *FD) ReadMsgInet4(p []byte, oob []byte, flags int, sa4 *syscall.Sockadd
|
||||
p = p[:maxRW]
|
||||
}
|
||||
|
||||
- msg := newWSAMsg(p, oob, flags, true)
|
||||
+ rsa := newWSARsa()
|
||||
+ defer wsaRsaPool.Put(rsa)
|
||||
+ msg := newWSAMsg(p, oob, flags, rsa)
|
||||
defer freeWSAMsg(msg)
|
||||
n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) {
|
||||
err = windows.WSARecvMsg(fd.Sysfd, msg, &qty, &o.o, nil)
|
||||
@@ -1422,7 +1435,9 @@ func (fd *FD) ReadMsgInet6(p []byte, oob []byte, flags int, sa6 *syscall.Sockadd
|
||||
p = p[:maxRW]
|
||||
}
|
||||
|
||||
- msg := newWSAMsg(p, oob, flags, true)
|
||||
+ rsa := newWSARsa()
|
||||
+ defer wsaRsaPool.Put(rsa)
|
||||
+ msg := newWSAMsg(p, oob, flags, rsa)
|
||||
defer freeWSAMsg(msg)
|
||||
n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) {
|
||||
err = windows.WSARecvMsg(fd.Sysfd, msg, &qty, &o.o, nil)
|
||||
@@ -1446,15 +1461,18 @@ func (fd *FD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (int, int, err
|
||||
}
|
||||
defer fd.writeUnlock()
|
||||
|
||||
- msg := newWSAMsg(p, oob, 0, sa != nil)
|
||||
- defer freeWSAMsg(msg)
|
||||
+ var rsa *wsaRsa
|
||||
if sa != nil {
|
||||
+ rsa = newWSARsa()
|
||||
+ defer wsaRsaPool.Put(rsa)
|
||||
var err error
|
||||
- msg.Namelen, err = sockaddrToRaw(msg.Name, sa)
|
||||
+ rsa.namelen, err = sockaddrToRaw(&rsa.name, sa)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
}
|
||||
+ msg := newWSAMsg(p, oob, 0, rsa)
|
||||
+ defer freeWSAMsg(msg)
|
||||
n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) {
|
||||
err = windows.WSASendMsg(fd.Sysfd, msg, 0, nil, &o.o, nil)
|
||||
return qty, err
|
||||
@@ -1473,11 +1491,14 @@ func (fd *FD) WriteMsgInet4(p []byte, oob []byte, sa *syscall.SockaddrInet4) (in
|
||||
}
|
||||
defer fd.writeUnlock()
|
||||
|
||||
- msg := newWSAMsg(p, oob, 0, sa != nil)
|
||||
- defer freeWSAMsg(msg)
|
||||
+ var rsa *wsaRsa
|
||||
if sa != nil {
|
||||
- msg.Namelen = sockaddrInet4ToRaw(msg.Name, sa)
|
||||
+ rsa = newWSARsa()
|
||||
+ defer wsaRsaPool.Put(rsa)
|
||||
+ rsa.namelen = sockaddrInet4ToRaw(&rsa.name, sa)
|
||||
}
|
||||
+ msg := newWSAMsg(p, oob, 0, rsa)
|
||||
+ defer freeWSAMsg(msg)
|
||||
n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) {
|
||||
err = windows.WSASendMsg(fd.Sysfd, msg, 0, nil, &o.o, nil)
|
||||
return qty, err
|
||||
@@ -1496,11 +1517,14 @@ func (fd *FD) WriteMsgInet6(p []byte, oob []byte, sa *syscall.SockaddrInet6) (in
|
||||
}
|
||||
defer fd.writeUnlock()
|
||||
|
||||
- msg := newWSAMsg(p, oob, 0, sa != nil)
|
||||
- defer freeWSAMsg(msg)
|
||||
+ var rsa *wsaRsa
|
||||
if sa != nil {
|
||||
- msg.Namelen = sockaddrInet6ToRaw(msg.Name, sa)
|
||||
+ rsa = newWSARsa()
|
||||
+ defer wsaRsaPool.Put(rsa)
|
||||
+ rsa.namelen = sockaddrInet6ToRaw(&rsa.name, sa)
|
||||
}
|
||||
+ msg := newWSAMsg(p, oob, 0, rsa)
|
||||
+ defer freeWSAMsg(msg)
|
||||
n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) {
|
||||
err = windows.WSASendMsg(fd.Sysfd, msg, 0, nil, &o.o, nil)
|
||||
return qty, err
|
||||
+20
-24
@@ -32,7 +32,7 @@ jobs:
|
||||
- { goos: linux, goarch: '386', go386: sse2, output: '386', debian: i386, rpm: i386}
|
||||
- { goos: linux, goarch: '386', go386: softfloat, output: '386-softfloat' }
|
||||
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-compatible} # old style file name will be removed in next released
|
||||
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64, debian: amd64, rpm: x86_64, pacman: x86_64}
|
||||
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64, debian: amd64, rpm: x86_64, pacman: x86_64, tarball: tarball}
|
||||
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-v1, debian: amd64, rpm: x86_64, pacman: x86_64, test: test }
|
||||
- { goos: linux, goarch: amd64, goamd64: v2, output: amd64-v2, debian: amd64, rpm: x86_64, pacman: x86_64}
|
||||
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64-v3, debian: amd64, rpm: x86_64, pacman: x86_64}
|
||||
@@ -186,27 +186,6 @@ jobs:
|
||||
- name: Verify Go env
|
||||
run: go env
|
||||
|
||||
# TODO: remove after issue77731 fixed, see: https://github.com/golang/go/issues/77731
|
||||
- name: Fix issue77731 for Golang1.26
|
||||
if: ${{ matrix.jobs.goversion == '' }}
|
||||
run: |
|
||||
cd $(go env GOROOT)
|
||||
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/issue77731.patch
|
||||
|
||||
# TODO: remove after issue77975 fixed, see: https://github.com/golang/go/issues/77975
|
||||
- name: Fix issue77975 for Golang1.26
|
||||
if: ${{ matrix.jobs.goversion == '' }}
|
||||
run: |
|
||||
cd $(go env GOROOT)
|
||||
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/issue77975.patch
|
||||
|
||||
# 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)"
|
||||
@@ -312,6 +291,21 @@ jobs:
|
||||
--architecture ${{ matrix.jobs.pacman }} \
|
||||
mihomo=/usr/bin/mihomo
|
||||
|
||||
- name: Pack Golang Toolchain
|
||||
if: ${{ matrix.jobs.goversion == '' && matrix.jobs.tarball == 'tarball' }}
|
||||
run: |
|
||||
mkdir -p $GITHUB_WORKSPACE/toolchain/go
|
||||
cp -r $(go env GOROOT)/* $GITHUB_WORKSPACE/toolchain/go/
|
||||
cd $GITHUB_WORKSPACE/toolchain/
|
||||
tar -czf $GITHUB_WORKSPACE/toolchain.tar.gz .
|
||||
rm -rf $GITHUB_WORKSPACE/toolchain
|
||||
|
||||
- name: Pack GoMod Vendor
|
||||
if: ${{ matrix.jobs.goversion == '' && matrix.jobs.tarball == 'tarball' }}
|
||||
run: |
|
||||
go mod vendor
|
||||
tar -czf $GITHUB_WORKSPACE/vendor.tar.gz vendor
|
||||
|
||||
- name: Save version
|
||||
run: |
|
||||
echo ${VERSION} > version.txt
|
||||
@@ -327,6 +321,8 @@ jobs:
|
||||
mihomo*.rpm
|
||||
mihomo*.pkg.tar.zst
|
||||
mihomo*.zip
|
||||
toolchain.tar.gz
|
||||
vendor.tar.gz
|
||||
version.txt
|
||||
checksums.txt
|
||||
|
||||
@@ -378,7 +374,7 @@ jobs:
|
||||
EOF
|
||||
|
||||
- name: Upload Prerelease
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
if: ${{ success() }}
|
||||
with:
|
||||
tag_name: Prerelease-${{ github.ref_name }}
|
||||
@@ -440,7 +436,7 @@ jobs:
|
||||
working-directory: bin
|
||||
|
||||
- name: Upload Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
if: ${{ success() }}
|
||||
with:
|
||||
tag_name: ${{ github.event.inputs.version }}
|
||||
|
||||
@@ -22,7 +22,8 @@ jobs:
|
||||
- 'windows-latest' # amd64 windows
|
||||
- 'macos-latest' # arm64 macos
|
||||
- 'ubuntu-24.04-arm' # arm64 linux
|
||||
- 'macos-15-intel' # amd64 macos
|
||||
- 'windows-11-arm' # arm64 windows
|
||||
- 'macos-26-intel' # amd64 macos
|
||||
go-version:
|
||||
- '1.26'
|
||||
- '1.25'
|
||||
@@ -56,13 +57,6 @@ jobs:
|
||||
- name: Verify Go env
|
||||
run: go env
|
||||
|
||||
# TODO: remove after issue77975 fixed, see: https://github.com/golang/go/issues/77975
|
||||
- name: Fix issue77975 for Golang1.26
|
||||
if: ${{ matrix.go-version == '1.26' }}
|
||||
run: |
|
||||
cd $(go env GOROOT)
|
||||
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/issue77975.patch
|
||||
|
||||
- name: Remove inbound test for macOS
|
||||
if: ${{ runner.os == 'macOS' }}
|
||||
run: |
|
||||
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
- uses: actions/create-github-app-token@v3
|
||||
id: generate-token
|
||||
with:
|
||||
app-id: ${{ secrets.MAINTAINER_APPID }}
|
||||
client-id: ${{ secrets.MAINTAINER_APPID }}
|
||||
private-key: ${{ secrets.MAINTAINER_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
|
||||
+12
-12
@@ -86,18 +86,18 @@ func (t *AnyTLS) Close() error {
|
||||
func NewAnyTLS(option AnyTLSOption) (*AnyTLS, error) {
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
outbound := &AnyTLS{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.AnyTLS,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.AnyTLS,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
|
||||
+39
-33
@@ -16,6 +16,8 @@ import (
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
)
|
||||
|
||||
type ProxyAdapter interface {
|
||||
@@ -37,7 +39,38 @@ type Base struct {
|
||||
rmark int
|
||||
prefer C.DNSPrefer
|
||||
dialer C.Dialer
|
||||
id string
|
||||
id uuid.UUID
|
||||
}
|
||||
|
||||
type BaseOption struct {
|
||||
Name string
|
||||
Addr string
|
||||
Type C.AdapterType
|
||||
ProviderName string
|
||||
UDP bool
|
||||
XUDP bool
|
||||
TFO bool
|
||||
MPTCP bool
|
||||
Interface string
|
||||
RoutingMark int
|
||||
Prefer C.DNSPrefer
|
||||
}
|
||||
|
||||
func NewBase(opt BaseOption) *Base {
|
||||
return &Base{
|
||||
name: opt.Name,
|
||||
addr: opt.Addr,
|
||||
tp: opt.Type,
|
||||
pdName: opt.ProviderName,
|
||||
udp: opt.UDP,
|
||||
xudp: opt.XUDP,
|
||||
tfo: opt.TFO,
|
||||
mpTcp: opt.MPTCP,
|
||||
iface: opt.Interface,
|
||||
rmark: opt.RoutingMark,
|
||||
prefer: opt.Prefer,
|
||||
id: utils.NewUUIDV4(),
|
||||
}
|
||||
}
|
||||
|
||||
// Name implements C.ProxyAdapter
|
||||
@@ -47,11 +80,7 @@ func (b *Base) Name() string {
|
||||
|
||||
// Id implements C.ProxyAdapter
|
||||
func (b *Base) Id() string {
|
||||
if b.id == "" {
|
||||
b.id = utils.NewUUIDV6().String()
|
||||
}
|
||||
|
||||
return b.id
|
||||
return b.id.String()
|
||||
}
|
||||
|
||||
// Type implements C.ProxyAdapter
|
||||
@@ -148,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)
|
||||
}
|
||||
@@ -173,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:"-"`
|
||||
}
|
||||
|
||||
@@ -188,32 +218,8 @@ func (b *BasicOption) NewDialer(opts []dialer.Option) C.Dialer {
|
||||
return cDialer
|
||||
}
|
||||
|
||||
type BaseOption struct {
|
||||
Name string
|
||||
Addr string
|
||||
Type C.AdapterType
|
||||
UDP bool
|
||||
XUDP bool
|
||||
TFO bool
|
||||
MPTCP bool
|
||||
Interface string
|
||||
RoutingMark int
|
||||
Prefer C.DNSPrefer
|
||||
}
|
||||
|
||||
func NewBase(opt BaseOption) *Base {
|
||||
return &Base{
|
||||
name: opt.Name,
|
||||
addr: opt.Addr,
|
||||
tp: opt.Type,
|
||||
udp: opt.UDP,
|
||||
xudp: opt.XUDP,
|
||||
tfo: opt.TFO,
|
||||
mpTcp: opt.MPTCP,
|
||||
iface: opt.Interface,
|
||||
rmark: opt.RoutingMark,
|
||||
prefer: opt.Prefer,
|
||||
}
|
||||
func (b *BasicOption) NewTunnel() C.Tunnel {
|
||||
return b.TunnelForAPI
|
||||
}
|
||||
|
||||
type conn struct {
|
||||
|
||||
+24
-24
@@ -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)
|
||||
}
|
||||
@@ -66,41 +66,41 @@ func (d *Direct) IsL3Protocol(metadata *C.Metadata) bool {
|
||||
|
||||
func NewDirectWithOption(option DirectOption) *Direct {
|
||||
return &Direct{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
tp: C.Direct,
|
||||
pdName: option.ProviderName,
|
||||
udp: true,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.Direct,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
loopBack: loopback.NewDetector(),
|
||||
}
|
||||
}
|
||||
|
||||
func NewDirect() *Direct {
|
||||
return &Direct{
|
||||
Base: &Base{
|
||||
name: "DIRECT",
|
||||
tp: C.Direct,
|
||||
udp: true,
|
||||
prefer: C.DualStack,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: "DIRECT",
|
||||
Type: C.Direct,
|
||||
UDP: true,
|
||||
Prefer: C.DualStack,
|
||||
}),
|
||||
loopBack: loopback.NewDetector(),
|
||||
}
|
||||
}
|
||||
|
||||
func NewCompatible() *Direct {
|
||||
return &Direct{
|
||||
Base: &Base{
|
||||
name: "COMPATIBLE",
|
||||
tp: C.Compatible,
|
||||
udp: true,
|
||||
prefer: C.DualStack,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: "COMPATIBLE",
|
||||
Type: C.Compatible,
|
||||
UDP: true,
|
||||
Prefer: C.DualStack,
|
||||
}),
|
||||
loopBack: loopback.NewDetector(),
|
||||
}
|
||||
}
|
||||
+11
-11
@@ -155,16 +155,16 @@ func (*dnsPacketConn) SetWriteDeadline(t time.Time) error {
|
||||
|
||||
func NewDnsWithOption(option DnsOption) *Dns {
|
||||
return &Dns{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
tp: C.Dns,
|
||||
pdName: option.ProviderName,
|
||||
udp: true,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.Dns,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+11
-11
@@ -167,17 +167,17 @@ func NewHttp(option HttpOption) (*Http, error) {
|
||||
}
|
||||
|
||||
outbound := &Http{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Http,
|
||||
pdName: option.ProviderName,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Type: C.Http,
|
||||
ProviderName: option.ProviderName,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
user: option.UserName,
|
||||
pass: option.Password,
|
||||
tlsConfig: tlsConfig,
|
||||
|
||||
@@ -239,17 +239,17 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
||||
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
||||
}
|
||||
outbound := &Hysteria{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Hysteria,
|
||||
pdName: option.ProviderName,
|
||||
udp: true,
|
||||
tfo: option.FastOpen,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Hysteria,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
TFO: option.FastOpen,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
client: client,
|
||||
tlsConfig: tlsClientConfig,
|
||||
|
||||
+103
-35
@@ -5,27 +5,27 @@ 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/proxydialer"
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
tuicCommon "github.com/metacubex/mihomo/transport/tuic/common"
|
||||
"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"
|
||||
)
|
||||
|
||||
func init() {
|
||||
hysteria2.SetCongestionController = tuicCommon.SetCongestionController
|
||||
}
|
||||
|
||||
const minHopInterval = 5
|
||||
const defaultHopInterval = 30
|
||||
|
||||
@@ -42,7 +42,7 @@ type Hysteria2Option struct {
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port,omitempty"`
|
||||
Ports string `proxy:"ports,omitempty"`
|
||||
HopInterval int `proxy:"hop-interval,omitempty"`
|
||||
HopInterval string `proxy:"hop-interval,omitempty"`
|
||||
Up string `proxy:"up,omitempty"`
|
||||
Down string `proxy:"down,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
@@ -56,8 +56,11 @@ type Hysteria2Option struct {
|
||||
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"`
|
||||
MaxStreamReceiveWindow uint64 `proxy:"max-stream-receive-window,omitempty"`
|
||||
@@ -65,6 +68,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 {
|
||||
@@ -105,20 +124,19 @@ func (h *Hysteria2) ProxyInfo() C.ProxyInfo {
|
||||
func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
outbound := &Hysteria2{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Hysteria2,
|
||||
pdName: option.ProviderName,
|
||||
udp: true,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Hysteria2,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
singDialer := proxydialer.NewSingDialer(outbound.dialer)
|
||||
|
||||
var salamanderPassword string
|
||||
if len(option.Obfs) > 0 {
|
||||
@@ -177,7 +195,6 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||
|
||||
clientOptions := hysteria2.ClientOptions{
|
||||
Context: context.TODO(),
|
||||
Dialer: singDialer,
|
||||
Logger: log.SingLogger,
|
||||
SendBPS: StringToBps(option.Up),
|
||||
ReceiveBPS: StringToBps(option.Down),
|
||||
@@ -186,25 +203,24 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||
TLSConfig: tlsClientConfig,
|
||||
QUICConfig: quicConfig,
|
||||
UDPDisabled: false,
|
||||
CWND: option.CWND,
|
||||
UdpMTU: option.UdpMTU,
|
||||
ServerAddress: func(ctx context.Context) (*net.UDPAddr, error) {
|
||||
udpAddr, err := resolveUDPAddr(ctx, "udp", addr, option.IPVersion)
|
||||
ServerAddress: M.ParseSocksaddr(addr),
|
||||
PacketListener: outbound.dialer,
|
||||
QuicDialer: qtls.QuicDialerFunc(func(ctx context.Context, addr string, dialer qtls.PacketDialer, tlsCfg *tls.Config, cfg *quic.Config, early bool) (net.PacketConn, *quic.Conn, error) {
|
||||
err := echConfig.ClientHandle(ctx, tlsCfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
err = echConfig.ClientHandle(ctx, tlsClientConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return udpAddr, nil
|
||||
return common.DialQuic(ctx, addr, outbound.DialOptions(), dialer, tlsCfg, cfg, early)
|
||||
}),
|
||||
SetBBRCongestion: func(quicConn *quic.Conn) {
|
||||
common.SetCongestionController(quicConn, "bbr", option.CWND, option.BBRProfile)
|
||||
},
|
||||
}
|
||||
|
||||
var ranges utils.IntRanges[uint16]
|
||||
var serverPorts []uint16
|
||||
if option.Ports != "" {
|
||||
ranges, err = utils.NewUnsignedRanges[uint16](option.Ports)
|
||||
ranges, err := utils.NewUnsignedRanges[uint16](option.Ports)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -213,12 +229,21 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||
return true
|
||||
})
|
||||
if len(serverPorts) > 0 {
|
||||
if option.HopInterval == 0 {
|
||||
option.HopInterval = defaultHopInterval
|
||||
} else if option.HopInterval < minHopInterval {
|
||||
option.HopInterval = minHopInterval
|
||||
hopRange, err := utils.NewUnsignedRange[uint64](option.HopInterval)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
clientOptions.HopInterval = time.Duration(option.HopInterval) * time.Second
|
||||
start, end := hopRange.Start(), hopRange.End()
|
||||
if start == 0 {
|
||||
start = defaultHopInterval
|
||||
} else if start < minHopInterval {
|
||||
start = minHopInterval
|
||||
}
|
||||
if end < start {
|
||||
end = start
|
||||
}
|
||||
clientOptions.HopInterval = time.Duration(start) * time.Second
|
||||
clientOptions.HopIntervalMax = time.Duration(end) * time.Second
|
||||
clientOptions.ServerPorts = serverPorts
|
||||
}
|
||||
}
|
||||
@@ -226,6 +251,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
|
||||
|
||||
+93
-57
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
@@ -25,7 +26,7 @@ import (
|
||||
"github.com/metacubex/mihomo/transport/masque"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
|
||||
connectip "github.com/metacubex/connect-ip-go"
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/quic-go"
|
||||
wireguard "github.com/metacubex/sing-wireguard"
|
||||
M "github.com/metacubex/sing/common/metadata"
|
||||
@@ -34,11 +35,12 @@ import (
|
||||
|
||||
type Masque struct {
|
||||
*Base
|
||||
tlsConfig *tls.Config
|
||||
quicConfig *quic.Config
|
||||
tunDevice wireguard.Device
|
||||
resolver resolver.Resolver
|
||||
uri string
|
||||
tlsConfig *tls.Config
|
||||
quicConfig *quic.Config
|
||||
tunDevice wireguard.Device
|
||||
resolver resolver.Resolver
|
||||
uri string
|
||||
h2Transport *http.Transport
|
||||
|
||||
runCtx context.Context
|
||||
runCancel context.CancelFunc
|
||||
@@ -51,20 +53,23 @@ type Masque struct {
|
||||
|
||||
type MasqueOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
PrivateKey string `proxy:"private-key"`
|
||||
PublicKey string `proxy:"public-key"`
|
||||
Ip string `proxy:"ip,omitempty"`
|
||||
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||
URI string `proxy:"uri,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
MTU int `proxy:"mtu,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
PrivateKey string `proxy:"private-key"`
|
||||
PublicKey string `proxy:"public-key"`
|
||||
Ip string `proxy:"ip,omitempty"`
|
||||
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||
URI string `proxy:"uri,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
MTU int `proxy:"mtu,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Network string `proxy:"network,omitempty"`
|
||||
|
||||
CongestionController string `proxy:"congestion-controller,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
BBRProfile string `proxy:"bbr-profile,omitempty"`
|
||||
|
||||
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
||||
Dns []string `proxy:"dns,omitempty"`
|
||||
@@ -100,16 +105,16 @@ func (option MasqueOption) Prefixes() ([]netip.Prefix, error) {
|
||||
|
||||
func NewMasque(option MasqueOption) (*Masque, error) {
|
||||
outbound := &Masque{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Masque,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Type: C.Masque,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
|
||||
@@ -150,12 +155,42 @@ func NewMasque(option MasqueOption) (*Masque, error) {
|
||||
sni = masque.ConnectSNI
|
||||
}
|
||||
|
||||
tlsConfig, err := masque.PrepareTlsConfig(privKey, ecPubKey, sni)
|
||||
tlsConfig, err := masque.PrepareTlsConfig(privKey, ecPubKey, sni, option.SkipCertVerify)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to prepare TLS config: %v\n", err)
|
||||
}
|
||||
outbound.tlsConfig = tlsConfig
|
||||
|
||||
if option.Network == "h2" {
|
||||
tlsConfig.NextProtos = []string{"h2"}
|
||||
// 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
|
||||
}
|
||||
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,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
outbound.quicConfig = &quic.Config{
|
||||
EnableDatagrams: true,
|
||||
InitialPacketSize: 1242,
|
||||
@@ -229,27 +264,28 @@ func (w *Masque) run(ctx context.Context) error {
|
||||
w.runDevice.Store(true)
|
||||
}
|
||||
|
||||
udpAddr, err := resolveUDPAddr(ctx, "udp", w.addr, w.prefer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var pc net.PacketConn
|
||||
var closer io.Closer
|
||||
var ipConn masque.IpConn
|
||||
var err error
|
||||
if w.h2Transport != nil {
|
||||
closer, ipConn, err = masque.ConnectTunnelH2(ctx, w.h2Transport, w.uri)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
var quicConn *quic.Conn
|
||||
pc, quicConn, err = common.DialQuic(ctx, w.addr, w.DialOptions(), w.dialer, w.tlsConfig, w.quicConfig, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
common.SetCongestionController(quicConn, w.option.CongestionController, w.option.CWND, w.option.BBRProfile)
|
||||
|
||||
pc, err := w.dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
quicConn, err := quic.Dial(ctx, pc, udpAddr, w.tlsConfig, w.quicConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
common.SetCongestionController(quicConn, w.option.CongestionController, w.option.CWND)
|
||||
|
||||
tr, ipConn, err := masque.ConnectTunnel(ctx, quicConn, w.uri)
|
||||
if err != nil {
|
||||
_ = pc.Close()
|
||||
return err
|
||||
closer, ipConn, err = masque.ConnectTunnel(ctx, quicConn, w.uri)
|
||||
if err != nil {
|
||||
_ = pc.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
w.running.Store(true)
|
||||
@@ -258,8 +294,10 @@ func (w *Masque) run(ctx context.Context) error {
|
||||
contextutils.AfterFunc(runCtx, func() {
|
||||
w.running.Store(false)
|
||||
_ = ipConn.Close()
|
||||
_ = tr.Close()
|
||||
_ = pc.Close()
|
||||
_ = closer.Close()
|
||||
if pc != nil {
|
||||
_ = pc.Close()
|
||||
}
|
||||
})
|
||||
|
||||
go func() {
|
||||
@@ -276,7 +314,7 @@ func (w *Masque) run(ctx context.Context) error {
|
||||
}
|
||||
icmp, err := ipConn.WritePacket(buf[:sizes[0]])
|
||||
if err != nil {
|
||||
if errors.As(err, new(*connectip.CloseError)) {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
|
||||
return
|
||||
}
|
||||
@@ -294,19 +332,17 @@ func (w *Masque) run(ctx context.Context) error {
|
||||
|
||||
go func() {
|
||||
defer runCancel()
|
||||
buf := pool.Get(pool.UDPBufferSize)
|
||||
defer pool.Put(buf)
|
||||
for runCtx.Err() == nil {
|
||||
n, err := ipConn.ReadPacket(buf)
|
||||
buf, err := ipConn.ReadPacket()
|
||||
if err != nil {
|
||||
if errors.As(err, new(*connectip.CloseError)) {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
|
||||
return
|
||||
}
|
||||
log.Warnln("[Masque](%s) error reading from IP connection: %v, continuing...", w.name, err)
|
||||
continue
|
||||
}
|
||||
if _, err := w.tunDevice.Write([][]byte{buf[:n]}, 0); err != nil {
|
||||
if _, err := w.tunDevice.Write([][]byte{buf}, 0); err != nil {
|
||||
log.Errorln("[Masque](%s) error writing to TUN device: %v", w.name, err)
|
||||
return
|
||||
}
|
||||
@@ -375,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)
|
||||
}
|
||||
|
||||
+13
-22
@@ -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)
|
||||
}
|
||||
@@ -166,17 +156,18 @@ func NewMieru(option MieruOption) (*Mieru, error) {
|
||||
addr = net.JoinHostPort(option.Server, strconv.Itoa(beginPort))
|
||||
}
|
||||
outbound := &Mieru{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Mieru,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
xudp: false,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Mieru,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
client: c,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
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
|
||||
runMutex sync.Mutex
|
||||
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"`
|
||||
CA string `proxy:"ca"`
|
||||
Cert string `proxy:"cert,omitempty"`
|
||||
Key string `proxy:"key,omitempty"`
|
||||
TLSCrypt string `proxy:"tls-crypt"`
|
||||
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,
|
||||
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,
|
||||
}
|
||||
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) {
|
||||
if err = o.run(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var conn net.Conn
|
||||
if !metadata.Resolved() || o.resolver != nil {
|
||||
r := resolver.DefaultResolver
|
||||
if o.resolver != nil {
|
||||
r = o.resolver
|
||||
}
|
||||
options := o.DialOptions()
|
||||
options = append(options, dialer.WithResolver(r))
|
||||
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: o.tunDevice}))
|
||||
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||
} else {
|
||||
conn, err = o.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
|
||||
if err = o.run(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = o.ResolveUDP(ctx, metadata); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pc, err = o.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 {
|
||||
if (!metadata.Resolved() || o.resolver != nil) && metadata.Host != "" {
|
||||
r := resolver.DefaultResolver
|
||||
if o.resolver != nil {
|
||||
r = o.resolver
|
||||
}
|
||||
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.runMutex.Lock()
|
||||
client := o.client
|
||||
tunDevice := o.tunDevice
|
||||
o.client = nil
|
||||
o.tunDevice = nil
|
||||
o.running = false
|
||||
o.runMutex.Unlock()
|
||||
|
||||
if client != nil {
|
||||
_ = client.Close()
|
||||
}
|
||||
if tunDevice != nil {
|
||||
return tunDevice.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *OpenVPN) run(ctx context.Context) error {
|
||||
o.runMutex.Lock()
|
||||
defer o.runMutex.Unlock()
|
||||
if o.running {
|
||||
return nil
|
||||
}
|
||||
if o.runCtx.Err() != nil {
|
||||
return o.runCtx.Err()
|
||||
}
|
||||
|
||||
packetIO, err := o.openPacketIO(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := ovpn.NewClient(o.config, packetIO)
|
||||
if err != nil {
|
||||
_ = packetIO.Close()
|
||||
return err
|
||||
}
|
||||
push, err := client.Handshake(ctx)
|
||||
if err != nil {
|
||||
_ = client.Close()
|
||||
return err
|
||||
}
|
||||
log.Debugln("[OpenVPN](%s) handshake complete: prefixes=%v peer-id=%d dns=%v redirect=%t block-ipv6=%t", o.name, push.Prefixes, 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 E.Cause(err, "create OpenVPN stack device")
|
||||
}
|
||||
if err := tunDevice.Start(); err != nil {
|
||||
_ = client.Close()
|
||||
_ = tunDevice.Close()
|
||||
return 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 nil
|
||||
}
|
||||
|
||||
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.runMutex.Lock()
|
||||
if o.client == client {
|
||||
o.client = nil
|
||||
o.tunDevice = nil
|
||||
o.running = false
|
||||
}
|
||||
o.runMutex.Unlock()
|
||||
})
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
+17
-17
@@ -46,33 +46,33 @@ func (r *Reject) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||
|
||||
func NewRejectWithOption(option RejectOption) *Reject {
|
||||
return &Reject{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
tp: C.Reject,
|
||||
udp: true,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.Reject,
|
||||
UDP: true,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func NewReject() *Reject {
|
||||
return &Reject{
|
||||
Base: &Base{
|
||||
name: "REJECT",
|
||||
tp: C.Reject,
|
||||
udp: true,
|
||||
prefer: C.DualStack,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: "REJECT",
|
||||
Type: C.Reject,
|
||||
UDP: true,
|
||||
Prefer: C.DualStack,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func NewRejectDrop() *Reject {
|
||||
return &Reject{
|
||||
Base: &Base{
|
||||
name: "REJECT-DROP",
|
||||
tp: C.RejectDrop,
|
||||
udp: true,
|
||||
prefer: C.DualStack,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: "REJECT-DROP",
|
||||
Type: C.RejectDrop,
|
||||
UDP: true,
|
||||
Prefer: C.DualStack,
|
||||
}),
|
||||
drop: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -446,18 +450,18 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
}
|
||||
|
||||
outbound := &ShadowSocks{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Shadowsocks,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Shadowsocks,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
method: method,
|
||||
|
||||
option: &option,
|
||||
|
||||
@@ -158,18 +158,18 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||
}
|
||||
|
||||
outbound := &ShadowSocksR{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.ShadowsocksR,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.ShadowsocksR,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
cipher: coreCiph,
|
||||
obfs: obfs,
|
||||
|
||||
@@ -103,6 +103,7 @@ func NewSingMux(option SingMuxOption, proxy ProxyAdapter) (ProxyAdapter, error)
|
||||
MinStreams: option.MinStreams,
|
||||
MaxStreams: option.MaxStreams,
|
||||
Padding: option.Padding,
|
||||
TCPTimeout: C.DefaultTCPTimeout,
|
||||
Brutal: mux.BrutalOptions{
|
||||
Enabled: option.BrutalOpts.Enabled,
|
||||
SendBPS: StringToBps(option.BrutalOpts.Up),
|
||||
|
||||
+17
-14
@@ -101,8 +101,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,6 +110,10 @@ 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)
|
||||
|
||||
pc := snell.PacketConn(c)
|
||||
@@ -161,18 +164,18 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
||||
}
|
||||
|
||||
s := &Snell{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Snell,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Snell,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
psk: psk,
|
||||
obfsOption: obfsOption,
|
||||
|
||||
+21
-20
@@ -96,18 +96,19 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
return
|
||||
}
|
||||
|
||||
if ss.tls {
|
||||
cc := tls.Client(c, ss.tlsConfig)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||
defer cancel()
|
||||
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{
|
||||
@@ -187,18 +188,18 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
||||
}
|
||||
|
||||
outbound := &Socks5{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Socks5,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Type: C.Socks5,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
user: option.UserName,
|
||||
pass: option.Password,
|
||||
|
||||
+13
-11
@@ -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 {
|
||||
@@ -182,16 +182,18 @@ func NewSsh(option SshOption) (*Ssh, error) {
|
||||
config.ClientVersion = version
|
||||
|
||||
outbound := &Ssh{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Ssh,
|
||||
pdName: option.ProviderName,
|
||||
udp: false,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Ssh,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: false,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
config: &config,
|
||||
}
|
||||
|
||||
+12
-12
@@ -223,18 +223,18 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
|
||||
}
|
||||
|
||||
outbound := &Sudoku{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: baseConf.ServerAddress,
|
||||
tp: C.Sudoku,
|
||||
pdName: option.ProviderName,
|
||||
udp: true,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: baseConf.ServerAddress,
|
||||
Type: C.Sudoku,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
baseConf: baseConf,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
//go:build !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/ipn"
|
||||
"github.com/metacubex/tailscale/net/netmon"
|
||||
"github.com/metacubex/tailscale/tsnet"
|
||||
D "github.com/miekg/dns"
|
||||
)
|
||||
|
||||
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() {
|
||||
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) {
|
||||
ifaces, err := anet.Interfaces()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, iff := range ifaces {
|
||||
addrs, err := anet.InterfaceAddrsByInterface(&iff)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
nif = append(nif, netmon.Interface{
|
||||
Interface: &iff,
|
||||
AltAddrs: addrs,
|
||||
})
|
||||
}
|
||||
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: outbound.dialer.DialContext,
|
||||
SystemPacketListener: tailscalePacketListener{dialer: outbound.dialer},
|
||||
ExtraRootCAs: ca.GetCertPool(),
|
||||
LookupHook: tailscaleLookupHook,
|
||||
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 tailscaleLookupHook(ctx context.Context, host string) ([]netip.Addr, error) {
|
||||
return resolver.LookupIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||
}
|
||||
|
||||
func (t *Tailscale) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||
if err = t.ensureStarted(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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) {
|
||||
if err = t.checkTailscaleRoute(ctx, network, address); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t.server.Dial(ctx, network, address)
|
||||
})))
|
||||
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
|
||||
}
|
||||
|
||||
func (t *Tailscale) checkTailscaleRoute(ctx context.Context, network, address string) error {
|
||||
ipp, viaTailscale, err := t.server.DialPlan(ctx, network, address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !viaTailscale {
|
||||
return fmt.Errorf("destination %s is not routed by Tailscale; configure exit-node or accept an advertised subnet route", ipp)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
type tailscalePacketListener struct {
|
||||
dialer C.Dialer
|
||||
}
|
||||
|
||||
func (l tailscalePacketListener) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
|
||||
return l.dialer.ListenPacket(ctx, network, address, netip.AddrPort{})
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
//go:build 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")
|
||||
}
|
||||
+29
-19
@@ -27,7 +27,7 @@ type Trojan struct {
|
||||
hexPassword [trojan.KeyLength]byte
|
||||
|
||||
// for gun mux
|
||||
gunTransport *gun.Transport
|
||||
gunClient *gun.Client
|
||||
|
||||
realityConfig *tlsC.RealityConfig
|
||||
echConfig *ech.Config
|
||||
@@ -115,7 +115,7 @@ func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.
|
||||
|
||||
c, err = vmess.StreamWebsocketConn(ctx, c, wsOpts)
|
||||
case "grpc":
|
||||
break // already handle in gun transport
|
||||
break // already handle in dialContext
|
||||
default:
|
||||
// default tcp network
|
||||
// handle TLS
|
||||
@@ -175,7 +175,7 @@ func (t *Trojan) writeHeaderContext(ctx context.Context, c net.Conn, metadata *C
|
||||
func (t *Trojan) dialContext(ctx context.Context) (c net.Conn, err error) {
|
||||
switch t.option.Network {
|
||||
case "grpc": // gun transport
|
||||
return t.gunTransport.Dial()
|
||||
return t.gunClient.Dial()
|
||||
default:
|
||||
}
|
||||
return t.dialer.DialContext(ctx, "tcp", t.addr)
|
||||
@@ -236,10 +236,13 @@ func (t *Trojan) ProxyInfo() C.ProxyInfo {
|
||||
|
||||
// Close implements C.ProxyAdapter
|
||||
func (t *Trojan) Close() error {
|
||||
if t.gunTransport != nil {
|
||||
return t.gunTransport.Close()
|
||||
var errs []error
|
||||
if t.gunClient != nil {
|
||||
if err := t.gunClient.Close(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||
@@ -250,18 +253,18 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||
}
|
||||
|
||||
t := &Trojan{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Trojan,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Trojan,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
hexPassword: trojan.Key(option.Password),
|
||||
}
|
||||
@@ -320,7 +323,14 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||
PingInterval: option.GrpcOpts.PingInterval,
|
||||
}
|
||||
|
||||
t.gunTransport = gun.NewTransport(dialFn, tlsConfig, gunConfig)
|
||||
t.gunClient = gun.NewClient(
|
||||
func() *gun.Transport {
|
||||
return gun.NewTransport(dialFn, tlsConfig, gunConfig)
|
||||
},
|
||||
option.GrpcOpts.MaxConnections,
|
||||
option.GrpcOpts.MinStreams,
|
||||
option.GrpcOpts.MaxStreams,
|
||||
)
|
||||
}
|
||||
|
||||
return t, nil
|
||||
|
||||
@@ -3,7 +3,6 @@ package outbound
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
@@ -14,7 +13,7 @@ import (
|
||||
|
||||
type TrustTunnel struct {
|
||||
*Base
|
||||
client *trusttunnel.Client
|
||||
client *trusttunnel.PoolClient
|
||||
option *TrustTunnelOption
|
||||
}
|
||||
|
||||
@@ -35,10 +34,15 @@ type TrustTunnelOption struct {
|
||||
PrivateKey string `proxy:"private-key,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
HealthCheck bool `proxy:"health-check,omitempty"`
|
||||
|
||||
// quic options
|
||||
Quic bool `proxy:"quic,omitempty"`
|
||||
CongestionController string `proxy:"congestion-controller,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
BBRProfile string `proxy:"bbr-profile,omitempty"`
|
||||
// reuse options
|
||||
MaxConnections int `proxy:"max-connections,omitempty"`
|
||||
MinStreams int `proxy:"min-streams,omitempty"`
|
||||
MaxStreams int `proxy:"max-streams,omitempty"`
|
||||
}
|
||||
|
||||
func (t *TrustTunnel) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||
@@ -82,38 +86,36 @@ func (t *TrustTunnel) Close() error {
|
||||
func NewTrustTunnel(option TrustTunnelOption) (*TrustTunnel, error) {
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
outbound := &TrustTunnel{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.TrustTunnel,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.TrustTunnel,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
|
||||
tOption := trusttunnel.ClientOptions{
|
||||
Dialer: outbound.dialer,
|
||||
ResolvUDP: func(ctx context.Context, server string) (netip.AddrPort, error) {
|
||||
udpAddr, err := resolveUDPAddr(ctx, "udp", server, option.IPVersion)
|
||||
if err != nil {
|
||||
return netip.AddrPort{}, err
|
||||
}
|
||||
return udpAddr.AddrPort(), nil
|
||||
},
|
||||
Dialer: outbound.dialer,
|
||||
DialOptions: outbound.DialOptions,
|
||||
Server: addr,
|
||||
Username: option.UserName,
|
||||
Password: option.Password,
|
||||
QUIC: option.Quic,
|
||||
QUICCongestionControl: option.CongestionController,
|
||||
QUICCwnd: option.CWND,
|
||||
QUICBBRProfile: option.BBRProfile,
|
||||
HealthCheck: option.HealthCheck,
|
||||
MaxConnections: option.MaxConnections,
|
||||
MinStreams: option.MinStreams,
|
||||
MaxStreams: option.MaxStreams,
|
||||
}
|
||||
echConfig, err := option.ECHOpts.Parse()
|
||||
if err != nil {
|
||||
@@ -134,7 +136,7 @@ func NewTrustTunnel(option TrustTunnelOption) (*TrustTunnel, error) {
|
||||
}
|
||||
tOption.TLSConfig = tlsConfig
|
||||
|
||||
client, err := trusttunnel.NewClient(context.TODO(), tOption)
|
||||
client, err := trusttunnel.NewPoolClient(context.TODO(), tOption)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+25
-44
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/metacubex/mihomo/component/ech"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/transport/tuic"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
"github.com/metacubex/quic-go"
|
||||
@@ -25,8 +26,9 @@ type Tuic struct {
|
||||
option *TuicOption
|
||||
client *tuic.PoolClient
|
||||
|
||||
tlsConfig *tls.Config
|
||||
echConfig *ech.Config
|
||||
quicConfig *quic.Config
|
||||
tlsConfig *tls.Config
|
||||
echConfig *ech.Config
|
||||
}
|
||||
|
||||
type TuicOption struct {
|
||||
@@ -50,6 +52,7 @@ type TuicOption struct {
|
||||
FastOpen bool `proxy:"fast-open,omitempty"`
|
||||
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
BBRProfile string `proxy:"bbr-profile,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
Certificate string `proxy:"certificate,omitempty"`
|
||||
@@ -106,25 +109,13 @@ func (t *Tuic) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_
|
||||
return newPacketConn(pc, t), nil
|
||||
}
|
||||
|
||||
func (t *Tuic) dial(ctx context.Context) (transport *quic.Transport, addr net.Addr, err error) {
|
||||
udpAddr, err := resolveUDPAddr(ctx, "udp", t.addr, t.prefer)
|
||||
func (t *Tuic) dial(ctx context.Context) (quicConn *quic.Conn, err error) {
|
||||
_, quicConn, err = common.DialQuic(ctx, t.addr, t.DialOptions(), t.dialer, t.tlsConfig, t.quicConfig, t.option.ReduceRtt)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, err
|
||||
}
|
||||
err = t.echConfig.ClientHandle(ctx, t.tlsConfig)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
addr = udpAddr
|
||||
var pc net.PacketConn
|
||||
pc, err = t.dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
transport = &quic.Transport{Conn: pc}
|
||||
transport.SetCreatedConn(true) // auto close conn
|
||||
transport.SetSingleUse(true) // auto close transport
|
||||
return
|
||||
common.SetCongestionController(quicConn, t.option.CongestionController, t.option.CWND, t.option.BBRProfile)
|
||||
return quicConn, nil
|
||||
}
|
||||
|
||||
// ProxyInfo implements C.ProxyAdapter
|
||||
@@ -232,7 +223,6 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
tlsConfig.InsecureSkipVerify = true // tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config
|
||||
}
|
||||
|
||||
tlsClientConfig := tlsConfig
|
||||
echConfig, err := option.ECHOpts.Parse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -247,20 +237,21 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
}
|
||||
|
||||
t := &Tuic{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Tuic,
|
||||
pdName: option.ProviderName,
|
||||
udp: true,
|
||||
tfo: option.FastOpen,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
option: &option,
|
||||
tlsConfig: tlsClientConfig,
|
||||
echConfig: echConfig,
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Tuic,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
TFO: option.FastOpen,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
quicConfig: quicConfig,
|
||||
tlsConfig: tlsConfig,
|
||||
echConfig: echConfig,
|
||||
}
|
||||
t.dialer = option.NewDialer(t.DialOptions())
|
||||
|
||||
@@ -278,17 +269,12 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
if len(option.Token) > 0 {
|
||||
tkn := tuic.GenTKN(option.Token)
|
||||
clientOption := &tuic.ClientOptionV4{
|
||||
TlsConfig: tlsClientConfig,
|
||||
QuicConfig: quicConfig,
|
||||
Token: tkn,
|
||||
UdpRelayMode: udpRelayMode,
|
||||
CongestionController: option.CongestionController,
|
||||
ReduceRtt: option.ReduceRtt,
|
||||
RequestTimeout: time.Duration(option.RequestTimeout) * time.Millisecond,
|
||||
MaxUdpRelayPacketSize: option.MaxUdpRelayPacketSize,
|
||||
FastOpen: option.FastOpen,
|
||||
MaxOpenStreams: clientMaxOpenStreams,
|
||||
CWND: option.CWND,
|
||||
}
|
||||
|
||||
t.client = tuic.NewPoolClientV4(clientOption, t.dial)
|
||||
@@ -298,16 +284,11 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
maxUdpRelayPacketSize = tuic.MaxFragSizeV5
|
||||
}
|
||||
clientOption := &tuic.ClientOptionV5{
|
||||
TlsConfig: tlsClientConfig,
|
||||
QuicConfig: quicConfig,
|
||||
Uuid: uuid.FromStringOrNil(option.UUID),
|
||||
Password: option.Password,
|
||||
UdpRelayMode: udpRelayMode,
|
||||
CongestionController: option.CongestionController,
|
||||
ReduceRtt: option.ReduceRtt,
|
||||
MaxUdpRelayPacketSize: maxUdpRelayPacketSize,
|
||||
MaxOpenStreams: clientMaxOpenStreams,
|
||||
CWND: option.CWND,
|
||||
}
|
||||
|
||||
t.client = tuic.NewPoolClientV5(clientOption, t.dial)
|
||||
|
||||
+14
-11
@@ -34,23 +34,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
|
||||
|
||||
+199
-47
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/convert"
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
@@ -15,12 +16,14 @@ import (
|
||||
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/transport/gun"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
"github.com/metacubex/mihomo/transport/vless"
|
||||
"github.com/metacubex/mihomo/transport/vless/encryption"
|
||||
"github.com/metacubex/mihomo/transport/vmess"
|
||||
"github.com/metacubex/mihomo/transport/xhttp"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/quic-go"
|
||||
vmessSing "github.com/metacubex/sing-vmess"
|
||||
"github.com/metacubex/sing-vmess/packetaddr"
|
||||
M "github.com/metacubex/sing/common/metadata"
|
||||
@@ -36,7 +39,7 @@ type Vless struct {
|
||||
encryption *encryption.ClientInstance
|
||||
|
||||
// for gun mux
|
||||
gunTransport *gun.Transport
|
||||
gunClient *gun.Client
|
||||
// for xhttp
|
||||
xhttpClient *xhttp.Client
|
||||
|
||||
@@ -76,22 +79,46 @@ type VlessOption struct {
|
||||
}
|
||||
|
||||
type XHTTPOptions struct {
|
||||
Path string `proxy:"path,omitempty"`
|
||||
Host string `proxy:"host,omitempty"`
|
||||
Mode string `proxy:"mode,omitempty"`
|
||||
Headers map[string]string `proxy:"headers,omitempty"`
|
||||
NoGRPCHeader bool `proxy:"no-grpc-header,omitempty"`
|
||||
XPaddingBytes string `proxy:"x-padding-bytes,omitempty"`
|
||||
DownloadSettings *XHTTPDownloadSettings `proxy:"download-settings,omitempty"`
|
||||
Path string `proxy:"path,omitempty"`
|
||||
Host string `proxy:"host,omitempty"`
|
||||
Mode string `proxy:"mode,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
|
||||
DownloadSettings *XHTTPDownloadSettings `proxy:"download-settings,omitempty"`
|
||||
}
|
||||
|
||||
type XHTTPReuseSettings struct {
|
||||
MaxConcurrency string `proxy:"max-concurrency,omitempty"`
|
||||
MaxConnections string `proxy:"max-connections,omitempty"`
|
||||
CMaxReuseTimes string `proxy:"c-max-reuse-times,omitempty"`
|
||||
HMaxRequestTimes string `proxy:"h-max-request-times,omitempty"`
|
||||
HMaxReusableSecs string `proxy:"h-max-reusable-secs,omitempty"`
|
||||
HKeepAlivePeriod int `proxy:"h-keep-alive-period,omitempty"`
|
||||
}
|
||||
|
||||
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"`
|
||||
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"`
|
||||
@@ -133,7 +160,6 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
||||
wsOpts.TLS = true
|
||||
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
|
||||
TLSConfig: &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
ServerName: host,
|
||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||
NextProtos: []string{"http/1.1"},
|
||||
@@ -187,9 +213,9 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
||||
|
||||
c, err = vmess.StreamH2Conn(ctx, c, h2Opts)
|
||||
case "grpc":
|
||||
break // already handle in gun transport
|
||||
break // already handle in dialContext
|
||||
case "xhttp":
|
||||
break // already handle in xhttp client
|
||||
break // already handle in dialContext
|
||||
default:
|
||||
// default tcp network
|
||||
// handle TLS
|
||||
@@ -271,9 +297,9 @@ func (v *Vless) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (ne
|
||||
func (v *Vless) dialContext(ctx context.Context) (c net.Conn, err error) {
|
||||
switch v.option.Network {
|
||||
case "grpc": // gun transport
|
||||
return v.gunTransport.Dial()
|
||||
return v.gunClient.Dial()
|
||||
case "xhttp":
|
||||
return v.xhttpClient.Dial()
|
||||
return v.xhttpClient.Dial(ctx)
|
||||
default:
|
||||
}
|
||||
return v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
@@ -349,8 +375,8 @@ func (v *Vless) ProxyInfo() C.ProxyInfo {
|
||||
// Close implements C.ProxyAdapter
|
||||
func (v *Vless) Close() error {
|
||||
var errs []error
|
||||
if v.gunTransport != nil {
|
||||
if err := v.gunTransport.Close(); err != nil {
|
||||
if v.gunClient != nil {
|
||||
if err := v.gunClient.Close(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
@@ -421,19 +447,19 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
}
|
||||
|
||||
v := &Vless{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Vless,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
xudp: option.XUDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Type: C.Vless,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
XUDP: option.XUDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
client: client,
|
||||
option: &option,
|
||||
}
|
||||
@@ -496,7 +522,14 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
}
|
||||
}
|
||||
|
||||
v.gunTransport = gun.NewTransport(dialFn, tlsConfig, gunConfig)
|
||||
v.gunClient = gun.NewClient(
|
||||
func() *gun.Transport {
|
||||
return gun.NewTransport(dialFn, tlsConfig, gunConfig)
|
||||
},
|
||||
option.GrpcOpts.MaxConnections,
|
||||
option.GrpcOpts.MinStreams,
|
||||
option.GrpcOpts.MaxStreams,
|
||||
)
|
||||
case "xhttp":
|
||||
requestHost := v.option.XHTTPOpts.Host
|
||||
if requestHost == "" {
|
||||
@@ -507,13 +540,43 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
}
|
||||
}
|
||||
|
||||
var hKeepAlivePeriod time.Duration
|
||||
|
||||
var reuseCfg *xhttp.ReuseConfig
|
||||
if option.XHTTPOpts.ReuseSettings != nil {
|
||||
reuseCfg = &xhttp.ReuseConfig{
|
||||
MaxConcurrency: option.XHTTPOpts.ReuseSettings.MaxConcurrency,
|
||||
MaxConnections: option.XHTTPOpts.ReuseSettings.MaxConnections,
|
||||
CMaxReuseTimes: option.XHTTPOpts.ReuseSettings.CMaxReuseTimes,
|
||||
HMaxRequestTimes: option.XHTTPOpts.ReuseSettings.HMaxRequestTimes,
|
||||
HMaxReusableSecs: option.XHTTPOpts.ReuseSettings.HMaxReusableSecs,
|
||||
}
|
||||
hKeepAlivePeriod = time.Duration(option.XHTTPOpts.ReuseSettings.HKeepAlivePeriod) * time.Second
|
||||
}
|
||||
|
||||
cfg := &xhttp.Config{
|
||||
Host: requestHost,
|
||||
Path: v.option.XHTTPOpts.Path,
|
||||
Mode: v.option.XHTTPOpts.Mode,
|
||||
Headers: v.option.XHTTPOpts.Headers,
|
||||
NoGRPCHeader: v.option.XHTTPOpts.NoGRPCHeader,
|
||||
XPaddingBytes: v.option.XHTTPOpts.XPaddingBytes,
|
||||
Host: requestHost,
|
||||
Path: v.option.XHTTPOpts.Path,
|
||||
Mode: v.option.XHTTPOpts.Mode,
|
||||
Headers: v.option.XHTTPOpts.Headers,
|
||||
NoGRPCHeader: v.option.XHTTPOpts.NoGRPCHeader,
|
||||
XPaddingBytes: v.option.XHTTPOpts.XPaddingBytes,
|
||||
XPaddingObfsMode: v.option.XHTTPOpts.XPaddingObfsMode,
|
||||
XPaddingKey: v.option.XHTTPOpts.XPaddingKey,
|
||||
XPaddingHeader: v.option.XHTTPOpts.XPaddingHeader,
|
||||
XPaddingPlacement: v.option.XHTTPOpts.XPaddingPlacement,
|
||||
XPaddingMethod: v.option.XHTTPOpts.XPaddingMethod,
|
||||
UplinkHTTPMethod: v.option.XHTTPOpts.UplinkHTTPMethod,
|
||||
SessionPlacement: v.option.XHTTPOpts.SessionPlacement,
|
||||
SessionKey: v.option.XHTTPOpts.SessionKey,
|
||||
SeqPlacement: v.option.XHTTPOpts.SeqPlacement,
|
||||
SeqKey: v.option.XHTTPOpts.SeqKey,
|
||||
UplinkDataPlacement: v.option.XHTTPOpts.UplinkDataPlacement,
|
||||
UplinkDataKey: v.option.XHTTPOpts.UplinkDataKey,
|
||||
UplinkChunkSize: v.option.XHTTPOpts.UplinkChunkSize,
|
||||
ScMaxEachPostBytes: v.option.XHTTPOpts.ScMaxEachPostBytes,
|
||||
ScMinPostsIntervalMs: v.option.XHTTPOpts.ScMinPostsIntervalMs,
|
||||
ReuseConfig: reuseCfg,
|
||||
}
|
||||
|
||||
makeTransport := func() http.RoundTripper {
|
||||
@@ -524,6 +587,45 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
func(ctx context.Context, raw net.Conn, isH2 bool) (net.Conn, error) {
|
||||
return v.streamTLSConn(ctx, raw, isH2)
|
||||
},
|
||||
func(ctx context.Context, cfg *quic.Config) (*quic.Conn, error) {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsOpts := &vmess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
FingerPrint: v.option.Fingerprint,
|
||||
Certificate: v.option.Certificate,
|
||||
PrivateKey: v.option.PrivateKey,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
ECH: v.echConfig,
|
||||
Reality: v.realityConfig,
|
||||
NextProtos: []string{"h3"},
|
||||
}
|
||||
if v.option.ServerName != "" {
|
||||
tlsOpts.Host = v.option.ServerName
|
||||
}
|
||||
if !v.option.TLS {
|
||||
return nil, errors.New("xhttp HTTP/3 requires TLS")
|
||||
}
|
||||
if v.realityConfig != nil {
|
||||
return nil, errors.New("xhttp HTTP/3 does not support reality")
|
||||
}
|
||||
tlsConfig, err := tlsOpts.ToStdConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = v.echConfig.ClientHandle(ctx, tlsConfig)
|
||||
if err != nil {
|
||||
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,
|
||||
hKeepAlivePeriod,
|
||||
)
|
||||
}
|
||||
var makeDownloadTransport func() http.RoundTripper
|
||||
@@ -569,15 +671,26 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
downloadHKeepAlivePeriod := hKeepAlivePeriod
|
||||
|
||||
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 {
|
||||
downloadCfg.ReuseConfig = &xhttp.ReuseConfig{
|
||||
MaxConcurrency: ds.ReuseSettings.MaxConcurrency,
|
||||
MaxConnections: ds.ReuseSettings.MaxConnections,
|
||||
CMaxReuseTimes: ds.ReuseSettings.CMaxReuseTimes,
|
||||
HMaxRequestTimes: ds.ReuseSettings.HMaxRequestTimes,
|
||||
HMaxReusableSecs: ds.ReuseSettings.HMaxReusableSecs,
|
||||
}
|
||||
downloadHKeepAlivePeriod = time.Duration(ds.ReuseSettings.HKeepAlivePeriod) * time.Second
|
||||
}
|
||||
|
||||
cfg.DownloadConfig = &downloadCfg
|
||||
|
||||
makeDownloadTransport = func() http.RoundTripper {
|
||||
return xhttp.NewTransport(
|
||||
func(ctx context.Context) (net.Conn, error) {
|
||||
@@ -612,6 +725,45 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
|
||||
return conn, nil
|
||||
},
|
||||
func(ctx context.Context, cfg *quic.Config) (*quic.Conn, error) {
|
||||
host, _, _ := net.SplitHostPort(downloadAddr)
|
||||
tlsOpts := &vmess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: downloadSkipCertVerify,
|
||||
FingerPrint: downloadFingerprint,
|
||||
Certificate: downloadCertificate,
|
||||
PrivateKey: downloadPrivateKey,
|
||||
ClientFingerprint: downloadClientFingerprint,
|
||||
ECH: downloadEchConfig,
|
||||
Reality: downloadRealityCfg,
|
||||
NextProtos: []string{"h3"},
|
||||
}
|
||||
if downloadServerName != "" {
|
||||
tlsOpts.Host = downloadServerName
|
||||
}
|
||||
if !downloadTLS {
|
||||
return nil, errors.New("xhttp HTTP/3 requires TLS")
|
||||
}
|
||||
if downloadRealityCfg != nil {
|
||||
return nil, errors.New("xhttp HTTP/3 does not support reality")
|
||||
}
|
||||
tlsConfig, err := tlsOpts.ToStdConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = downloadEchConfig.ClientHandle(ctx, tlsConfig)
|
||||
if err != nil {
|
||||
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,
|
||||
downloadHKeepAlivePeriod,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+69
-75
@@ -34,7 +34,7 @@ type Vmess struct {
|
||||
option *VmessOption
|
||||
|
||||
// for gun mux
|
||||
gunTransport *gun.Transport
|
||||
gunClient *gun.Client
|
||||
|
||||
realityConfig *tlsC.RealityConfig
|
||||
echConfig *ech.Config
|
||||
@@ -86,6 +86,9 @@ type GrpcOptions struct {
|
||||
GrpcServiceName string `proxy:"grpc-service-name,omitempty"`
|
||||
GrpcUserAgent string `proxy:"grpc-user-agent,omitempty"`
|
||||
PingInterval int `proxy:"ping-interval,omitempty"`
|
||||
MaxConnections int `proxy:"max-connections,omitempty"`
|
||||
MinStreams int `proxy:"min-streams,omitempty"`
|
||||
MaxStreams int `proxy:"max-streams,omitempty"`
|
||||
}
|
||||
|
||||
type WSOptions struct {
|
||||
@@ -145,24 +148,9 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
||||
c, err = mihomoVMess.StreamWebsocketConn(ctx, c, wsOpts)
|
||||
case "http":
|
||||
// readability first, so just copy default TLS logic
|
||||
if v.option.TLS {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsOpts := &mihomoVMess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
ECH: v.echConfig,
|
||||
Reality: v.realityConfig,
|
||||
NextProtos: v.option.ALPN,
|
||||
}
|
||||
|
||||
if v.option.ServerName != "" {
|
||||
tlsOpts.Host = v.option.ServerName
|
||||
}
|
||||
c, err = mihomoVMess.StreamTLSConn(ctx, c, tlsOpts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, err = v.streamTLSConn(ctx, c, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
@@ -175,23 +163,7 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
||||
|
||||
c = mihomoVMess.StreamHTTPConn(c, httpOpts)
|
||||
case "h2":
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsOpts := mihomoVMess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
FingerPrint: v.option.Fingerprint,
|
||||
Certificate: v.option.Certificate,
|
||||
PrivateKey: v.option.PrivateKey,
|
||||
NextProtos: []string{"h2"},
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
Reality: v.realityConfig,
|
||||
}
|
||||
|
||||
if v.option.ServerName != "" {
|
||||
tlsOpts.Host = v.option.ServerName
|
||||
}
|
||||
|
||||
c, err = mihomoVMess.StreamTLSConn(ctx, c, &tlsOpts)
|
||||
c, err = v.streamTLSConn(ctx, c, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -203,29 +175,11 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
||||
|
||||
c, err = mihomoVMess.StreamH2Conn(ctx, c, h2Opts)
|
||||
case "grpc":
|
||||
break // already handle in gun transport
|
||||
break // already handle in dialContext
|
||||
default:
|
||||
// default tcp network
|
||||
// handle TLS
|
||||
if v.option.TLS {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsOpts := &mihomoVMess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
FingerPrint: v.option.Fingerprint,
|
||||
Certificate: v.option.Certificate,
|
||||
PrivateKey: v.option.PrivateKey,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
ECH: v.echConfig,
|
||||
Reality: v.realityConfig,
|
||||
NextProtos: v.option.ALPN,
|
||||
}
|
||||
|
||||
if v.option.ServerName != "" {
|
||||
tlsOpts.Host = v.option.ServerName
|
||||
}
|
||||
|
||||
c, err = mihomoVMess.StreamTLSConn(ctx, c, tlsOpts)
|
||||
}
|
||||
c, err = v.streamTLSConn(ctx, c, false)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
@@ -290,10 +244,40 @@ func (v *Vmess) streamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
||||
return
|
||||
}
|
||||
|
||||
func (v *Vmess) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (net.Conn, error) {
|
||||
if v.option.TLS {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
|
||||
tlsOpts := mihomoVMess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
FingerPrint: v.option.Fingerprint,
|
||||
Certificate: v.option.Certificate,
|
||||
PrivateKey: v.option.PrivateKey,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
ECH: v.echConfig,
|
||||
Reality: v.realityConfig,
|
||||
NextProtos: v.option.ALPN,
|
||||
}
|
||||
|
||||
if isH2 {
|
||||
tlsOpts.NextProtos = []string{"h2"}
|
||||
}
|
||||
|
||||
if v.option.ServerName != "" {
|
||||
tlsOpts.Host = v.option.ServerName
|
||||
}
|
||||
|
||||
return mihomoVMess.StreamTLSConn(ctx, conn, &tlsOpts)
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (v *Vmess) dialContext(ctx context.Context) (c net.Conn, err error) {
|
||||
switch v.option.Network {
|
||||
case "grpc": // gun transport
|
||||
return v.gunTransport.Dial()
|
||||
return v.gunClient.Dial()
|
||||
default:
|
||||
}
|
||||
return v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
@@ -350,10 +334,13 @@ func (v *Vmess) ProxyInfo() C.ProxyInfo {
|
||||
|
||||
// Close implements C.ProxyAdapter
|
||||
func (v *Vmess) Close() error {
|
||||
if v.gunTransport != nil {
|
||||
return v.gunTransport.Close()
|
||||
var errs []error
|
||||
if v.gunClient != nil {
|
||||
if err := v.gunClient.Close(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
@@ -387,19 +374,19 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
}
|
||||
|
||||
v := &Vmess{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Vmess,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
xudp: option.XUDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Type: C.Vmess,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
XUDP: option.XUDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
client: client,
|
||||
option: &option,
|
||||
}
|
||||
@@ -457,7 +444,14 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
}
|
||||
}
|
||||
|
||||
v.gunTransport = gun.NewTransport(dialFn, tlsConfig, gunConfig)
|
||||
v.gunClient = gun.NewClient(
|
||||
func() *gun.Transport {
|
||||
return gun.NewTransport(dialFn, tlsConfig, gunConfig)
|
||||
},
|
||||
option.GrpcOpts.MaxConnections,
|
||||
option.GrpcOpts.MinStreams,
|
||||
option.GrpcOpts.MaxStreams,
|
||||
)
|
||||
}
|
||||
|
||||
return v, nil
|
||||
|
||||
@@ -166,16 +166,16 @@ func (option WireGuardOption) Prefixes() ([]netip.Prefix, error) {
|
||||
|
||||
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
||||
outbound := &WireGuard{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.WireGuard,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Type: C.WireGuard,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
singDialer := proxydialer.NewSingDialer(proxydialer.NewSlowDownDialer(outbound.dialer, slowdown.New()))
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package cmd
|
||||
import (
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -34,3 +35,19 @@ func splitArgs(cmd string) []string {
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
func ExecShell(shellStr string) (string, error) {
|
||||
var cmd *exec.Cmd
|
||||
if runtime.GOOS == "windows" {
|
||||
cmd = exec.Command("cmd.exe", "/C", shellStr)
|
||||
} else {
|
||||
cmd = exec.Command("sh", "-c", shellStr)
|
||||
}
|
||||
|
||||
prepareBackgroundCommand(cmd)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%v, %s", err, string(out))
|
||||
}
|
||||
return string(out), nil
|
||||
}
|
||||
@@ -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":
|
||||
@@ -453,10 +452,18 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||
"host": pluginInfo.Get("obfs-host"),
|
||||
}
|
||||
} else if strings.Contains(pluginName, "v2ray-plugin") {
|
||||
mode := pluginInfo.Get("mode")
|
||||
if mode == "" {
|
||||
mode = pluginInfo.Get("obfs")
|
||||
}
|
||||
host := pluginInfo.Get("host")
|
||||
if host == "" {
|
||||
host = pluginInfo.Get("obfs-host")
|
||||
}
|
||||
ss["plugin"] = "v2ray-plugin"
|
||||
ss["plugin-opts"] = map[string]any{
|
||||
"mode": pluginInfo.Get("mode"),
|
||||
"host": pluginInfo.Get("host"),
|
||||
"mode": mode,
|
||||
"host": host,
|
||||
"path": pluginInfo.Get("path"),
|
||||
"tls": strings.Contains(plugin, "tls"),
|
||||
}
|
||||
|
||||
@@ -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,4 +140,115 @@ 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=ppQ9FwLrLIa0AOrp1WvcyiaQ37vg2WSy_CD4bIdiTUw&sid=6ba85179f3a2b4c5&flow=xtls-rprx-vision#My-VLESS-Reality-Vision"
|
||||
|
||||
proxies, err := ConvertsV2Ray([]byte(vlessTest))
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.Len(t, proxies, 1)
|
||||
assert.Equal(t, "tcp", proxies[0]["network"])
|
||||
assert.Equal(t, "xtls-rprx-vision", proxies[0]["flow"])
|
||||
assert.Equal(t, "none", proxies[0]["encryption"])
|
||||
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) {
|
||||
vlessTest := "vless://uuid@example.com:443?security=tls&type=tcp&headerType=http&host=cdn.example.com&path=%2Fedge&method=POST#vless-http"
|
||||
|
||||
proxies, err := ConvertsV2Ray([]byte(vlessTest))
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.Len(t, proxies, 1)
|
||||
assert.Equal(t, "http", proxies[0]["network"])
|
||||
assert.Equal(t, map[string]any{
|
||||
"method": "POST",
|
||||
"path": []string{"/edge"},
|
||||
"headers": map[string]any{
|
||||
"Host": []string{"cdn.example.com"},
|
||||
},
|
||||
}, 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) {
|
||||
vlessTest := "vless://uuid@example.com:443?security=tls&type=http&host=cdn.example.com&path=%2Fgrpc#vless-h2"
|
||||
|
||||
proxies, err := ConvertsV2Ray([]byte(vlessTest))
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
+237
-25
@@ -1,6 +1,7 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
@@ -62,7 +63,7 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
||||
network = "tcp"
|
||||
}
|
||||
fakeType := strings.ToLower(query.Get("headerType"))
|
||||
if fakeType == "http" {
|
||||
if network == "tcp" && fakeType == "http" {
|
||||
network = "http"
|
||||
} else if network == "http" {
|
||||
network = "h2"
|
||||
@@ -70,37 +71,34 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
||||
proxy["network"] = network
|
||||
switch network {
|
||||
case "tcp":
|
||||
if fakeType != "none" {
|
||||
headers := make(map[string]any)
|
||||
httpOpts := make(map[string]any)
|
||||
httpOpts["path"] = []string{"/"}
|
||||
|
||||
if host := query.Get("host"); host != "" {
|
||||
headers["Host"] = []string{host}
|
||||
}
|
||||
|
||||
if method := query.Get("method"); method != "" {
|
||||
httpOpts["method"] = method
|
||||
}
|
||||
|
||||
if path := query.Get("path"); path != "" {
|
||||
httpOpts["path"] = []string{path}
|
||||
}
|
||||
httpOpts["headers"] = headers
|
||||
proxy["http-opts"] = httpOpts
|
||||
}
|
||||
|
||||
case "http":
|
||||
headers := make(map[string]any)
|
||||
h2Opts := make(map[string]any)
|
||||
h2Opts["path"] = []string{"/"}
|
||||
httpOpts := make(map[string]any)
|
||||
httpOpts["path"] = []string{"/"}
|
||||
|
||||
if host := query.Get("host"); host != "" {
|
||||
headers["Host"] = []string{host}
|
||||
}
|
||||
|
||||
if method := query.Get("method"); method != "" {
|
||||
httpOpts["method"] = method
|
||||
}
|
||||
|
||||
if path := query.Get("path"); path != "" {
|
||||
h2Opts["path"] = []string{path}
|
||||
httpOpts["path"] = []string{path}
|
||||
}
|
||||
httpOpts["headers"] = headers
|
||||
proxy["http-opts"] = httpOpts
|
||||
|
||||
case "h2":
|
||||
h2Opts := make(map[string]any)
|
||||
h2Opts["path"] = "/"
|
||||
if path := query.Get("path"); path != "" {
|
||||
h2Opts["path"] = path
|
||||
}
|
||||
if host := query.Get("host"); host != "" {
|
||||
h2Opts["host"] = []string{host}
|
||||
}
|
||||
h2Opts["headers"] = headers
|
||||
proxy["h2-opts"] = h2Opts
|
||||
|
||||
case "ws", "httpupgrade":
|
||||
@@ -134,6 +132,220 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
||||
grpcOpts := make(map[string]any)
|
||||
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
||||
proxy["grpc-opts"] = grpcOpts
|
||||
|
||||
case "xhttp":
|
||||
proxy["network"] = "xhttp"
|
||||
xhttpOpts := make(map[string]any)
|
||||
|
||||
if path := query.Get("path"); path != "" {
|
||||
xhttpOpts["path"] = path
|
||||
}
|
||||
|
||||
if host := query.Get("host"); host != "" {
|
||||
xhttpOpts["host"] = host
|
||||
}
|
||||
|
||||
if mode := query.Get("mode"); mode != "" {
|
||||
xhttpOpts["mode"] = mode
|
||||
}
|
||||
|
||||
if extra := query.Get("extra"); extra != "" {
|
||||
var extraMap map[string]any
|
||||
if err := json.Unmarshal([]byte(extra), &extraMap); err == nil {
|
||||
parseXHTTPExtra(extraMap, xhttpOpts)
|
||||
}
|
||||
}
|
||||
|
||||
proxy["xhttp-opts"] = xhttpOpts
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseXHTTPExtra maps xray-core extra JSON fields to mihomo xhttp-opts fields.
|
||||
func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
|
||||
// xmuxToReuse converts an xmux map to mihomo reuse-settings.
|
||||
xmuxToReuse := func(xmux map[string]any) map[string]any {
|
||||
reuse := make(map[string]any)
|
||||
set := func(src, dst string) {
|
||||
if v, ok := xmux[src]; ok {
|
||||
switch val := v.(type) {
|
||||
case string:
|
||||
if val != "" {
|
||||
reuse[dst] = val
|
||||
}
|
||||
case float64:
|
||||
reuse[dst] = strconv.FormatInt(int64(val), 10)
|
||||
}
|
||||
}
|
||||
}
|
||||
set("maxConnections", "max-connections")
|
||||
set("maxConcurrency", "max-concurrency")
|
||||
set("cMaxReuseTimes", "c-max-reuse-times")
|
||||
set("hMaxRequestTimes", "h-max-request-times")
|
||||
set("hMaxReusableSecs", "h-max-reusable-secs")
|
||||
if v, ok := xmux["hKeepAlivePeriod"].(float64); ok {
|
||||
reuse["h-keep-alive-period"] = int(v)
|
||||
}
|
||||
return reuse
|
||||
}
|
||||
|
||||
if v, ok := extra["noGRPCHeader"].(bool); ok && v {
|
||||
opts["no-grpc-header"] = true
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
if addr, ok := dsAny["address"].(string); ok && addr != "" {
|
||||
ds["server"] = addr
|
||||
}
|
||||
|
||||
if port, ok := dsAny["port"].(float64); ok {
|
||||
ds["port"] = int(port)
|
||||
}
|
||||
|
||||
sec := ""
|
||||
if s, ok := dsAny["security"].(string); ok {
|
||||
sec = strings.ToLower(s)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
if fp, ok := tlsAny["fingerprint"].(string); ok && fp != "" {
|
||||
ds["client-fingerprint"] = fp
|
||||
}
|
||||
if alpnAny, ok := tlsAny["alpn"].([]any); ok && len(alpnAny) > 0 {
|
||||
alpnList := make([]string, 0, len(alpnAny))
|
||||
for _, a := range alpnAny {
|
||||
if s, ok := a.(string); ok {
|
||||
alpnList = append(alpnList, s)
|
||||
}
|
||||
}
|
||||
if len(alpnList) > 0 {
|
||||
ds["alpn"] = alpnList
|
||||
}
|
||||
}
|
||||
if v, ok := tlsAny["allowInsecure"].(bool); ok && v {
|
||||
ds["skip-cert-verify"] = true
|
||||
}
|
||||
}
|
||||
|
||||
if sec == "reality" {
|
||||
if realityAny, ok := dsAny["realitySettings"].(map[string]any); ok {
|
||||
realityOpts := make(map[string]any)
|
||||
if pk, ok := realityAny["publicKey"].(string); ok && pk != "" {
|
||||
realityOpts["public-key"] = pk
|
||||
}
|
||||
if sid, ok := realityAny["shortId"].(string); ok && sid != "" {
|
||||
realityOpts["short-id"] = sid
|
||||
}
|
||||
if len(realityOpts) > 0 {
|
||||
ds["reality-opts"] = realityOpts
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if xhttpAny, ok := dsAny["xhttpSettings"].(map[string]any); ok {
|
||||
if path, ok := xhttpAny["path"].(string); ok && path != "" {
|
||||
ds["path"] = path
|
||||
}
|
||||
if host, ok := xhttpAny["host"].(string); ok && host != "" {
|
||||
ds["host"] = host
|
||||
}
|
||||
if headers, ok := xhttpAny["headers"].(map[string]any); ok && len(headers) > 0 {
|
||||
ds["headers"] = headers
|
||||
}
|
||||
|
||||
// xmux inside downloadSettings.xhttpSettings.extra → download-settings.reuse-settings
|
||||
if dsExtraAny, ok := xhttpAny["extra"].(map[string]any); ok {
|
||||
if xmuxAny, ok := dsExtraAny["xmux"].(map[string]any); ok && len(xmuxAny) > 0 {
|
||||
if reuse := xmuxToReuse(xmuxAny); len(reuse) > 0 {
|
||||
ds["reuse-settings"] = reuse
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(ds) > 0 {
|
||||
opts["download-settings"] = ds
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -1,6 +1,10 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/exp/constraints"
|
||||
)
|
||||
|
||||
@@ -42,3 +46,58 @@ func (r Range[T]) Start() T {
|
||||
func (r Range[T]) End() T {
|
||||
return r.end
|
||||
}
|
||||
|
||||
func (r Range[T]) String() string {
|
||||
if r.start == r.end {
|
||||
return fmt.Sprintf("%v", r.start)
|
||||
}
|
||||
return fmt.Sprintf("%v-%v", r.start, r.end)
|
||||
}
|
||||
|
||||
func NewUnsignedRange[T constraints.Unsigned](expected string) (Range[T], error) {
|
||||
return newIntRange(expected, parseUnsigned[T])
|
||||
}
|
||||
|
||||
func NewSignedRange[T constraints.Signed](expected string) (Range[T], error) {
|
||||
return newIntRange(expected, parseSigned[T])
|
||||
}
|
||||
|
||||
func newIntRange[T constraints.Integer](s string, parseFn func(string) (T, error)) (Range[T], error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) == 0 {
|
||||
return NewRange[T](0, 0), nil
|
||||
}
|
||||
status := strings.Split(s, "-")
|
||||
start, err := parseFn(strings.Trim(status[0], "[ ]"))
|
||||
if err != nil {
|
||||
return Range[T]{}, fmt.Errorf("invalid range: %s", s)
|
||||
}
|
||||
switch len(status) {
|
||||
case 1: // Port range
|
||||
return NewRange(start, start), nil
|
||||
case 2: // Single port
|
||||
end, err := parseFn(strings.Trim(status[1], "[ ]"))
|
||||
if err != nil {
|
||||
return Range[T]{}, fmt.Errorf("invalid range: %s", s)
|
||||
}
|
||||
return NewRange(start, end), nil
|
||||
default:
|
||||
return Range[T]{}, fmt.Errorf("invalid range: %s", s)
|
||||
}
|
||||
}
|
||||
|
||||
func parseUnsigned[T constraints.Unsigned](s string) (T, error) {
|
||||
if val, err := strconv.ParseUint(s, 10, 64); err == nil {
|
||||
return T(val), nil
|
||||
} else {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
func parseSigned[T constraints.Signed](s string) (T, error) {
|
||||
if val, err := strconv.ParseInt(s, 10, 64); err == nil {
|
||||
return T(val), nil
|
||||
} else {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
+4
-48
@@ -4,7 +4,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/exp/constraints"
|
||||
@@ -38,41 +37,16 @@ func newIntRangesFromList[T constraints.Integer](list []string, parseFn func(str
|
||||
continue
|
||||
}
|
||||
|
||||
status := strings.Split(s, "-")
|
||||
statusLen := len(status)
|
||||
if statusLen > 2 {
|
||||
return nil, errIntRanges
|
||||
}
|
||||
|
||||
start, err := parseFn(strings.Trim(status[0], "[ ]"))
|
||||
r, err := newIntRange[T](s, parseFn)
|
||||
if err != nil {
|
||||
return nil, errIntRanges
|
||||
}
|
||||
|
||||
switch statusLen {
|
||||
case 1: // Port range
|
||||
ranges = append(ranges, NewRange(T(start), T(start)))
|
||||
case 2: // Single port
|
||||
end, err := parseFn(strings.Trim(status[1], "[ ]"))
|
||||
if err != nil {
|
||||
return nil, errIntRanges
|
||||
}
|
||||
|
||||
ranges = append(ranges, NewRange(T(start), T(end)))
|
||||
return nil, err
|
||||
}
|
||||
ranges = append(ranges, r)
|
||||
}
|
||||
|
||||
return ranges, nil
|
||||
}
|
||||
|
||||
func parseUnsigned[T constraints.Unsigned](s string) (T, error) {
|
||||
if val, err := strconv.ParseUint(s, 10, 64); err == nil {
|
||||
return T(val), nil
|
||||
} else {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
func NewUnsignedRanges[T constraints.Unsigned](expected string) (IntRanges[T], error) {
|
||||
return newIntRanges(expected, parseUnsigned[T])
|
||||
}
|
||||
@@ -81,14 +55,6 @@ func NewUnsignedRangesFromList[T constraints.Unsigned](list []string) (IntRanges
|
||||
return newIntRangesFromList(list, parseUnsigned[T])
|
||||
}
|
||||
|
||||
func parseSigned[T constraints.Signed](s string) (T, error) {
|
||||
if val, err := strconv.ParseInt(s, 10, 64); err == nil {
|
||||
return T(val), nil
|
||||
} else {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
func NewSignedRanges[T constraints.Signed](expected string) (IntRanges[T], error) {
|
||||
return newIntRanges(expected, parseSigned[T])
|
||||
}
|
||||
@@ -118,17 +84,7 @@ func (ranges IntRanges[T]) String() string {
|
||||
|
||||
terms := make([]string, len(ranges))
|
||||
for i, r := range ranges {
|
||||
start := r.Start()
|
||||
end := r.End()
|
||||
|
||||
var term string
|
||||
if start == end {
|
||||
term = strconv.Itoa(int(start))
|
||||
} else {
|
||||
term = strconv.Itoa(int(start)) + "-" + strconv.Itoa(int(end))
|
||||
}
|
||||
|
||||
terms[i] = term
|
||||
terms[i] = r.String()
|
||||
}
|
||||
|
||||
return strings.Join(terms, "/")
|
||||
|
||||
+30
-49
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -209,6 +209,12 @@ func dualStackDialContext(ctx context.Context, dialFn dialFunc, network string,
|
||||
if len(ipv4s) == 0 && len(ipv6s) == 0 {
|
||||
return nil, ErrorNoIpAddress
|
||||
}
|
||||
if len(ipv4s) == 0 && len(ipv6s) != 0 {
|
||||
return dialFn(ctx, network, ipv6s, port, opt)
|
||||
}
|
||||
if len(ipv4s) != 0 && len(ipv6s) == 0 {
|
||||
return dialFn(ctx, network, ipv4s, port, opt)
|
||||
}
|
||||
|
||||
preferIPVersion := opt.prefer
|
||||
fallbackTicker := time.NewTicker(dualStackFallbackTimeout)
|
||||
@@ -289,6 +295,9 @@ func parallelDialContext(ctx context.Context, network string, ips []netip.Addr,
|
||||
if len(ips) == 0 {
|
||||
return nil, ErrorNoIpAddress
|
||||
}
|
||||
if len(ips) == 1 {
|
||||
return dialContext(ctx, network, ips[0], port, opt)
|
||||
}
|
||||
results := make(chan dialResult)
|
||||
returned := make(chan struct{})
|
||||
defer close(returned)
|
||||
|
||||
@@ -24,6 +24,12 @@ type NetDialer interface {
|
||||
DialContext(ctx context.Context, network, address string) (net.Conn, error)
|
||||
}
|
||||
|
||||
type NetDialerFunc func(ctx context.Context, network, address string) (net.Conn, error)
|
||||
|
||||
func (f NetDialerFunc) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
return f(ctx, network, address)
|
||||
}
|
||||
|
||||
type option struct {
|
||||
interfaceName string
|
||||
fallbackBind bool
|
||||
@@ -115,6 +121,14 @@ func WithOption(o option) Option {
|
||||
}
|
||||
}
|
||||
|
||||
func WithOptions(options ...Option) Option {
|
||||
return func(opt *option) {
|
||||
for _, o := range options {
|
||||
o(opt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func IsZeroOptions(opts []Option) bool {
|
||||
return applyOptions(opts...) == option{}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -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()
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
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) {
|
||||
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) {
|
||||
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) {
|
||||
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) {
|
||||
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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -22,6 +22,7 @@ var (
|
||||
bucketFakeip6 = []byte("fakeip6")
|
||||
bucketETag = []byte("etag")
|
||||
bucketSubscriptionInfo = []byte("subscriptioninfo")
|
||||
bucketStorage = []byte("storage")
|
||||
)
|
||||
|
||||
// CacheFile store and update the cache file
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package cachefile
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
"github.com/metacubex/bbolt"
|
||||
"github.com/vmihailenco/msgpack/v5"
|
||||
)
|
||||
|
||||
const storageSizeLimit = 1024 * 1024
|
||||
const storageKeySizeLimit = 64
|
||||
const maxStorageEntries = storageSizeLimit / storageKeySizeLimit
|
||||
|
||||
type StorageData struct {
|
||||
Data []byte
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
func decodeStorageData(v []byte) (StorageData, error) {
|
||||
var storage StorageData
|
||||
if err := msgpack.Unmarshal(v, &storage); err != nil {
|
||||
return StorageData{}, err
|
||||
}
|
||||
return storage, nil
|
||||
}
|
||||
|
||||
func (c *CacheFile) GetStorage(key string) []byte {
|
||||
if c.DB == nil {
|
||||
return nil
|
||||
}
|
||||
var data []byte
|
||||
decodeFailed := false
|
||||
err := c.DB.View(func(t *bbolt.Tx) error {
|
||||
if bucket := t.Bucket(bucketStorage); bucket != nil {
|
||||
if v := bucket.Get([]byte(key)); v != nil {
|
||||
storage, err := decodeStorageData(v)
|
||||
if err != nil {
|
||||
decodeFailed = true
|
||||
return err
|
||||
}
|
||||
data = storage.Data
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnln("[CacheFile] read cache for key %s failed: %s", key, err.Error())
|
||||
if decodeFailed {
|
||||
c.DeleteStorage(key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func (c *CacheFile) SetStorage(key string, data []byte) {
|
||||
if c.DB == nil {
|
||||
return
|
||||
}
|
||||
if len(key) > storageKeySizeLimit {
|
||||
log.Warnln("[CacheFile] skip storage for key %s: key exceeds %d bytes", key, storageKeySizeLimit)
|
||||
return
|
||||
}
|
||||
if len(data) > storageSizeLimit {
|
||||
log.Warnln("[CacheFile] skip storage for key %s: payload exceeds %d bytes", key, storageSizeLimit)
|
||||
return
|
||||
}
|
||||
keyBytes := []byte(key)
|
||||
payload, err := msgpack.Marshal(StorageData{
|
||||
Data: data,
|
||||
Time: time.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = c.DB.Batch(func(t *bbolt.Tx) error {
|
||||
bucket, err := t.CreateBucketIfNotExists(bucketStorage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
type storageEntry struct {
|
||||
Key string
|
||||
Data StorageData
|
||||
}
|
||||
|
||||
entries := make(map[string]StorageData)
|
||||
usedSize := 0
|
||||
entryCount := 0
|
||||
corruptedKeys := make([][]byte, 0)
|
||||
c := bucket.Cursor()
|
||||
for k, v := c.First(); k != nil; k, v = c.Next() {
|
||||
storage, err := decodeStorageData(v)
|
||||
if err != nil {
|
||||
log.Warnln("[CacheFile] drop corrupted storage entry %s: %s", string(k), err.Error())
|
||||
corruptedKeys = append(corruptedKeys, append([]byte(nil), k...))
|
||||
continue
|
||||
}
|
||||
entryKey := string(k)
|
||||
entries[entryKey] = storage
|
||||
if entryKey != key {
|
||||
usedSize += len(storage.Data)
|
||||
entryCount++
|
||||
}
|
||||
}
|
||||
for _, k := range corruptedKeys {
|
||||
if err := bucket.Delete(k); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
evictionQueue := make([]storageEntry, 0, len(entries))
|
||||
for entryKey, storage := range entries {
|
||||
if entryKey == key {
|
||||
continue
|
||||
}
|
||||
evictionQueue = append(evictionQueue, storageEntry{
|
||||
Key: entryKey,
|
||||
Data: storage,
|
||||
})
|
||||
}
|
||||
sort.Slice(evictionQueue, func(i, j int) bool {
|
||||
left := evictionQueue[i]
|
||||
right := evictionQueue[j]
|
||||
if left.Data.Time.Equal(right.Data.Time) {
|
||||
return left.Key < right.Key
|
||||
}
|
||||
return left.Data.Time.Before(right.Data.Time)
|
||||
})
|
||||
|
||||
for _, entry := range evictionQueue {
|
||||
if usedSize+len(data) <= storageSizeLimit && entryCount < maxStorageEntries {
|
||||
break
|
||||
}
|
||||
if err := bucket.Delete([]byte(entry.Key)); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Infoln("[CacheFile] evict storage entry %s to make room for %s", entry.Key, key)
|
||||
usedSize -= len(entry.Data.Data)
|
||||
entryCount--
|
||||
}
|
||||
return bucket.Put(keyBytes, payload)
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnln("[CacheFile] write cache to %s failed: %s", c.DB.Path(), err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CacheFile) DeleteStorage(key string) {
|
||||
if c.DB == nil {
|
||||
return
|
||||
}
|
||||
err := c.DB.Batch(func(t *bbolt.Tx) error {
|
||||
bucket := t.Bucket(bucketStorage)
|
||||
if bucket == nil {
|
||||
return nil
|
||||
}
|
||||
return bucket.Delete([]byte(key))
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnln("[CacheFile] delete cache from %s failed: %s", c.DB.Path(), err.Error())
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -308,6 +308,18 @@ func BuildRemovedX25519MLKEM768HandshakeState(c *UConn) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetTLSConnectionState(conn net.Conn) (tlsState tls.ConnectionState) {
|
||||
switch tlsConn := conn.(type) {
|
||||
case interface{ ConnectionState() tls.ConnectionState }:
|
||||
state := tlsConn.ConnectionState()
|
||||
return state
|
||||
case interface{ ConnectionState() utls.ConnectionState }:
|
||||
state := tlsConn.ConnectionState()
|
||||
return tlsConnectionState(state)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var globalFingerprint string
|
||||
|
||||
func SetGlobalFingerprint(fingerprint string) {
|
||||
|
||||
+12
-2
@@ -302,6 +302,8 @@ type RawTun struct {
|
||||
IncludeAndroidUser []int `yaml:"include-android-user" json:"include-android-user,omitempty"`
|
||||
IncludePackage []string `yaml:"include-package" json:"include-package,omitempty"`
|
||||
ExcludePackage []string `yaml:"exclude-package" json:"exclude-package,omitempty"`
|
||||
IncludeMACAddress []string `yaml:"include-mac-address" json:"include-mac-address,omitempty"`
|
||||
ExcludeMACAddress []string `yaml:"exclude-mac-address" json:"exclude-mac-address,omitempty"`
|
||||
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
|
||||
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
|
||||
@@ -874,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)
|
||||
}
|
||||
@@ -911,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)
|
||||
}
|
||||
@@ -1215,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
|
||||
@@ -1680,6 +1688,8 @@ func parseTun(rawTun RawTun, dns *DNS, general *General) error {
|
||||
IncludeAndroidUser: rawTun.IncludeAndroidUser,
|
||||
IncludePackage: rawTun.IncludePackage,
|
||||
ExcludePackage: rawTun.ExcludePackage,
|
||||
IncludeMACAddress: rawTun.IncludeMACAddress,
|
||||
ExcludeMACAddress: rawTun.ExcludeMACAddress,
|
||||
EndpointIndependentNat: rawTun.EndpointIndependentNat,
|
||||
UDPTimeout: rawTun.UDPTimeout,
|
||||
DisableICMPForwarding: rawTun.DisableICMPForwarding,
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build no_tailscale
|
||||
|
||||
package features
|
||||
|
||||
const NoTailscale = true
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build !no_tailscale
|
||||
|
||||
package features
|
||||
|
||||
const NoTailscale = false
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
+18
-16
@@ -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
|
||||
}
|
||||
@@ -554,11 +551,11 @@ func (doh *dnsOverHTTPS) dialQuic(ctx context.Context, addr string, tlsCfg *tls.
|
||||
IP: net.ParseIP(ip),
|
||||
Port: portInt,
|
||||
}
|
||||
conn, err := doh.dialer.ListenPacket(ctx, "udp", addr)
|
||||
packetConn, err := doh.dialer.ListenPacket(ctx, "udp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
transport := quic.Transport{Conn: conn}
|
||||
transport := quic.Transport{Conn: packetConn}
|
||||
transport.SetCreatedConn(true) // auto close conn
|
||||
transport.SetSingleUse(true) // auto close transport
|
||||
tlsCfg = tlsCfg.Clone()
|
||||
@@ -568,7 +565,12 @@ func (doh *dnsOverHTTPS) dialQuic(ctx context.Context, addr string, tlsCfg *tls.
|
||||
// It's ok if net.SplitHostPort returns an error - it could be a hostname/IP address without a port.
|
||||
tlsCfg.ServerName = doh.url.Host
|
||||
}
|
||||
return transport.DialEarly(ctx, &udpAddr, tlsCfg, cfg)
|
||||
quicConn, err := transport.DialEarly(ctx, &udpAddr, tlsCfg, cfg)
|
||||
if err != nil {
|
||||
_ = packetConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
return quicConn, nil
|
||||
}
|
||||
|
||||
// probeH3 runs a test to check whether QUIC is faster than TLS for this
|
||||
@@ -730,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
|
||||
}
|
||||
|
||||
|
||||
+6
-5
@@ -279,7 +279,7 @@ func (doq *dnsOverQUIC) openStream(ctx context.Context, conn *quic.Conn) (*quic.
|
||||
}
|
||||
|
||||
// openConnection opens a new QUIC connection.
|
||||
func (doq *dnsOverQUIC) openConnection(ctx context.Context) (conn *quic.Conn, err error) {
|
||||
func (doq *dnsOverQUIC) openConnection(ctx context.Context) (quicConn *quic.Conn, err error) {
|
||||
// we're using bootstrapped address instead of what's passed to the function
|
||||
// it does not create an actual connection, but it helps us determine
|
||||
// what IP is actually reachable (when there're v4/v6 addresses).
|
||||
@@ -298,7 +298,7 @@ func (doq *dnsOverQUIC) openConnection(ctx context.Context) (conn *quic.Conn, er
|
||||
|
||||
p, err := strconv.Atoi(port)
|
||||
udpAddr := net.UDPAddr{IP: net.ParseIP(ip), Port: p}
|
||||
udp, err := doq.dialer.ListenPacket(ctx, "udp", addr)
|
||||
packetConn, err := doq.dialer.ListenPacket(ctx, "udp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -322,15 +322,16 @@ func (doq *dnsOverQUIC) openConnection(ctx context.Context) (conn *quic.Conn, er
|
||||
return nil, err
|
||||
}
|
||||
|
||||
transport := quic.Transport{Conn: udp}
|
||||
transport := quic.Transport{Conn: packetConn}
|
||||
transport.SetCreatedConn(true) // auto close conn
|
||||
transport.SetSingleUse(true) // auto close transport
|
||||
conn, err = transport.Dial(ctx, &udpAddr, tlsConfig, doq.getQUICConfig())
|
||||
quicConn, err = transport.Dial(ctx, &udpAddr, tlsConfig, doq.getQUICConfig())
|
||||
if err != nil {
|
||||
_ = packetConn.Close()
|
||||
return nil, fmt.Errorf("opening quic connection to %s: %w", doq.addr, err)
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
return quicConn, nil
|
||||
}
|
||||
|
||||
// closeConnWithError closes the active connection with error to make sure that
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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() {}
|
||||
@@ -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":
|
||||
|
||||
+274
-11
@@ -171,6 +171,10 @@ tun:
|
||||
#- 1000
|
||||
# exclude-uid-range: # 排除路由的的用户范围
|
||||
# - 1000:9999
|
||||
# include-mac-address:
|
||||
# - 00:11:22:33:44:55
|
||||
# exclude-mac-address:
|
||||
# - 00:11:22:33:44:55
|
||||
|
||||
# Android 用户和应用规则仅在 Android 下被支持
|
||||
# 并且需要 auto-route
|
||||
@@ -306,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 出口网卡
|
||||
|
||||
@@ -506,6 +511,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]
|
||||
@@ -670,6 +729,9 @@ proxies: # socks5
|
||||
grpc-service-name: "example"
|
||||
# grpc-user-agent: "grpc-go/1.36.0"
|
||||
# ping-interval: 0 # 默认关闭,单位为秒
|
||||
# max-connections: 1 # Maximum connections. Conflict with max-streams.
|
||||
# min-streams: 0 # Minimum multiplexed streams in a connection before opening a new connection. Conflict with max-streams.
|
||||
# max-streams: 0 # Maximum multiplexed streams in a connection before opening a new connection. Conflict with max-connections and min-streams.
|
||||
# ip-version: ipv4
|
||||
|
||||
# vless
|
||||
@@ -761,6 +823,9 @@ proxies: # socks5
|
||||
grpc-service-name: "grpc"
|
||||
# grpc-user-agent: "grpc-go/1.36.0"
|
||||
# ping-interval: 0 # 默认关闭,单位为秒
|
||||
# max-connections: 1 # Maximum connections. Conflict with max-streams.
|
||||
# min-streams: 0 # Minimum multiplexed streams in a connection before opening a new connection. Conflict with max-streams.
|
||||
# max-streams: 0 # Maximum multiplexed streams in a connection before opening a new connection. Conflict with max-connections and min-streams.
|
||||
|
||||
reality-opts:
|
||||
public-key: CrrQSjAG_YkHLwvM2M-7XkKJilgL5upBKCp0od0tLhE
|
||||
@@ -797,8 +862,7 @@ proxies: # socks5
|
||||
udp: true
|
||||
tls: true
|
||||
network: xhttp
|
||||
alpn:
|
||||
- h2
|
||||
alpn: [h2] # 默认仅支持h2,如果开启h3模式需要设置alpn: [h3],如果开启http1.1模式需要设置alpn: [http/1.1]
|
||||
# ech-opts: ...
|
||||
# reality-opts: ...
|
||||
# skip-cert-verify: false
|
||||
@@ -816,20 +880,46 @@ proxies: # socks5
|
||||
# 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"
|
||||
# c-max-reuse-times: "0"
|
||||
# h-max-request-times: "600-900"
|
||||
# h-max-reusable-secs: "1800-3000"
|
||||
# h-keep-alive-period: 0
|
||||
# download-settings:
|
||||
# ## xhttp part
|
||||
# path: "/"
|
||||
# host: xxx.com
|
||||
# headers:
|
||||
# X-Forwarded-For: ""
|
||||
# no-grpc-header: false
|
||||
# x-padding-bytes: "100-1000"
|
||||
# reuse-settings: # aka XMUX
|
||||
# max-concurrency: "16-32"
|
||||
# max-connections: "0"
|
||||
# c-max-reuse-times: "0"
|
||||
# h-max-request-times: "600-900"
|
||||
# h-max-reusable-secs: "1800-3000"
|
||||
# h-keep-alive-period: 0
|
||||
# ## proxy part
|
||||
# server: server
|
||||
# port: 443
|
||||
# tls: true
|
||||
# alpn:
|
||||
# - h2
|
||||
# alpn: ...
|
||||
# ech-opts: ...
|
||||
# reality-opts: ...
|
||||
# skip-cert-verify: false
|
||||
@@ -884,6 +974,9 @@ proxies: # socks5
|
||||
grpc-service-name: "example"
|
||||
# grpc-user-agent: "grpc-go/1.36.0"
|
||||
# ping-interval: 0 # 默认关闭,单位为秒
|
||||
# max-connections: 1 # Maximum connections. Conflict with max-streams.
|
||||
# min-streams: 0 # Minimum multiplexed streams in a connection before opening a new connection. Conflict with max-streams.
|
||||
# max-streams: 0 # Maximum multiplexed streams in a connection before opening a new connection. Conflict with max-connections and min-streams.
|
||||
|
||||
- name: trojan-ws
|
||||
server: server
|
||||
@@ -955,10 +1048,11 @@ proxies: # socks5
|
||||
server: server.com
|
||||
port: 443
|
||||
# ports: 1000,2000-3000,5000 # port 不可省略
|
||||
# hop-interval: 15
|
||||
# hop-interval: 15 # 支持填写"15-30"会每次随机选取其中一个值作为切换间隔,仅支持写一个范围(即不允许出现逗号)
|
||||
# up 和 down 均不写或为 0 则使用 BBR 流控
|
||||
# up: "30 Mbps" # 若不写单位,默认为 Mbps
|
||||
# down: "200 Mbps" # 若不写单位,默认为 Mbps
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
password: yourpassword
|
||||
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前仅支持 salamander
|
||||
# obfs-password: yourpassword
|
||||
@@ -975,6 +1069,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
|
||||
@@ -1036,6 +1142,66 @@ 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-256-GCM,默认 AES-128-GCM
|
||||
# auth: SHA256 # 目前仅支持 SHA256,默认 SHA256
|
||||
# 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: |
|
||||
-----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
|
||||
@@ -1053,6 +1219,23 @@ proxies: # socks5
|
||||
# dns: [ 1.1.1.1, 8.8.8.8 ] # 仅在 remote-dns-resolve 为 true 时生效
|
||||
# congestion-controller: bbr # 默认不开启
|
||||
|
||||
# masque-h2
|
||||
- name: "masque-h2"
|
||||
type: masque
|
||||
server: 162.159.198.2
|
||||
port: 443
|
||||
private-key: MHcCAQEEILI1eOtnbEIh89Fj4yNDuFR6UjayCKI3NdLl3DhetimWoAoGCCqGSM49AwEHoUQDQgAEgyXrE8v+hHsHy3ewSb3WcRjYgCrM9T9hiE0Uv6k2DZ1+4kefrDT9v1Q/8wdRigTf6t6gGNUV8W+IUMdrfUt+9g==
|
||||
public-key: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIaU7MToJm9NKp8YfGxR6r+/h4mcG7SxI8tsW8OR1A5tv/zCzVbCRRh2t87/kxnP6lAy0lkr7qYwu+ox+k3dr6w==
|
||||
ip: 172.16.0.2
|
||||
ipv6: 2606:4700:110:84c0:163a:4914:a0ad:3342
|
||||
mtu: 1280
|
||||
udp: true
|
||||
network: h2
|
||||
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
|
||||
# dialer-proxy: "ss1"
|
||||
# remote-dns-resolve: true # 强制 dns 远程解析,默认值为 false
|
||||
# dns: [ 1.1.1.1, 8.8.8.8 ] # 仅在 remote-dns-resolve 为 true 时生效
|
||||
|
||||
# tuic
|
||||
- name: tuic
|
||||
server: www.example.com
|
||||
@@ -1072,6 +1255,7 @@ proxies: # socks5
|
||||
udp-relay-mode: native # Available: "native", "quic". Default: "native"
|
||||
# congestion-controller: bbr # Available: "cubic", "new_reno", "bbr". Default: "cubic"
|
||||
# cwnd: 10 # default: 32
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
# max-udp-relay-packet-size: 1500
|
||||
# fast-open: true
|
||||
# skip-cert-verify: true
|
||||
@@ -1140,7 +1324,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
|
||||
@@ -1154,7 +1338,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
|
||||
@@ -1187,8 +1371,14 @@ proxies: # socks5
|
||||
# alpn:
|
||||
# - h2
|
||||
# skip-cert-verify: true
|
||||
### quic options
|
||||
# quic: true # 默认为false
|
||||
# congestion-controller: bbr
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
### reuse options
|
||||
# max-connections: 8 # Maximum connections. Conflict with max-streams.
|
||||
# min-streams: 5 # Minimum multiplexed streams in a connection before opening a new connection. Conflict with max-streams.
|
||||
# max-streams: 0 # Maximum multiplexed streams in a connection before opening a new connection. Conflict with max-connections and min-streams.
|
||||
|
||||
# dns 出站会将请求劫持到内部 dns 模块,所有请求均在内部处理
|
||||
- name: "dns-out"
|
||||
@@ -1496,6 +1686,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
|
||||
@@ -1600,6 +1793,7 @@ listeners:
|
||||
# dC5jb20AAA==
|
||||
# -----END ECH KEYS-----
|
||||
# congestion-controller: bbr
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
# max-idle-time: 15000
|
||||
# authentication-timeout: 1000
|
||||
# alpn:
|
||||
@@ -1627,6 +1821,28 @@ listeners:
|
||||
flow: xtls-rprx-vision
|
||||
# ws-path: "/" # 如果不为空则开启 websocket 传输层
|
||||
# grpc-service-name: "GunService" # 如果不为空则开启 grpc 传输层
|
||||
# xhttp-config: # 如果不为空则开启 xhttp 传输层
|
||||
# path: "/"
|
||||
# host: ""
|
||||
# mode: auto # Available: "stream-one", "stream-up" or "packet-up"
|
||||
# no-sse-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-buffered-posts: 30
|
||||
# sc-stream-up-server-secs: "20-80"
|
||||
# sc-max-each-post-bytes: 1000000
|
||||
# -------------------------
|
||||
# vless encryption服务端配置:
|
||||
# (原生外观 / 只 XOR 公钥 / 全随机数。1-RTT 每次下发随机 300 到 600 秒的 ticket 以便 0-RTT 复用 / 只允许 1-RTT)
|
||||
@@ -1705,20 +1921,22 @@ listeners:
|
||||
username2: password2
|
||||
# 一个 base64 字符串用于微调网络行为
|
||||
# traffic-pattern: ""
|
||||
# 如果开启,且客户端不发送用户提示,代理服务器将拒绝连接
|
||||
# user-hint-is-mandatory: false
|
||||
|
||||
- name: sudoku-in-1
|
||||
type: sudoku
|
||||
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 伪装/隧道
|
||||
@@ -1803,6 +2021,7 @@ listeners:
|
||||
# down: "200 Mbps" # 若不写单位,默认为 Mbps
|
||||
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前仅支持 salamander
|
||||
# obfs-password: yourpassword
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
# max-idle-time: 15000
|
||||
# alpn:
|
||||
# - h3
|
||||
@@ -1811,6 +2030,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
|
||||
@@ -1825,6 +2082,7 @@ listeners:
|
||||
private-key: ./server.key # 证书对应的私钥 PEM 格式,或者私钥路径
|
||||
network: ["tcp", "udp"] # http2+http3
|
||||
congestion-controller: bbr
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
# 下面两项为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 格式,或者 证书的路径
|
||||
@@ -1867,6 +2125,10 @@ listeners:
|
||||
# - 1000
|
||||
# exclude-uid-range: # 排除路由的的用户范围
|
||||
# - 1000:99999
|
||||
# include-mac-address:
|
||||
# - 00:11:22:33:44:55
|
||||
# exclude-mac-address:
|
||||
# - 00:11:22:33:44:55
|
||||
|
||||
# Android 用户和应用规则仅在 Android 下被支持
|
||||
# 并且需要 auto-route
|
||||
@@ -1896,6 +2158,7 @@ listeners:
|
||||
# certificate: ./server.crt
|
||||
# private-key: ./server.key
|
||||
# congestion-controller: bbr
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
# max-idle-time: 15000
|
||||
# authentication-timeout: 1000
|
||||
# alpn:
|
||||
|
||||
@@ -5,8 +5,8 @@ go 1.20
|
||||
require (
|
||||
github.com/bahlo/generic-list-go v0.2.0
|
||||
github.com/coreos/go-iptables v0.8.0
|
||||
github.com/dlclark/regexp2 v1.11.5
|
||||
github.com/enfein/mieru/v3 v3.30.0
|
||||
github.com/dlclark/regexp2 v1.12.0
|
||||
github.com/enfein/mieru/v3 v3.31.0
|
||||
github.com/gobwas/ws v1.4.0
|
||||
github.com/gofrs/uuid/v5 v5.4.0
|
||||
github.com/golang/snappy v1.0.0
|
||||
@@ -16,30 +16,32 @@ require (
|
||||
github.com/metacubex/blake3 v0.1.0
|
||||
github.com/metacubex/chacha v0.1.5
|
||||
github.com/metacubex/chi v0.1.0
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260128031117-1cad62060727
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260412152424-e1625567920a
|
||||
github.com/metacubex/cpu v0.1.1
|
||||
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.0
|
||||
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.20260213014310-4df8f0de5b56
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306
|
||||
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.5
|
||||
github.com/metacubex/sing-quic v0.0.0-20260112044712-65d17608159e
|
||||
github.com/metacubex/sing-mux v0.3.9
|
||||
github.com/metacubex/sing-quic v0.0.0-20260512151354-8475655be853
|
||||
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.16
|
||||
github.com/metacubex/sing-tun v0.4.18
|
||||
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-20260507084707-690d479ec947
|
||||
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141
|
||||
github.com/metacubex/ssh v0.1.0
|
||||
github.com/metacubex/tailscale v0.0.0-20260516120020-a21c2c99dcbe
|
||||
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443
|
||||
github.com/metacubex/tls v0.1.4
|
||||
github.com/metacubex/tls v0.1.5
|
||||
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
|
||||
@@ -74,7 +76,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 +87,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-20260513175203-1c6abea7534c // 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-20260513233728-8bc7ee255d04 // 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
|
||||
|
||||
@@ -5,23 +5,30 @@ 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=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
|
||||
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8=
|
||||
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.30.0 h1:g7v0TuK7y0ZMn6TOdjOs8WEUQk8bvs6WYPBJ16SKdBU=
|
||||
github.com/enfein/mieru/v3 v3.30.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
|
||||
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/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=
|
||||
@@ -87,8 +105,8 @@ github.com/metacubex/chacha v0.1.5 h1:fKWMb/5c7ZrY8Uoqi79PPFxl+qwR7X/q0OrsAubyX2
|
||||
github.com/metacubex/chacha v0.1.5/go.mod h1:Djn9bPZxLTXbJFSeyo0/qzEzQI+gUSSzttuzZM75GH8=
|
||||
github.com/metacubex/chi v0.1.0 h1:rjNDyDj50nRpicG43CNkIw4ssiCbmDL8d7wJXKlUCsg=
|
||||
github.com/metacubex/chi v0.1.0/go.mod h1:zM5u5oMQt8b2DjvDHvzadKrP6B2ztmasL1YHRMbVV+g=
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260128031117-1cad62060727 h1:qbZQ0sO0bDBKPvTd/qNQK6513300WJ5GRsHnw3PO4Ho=
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260128031117-1cad62060727/go.mod h1:xYC8Ik7/rN6no+vTRuWMEziGwm3brA0wNM/zZP9qhOQ=
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260412152424-e1625567920a h1:Ph5UfTWDsGruZ+v95Df1ycTflQFmpZBFg2LUvj2kx/M=
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260412152424-e1625567920a/go.mod h1:xYC8Ik7/rN6no+vTRuWMEziGwm3brA0wNM/zZP9qhOQ=
|
||||
github.com/metacubex/cpu v0.1.1 h1:rRV5HGmeuGzjiKI3hYbL0dCd0qGwM7VUtk4ICXD06mI=
|
||||
github.com/metacubex/cpu v0.1.1/go.mod h1:09VEt4dSRLR+bOA8l4w4NDuzGZ8n5dkMv7e8axgEeTU=
|
||||
github.com/metacubex/edwards25519 v1.2.0 h1:pIQZLBsjQgg3Nl/c86YYFEUAbL5qQRnPq4LrgIw0KK4=
|
||||
@@ -103,50 +121,58 @@ 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.0 h1:Jcy0I9zKjYijSUaksZU34XEe2xNdoFkgUTB7z7K5q0o=
|
||||
github.com/metacubex/http v0.1.0/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-20260513175203-1c6abea7534c h1:KGhBHDe6FveU0ury+9RyX329nclM1CHODa0Fi+uOAYM=
|
||||
github.com/metacubex/jsonv2 v0.0.0-20260513175203-1c6abea7534c/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.20260213014310-4df8f0de5b56 h1:7yfF31COW2hiCovb5+3uSxRl3UKWOXjpS0j4N5U0qZ8=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260213014310-4df8f0de5b56/go.mod h1:oNzMrmylS897M3zSMuapIdwSwfq6F2qW01Z3NhVRJhk=
|
||||
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/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=
|
||||
github.com/metacubex/restls-client-go v0.1.7/go.mod h1:BN/U52vPw7j8VTSh2vleD/MnmVKCov84mS5VcjVHH4g=
|
||||
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.5 h1:UqVN+o62SR8kJaC9/3VfOc5UiVqgVY/ef9WwfGYYkk0=
|
||||
github.com/metacubex/sing-mux v0.3.5/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260112044712-65d17608159e h1:MLxp42z9Jd6LtY2suyawnl24oNzIsFxWc15bNeDIGxA=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260112044712-65d17608159e/go.mod h1:+lgKTd52xAarGtqugALISShyw4KxnoEpYe2u0zJh26w=
|
||||
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-20260512151354-8475655be853 h1:nZ5WNU6kjj6kBu4+2eMySFkUVGCop64rZnLMm+HPh8w=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260512151354-8475655be853/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.16 h1:LosAe4A6TOPVcD7T1ReV9D2r5501woIXXZiim3D0RRg=
|
||||
github.com/metacubex/sing-tun v0.4.16/go.mod h1:L/TjQY5JEGy8nvsuYmy/XgMFMCPiF0+AWSFCYfS6r9w=
|
||||
github.com/metacubex/sing-tun v0.4.18 h1:WRzAosG0YkT3aZq5RJWtF+RdCgeJ8EpooS5ZM1lkXo0=
|
||||
github.com/metacubex/sing-tun v0.4.18/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-20260507084707-690d479ec947 h1:IB03BvRQtvjWScyOK5jSQVJYY8osmZXHL+4VCEFMWcM=
|
||||
github.com/metacubex/sing-wireguard v0.0.0-20260507084707-690d479ec947/go.mod h1:jpAkVLPnCpGSfNyVmj6Cq4YbuZsFepm/Dc+9BAOcR80=
|
||||
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-20260516120020-a21c2c99dcbe h1:ZdAKshacNruZGuKTE8WMTuxyGgpv/LySLoE/EEmgF9c=
|
||||
github.com/metacubex/tailscale v0.0.0-20260516120020-a21c2c99dcbe/go.mod h1:2G1V82OGXgxT7m7046GA80I9SlcvczljCK0C7NQ3c10=
|
||||
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260513233728-8bc7ee255d04 h1:zk+mDDSBl5lv80WWtaFUbpj8XLb7AhjCUbn2pB37N0U=
|
||||
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260513233728-8bc7ee255d04/go.mod h1:pKUKBy7IcQ5r0i66gWENHgxKvBn8tlgAGx0DZMq8h5M=
|
||||
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.4 h1:Gm5GrkyMUh52gYOMIAQ1kHIym4v4M3Qb87Wsmd8Kpdc=
|
||||
github.com/metacubex/tls v0.1.4/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
|
||||
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/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,14 @@ 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/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 +222,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 +253,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 +271,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 +283,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 +305,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=
|
||||
@@ -93,6 +93,8 @@ type tunSchema struct {
|
||||
IncludeAndroidUser *[]int `yaml:"include-android-user" json:"include-android-user,omitempty"`
|
||||
IncludePackage *[]string `yaml:"include-package" json:"include-package,omitempty"`
|
||||
ExcludePackage *[]string `yaml:"exclude-package" json:"exclude-package,omitempty"`
|
||||
IncludeMACAddress *[]string `yaml:"include-mac-address" json:"include-mac-address,omitempty"`
|
||||
ExcludeMACAddress *[]string `yaml:"exclude-mac-address" json:"exclude-mac-address,omitempty"`
|
||||
EndpointIndependentNat *bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout *int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
|
||||
FileDescriptor *int `yaml:"file-descriptor" json:"file-descriptor"`
|
||||
@@ -120,6 +122,7 @@ type tuicServerSchema struct {
|
||||
ALPN *[]string `yaml:"alpn" json:"alpn,omitempty"`
|
||||
MaxUdpRelayPacketSize *int `yaml:"max-udp-relay-packet-size" json:"max-udp-relay-packet-size,omitempty"`
|
||||
CWND *int `yaml:"cwnd" json:"cwnd,omitempty"`
|
||||
BBRProfile *string `yaml:"bbr-profile" json:"bbr-profile,omitempty"`
|
||||
}
|
||||
|
||||
func getConfigs(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -242,6 +245,12 @@ func pointerOrDefaultTun(p *tunSchema, def LC.Tun) LC.Tun {
|
||||
if p.ExcludePackage != nil {
|
||||
def.ExcludePackage = *p.ExcludePackage
|
||||
}
|
||||
if p.IncludeMACAddress != nil {
|
||||
def.IncludeMACAddress = *p.IncludeMACAddress
|
||||
}
|
||||
if p.ExcludeMACAddress != nil {
|
||||
def.ExcludeMACAddress = *p.ExcludeMACAddress
|
||||
}
|
||||
if p.EndpointIndependentNat != nil {
|
||||
def.EndpointIndependentNat = *p.EndpointIndependentNat
|
||||
}
|
||||
@@ -297,6 +306,9 @@ func pointerOrDefaultTuicServer(p *tuicServerSchema, def LC.TuicServer) LC.TuicS
|
||||
if p.CWND != nil {
|
||||
def.CWND = *p.CWND
|
||||
}
|
||||
if p.BBRProfile != nil {
|
||||
def.BBRProfile = *p.BBRProfile
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
@@ -132,6 +132,7 @@ func router(isDebug bool, secret string, dohServer string, cors Cors) *chi.Mux {
|
||||
r.Mount("/providers/rules", ruleProviderRouter())
|
||||
r.Mount("/cache", cacheRouter())
|
||||
r.Mount("/dns", dnsRouter())
|
||||
r.Mount("/storage", storageRouter())
|
||||
if !embedMode { // disallow restart in embed mode
|
||||
r.Mount("/restart", restartRouter())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
|
||||
"github.com/metacubex/mihomo/component/profile/cachefile"
|
||||
|
||||
"github.com/metacubex/chi"
|
||||
"github.com/metacubex/chi/render"
|
||||
"github.com/metacubex/http"
|
||||
)
|
||||
|
||||
func storageRouter() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Get("/{key}", getStorage)
|
||||
r.Put("/{key}", setStorage)
|
||||
r.Delete("/{key}", deleteStorage)
|
||||
return r
|
||||
}
|
||||
|
||||
func getStorage(w http.ResponseWriter, r *http.Request) {
|
||||
key := getEscapeParam(r, "key")
|
||||
data := cachefile.Cache().GetStorage(key)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if len(data) == 0 {
|
||||
w.Write([]byte("null"))
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}
|
||||
|
||||
func setStorage(w http.ResponseWriter, r *http.Request) {
|
||||
key := getEscapeParam(r, "key")
|
||||
data, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
render.Status(r, http.StatusBadRequest)
|
||||
render.JSON(w, r, newError(err.Error()))
|
||||
return
|
||||
}
|
||||
if !json.Valid(data) {
|
||||
render.Status(r, http.StatusBadRequest)
|
||||
render.JSON(w, r, ErrBadRequest)
|
||||
return
|
||||
}
|
||||
if len(data) > 1024*1024 {
|
||||
render.Status(r, http.StatusRequestEntityTooLarge)
|
||||
render.JSON(w, r, newError("payload exceeds 1MB limit"))
|
||||
return
|
||||
}
|
||||
cachefile.Cache().SetStorage(key, data)
|
||||
render.NoContent(w, r)
|
||||
}
|
||||
|
||||
func deleteStorage(w http.ResponseWriter, r *http.Request) {
|
||||
key := getEscapeParam(r, "key")
|
||||
cachefile.Cache().DeleteStorage(key)
|
||||
render.NoContent(w, r)
|
||||
}
|
||||
@@ -24,9 +24,12 @@ type Hysteria2Server struct {
|
||||
IgnoreClientBandwidth bool `yaml:"ignore-client-bandwidth" json:"ignore-client-bandwidth,omitempty"`
|
||||
Masquerade string `yaml:"masquerade" json:"masquerade,omitempty"`
|
||||
CWND int `yaml:"cwnd" json:"cwnd,omitempty"`
|
||||
BBRProfile string `yaml:"bbr-profile" json:"bbr-profile,omitempty"`
|
||||
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"`
|
||||
@@ -34,6 +37,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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -16,6 +16,7 @@ type TrustTunnelServer struct {
|
||||
Network []string `yaml:"network" json:"network,omitempty"`
|
||||
CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
|
||||
CWND int `yaml:"cwnd" json:"cwnd,omitempty"`
|
||||
BBRProfile string `yaml:"bbr-profile" json:"bbr-profile,omitempty"`
|
||||
}
|
||||
|
||||
func (t TrustTunnelServer) String() string {
|
||||
|
||||
@@ -23,6 +23,7 @@ type TuicServer struct {
|
||||
MaxUdpRelayPacketSize int `yaml:"max-udp-relay-packet-size" json:"max-udp-relay-packet-size,omitempty"`
|
||||
MaxDatagramFrameSize int `yaml:"max-datagram-frame-size" json:"max-datagram-frame-size,omitempty"`
|
||||
CWND int `yaml:"cwnd" json:"cwnd,omitempty"`
|
||||
BBRProfile string `yaml:"bbr-profile" json:"bbr-profile,omitempty"`
|
||||
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,8 @@ type Tun struct {
|
||||
IncludeAndroidUser []int `yaml:"include-android-user" json:"include-android-user,omitempty"`
|
||||
IncludePackage []string `yaml:"include-package" json:"include-package,omitempty"`
|
||||
ExcludePackage []string `yaml:"exclude-package" json:"exclude-package,omitempty"`
|
||||
IncludeMACAddress []string `yaml:"include-mac-address" json:"include-mac-address,omitempty"`
|
||||
ExcludeMACAddress []string `yaml:"exclude-mac-address" json:"exclude-mac-address,omitempty"`
|
||||
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
|
||||
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
|
||||
@@ -80,6 +82,8 @@ func (t *Tun) Sort() {
|
||||
slices.Sort(t.IncludeAndroidUser)
|
||||
slices.Sort(t.IncludePackage)
|
||||
slices.Sort(t.ExcludePackage)
|
||||
slices.Sort(t.IncludeMACAddress)
|
||||
slices.Sort(t.ExcludeMACAddress)
|
||||
|
||||
slices.SortFunc(t.Inet4RouteAddress, netipx.ComparePrefix)
|
||||
slices.SortFunc(t.Inet6RouteAddress, netipx.ComparePrefix)
|
||||
@@ -185,6 +189,12 @@ func (t *Tun) Equal(other Tun) bool {
|
||||
if !slices.Equal(t.ExcludePackage, other.ExcludePackage) {
|
||||
return false
|
||||
}
|
||||
if !slices.Equal(t.IncludeMACAddress, other.IncludeMACAddress) {
|
||||
return false
|
||||
}
|
||||
if !slices.Equal(t.ExcludeMACAddress, other.ExcludeMACAddress) {
|
||||
return false
|
||||
}
|
||||
if t.EndpointIndependentNat != other.EndpointIndependentNat {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -31,9 +31,27 @@ type VlessServer struct {
|
||||
}
|
||||
|
||||
type XHTTPConfig struct {
|
||||
Path string
|
||||
Host string
|
||||
Mode string
|
||||
Path string
|
||||
Host string
|
||||
Mode string
|
||||
XPaddingBytes string
|
||||
XPaddingObfsMode bool
|
||||
XPaddingKey string
|
||||
XPaddingHeader string
|
||||
XPaddingPlacement string
|
||||
XPaddingMethod string
|
||||
UplinkHTTPMethod string
|
||||
SessionPlacement string
|
||||
SessionKey string
|
||||
SeqPlacement string
|
||||
SeqKey string
|
||||
UplinkDataPlacement string
|
||||
UplinkDataKey string
|
||||
UplinkChunkSize string
|
||||
NoSSEHeader bool
|
||||
ScStreamUpServerSecs string
|
||||
ScMaxBufferedPosts string
|
||||
ScMaxEachPostBytes string
|
||||
}
|
||||
|
||||
func (t VlessServer) String() string {
|
||||
|
||||
+15
-12
@@ -43,11 +43,10 @@ func HandleConn(c net.Conn, tunnel C.Tunnel, store auth.AuthStore, additions ...
|
||||
conn := N.NewBufferedConn(c)
|
||||
|
||||
authenticator := store.Authenticator()
|
||||
keepAlive := true
|
||||
trusted := authenticator == nil // disable authenticate if lru is nil
|
||||
lastUser := ""
|
||||
|
||||
for keepAlive {
|
||||
for {
|
||||
peekMutex.Lock()
|
||||
request, err := ReadRequest(conn.Reader())
|
||||
peekMutex.Unlock()
|
||||
@@ -57,13 +56,12 @@ func HandleConn(c net.Conn, tunnel C.Tunnel, store auth.AuthStore, additions ...
|
||||
|
||||
request.RemoteAddr = conn.RemoteAddr().String()
|
||||
|
||||
keepAlive = strings.TrimSpace(strings.ToLower(request.Header.Get("Proxy-Connection"))) == "keep-alive"
|
||||
keepAlive := strings.TrimSpace(strings.ToLower(request.Header.Get("Proxy-Connection"))) == "keep-alive"
|
||||
|
||||
var resp *http.Response
|
||||
|
||||
var user string
|
||||
resp, user = authenticate(request, authenticator) // always call authenticate function to get user
|
||||
trusted = trusted || resp == nil
|
||||
resp, user := authenticate(request, authenticator) // always call authenticate function to get user
|
||||
if resp == nil {
|
||||
trusted = true
|
||||
}
|
||||
additions[inUserIdx] = inbound.WithInUser(user)
|
||||
|
||||
if trusted {
|
||||
@@ -130,16 +128,21 @@ func HandleConn(c net.Conn, tunnel C.Tunnel, store auth.AuthStore, additions ...
|
||||
removeHopByHopHeaders(resp.Header)
|
||||
}
|
||||
|
||||
if keepAlive {
|
||||
if !keepAlive {
|
||||
resp.Close = true // close connection if keep-alive is not set
|
||||
}
|
||||
if keepAlive && resp.ContentLength > 0 {
|
||||
resp.Close = false // don't need to close connection if content length is positive numbers
|
||||
}
|
||||
|
||||
if !resp.Close {
|
||||
resp.Header.Set("Proxy-Connection", "keep-alive")
|
||||
resp.Header.Set("Connection", "keep-alive")
|
||||
resp.Header.Set("Keep-Alive", "timeout=4")
|
||||
}
|
||||
|
||||
resp.Close = !keepAlive
|
||||
|
||||
err = resp.Write(conn)
|
||||
if err != nil {
|
||||
if err != nil || resp.Close {
|
||||
break // close connection
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
// Package hysteria2_realm copy and modify from:
|
||||
// https://github.com/apernet/hysteria-realm-server/tree/1ec22609705b5896df17d4ae4bfb2a1675cdb606
|
||||
package hysteria2_realm
|
||||
@@ -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...)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -41,6 +41,8 @@ func testInboundAnyTLS(t *testing.T, inboundOptions inbound.AnyTLSOption, outbou
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
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) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -57,6 +58,30 @@ func init() {
|
||||
realityPublickey = base64.RawURLEncoding.EncodeToString(privateKey.PublicKey().Bytes())
|
||||
}
|
||||
|
||||
type TestDialer struct {
|
||||
dialer C.Dialer
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (t *TestDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
start:
|
||||
conn, err := t.dialer.DialContext(ctx, network, address)
|
||||
if err != nil && ctx.Err() == nil && t.ctx.Err() == nil {
|
||||
// We are conducting tests locally, and they shouldn't fail.
|
||||
// However, a large number of requests in a short period during concurrent testing can exhaust system ports.
|
||||
// This can lead to various errors such as WSAECONNREFUSED and WSAENOBUFS.
|
||||
// So we just retry if the context is not canceled.
|
||||
goto start
|
||||
}
|
||||
return conn, err
|
||||
}
|
||||
|
||||
func (t *TestDialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
||||
return t.dialer.ListenPacket(ctx, network, address, rAddrPort)
|
||||
}
|
||||
|
||||
var _ C.Dialer = (*TestDialer)(nil)
|
||||
|
||||
type TestTunnel struct {
|
||||
HandleTCPConnFn func(conn net.Conn, metadata *C.Metadata)
|
||||
HandleUDPPacketFn func(packet C.UDPPacket, metadata *C.Metadata)
|
||||
@@ -64,6 +89,7 @@ type TestTunnel struct {
|
||||
CloseFn func() error
|
||||
DoSequentialTestFn func(t *testing.T, proxy C.ProxyAdapter)
|
||||
DoConcurrentTestFn func(t *testing.T, proxy C.ProxyAdapter)
|
||||
NewDialerFn func() C.Dialer
|
||||
}
|
||||
|
||||
func (tt *TestTunnel) HandleTCPConn(conn net.Conn, metadata *C.Metadata) {
|
||||
@@ -95,6 +121,10 @@ func (tt *TestTunnel) DoConcurrentTest(t *testing.T, proxy C.ProxyAdapter) {
|
||||
tt.DoConcurrentTestFn(t, proxy)
|
||||
}
|
||||
|
||||
func (tt *TestTunnel) NewDialer() C.Dialer {
|
||||
return tt.NewDialerFn()
|
||||
}
|
||||
|
||||
type TestTunnelListener struct {
|
||||
ch chan net.Conn
|
||||
ctx context.Context
|
||||
@@ -182,15 +212,39 @@ func NewHttpTestTunnel() *TestTunnel {
|
||||
}
|
||||
defer instance.Close()
|
||||
|
||||
var dialNum atomic.Int32
|
||||
var extraConns []net.Conn
|
||||
var extraConnsMu sync.Mutex
|
||||
defer func() {
|
||||
extraConnsMu.Lock()
|
||||
extraConns := append([]net.Conn{}, extraConns...) // clone conn list avoid race condition
|
||||
extraConnsMu.Unlock()
|
||||
for _, conn := range extraConns {
|
||||
_ = conn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
transport := &http.Transport{
|
||||
DialContext: func(context.Context, string, string) (net.Conn, error) {
|
||||
return instance, nil
|
||||
DialContext: func(ctx context.Context, network string, addr string) (net.Conn, error) {
|
||||
dianNum := dialNum.Add(1)
|
||||
if dianNum == 1 { // first dial, return instance
|
||||
return instance, nil
|
||||
}
|
||||
t.Logf("transport dial time %d more than once in: %s", dianNum, t.Name())
|
||||
conn, err := proxy.DialContext(ctx, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
extraConnsMu.Lock()
|
||||
extraConns = append(extraConns, conn)
|
||||
extraConnsMu.Unlock()
|
||||
return conn, nil
|
||||
},
|
||||
// from http.DefaultTransport
|
||||
MaxIdleConns: 100,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
//// from http.DefaultTransport
|
||||
//MaxIdleConns: 100,
|
||||
//IdleConnTimeout: 90 * time.Second,
|
||||
//TLSHandshakeTimeout: 10 * time.Second,
|
||||
//ExpectContinueTimeout: 1 * time.Second,
|
||||
// for our self-signed cert
|
||||
TLSClientConfig: tlsClientConfig.Clone(),
|
||||
// open http2
|
||||
@@ -198,7 +252,7 @@ func NewHttpTestTunnel() *TestTunnel {
|
||||
}
|
||||
|
||||
client := http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Timeout: 60 * time.Second,
|
||||
Transport: transport,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
@@ -284,8 +338,8 @@ func NewHttpTestTunnel() *TestTunnel {
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, C.DefaultTLSTimeout)
|
||||
defer cancel()
|
||||
//ctx, cancel := context.WithTimeout(ctx, C.DefaultTLSTimeout)
|
||||
//defer cancel()
|
||||
if err := tlsConn.HandshakeContext(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -300,9 +354,13 @@ func NewHttpTestTunnel() *TestTunnel {
|
||||
}
|
||||
<-c.ch
|
||||
},
|
||||
HandleUDPPacketFn: func(packet C.UDPPacket, metadata *C.Metadata) {
|
||||
// TODO
|
||||
},
|
||||
CloseFn: ln.Close,
|
||||
DoSequentialTestFn: sequentialTestFn,
|
||||
DoConcurrentTestFn: concurrentTestFn,
|
||||
NewDialerFn: func() C.Dialer { return &TestDialer{dialer: dialer.NewDialer(), ctx: ctx} },
|
||||
}
|
||||
return tunnel
|
||||
}
|
||||
@@ -26,9 +26,12 @@ type Hysteria2Option struct {
|
||||
IgnoreClientBandwidth bool `inbound:"ignore-client-bandwidth,omitempty"`
|
||||
Masquerade string `inbound:"masquerade,omitempty"`
|
||||
CWND int `inbound:"cwnd,omitempty"`
|
||||
BBRProfile string `inbound:"bbr-profile,omitempty"`
|
||||
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"`
|
||||
@@ -36,6 +39,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)
|
||||
}
|
||||
@@ -73,8 +110,10 @@ func NewHysteria2(options *Hysteria2Option) (*Hysteria2, error) {
|
||||
IgnoreClientBandwidth: options.IgnoreClientBandwidth,
|
||||
Masquerade: options.Masquerade,
|
||||
CWND: options.CWND,
|
||||
BBRProfile: options.BBRProfile,
|
||||
UdpMTU: options.UdpMTU,
|
||||
MuxOption: options.MuxOption.Build(),
|
||||
RealmOpts: options.RealmOpts.Build(),
|
||||
// quic-go special config
|
||||
InitialStreamReceiveWindow: options.InitialStreamReceiveWindow,
|
||||
MaxStreamReceiveWindow: options.MaxStreamReceiveWindow,
|
||||
|
||||
@@ -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)
|
||||
@@ -41,6 +41,8 @@ func testInboundHysteria2(t *testing.T, inboundOptions inbound.Hysteria2Option,
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
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) {
|
||||
|
||||
@@ -27,9 +27,10 @@ type Mieru struct {
|
||||
|
||||
type MieruOption struct {
|
||||
BaseOption
|
||||
Transport string `inbound:"transport"`
|
||||
Users map[string]string `inbound:"users"`
|
||||
TrafficPattern string `inbound:"traffic-pattern,omitempty"`
|
||||
Transport string `inbound:"transport"`
|
||||
Users map[string]string `inbound:"users"`
|
||||
TrafficPattern string `inbound:"traffic-pattern,omitempty"`
|
||||
UserHintIsMandatory bool `inbound:"user-hint-is-mandatory,omitempty"`
|
||||
}
|
||||
|
||||
type mieruListenerFactory struct{}
|
||||
@@ -158,11 +159,18 @@ func buildMieruServerConfig(option *MieruOption, ports utils.IntRanges[uint16])
|
||||
}
|
||||
var trafficPattern *mierupb.TrafficPattern
|
||||
trafficPattern, _ = mierutp.Decode(option.TrafficPattern)
|
||||
var advancedSettings *mierupb.ServerAdvancedSettings
|
||||
if option.UserHintIsMandatory {
|
||||
advancedSettings = &mierupb.ServerAdvancedSettings{
|
||||
UserHintIsMandatory: proto.Bool(true),
|
||||
}
|
||||
}
|
||||
return &mieruserver.ServerConfig{
|
||||
Config: &mierupb.ServerConfig{
|
||||
PortBindings: portBindings,
|
||||
Users: users,
|
||||
TrafficPattern: trafficPattern,
|
||||
PortBindings: portBindings,
|
||||
Users: users,
|
||||
TrafficPattern: trafficPattern,
|
||||
AdvancedSettings: advancedSettings,
|
||||
},
|
||||
StreamListenerFactory: mieruListenerFactory{},
|
||||
PacketListenerFactory: mieruListenerFactory{},
|
||||
|
||||
@@ -206,8 +206,9 @@ func testInboundMieruTCP(t *testing.T, handshakeMode string) {
|
||||
Listen: "127.0.0.1",
|
||||
Port: strconv.Itoa(port),
|
||||
},
|
||||
Transport: "TCP",
|
||||
Users: map[string]string{"test": "password"},
|
||||
Transport: "TCP",
|
||||
Users: map[string]string{"test": "password"},
|
||||
UserHintIsMandatory: true,
|
||||
}
|
||||
in, err := inbound.NewMieru(&inboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
@@ -236,6 +237,8 @@ func testInboundMieruTCP(t *testing.T, handshakeMode string) {
|
||||
Password: "password",
|
||||
HandshakeMode: handshakeMode,
|
||||
}
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
outboundOptions.TunnelForAPI = tunnel
|
||||
out, err := outbound.NewMieru(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
@@ -260,8 +263,9 @@ func testInboundMieruUDP(t *testing.T, handshakeMode string) {
|
||||
Listen: "127.0.0.1",
|
||||
Port: strconv.Itoa(port),
|
||||
},
|
||||
Transport: "UDP",
|
||||
Users: map[string]string{"test": "password"},
|
||||
Transport: "UDP",
|
||||
Users: map[string]string{"test": "password"},
|
||||
UserHintIsMandatory: true,
|
||||
}
|
||||
in, err := inbound.NewMieru(&inboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
@@ -290,6 +294,7 @@ func testInboundMieruUDP(t *testing.T, handshakeMode string) {
|
||||
Password: "password",
|
||||
HandshakeMode: handshakeMode,
|
||||
}
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
out, err := outbound.NewMieru(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
|
||||
@@ -28,7 +28,6 @@ func testSingMux(t *testing.T, tunnel *TestTunnel, out outbound.ProxyAdapter) {
|
||||
for _, protocol := range singMuxProtocolList {
|
||||
protocol := protocol
|
||||
t.Run(protocol, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
singMuxOption := outbound.SingMuxOption{
|
||||
Enabled: true,
|
||||
Protocol: protocol,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Loaded 100 of 198 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user