mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-11-27 22:18:32 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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,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
-17
@@ -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,20 +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 == '' }}
|
||||
@@ -312,6 +298,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 +328,8 @@ jobs:
|
||||
mihomo*.rpm
|
||||
mihomo*.pkg.tar.zst
|
||||
mihomo*.zip
|
||||
toolchain.tar.gz
|
||||
vendor.tar.gz
|
||||
version.txt
|
||||
checksums.txt
|
||||
|
||||
@@ -378,7 +381,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 +443,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())
|
||||
|
||||
+35
-34
@@ -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.NewUUIDV6(),
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -188,34 +217,6 @@ 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,
|
||||
}
|
||||
}
|
||||
|
||||
type conn struct {
|
||||
N.ExtendedConn
|
||||
chain C.Chain
|
||||
|
||||
+23
-23
@@ -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,
|
||||
}),
|
||||
}
|
||||
}
|
||||
+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,
|
||||
|
||||
@@ -11,21 +11,17 @@ import (
|
||||
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"
|
||||
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/quic-go"
|
||||
qtls "github.com/metacubex/sing-quic"
|
||||
"github.com/metacubex/sing-quic/hysteria2"
|
||||
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 +38,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,6 +52,7 @@ 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"`
|
||||
|
||||
// quic-go special config
|
||||
@@ -105,20 +102,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 +173,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 +181,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 +207,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
|
||||
}
|
||||
}
|
||||
|
||||
+76
-56
@@ -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.Http2Transport
|
||||
|
||||
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,26 @@ 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"}
|
||||
outbound.h2Transport = &http.Http2Transport{
|
||||
DialTLSContext: func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) {
|
||||
c, err := outbound.dialer.DialContext(ctx, "tcp", outbound.addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tls.Client(c, tlsConfig), nil
|
||||
},
|
||||
ReadIdleTimeout: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
outbound.quicConfig = &quic.Config{
|
||||
EnableDatagrams: true,
|
||||
InitialPacketSize: 1242,
|
||||
@@ -229,27 +248,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 +278,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 +298,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 +316,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
|
||||
}
|
||||
|
||||
+12
-11
@@ -166,17 +166,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,
|
||||
}
|
||||
|
||||
+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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -446,18 +446,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),
|
||||
|
||||
+12
-12
@@ -161,18 +161,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,
|
||||
|
||||
+12
-14
@@ -98,8 +98,6 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
|
||||
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
|
||||
}
|
||||
@@ -187,18 +185,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,
|
||||
|
||||
+12
-10
@@ -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,
|
||||
}
|
||||
|
||||
+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)
|
||||
|
||||
+227
-45
@@ -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,63 @@ 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"`
|
||||
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
|
||||
// proxy part
|
||||
Server *string `proxy:"server,omitempty"`
|
||||
Port *int `proxy:"port,omitempty"`
|
||||
@@ -133,7 +177,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 +230,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,7 +314,7 @@ 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()
|
||||
default:
|
||||
@@ -349,8 +392,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 +464,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 +539,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 +557,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 +604,42 @@ 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)
|
||||
return quicConn, nil
|
||||
},
|
||||
v.option.ALPN,
|
||||
hKeepAlivePeriod,
|
||||
)
|
||||
}
|
||||
var makeDownloadTransport func() http.RoundTripper
|
||||
@@ -569,13 +685,43 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
}
|
||||
}
|
||||
|
||||
downloadHKeepAlivePeriod := hKeepAlivePeriod
|
||||
|
||||
downloadReuseCfg := reuseCfg
|
||||
if ds.ReuseSettings != nil {
|
||||
downloadReuseCfg = &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 = &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),
|
||||
Host: downloadHost,
|
||||
Path: lo.FromPtrOr(ds.Path, v.option.XHTTPOpts.Path),
|
||||
Mode: v.option.XHTTPOpts.Mode,
|
||||
Headers: lo.FromPtrOr(ds.Headers, v.option.XHTTPOpts.Headers),
|
||||
NoGRPCHeader: lo.FromPtrOr(ds.NoGRPCHeader, v.option.XHTTPOpts.NoGRPCHeader),
|
||||
XPaddingBytes: lo.FromPtrOr(ds.XPaddingBytes, v.option.XHTTPOpts.XPaddingBytes),
|
||||
XPaddingObfsMode: lo.FromPtrOr(ds.XPaddingObfsMode, v.option.XHTTPOpts.XPaddingObfsMode),
|
||||
XPaddingKey: lo.FromPtrOr(ds.XPaddingKey, v.option.XHTTPOpts.XPaddingKey),
|
||||
XPaddingHeader: lo.FromPtrOr(ds.XPaddingHeader, v.option.XHTTPOpts.XPaddingHeader),
|
||||
XPaddingPlacement: lo.FromPtrOr(ds.XPaddingPlacement, v.option.XHTTPOpts.XPaddingPlacement),
|
||||
XPaddingMethod: lo.FromPtrOr(ds.XPaddingMethod, v.option.XHTTPOpts.XPaddingMethod),
|
||||
UplinkHTTPMethod: lo.FromPtrOr(ds.UplinkHTTPMethod, v.option.XHTTPOpts.UplinkHTTPMethod),
|
||||
SessionPlacement: lo.FromPtrOr(ds.SessionPlacement, v.option.XHTTPOpts.SessionPlacement),
|
||||
SessionKey: lo.FromPtrOr(ds.SessionKey, v.option.XHTTPOpts.SessionKey),
|
||||
SeqPlacement: lo.FromPtrOr(ds.SeqPlacement, v.option.XHTTPOpts.SeqPlacement),
|
||||
SeqKey: lo.FromPtrOr(ds.SeqKey, v.option.XHTTPOpts.SeqKey),
|
||||
UplinkDataPlacement: lo.FromPtrOr(ds.UplinkDataPlacement, v.option.XHTTPOpts.UplinkDataPlacement),
|
||||
UplinkDataKey: lo.FromPtrOr(ds.UplinkDataKey, v.option.XHTTPOpts.UplinkDataKey),
|
||||
UplinkChunkSize: lo.FromPtrOr(ds.UplinkChunkSize, v.option.XHTTPOpts.UplinkChunkSize),
|
||||
ScMaxEachPostBytes: lo.FromPtrOr(ds.ScMaxEachPostBytes, v.option.XHTTPOpts.ScMaxEachPostBytes),
|
||||
ScMinPostsIntervalMs: lo.FromPtrOr(ds.ScMinPostsIntervalMs, v.option.XHTTPOpts.ScMinPostsIntervalMs),
|
||||
ReuseConfig: downloadReuseCfg,
|
||||
}
|
||||
|
||||
makeDownloadTransport = func() http.RoundTripper {
|
||||
@@ -612,6 +758,42 @@ 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)
|
||||
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()))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -453,10 +453,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"),
|
||||
}
|
||||
|
||||
@@ -129,3 +129,52 @@ func TestConvertsV2RayMieruFragment(t *testing.T) {
|
||||
assert.Len(t, proxies, 1)
|
||||
assert.Equal(t, "myproxy:443/TCP", proxies[0]["name"])
|
||||
}
|
||||
|
||||
func TestConvertsV2RayVlessRealityVisionTCPWithoutHeaderType(t *testing.T) {
|
||||
vlessTest := "vless://a1b2c3d4-eacc-4433-981b-7e5f9a8b@142.98.76.54:34888?encryption=none&security=reality&type=tcp&sni=github.io&fp=chrome&pbk=TifX9kL2mPqRsTuVwXyZ_JdUWw&sid=6ba85179f3a2b4c5&flow=xtls-rprx-vision#My-VLESS-Reality-Vision"
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
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": []string{"/grpc"},
|
||||
"headers": map[string]any{},
|
||||
}, proxies[0]["h2-opts"])
|
||||
assert.NotContains(t, proxies[0], "http-opts")
|
||||
}
|
||||
+284
-19
@@ -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,27 +71,26 @@ 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{"/"}
|
||||
case "http":
|
||||
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
|
||||
if host := query.Get("host"); host != "" {
|
||||
headers["Host"] = []string{host}
|
||||
}
|
||||
|
||||
case "http":
|
||||
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 "h2":
|
||||
headers := make(map[string]any)
|
||||
h2Opts := make(map[string]any)
|
||||
h2Opts["path"] = []string{"/"}
|
||||
@@ -134,6 +134,271 @@ 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
|
||||
}
|
||||
if v, ok := xhttpAny["noGRPCHeader"].(bool); ok && v {
|
||||
ds["no-grpc-header"] = true
|
||||
}
|
||||
if v, ok := xhttpAny["xPaddingBytes"].(string); ok && v != "" {
|
||||
ds["x-padding-bytes"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["xPaddingObfsMode"].(bool); ok {
|
||||
ds["x-padding-obfs-mode"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["xPaddingKey"].(string); ok && v != "" {
|
||||
ds["x-padding-key"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["xPaddingHeader"].(string); ok && v != "" {
|
||||
ds["x-padding-header"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["xPaddingPlacement"].(string); ok && v != "" {
|
||||
ds["x-padding-placement"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["xPaddingMethod"].(string); ok && v != "" {
|
||||
ds["x-padding-method"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["uplinkHttpMethod"].(string); ok && v != "" {
|
||||
ds["uplink-http-method"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["sessionPlacement"].(string); ok && v != "" {
|
||||
ds["session-placement"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["sessionKey"].(string); ok && v != "" {
|
||||
ds["session-key"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["seqPlacement"].(string); ok && v != "" {
|
||||
ds["seq-placement"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["seqKey"].(string); ok && v != "" {
|
||||
ds["seq-key"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["uplinkDataPlacement"].(string); ok && v != "" {
|
||||
ds["uplink-data-placement"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["uplinkDataKey"].(string); ok && v != "" {
|
||||
ds["uplink-data-key"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["uplinkChunkSize"].(float64); ok {
|
||||
ds["uplink-chunk-size"] = int(v)
|
||||
}
|
||||
if v, ok := xhttpAny["scMaxEachPostBytes"].(float64); ok {
|
||||
ds["sc-max-each-post-bytes"] = int(v)
|
||||
}
|
||||
if v, ok := xhttpAny["scMinPostsIntervalMs"].(float64); ok {
|
||||
ds["sc-min-posts-interval-ms"] = int(v)
|
||||
}
|
||||
|
||||
// xmux inside downloadSettings.xhttpSettings.extra → download-settings.reuse-settings
|
||||
if dsExtraAny, ok := xhttpAny["extra"].(map[string]any); ok {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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, "/")
|
||||
|
||||
@@ -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{}
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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"`
|
||||
@@ -1680,6 +1682,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,
|
||||
|
||||
+8
-3
@@ -554,11 +554,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 +568,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
|
||||
|
||||
+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
|
||||
|
||||
+116
-5
@@ -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
|
||||
@@ -670,6 +674,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 +768,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 +807,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,6 +825,28 @@ 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: "/"
|
||||
@@ -824,12 +855,33 @@ 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
|
||||
# ## proxy part
|
||||
# server: server
|
||||
# port: 443
|
||||
# tls: true
|
||||
# alpn:
|
||||
# - h2
|
||||
# alpn: ...
|
||||
# ech-opts: ...
|
||||
# reality-opts: ...
|
||||
# skip-cert-verify: false
|
||||
@@ -884,6 +936,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 +1010,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
|
||||
@@ -1053,6 +1109,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 +1145,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
|
||||
@@ -1187,8 +1261,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"
|
||||
@@ -1600,6 +1680,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 +1708,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,6 +1808,8 @@ listeners:
|
||||
username2: password2
|
||||
# 一个 base64 字符串用于微调网络行为
|
||||
# traffic-pattern: ""
|
||||
# 如果开启,且客户端不发送用户提示,代理服务器将拒绝连接
|
||||
# user-hint-is-mandatory: false
|
||||
|
||||
- name: sudoku-in-1
|
||||
type: sudoku
|
||||
@@ -1825,6 +1930,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 +1973,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 +2006,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,30 @@ 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.2
|
||||
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-20260414034501-3ea3410d197a
|
||||
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.17
|
||||
github.com/metacubex/sing-vmess v0.2.5
|
||||
github.com/metacubex/sing-wireguard v0.0.0-20250503063753-2dc62acc626f
|
||||
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141
|
||||
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
|
||||
|
||||
@@ -16,12 +16,12 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
|
||||
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=
|
||||
@@ -87,8 +87,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,8 +103,8 @@ 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.2 h1:XxW+pMaGAvVveRqREbyWJJDDl9dRZQGJoyKBiPPPKs8=
|
||||
github.com/metacubex/http v0.1.2/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
|
||||
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=
|
||||
@@ -117,26 +117,26 @@ github.com/metacubex/protobuf-go v0.0.0-20260306035419-7ceee0674686 h1:PIXmYT2an
|
||||
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-20260414034501-3ea3410d197a h1:977o0ZYYbiQAGuOxql7Q6UN3rEy59OyAE0tELq4gZfI=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260414034501-3ea3410d197a/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.17 h1:ehzvPLyxG1vmjaKVeB0aEK1eqhR3reEzdbqQfM3+5XA=
|
||||
github.com/metacubex/sing-tun v0.4.17/go.mod h1:L/TjQY5JEGy8nvsuYmy/XgMFMCPiF0+AWSFCYfS6r9w=
|
||||
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=
|
||||
@@ -145,8 +145,8 @@ github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141 h1:DK2l6m2Fc85H2Bhi
|
||||
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141/go.mod h1:/yI4OiGOSn0SURhZdJF3CbtPg3nwK700bG8TZLMBvAg=
|
||||
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=
|
||||
|
||||
@@ -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,6 +24,7 @@ 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"`
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ 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()
|
||||
|
||||
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
|
||||
}
|
||||
@@ -303,6 +357,7 @@ func NewHttpTestTunnel() *TestTunnel {
|
||||
CloseFn: ln.Close,
|
||||
DoSequentialTestFn: sequentialTestFn,
|
||||
DoConcurrentTestFn: concurrentTestFn,
|
||||
NewDialerFn: func() C.Dialer { return &TestDialer{dialer: dialer.NewDialer(), ctx: ctx} },
|
||||
}
|
||||
return tunnel
|
||||
}
|
||||
@@ -26,6 +26,7 @@ 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"`
|
||||
|
||||
@@ -73,6 +74,7 @@ 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(),
|
||||
// quic-go special config
|
||||
|
||||
@@ -41,6 +41,7 @@ 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()
|
||||
|
||||
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,7 @@ func testInboundMieruTCP(t *testing.T, handshakeMode string) {
|
||||
Password: "password",
|
||||
HandshakeMode: handshakeMode,
|
||||
}
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
out, err := outbound.NewMieru(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
@@ -260,8 +262,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 +293,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,
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/base64"
|
||||
"net"
|
||||
"net/netip"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -84,6 +85,7 @@ func testInboundShadowSocks0(t *testing.T, inboundOptions inbound.ShadowSocksOpt
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.Password = password
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewShadowSocks(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
@@ -166,6 +168,9 @@ func TestInboundShadowSocks_ShadowTlsv3(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestInboundShadowSocks_KcpTun(t *testing.T) {
|
||||
if runtime.GOOS == "windows" && strings.HasPrefix(runtime.Version(), "go1.20") {
|
||||
t.Skip("skip kcptun test on windows go1.20")
|
||||
}
|
||||
inboundOptions := inbound.ShadowSocksOption{
|
||||
KcpTun: inbound.KcpTun{
|
||||
Enable: true,
|
||||
|
||||
@@ -2,6 +2,7 @@ package inbound_test
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/metacubex/mihomo/adapter/outbound"
|
||||
@@ -42,6 +43,7 @@ func testInboundSudoku(t *testing.T, inboundOptions inbound.SudokuOption, outbou
|
||||
outboundOptions.Name = "sudoku_outbound"
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewSudoku(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
@@ -166,6 +168,10 @@ func TestInboundSudoku_CustomTable(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestInboundSudoku_HTTPMaskMode(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("temporarily skipped on windows due to intermittent failures; tracked in PR")
|
||||
}
|
||||
|
||||
key := "test_key_http_mask_mode"
|
||||
|
||||
for _, mode := range []string{"ws", "stream", "poll", "auto"} {
|
||||
|
||||
@@ -43,6 +43,7 @@ func testInboundTrojan(t *testing.T, inboundOptions inbound.TrojanOption, outbou
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.Password = userUUID
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewTrojan(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
|
||||
@@ -20,6 +20,7 @@ type TrustTunnelOption struct {
|
||||
Network []string `inbound:"network,omitempty"`
|
||||
CongestionController string `inbound:"congestion-controller,omitempty"`
|
||||
CWND int `inbound:"cwnd,omitempty"`
|
||||
BBRProfile string `inbound:"bbr-profile,omitempty"`
|
||||
}
|
||||
|
||||
func (o TrustTunnelOption) Equal(config C.InboundConfig) bool {
|
||||
@@ -57,6 +58,7 @@ func NewTrustTunnel(options *TrustTunnelOption) (*TrustTunnel, error) {
|
||||
Network: options.Network,
|
||||
CongestionController: options.CongestionController,
|
||||
CWND: options.CWND,
|
||||
BBRProfile: options.BBRProfile,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ func testInboundTrustTunnel(t *testing.T, inboundOptions inbound.TrustTunnelOpti
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.UserName = "test"
|
||||
outboundOptions.Password = userUUID
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewTrustTunnel(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
|
||||
@@ -24,6 +24,7 @@ type TuicOption struct {
|
||||
ALPN []string `inbound:"alpn,omitempty"`
|
||||
MaxUdpRelayPacketSize int `inbound:"max-udp-relay-packet-size,omitempty"`
|
||||
CWND int `inbound:"cwnd,omitempty"`
|
||||
BBRProfile string `inbound:"bbr-profile,omitempty"`
|
||||
MuxOption MuxOption `inbound:"mux-option,omitempty"`
|
||||
}
|
||||
|
||||
@@ -62,6 +63,7 @@ func NewTuic(options *TuicOption) (*Tuic, error) {
|
||||
ALPN: options.ALPN,
|
||||
MaxUdpRelayPacketSize: options.MaxUdpRelayPacketSize,
|
||||
CWND: options.CWND,
|
||||
BBRProfile: options.BBRProfile,
|
||||
MuxOption: options.MuxOption.Build(),
|
||||
},
|
||||
}, nil
|
||||
|
||||
@@ -69,6 +69,7 @@ func testInboundTuic0(t *testing.T, inboundOptions inbound.TuicOption, outboundO
|
||||
outboundOptions.Name = "tuic_outbound"
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewTuic(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
|
||||
@@ -48,6 +48,8 @@ type TunOption struct {
|
||||
IncludeAndroidUser []int `inbound:"include-android-user,omitempty"`
|
||||
IncludePackage []string `inbound:"include-package,omitempty"`
|
||||
ExcludePackage []string `inbound:"exclude-package,omitempty"`
|
||||
IncludeMACAddress []string `inbound:"include-mac-address,omitempty"`
|
||||
ExcludeMACAddress []string `inbound:"exclude-mac-address,omitempty"`
|
||||
EndpointIndependentNat bool `inbound:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout int64 `inbound:"udp-timeout,omitempty"`
|
||||
DisableICMPForwarding bool `inbound:"disable-icmp-forwarding,omitempty"`
|
||||
@@ -123,6 +125,8 @@ func NewTun(options *TunOption) (*Tun, error) {
|
||||
IncludeAndroidUser: options.IncludeAndroidUser,
|
||||
IncludePackage: options.IncludePackage,
|
||||
ExcludePackage: options.ExcludePackage,
|
||||
IncludeMACAddress: options.IncludeMACAddress,
|
||||
ExcludeMACAddress: options.ExcludeMACAddress,
|
||||
EndpointIndependentNat: options.EndpointIndependentNat,
|
||||
UDPTimeout: options.UDPTimeout,
|
||||
DisableICMPForwarding: options.DisableICMPForwarding,
|
||||
|
||||
@@ -32,16 +32,51 @@ type VlessUser struct {
|
||||
}
|
||||
|
||||
type XHTTPConfig struct {
|
||||
Path string `inbound:"path,omitempty"`
|
||||
Host string `inbound:"host,omitempty"`
|
||||
Mode string `inbound:"mode,omitempty"`
|
||||
Path string `inbound:"path,omitempty"`
|
||||
Host string `inbound:"host,omitempty"`
|
||||
Mode string `inbound:"mode,omitempty"`
|
||||
XPaddingBytes string `inbound:"x-padding-bytes,omitempty"`
|
||||
XPaddingObfsMode bool `inbound:"x-padding-obfs-mode,omitempty"`
|
||||
XPaddingKey string `inbound:"x-padding-key,omitempty"`
|
||||
XPaddingHeader string `inbound:"x-padding-header,omitempty"`
|
||||
XPaddingPlacement string `inbound:"x-padding-placement,omitempty"`
|
||||
XPaddingMethod string `inbound:"x-padding-method,omitempty"`
|
||||
UplinkHTTPMethod string `inbound:"uplink-http-method,omitempty"`
|
||||
SessionPlacement string `inbound:"session-placement,omitempty"`
|
||||
SessionKey string `inbound:"session-key,omitempty"`
|
||||
SeqPlacement string `inbound:"seq-placement,omitempty"`
|
||||
SeqKey string `inbound:"seq-key,omitempty"`
|
||||
UplinkDataPlacement string `inbound:"uplink-data-placement,omitempty"`
|
||||
UplinkDataKey string `inbound:"uplink-data-key,omitempty"`
|
||||
UplinkChunkSize string `inbound:"uplink-chunk-size,omitempty"`
|
||||
NoSSEHeader bool `inbound:"no-sse-header,omitempty"`
|
||||
ScStreamUpServerSecs string `inbound:"sc-stream-up-server-secs,omitempty"`
|
||||
ScMaxBufferedPosts string `inbound:"sc-max-buffered-posts,omitempty"`
|
||||
ScMaxEachPostBytes string `inbound:"sc-max-each-post-bytes,omitempty"`
|
||||
}
|
||||
|
||||
func (o XHTTPConfig) Build() LC.XHTTPConfig {
|
||||
return LC.XHTTPConfig{
|
||||
Path: o.Path,
|
||||
Host: o.Host,
|
||||
Mode: o.Mode,
|
||||
Path: o.Path,
|
||||
Host: o.Host,
|
||||
Mode: o.Mode,
|
||||
NoSSEHeader: o.NoSSEHeader,
|
||||
XPaddingBytes: o.XPaddingBytes,
|
||||
XPaddingObfsMode: o.XPaddingObfsMode,
|
||||
XPaddingKey: o.XPaddingKey,
|
||||
XPaddingHeader: o.XPaddingHeader,
|
||||
XPaddingPlacement: o.XPaddingPlacement,
|
||||
UplinkHTTPMethod: o.UplinkHTTPMethod,
|
||||
SessionPlacement: o.SessionPlacement,
|
||||
SessionKey: o.SessionKey,
|
||||
SeqPlacement: o.SeqPlacement,
|
||||
SeqKey: o.SeqKey,
|
||||
UplinkDataPlacement: o.UplinkDataPlacement,
|
||||
UplinkDataKey: o.UplinkDataKey,
|
||||
UplinkChunkSize: o.UplinkChunkSize,
|
||||
ScStreamUpServerSecs: o.ScStreamUpServerSecs,
|
||||
ScMaxBufferedPosts: o.ScMaxBufferedPosts,
|
||||
ScMaxEachPostBytes: o.ScMaxEachPostBytes,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+322
-95
@@ -44,6 +44,7 @@ func testInboundVless(t *testing.T, inboundOptions inbound.VlessOption, outbound
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.UUID = userUUID
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewVless(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
@@ -342,105 +343,331 @@ func TestInboundVless_Reality_Grpc(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestInboundVless_XHTTP(t *testing.T) {
|
||||
inboundOptions := inbound.VlessOption{
|
||||
Certificate: tlsCertificate,
|
||||
PrivateKey: tlsPrivateKey,
|
||||
XHTTPConfig: inbound.XHTTPConfig{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: "auto",
|
||||
},
|
||||
testCases := []struct {
|
||||
mode string
|
||||
}{
|
||||
{mode: "auto"},
|
||||
{mode: "stream-one"},
|
||||
{mode: "stream-up"},
|
||||
{mode: "packet-up"},
|
||||
}
|
||||
outboundOptions := outbound.VlessOption{
|
||||
TLS: true,
|
||||
Fingerprint: tlsFingerprint,
|
||||
Network: "xhttp",
|
||||
XHTTPOpts: outbound.XHTTPOptions{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: "auto",
|
||||
},
|
||||
}
|
||||
testInboundVlessTLS(t, inboundOptions, outboundOptions, false)
|
||||
}
|
||||
|
||||
func TestInboundVless_Reality_XHTTP(t *testing.T) {
|
||||
inboundOptions := inbound.VlessOption{
|
||||
RealityConfig: inbound.RealityConfig{
|
||||
Dest: net.JoinHostPort(realityDest, "443"),
|
||||
PrivateKey: realityPrivateKey,
|
||||
ShortID: []string{realityShortid},
|
||||
ServerNames: []string{realityDest},
|
||||
},
|
||||
XHTTPConfig: inbound.XHTTPConfig{
|
||||
Mode: "auto",
|
||||
},
|
||||
}
|
||||
outboundOptions := outbound.VlessOption{
|
||||
TLS: true,
|
||||
ServerName: realityDest,
|
||||
RealityOpts: outbound.RealityOptions{
|
||||
PublicKey: realityPublickey,
|
||||
ShortID: realityShortid,
|
||||
},
|
||||
ClientFingerprint: "chrome",
|
||||
Network: "xhttp",
|
||||
XHTTPOpts: outbound.XHTTPOptions{
|
||||
Mode: "auto",
|
||||
},
|
||||
}
|
||||
testInboundVless(t, inboundOptions, outboundOptions)
|
||||
}
|
||||
|
||||
func TestInboundVless_XHTTP_DownloadSettings(t *testing.T) {
|
||||
for _, mode := range []string{"stream-up", "packet-up"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
inboundOptions := inbound.VlessOption{
|
||||
Certificate: tlsCertificate,
|
||||
PrivateKey: tlsPrivateKey,
|
||||
XHTTPConfig: inbound.XHTTPConfig{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: mode,
|
||||
},
|
||||
for _, testCase := range testCases {
|
||||
testCase := testCase
|
||||
t.Run(testCase.mode, func(t *testing.T) {
|
||||
getConfig := func() (inbound.VlessOption, outbound.VlessOption) {
|
||||
inboundOptions := inbound.VlessOption{
|
||||
Certificate: tlsCertificate,
|
||||
PrivateKey: tlsPrivateKey,
|
||||
XHTTPConfig: inbound.XHTTPConfig{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
outboundOptions := outbound.VlessOption{
|
||||
TLS: true,
|
||||
Fingerprint: tlsFingerprint,
|
||||
ServerName: "example.org",
|
||||
ClientFingerprint: "chrome",
|
||||
Network: "xhttp",
|
||||
XHTTPOpts: outbound.XHTTPOptions{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
return inboundOptions, outboundOptions
|
||||
}
|
||||
outboundOptions := outbound.VlessOption{
|
||||
TLS: true,
|
||||
Fingerprint: tlsFingerprint,
|
||||
ServerName: "example.org",
|
||||
ClientFingerprint: "chrome",
|
||||
Network: "xhttp",
|
||||
XHTTPOpts: outbound.XHTTPOptions{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: mode,
|
||||
DownloadSettings: &outbound.XHTTPDownloadSettings{},
|
||||
},
|
||||
}
|
||||
testInboundVlessTLS(t, inboundOptions, outboundOptions, false)
|
||||
testInboundVless_XHTTP(t, getConfig, testCase.mode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboundVless_XHTTP_StreamUp(t *testing.T) {
|
||||
inboundOptions := inbound.VlessOption{
|
||||
Certificate: tlsCertificate,
|
||||
PrivateKey: tlsPrivateKey,
|
||||
XHTTPConfig: inbound.XHTTPConfig{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: "stream-up",
|
||||
},
|
||||
}
|
||||
outboundOptions := outbound.VlessOption{
|
||||
TLS: true,
|
||||
Fingerprint: tlsFingerprint,
|
||||
Network: "xhttp",
|
||||
XHTTPOpts: outbound.XHTTPOptions{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: "stream-up",
|
||||
},
|
||||
}
|
||||
testInboundVlessTLS(t, inboundOptions, outboundOptions, false)
|
||||
func testInboundVless_XHTTP(t *testing.T, getConfig func() (inbound.VlessOption, outbound.VlessOption), mode string) {
|
||||
t.Run("nosplit", func(t *testing.T) {
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVlessTLS(t, inboundOptions, outboundOptions, false)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVlessTLS(t, inboundOptions, withXHTTPReuse(outboundOptions), false)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("split", func(t *testing.T) {
|
||||
if mode == "stream-one" { // stream-one not supported download settings
|
||||
return
|
||||
}
|
||||
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVlessTLS(t, inboundOptions, outboundOptions, false)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVlessTLS(t, inboundOptions, withXHTTPReuse(outboundOptions), false)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestInboundVless_XHTTP_Reality(t *testing.T) {
|
||||
testCases := []struct {
|
||||
mode string
|
||||
}{
|
||||
{mode: "auto"},
|
||||
{mode: "stream-one"},
|
||||
{mode: "stream-up"},
|
||||
{mode: "packet-up"},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
testCase := testCase
|
||||
t.Run(testCase.mode, func(t *testing.T) {
|
||||
getConfig := func() (inbound.VlessOption, outbound.VlessOption) {
|
||||
inboundOptions := inbound.VlessOption{
|
||||
RealityConfig: inbound.RealityConfig{
|
||||
Dest: net.JoinHostPort(realityDest, "443"),
|
||||
PrivateKey: realityPrivateKey,
|
||||
ShortID: []string{realityShortid},
|
||||
ServerNames: []string{realityDest},
|
||||
},
|
||||
XHTTPConfig: inbound.XHTTPConfig{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
outboundOptions := outbound.VlessOption{
|
||||
TLS: true,
|
||||
ServerName: realityDest,
|
||||
RealityOpts: outbound.RealityOptions{
|
||||
PublicKey: realityPublickey,
|
||||
ShortID: realityShortid,
|
||||
},
|
||||
ClientFingerprint: "chrome",
|
||||
Network: "xhttp",
|
||||
XHTTPOpts: outbound.XHTTPOptions{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
return inboundOptions, outboundOptions
|
||||
}
|
||||
testInboundVless_XHTTP_Reality(t, getConfig, testCase.mode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testInboundVless_XHTTP_Reality(t *testing.T, getConfig func() (inbound.VlessOption, outbound.VlessOption), mode string) {
|
||||
t.Run("nosplit", func(t *testing.T) {
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVless(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVless(t, inboundOptions, withXHTTPReuse(outboundOptions))
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("split", func(t *testing.T) {
|
||||
if mode == "stream-one" { // stream-one not supported download settings
|
||||
return
|
||||
}
|
||||
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVless(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVless(t, inboundOptions, withXHTTPReuse(outboundOptions))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestInboundVless_XHTTP_Encryption(t *testing.T) {
|
||||
privateKeyBase64, passwordBase64, _, err := encryption.GenX25519("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
testCases := []struct {
|
||||
mode string
|
||||
}{
|
||||
{mode: "auto"},
|
||||
{mode: "stream-one"},
|
||||
{mode: "stream-up"},
|
||||
{mode: "packet-up"},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
testCase := testCase
|
||||
t.Run(testCase.mode, func(t *testing.T) {
|
||||
getConfig := func() (inbound.VlessOption, outbound.VlessOption) {
|
||||
inboundOptions := inbound.VlessOption{
|
||||
Decryption: "mlkem768x25519plus.native.600s." + privateKeyBase64,
|
||||
XHTTPConfig: inbound.XHTTPConfig{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
outboundOptions := outbound.VlessOption{
|
||||
Encryption: "mlkem768x25519plus.native.0rtt." + passwordBase64,
|
||||
Network: "xhttp",
|
||||
XHTTPOpts: outbound.XHTTPOptions{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
return inboundOptions, outboundOptions
|
||||
}
|
||||
testInboundVless_XHTTP_Encryption(t, getConfig, testCase.mode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testInboundVless_XHTTP_Encryption(t *testing.T, getConfig func() (inbound.VlessOption, outbound.VlessOption), mode string) {
|
||||
t.Run("nosplit", func(t *testing.T) {
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVless(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVless(t, inboundOptions, withXHTTPReuse(outboundOptions))
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("split", func(t *testing.T) {
|
||||
if mode == "stream-one" { // stream-one not supported download settings
|
||||
return
|
||||
}
|
||||
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVless(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVless(t, inboundOptions, withXHTTPReuse(outboundOptions))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestInboundVless_XHTTP_H1(t *testing.T) {
|
||||
testCases := []struct {
|
||||
mode string
|
||||
}{
|
||||
{mode: "auto"},
|
||||
{mode: "stream-one"},
|
||||
{mode: "stream-up"},
|
||||
{mode: "packet-up"},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
testCase := testCase
|
||||
t.Run(testCase.mode, func(t *testing.T) {
|
||||
getConfig := func() (inbound.VlessOption, outbound.VlessOption) {
|
||||
inboundOptions := inbound.VlessOption{
|
||||
Certificate: tlsCertificate,
|
||||
PrivateKey: tlsPrivateKey,
|
||||
XHTTPConfig: inbound.XHTTPConfig{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
outboundOptions := outbound.VlessOption{
|
||||
TLS: true,
|
||||
Fingerprint: tlsFingerprint,
|
||||
Network: "xhttp",
|
||||
ALPN: []string{"http/1.1"},
|
||||
XHTTPOpts: outbound.XHTTPOptions{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
return inboundOptions, outboundOptions
|
||||
}
|
||||
testInboundVless_XHTTP(t, getConfig, testCase.mode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboundVless_XHTTP_H1_Encryption(t *testing.T) {
|
||||
privateKeyBase64, passwordBase64, _, err := encryption.GenX25519("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
testCases := []struct {
|
||||
mode string
|
||||
}{
|
||||
{mode: "auto"},
|
||||
{mode: "stream-one"},
|
||||
{mode: "stream-up"},
|
||||
{mode: "packet-up"},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
testCase := testCase
|
||||
t.Run(testCase.mode, func(t *testing.T) {
|
||||
getConfig := func() (inbound.VlessOption, outbound.VlessOption) {
|
||||
inboundOptions := inbound.VlessOption{
|
||||
Decryption: "mlkem768x25519plus.native.600s." + privateKeyBase64,
|
||||
XHTTPConfig: inbound.XHTTPConfig{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
outboundOptions := outbound.VlessOption{
|
||||
Encryption: "mlkem768x25519plus.native.0rtt." + passwordBase64,
|
||||
Network: "xhttp",
|
||||
ALPN: []string{"http/1.1"},
|
||||
XHTTPOpts: outbound.XHTTPOptions{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
return inboundOptions, outboundOptions
|
||||
}
|
||||
testInboundVless_XHTTP_Encryption(t, getConfig, testCase.mode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func withXHTTPReuse(out outbound.VlessOption) outbound.VlessOption {
|
||||
out.XHTTPOpts.ReuseSettings = &outbound.XHTTPReuseSettings{
|
||||
MaxConnections: "0",
|
||||
MaxConcurrency: "16-32",
|
||||
CMaxReuseTimes: "0",
|
||||
HMaxRequestTimes: "600-900",
|
||||
HMaxReusableSecs: "1800-3000",
|
||||
}
|
||||
if out.XHTTPOpts.DownloadSettings != nil {
|
||||
out.XHTTPOpts.DownloadSettings.ReuseSettings = &outbound.XHTTPReuseSettings{
|
||||
MaxConnections: "0",
|
||||
MaxConcurrency: "16-32",
|
||||
CMaxReuseTimes: "0",
|
||||
HMaxRequestTimes: "600-900",
|
||||
HMaxReusableSecs: "1800-3000",
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -45,6 +45,7 @@ func testInboundVMess(t *testing.T, inboundOptions inbound.VmessOption, outbound
|
||||
outboundOptions.UUID = userUUID
|
||||
outboundOptions.AlterID = 0
|
||||
outboundOptions.Cipher = "auto"
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewVmess(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/metacubex/mihomo/listener/sing"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
"github.com/metacubex/mihomo/ntp"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/http/httputil"
|
||||
@@ -171,8 +172,10 @@ func New(config LC.Hysteria2Server, tunnel C.Tunnel, additions ...inbound.Additi
|
||||
UDPTimeout: sing.UDPTimeout,
|
||||
Handler: h,
|
||||
MasqueradeHandler: masqueradeHandler,
|
||||
CWND: config.CWND,
|
||||
UdpMTU: config.UdpMTU,
|
||||
SetBBRCongestion: func(quicConn *quic.Conn) {
|
||||
common.SetCongestionController(quicConn, "bbr", config.CWND, config.BBRProfile)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -19,9 +19,6 @@ import (
|
||||
)
|
||||
|
||||
func (h *ListenerHandler) ShouldHijackDns(targetAddr netip.AddrPort) bool {
|
||||
if targetAddr.Addr().IsLoopback() && targetAddr.Port() == 53 { // cause by system stack
|
||||
return true
|
||||
}
|
||||
for _, addrPort := range h.DnsAddrPorts {
|
||||
if addrPort == targetAddr || (addrPort.Addr().IsUnspecified() && targetAddr.Port() == 53) {
|
||||
return true
|
||||
|
||||
@@ -157,7 +157,7 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
|
||||
if options.FileDescriptor > 0 {
|
||||
if tunnelName, err := getTunnelName(int32(options.FileDescriptor)); err == nil {
|
||||
tunName = tunnelName // sing-tun must have the truth tun interface name even it from a fd
|
||||
forwarderBindInterface = true
|
||||
//forwarderBindInterface = true
|
||||
log.Debugln("[TUN] use tun name %s for fd %d", tunnelName, options.FileDescriptor)
|
||||
} else {
|
||||
log.Warnln("[TUN] get tun name failed for fd %d, fallback to use tun interface name %s", options.FileDescriptor, tunName)
|
||||
@@ -251,6 +251,22 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
|
||||
return nil, E.Cause(err, "parse exclude_dst_port_range")
|
||||
}
|
||||
}
|
||||
var includeMACAddress []net.HardwareAddr
|
||||
for _, mac := range options.IncludeMACAddress {
|
||||
addr, err := net.ParseMAC(mac)
|
||||
if err != nil {
|
||||
return nil, E.Cause(err, "parse include_mac_address")
|
||||
}
|
||||
includeMACAddress = append(includeMACAddress, addr)
|
||||
}
|
||||
var excludeMACAddress []net.HardwareAddr
|
||||
for _, mac := range options.ExcludeMACAddress {
|
||||
addr, err := net.ParseMAC(mac)
|
||||
if err != nil {
|
||||
return nil, E.Cause(err, "parse exclude_mac_address")
|
||||
}
|
||||
excludeMACAddress = append(excludeMACAddress, addr)
|
||||
}
|
||||
|
||||
var dnsAdds []netip.AddrPort
|
||||
|
||||
@@ -390,6 +406,8 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
|
||||
IncludeAndroidUser: options.IncludeAndroidUser,
|
||||
IncludePackage: options.IncludePackage,
|
||||
ExcludePackage: options.ExcludePackage,
|
||||
IncludeMACAddress: includeMACAddress,
|
||||
ExcludeMACAddress: excludeMACAddress,
|
||||
FileDescriptor: options.FileDescriptor,
|
||||
InterfaceMonitor: defaultInterfaceMonitor,
|
||||
EXP_RecvMsgX: options.RecvMsgX,
|
||||
|
||||
@@ -154,15 +154,41 @@ func New(config LC.VlessServer, tunnel C.Tunnel, additions ...inbound.Addition)
|
||||
}
|
||||
}
|
||||
if config.XHTTPConfig.Path != "" || config.XHTTPConfig.Host != "" || config.XHTTPConfig.Mode != "" {
|
||||
httpServer.Handler = xhttp.NewServerHandler(xhttp.ServerOption{
|
||||
Path: config.XHTTPConfig.Path,
|
||||
Host: config.XHTTPConfig.Host,
|
||||
Mode: config.XHTTPConfig.Mode,
|
||||
httpServer.Handler, err = xhttp.NewServerHandler(xhttp.ServerOption{
|
||||
Config: xhttp.Config{
|
||||
Host: config.XHTTPConfig.Host,
|
||||
Path: config.XHTTPConfig.Path,
|
||||
Mode: config.XHTTPConfig.Mode,
|
||||
XPaddingBytes: config.XHTTPConfig.XPaddingBytes,
|
||||
XPaddingObfsMode: config.XHTTPConfig.XPaddingObfsMode,
|
||||
XPaddingKey: config.XHTTPConfig.XPaddingKey,
|
||||
XPaddingHeader: config.XHTTPConfig.XPaddingHeader,
|
||||
XPaddingPlacement: config.XHTTPConfig.XPaddingPlacement,
|
||||
XPaddingMethod: config.XHTTPConfig.XPaddingMethod,
|
||||
UplinkHTTPMethod: config.XHTTPConfig.UplinkHTTPMethod,
|
||||
SessionPlacement: config.XHTTPConfig.SessionPlacement,
|
||||
SessionKey: config.XHTTPConfig.SessionKey,
|
||||
SeqPlacement: config.XHTTPConfig.SeqPlacement,
|
||||
SeqKey: config.XHTTPConfig.SeqKey,
|
||||
UplinkDataPlacement: config.XHTTPConfig.UplinkDataPlacement,
|
||||
UplinkDataKey: config.XHTTPConfig.UplinkDataKey,
|
||||
UplinkChunkSize: config.XHTTPConfig.UplinkChunkSize,
|
||||
NoSSEHeader: config.XHTTPConfig.NoSSEHeader,
|
||||
ScStreamUpServerSecs: config.XHTTPConfig.ScStreamUpServerSecs,
|
||||
ScMaxBufferedPosts: config.XHTTPConfig.ScMaxBufferedPosts,
|
||||
ScMaxEachPostBytes: config.XHTTPConfig.ScMaxEachPostBytes,
|
||||
},
|
||||
ConnHandler: func(conn net.Conn) {
|
||||
sl.HandleConn(conn, tunnel, additions...)
|
||||
},
|
||||
HttpHandler: httpServer.Handler,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !slices.Contains(tlsConfig.NextProtos, "http/1.1") {
|
||||
tlsConfig.NextProtos = append([]string{"http/1.1"}, tlsConfig.NextProtos...)
|
||||
}
|
||||
if !slices.Contains(tlsConfig.NextProtos, "h2") {
|
||||
tlsConfig.NextProtos = append([]string{"h2"}, tlsConfig.NextProtos...)
|
||||
}
|
||||
|
||||
@@ -135,6 +135,7 @@ func New(config LC.TrustTunnelServer, tunnel C.Tunnel, additions ...inbound.Addi
|
||||
ICMPHandler: nil,
|
||||
QUICCongestionControl: config.CongestionController,
|
||||
QUICCwnd: config.CWND,
|
||||
QUICBBRProfile: config.BBRProfile,
|
||||
})
|
||||
service.UpdateUsers(config.Users)
|
||||
err = service.Start(tcpListener, udpConn, tlsConfig)
|
||||
|
||||
@@ -155,6 +155,7 @@ func New(config LC.TuicServer, tunnel C.Tunnel, additions ...inbound.Addition) (
|
||||
AuthenticationTimeout: time.Duration(config.AuthenticationTimeout) * time.Millisecond,
|
||||
MaxUdpRelayPacketSize: config.MaxUdpRelayPacketSize,
|
||||
CWND: config.CWND,
|
||||
BBRProfile: config.BBRProfile,
|
||||
}
|
||||
if len(config.Token) > 0 {
|
||||
tokens := make([][32]byte, len(config.Token))
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/metacubex/mihomo/common/cmd"
|
||||
"github.com/metacubex/mihomo/component/generator"
|
||||
"github.com/metacubex/mihomo/component/geodata"
|
||||
"github.com/metacubex/mihomo/component/updater"
|
||||
@@ -41,6 +42,8 @@ var (
|
||||
externalControllerUnix string
|
||||
externalControllerPipe string
|
||||
secret string
|
||||
postUp string
|
||||
postDown string
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -52,6 +55,8 @@ func init() {
|
||||
flag.StringVar(&externalControllerUnix, "ext-ctl-unix", os.Getenv("CLASH_OVERRIDE_EXTERNAL_CONTROLLER_UNIX"), "override external controller unix address")
|
||||
flag.StringVar(&externalControllerPipe, "ext-ctl-pipe", os.Getenv("CLASH_OVERRIDE_EXTERNAL_CONTROLLER_PIPE"), "override external controller pipe address")
|
||||
flag.StringVar(&secret, "secret", os.Getenv("CLASH_OVERRIDE_SECRET"), "override secret for RESTful API")
|
||||
flag.StringVar(&postUp, "post-up", os.Getenv("CLASH_POST_UP"), "set post-up script")
|
||||
flag.StringVar(&postDown, "post-down", os.Getenv("CLASH_POST_DOWN"), "set post-down script")
|
||||
flag.BoolVar(&geodataMode, "m", false, "set geodata mode")
|
||||
flag.BoolVar(&version, "v", false, "show current version of mihomo")
|
||||
flag.BoolVar(&testConfig, "t", false, "test configuration and exit")
|
||||
@@ -184,6 +189,19 @@ func main() {
|
||||
updater.RegisterGeoUpdater()
|
||||
}
|
||||
|
||||
if postDown != "" {
|
||||
defer func() {
|
||||
if _, err := cmd.ExecShell(postDown); err != nil {
|
||||
log.Errorln("post-down script error: %s", err.Error())
|
||||
}
|
||||
}()
|
||||
}
|
||||
if postUp != "" {
|
||||
if _, err := cmd.ExecShell(postUp); err != nil {
|
||||
log.Fatalln("post-up script error: %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
defer executor.Shutdown()
|
||||
|
||||
termSign := make(chan os.Signal, 1)
|
||||
|
||||
+90
-14
@@ -13,6 +13,7 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/buf"
|
||||
@@ -51,6 +52,7 @@ type Conn struct {
|
||||
|
||||
closeMutex sync.Mutex
|
||||
closed bool
|
||||
onClose func()
|
||||
|
||||
// deadlines
|
||||
deadline *time.Timer
|
||||
@@ -103,7 +105,7 @@ func (g *Conn) read(b []byte) (n int, err error) {
|
||||
size = len(b)
|
||||
}
|
||||
|
||||
n, err = io.ReadFull(g.reader, b[:size])
|
||||
n, err = g.reader.Read(b[:size])
|
||||
g.remain -= n
|
||||
return
|
||||
}
|
||||
@@ -112,6 +114,9 @@ func (g *Conn) read(b []byte) (n int, err error) {
|
||||
var discard [6]byte
|
||||
_, err = io.ReadFull(g.reader, discard[:])
|
||||
if err != nil {
|
||||
if err == io.ErrUnexpectedEOF {
|
||||
err = io.EOF
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -206,6 +211,10 @@ func (g *Conn) Close() error {
|
||||
}
|
||||
}
|
||||
|
||||
if g.onClose != nil {
|
||||
g.onClose()
|
||||
}
|
||||
|
||||
return errors.Join(errorArr...)
|
||||
}
|
||||
|
||||
@@ -237,6 +246,7 @@ type Transport struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
closeOnce sync.Once
|
||||
count atomic.Int64
|
||||
}
|
||||
|
||||
func (t *Transport) Close() error {
|
||||
@@ -267,19 +277,10 @@ func NewTransport(dialFn DialFn, tlsConfig *vmess.TLSConfig, gunCfg *Config) *Tr
|
||||
}
|
||||
|
||||
if tlsConfig.Reality == nil { // reality doesn't return the negotiated ALPN
|
||||
switch tlsConn := conn.(type) {
|
||||
case interface{ ConnectionState() tls.ConnectionState }:
|
||||
state := tlsConn.ConnectionState()
|
||||
if p := state.NegotiatedProtocol; p != http.Http2NextProtoTLS {
|
||||
_ = conn.Close()
|
||||
return nil, fmt.Errorf("http2: unexpected ALPN protocol %s, want %s", p, http.Http2NextProtoTLS)
|
||||
}
|
||||
case interface{ ConnectionState() tlsC.ConnectionState }:
|
||||
state := tlsConn.ConnectionState()
|
||||
if p := state.NegotiatedProtocol; p != http.Http2NextProtoTLS {
|
||||
_ = conn.Close()
|
||||
return nil, fmt.Errorf("http2: unexpected ALPN protocol %s, want %s", p, http.Http2NextProtoTLS)
|
||||
}
|
||||
state := tlsC.GetTLSConnectionState(conn)
|
||||
if p := state.NegotiatedProtocol; p != http.Http2NextProtoTLS {
|
||||
_ = conn.Close()
|
||||
return nil, fmt.Errorf("http2: unexpected ALPN protocol %s, want %s", p, http.Http2NextProtoTLS)
|
||||
}
|
||||
}
|
||||
return conn, nil
|
||||
@@ -355,6 +356,9 @@ func (t *Transport) Dial() (net.Conn, error) {
|
||||
writer: writer,
|
||||
}
|
||||
|
||||
t.count.Add(1)
|
||||
conn.onClose = func() { t.count.Add(-1) }
|
||||
|
||||
go conn.Init()
|
||||
|
||||
// ensure conn.initOnce.Do has been called before return
|
||||
@@ -364,6 +368,78 @@ func (t *Transport) Dial() (net.Conn, error) {
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
mutex sync.Mutex
|
||||
maxConnections int
|
||||
minStreams int
|
||||
maxStreams int
|
||||
transports []*Transport
|
||||
maker func() *Transport
|
||||
}
|
||||
|
||||
func NewClient(maker func() *Transport, maxConnections, minStreams, maxStreams int) *Client {
|
||||
if maxConnections == 0 && minStreams == 0 && maxStreams == 0 {
|
||||
maxConnections = 1
|
||||
}
|
||||
return &Client{
|
||||
maxConnections: maxConnections,
|
||||
minStreams: minStreams,
|
||||
maxStreams: maxStreams,
|
||||
maker: maker,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Dial() (net.Conn, error) {
|
||||
return c.getTransport().Dial()
|
||||
}
|
||||
|
||||
func (c *Client) Close() error {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
var errs []error
|
||||
for _, t := range c.transports {
|
||||
if err := t.Close(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
c.transports = nil
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func (c *Client) getTransport() *Transport {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
var transport *Transport
|
||||
for _, t := range c.transports {
|
||||
if transport == nil || t.count.Load() < transport.count.Load() {
|
||||
transport = t
|
||||
}
|
||||
}
|
||||
if transport == nil {
|
||||
return c.newTransportLocked()
|
||||
}
|
||||
numStreams := int(transport.count.Load())
|
||||
if numStreams == 0 {
|
||||
return transport
|
||||
}
|
||||
if c.maxConnections > 0 {
|
||||
if len(c.transports) >= c.maxConnections || numStreams < c.minStreams {
|
||||
return transport
|
||||
}
|
||||
} else {
|
||||
if c.maxStreams > 0 && numStreams < c.maxStreams {
|
||||
return transport
|
||||
}
|
||||
}
|
||||
return c.newTransportLocked()
|
||||
}
|
||||
|
||||
func (c *Client) newTransportLocked() *Transport {
|
||||
transport := c.maker()
|
||||
c.transports = append(c.transports, transport)
|
||||
return transport
|
||||
}
|
||||
|
||||
func StreamGunWithConn(conn net.Conn, tlsConfig *vmess.TLSConfig, gunCfg *Config) (net.Conn, error) {
|
||||
dialFn := func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return conn, nil
|
||||
|
||||
@@ -112,11 +112,6 @@ func (w *h2ConnWrapper) CloseWrapper() {
|
||||
w.closed = true
|
||||
}
|
||||
|
||||
func (w *h2ConnWrapper) Close() error {
|
||||
w.CloseWrapper()
|
||||
return w.ExtendedConn.Close()
|
||||
}
|
||||
|
||||
func (w *h2ConnWrapper) Upstream() any {
|
||||
return w.ExtendedConn
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package masque
|
||||
|
||||
// copy and modify from: https://github.com/Diniboy1123/connect-ip-go/blob/8d7bb0a858a2674046a7cb5538749e4c826c3538/client_h2.go
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/metacubex/mihomo/common/contextutils"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/quic-go/quicvarint"
|
||||
"github.com/yosida95/uritemplate/v3"
|
||||
)
|
||||
|
||||
const h2DatagramCapsuleType uint64 = 0
|
||||
|
||||
const (
|
||||
ipv4HeaderLen = 20
|
||||
ipv6HeaderLen = 40
|
||||
)
|
||||
|
||||
func ConnectTunnelH2(ctx context.Context, h2Transport *http.Http2Transport, connectUri string) (*http.Http2ClientConn, IpConn, error) {
|
||||
additionalHeaders := http.Header{
|
||||
"User-Agent": []string{""},
|
||||
}
|
||||
template := uritemplate.MustNew(connectUri)
|
||||
|
||||
h2Headers := additionalHeaders.Clone()
|
||||
h2Headers.Set("cf-connect-proto", "cf-connect-ip")
|
||||
// TODO: support PQC
|
||||
h2Headers.Set("pq-enabled", "false")
|
||||
|
||||
conn, err := h2Transport.DialTLSContext(ctx, "tcp", ":0", nil)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to dial: %w", err)
|
||||
}
|
||||
|
||||
cc, err := h2Transport.NewClientConn(conn)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to create client connection: %w", err)
|
||||
}
|
||||
|
||||
if !cc.ReserveNewRequest() {
|
||||
_ = cc.Close()
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to reserve client connection: %w", err)
|
||||
}
|
||||
|
||||
ipConn, rsp, err := dialH2(ctx, cc, template, h2Headers)
|
||||
if err != nil {
|
||||
_ = cc.Close()
|
||||
if strings.Contains(err.Error(), "tls: access denied") {
|
||||
return nil, nil, errors.New("login failed! Please double-check if your tls key and cert is enrolled in the Cloudflare Access service")
|
||||
}
|
||||
return nil, nil, fmt.Errorf("failed to dial connect-ip over HTTP/2: %w", err)
|
||||
}
|
||||
|
||||
if rsp.StatusCode != http.StatusOK {
|
||||
_ = ipConn.Close()
|
||||
_ = cc.Close()
|
||||
return nil, nil, fmt.Errorf("failed to dial connect-ip: %v", rsp.Status)
|
||||
}
|
||||
|
||||
return cc, ipConn, nil
|
||||
}
|
||||
|
||||
// dialH2 dials a proxied connection over HTTP/2 CONNECT-IP.
|
||||
//
|
||||
// This transport carries proxied packets inside HTTP capsule DATAGRAM frames.
|
||||
func dialH2(ctx context.Context, rt http.RoundTripper, template *uritemplate.Template, additionalHeaders http.Header) (*h2IpConn, *http.Response, error) {
|
||||
if len(template.Varnames()) > 0 {
|
||||
return nil, nil, errors.New("connect-ip: IP flow forwarding not supported")
|
||||
}
|
||||
|
||||
u, err := url.Parse(template.Raw())
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to parse URI: %w", err)
|
||||
}
|
||||
|
||||
reqCtx, cancel := context.WithCancel(context.Background()) // reqCtx must disconnect from ctx, otherwise ctx would close the entire HTTP/2 connection.
|
||||
|
||||
pr, pw := io.Pipe()
|
||||
req, err := http.NewRequestWithContext(reqCtx, http.MethodConnect, u.String(), pr)
|
||||
if err != nil {
|
||||
cancel()
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to create request: %w", err)
|
||||
}
|
||||
req.Host = authorityFromURL(u)
|
||||
req.ContentLength = -1
|
||||
req.Header = make(http.Header)
|
||||
for k, v := range additionalHeaders {
|
||||
req.Header[k] = v
|
||||
}
|
||||
|
||||
stop := contextutils.AfterFunc(ctx, cancel) // temporarily connect ctx with reqCtx when client.Do
|
||||
rsp, err := rt.RoundTrip(req)
|
||||
stop() // disconnect ctx with reqCtx after client.Do
|
||||
if err != nil {
|
||||
cancel()
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to send request: %w", err)
|
||||
}
|
||||
if rsp.StatusCode < 200 || rsp.StatusCode > 299 {
|
||||
cancel()
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
_ = rsp.Body.Close()
|
||||
return nil, rsp, fmt.Errorf("connect-ip: server responded with %d", rsp.StatusCode)
|
||||
}
|
||||
|
||||
stream := &h2DatagramStream{
|
||||
requestBody: pw,
|
||||
responseBody: rsp.Body,
|
||||
cancel: cancel,
|
||||
}
|
||||
return &h2IpConn{
|
||||
str: stream,
|
||||
closeChan: make(chan struct{}),
|
||||
}, rsp, nil
|
||||
}
|
||||
|
||||
func authorityFromURL(u *url.URL) string {
|
||||
if u.Port() != "" {
|
||||
return u.Host
|
||||
}
|
||||
host := u.Hostname()
|
||||
if host == "" {
|
||||
return u.Host
|
||||
}
|
||||
return host + ":443"
|
||||
}
|
||||
|
||||
type h2IpConn struct {
|
||||
str *h2DatagramStream
|
||||
|
||||
mu sync.Mutex
|
||||
|
||||
closeChan chan struct{}
|
||||
closeErr error
|
||||
}
|
||||
|
||||
func (c *h2IpConn) ReadPacket() (b []byte, err error) {
|
||||
start:
|
||||
data, err := c.str.ReceiveDatagram(context.Background())
|
||||
if err != nil {
|
||||
defer func() {
|
||||
// There are no errors that can be recovered in h2 mode,
|
||||
// so calling Close allows the outer read loop to exit in the next iteration by returning net.ErrClosed.
|
||||
_ = c.Close()
|
||||
}()
|
||||
select {
|
||||
case <-c.closeChan:
|
||||
return nil, c.closeErr
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := c.handleIncomingProxiedPacket(data); err != nil {
|
||||
log.Debugln("dropping proxied packet: %s", err)
|
||||
goto start
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (c *h2IpConn) handleIncomingProxiedPacket(data []byte) error {
|
||||
if len(data) == 0 {
|
||||
return errors.New("connect-ip: empty packet")
|
||||
}
|
||||
switch v := ipVersion(data); v {
|
||||
default:
|
||||
return fmt.Errorf("connect-ip: unknown IP versions: %d", v)
|
||||
case 4:
|
||||
if len(data) < ipv4HeaderLen {
|
||||
return fmt.Errorf("connect-ip: malformed datagram: too short")
|
||||
}
|
||||
case 6:
|
||||
if len(data) < ipv6HeaderLen {
|
||||
return fmt.Errorf("connect-ip: malformed datagram: too short")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WritePacket writes an IP packet to the stream.
|
||||
// If sending the packet fails, it might return an ICMP packet.
|
||||
// It is the caller's responsibility to send the ICMP packet to the sender.
|
||||
func (c *h2IpConn) WritePacket(b []byte) (icmp []byte, err error) {
|
||||
data, err := c.composeDatagram(b)
|
||||
if err != nil {
|
||||
log.Debugln("dropping proxied packet (%d bytes) that can't be proxied: %s", len(b), err)
|
||||
return nil, nil
|
||||
}
|
||||
if err := c.str.SendDatagram(data); err != nil {
|
||||
select {
|
||||
case <-c.closeChan:
|
||||
return nil, c.closeErr
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *h2IpConn) composeDatagram(b []byte) ([]byte, error) {
|
||||
// TODO: implement src, dst and ipproto checks
|
||||
if len(b) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
switch v := ipVersion(b); v {
|
||||
default:
|
||||
return nil, fmt.Errorf("connect-ip: unknown IP versions: %d", v)
|
||||
case 4:
|
||||
if len(b) < ipv4HeaderLen {
|
||||
return nil, fmt.Errorf("connect-ip: IPv4 packet too short")
|
||||
}
|
||||
ttl := b[8]
|
||||
if ttl <= 1 {
|
||||
return nil, fmt.Errorf("connect-ip: datagram TTL too small: %d", ttl)
|
||||
}
|
||||
b[8]-- // decrement TTL
|
||||
// recalculate the checksum
|
||||
binary.BigEndian.PutUint16(b[10:12], calculateIPv4Checksum(([ipv4HeaderLen]byte)(b[:ipv4HeaderLen])))
|
||||
case 6:
|
||||
if len(b) < ipv6HeaderLen {
|
||||
return nil, fmt.Errorf("connect-ip: IPv6 packet too short")
|
||||
}
|
||||
hopLimit := b[7]
|
||||
if hopLimit <= 1 {
|
||||
return nil, fmt.Errorf("connect-ip: datagram Hop Limit too small: %d", hopLimit)
|
||||
}
|
||||
b[7]-- // Decrement Hop Limit
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (c *h2IpConn) Close() error {
|
||||
c.mu.Lock()
|
||||
if c.closeErr == nil {
|
||||
c.closeErr = net.ErrClosed
|
||||
close(c.closeChan)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
err := c.str.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
func ipVersion(b []byte) uint8 { return b[0] >> 4 }
|
||||
|
||||
func calculateIPv4Checksum(header [ipv4HeaderLen]byte) uint16 {
|
||||
// add every 16-bit word in the header, skipping the checksum field (bytes 10 and 11)
|
||||
var sum uint32
|
||||
for i := 0; i < len(header); i += 2 {
|
||||
if i == 10 {
|
||||
continue // skip checksum field
|
||||
}
|
||||
sum += uint32(binary.BigEndian.Uint16(header[i : i+2]))
|
||||
}
|
||||
for (sum >> 16) > 0 {
|
||||
sum = (sum & 0xffff) + (sum >> 16)
|
||||
}
|
||||
return ^uint16(sum)
|
||||
}
|
||||
|
||||
type h2DatagramStream struct {
|
||||
requestBody *io.PipeWriter
|
||||
responseBody io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
|
||||
readMu sync.Mutex
|
||||
writeMu sync.Mutex
|
||||
}
|
||||
|
||||
func (s *h2DatagramStream) ReceiveDatagram(_ context.Context) ([]byte, error) {
|
||||
s.readMu.Lock()
|
||||
defer s.readMu.Unlock()
|
||||
|
||||
reader := quicvarint.NewReader(s.responseBody)
|
||||
for {
|
||||
capsuleType, err := quicvarint.Read(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payloadLen, err := quicvarint.Read(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload := make([]byte, payloadLen)
|
||||
_, err = io.ReadFull(reader, payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if capsuleType != h2DatagramCapsuleType {
|
||||
continue
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *h2DatagramStream) SendDatagram(data []byte) error {
|
||||
frame := make([]byte, 0, quicvarint.Len(h2DatagramCapsuleType)+quicvarint.Len(uint64(len(data)))+len(data))
|
||||
frame = quicvarint.Append(frame, h2DatagramCapsuleType)
|
||||
frame = quicvarint.Append(frame, uint64(len(data)))
|
||||
frame = append(frame, data...)
|
||||
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
_, err := s.requestBody.Write(frame)
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect-ip: failed to send datagram capsule: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *h2DatagramStream) Close() error {
|
||||
_ = s.requestBody.Close()
|
||||
err := s.responseBody.Close()
|
||||
s.cancel()
|
||||
return err
|
||||
}
|
||||
@@ -27,9 +27,15 @@ const (
|
||||
ConnectURI = "https://cloudflareaccess.com"
|
||||
)
|
||||
|
||||
type IpConn interface {
|
||||
ReadPacket() (b []byte, err error)
|
||||
WritePacket(b []byte) (icmp []byte, err error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
// PrepareTlsConfig creates a TLS configuration using the provided certificate and SNI (Server Name Indication).
|
||||
// It also verifies the peer's public key against the provided public key.
|
||||
func PrepareTlsConfig(privKey *ecdsa.PrivateKey, peerPubKey *ecdsa.PublicKey, sni string) (*tls.Config, error) {
|
||||
func PrepareTlsConfig(privKey *ecdsa.PrivateKey, peerPubKey *ecdsa.PublicKey, sni string, insecure bool) (*tls.Config, error) {
|
||||
verfiyCert := func(cert *x509.Certificate) error {
|
||||
if _, ok := cert.PublicKey.(*ecdsa.PublicKey); !ok {
|
||||
// we only support ECDSA
|
||||
@@ -77,6 +83,9 @@ func PrepareTlsConfig(privKey *ecdsa.PrivateKey, peerPubKey *ecdsa.PublicKey, sn
|
||||
return err
|
||||
},
|
||||
}
|
||||
if insecure {
|
||||
tlsConfig.VerifyConnection = nil
|
||||
}
|
||||
|
||||
return tlsConfig, nil
|
||||
}
|
||||
|
||||
@@ -66,13 +66,7 @@ func WriteKIPMessage(w io.Writer, typ byte, payload []byte) error {
|
||||
hdr[3] = typ
|
||||
binary.BigEndian.PutUint16(hdr[4:], uint16(len(payload)))
|
||||
|
||||
if err := writeFull(w, hdr[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(payload) == 0 {
|
||||
return nil
|
||||
}
|
||||
return writeFull(w, payload)
|
||||
return writeAllChunks(w, hdr[:], payload)
|
||||
}
|
||||
|
||||
func ReadKIPMessage(r io.Reader) (*KIPMessage, error) {
|
||||
|
||||
@@ -173,16 +173,10 @@ func (s *Session) sendFrame(frameType byte, streamID uint32, payload []byte) err
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
|
||||
if err := writeFull(s.conn, header[:]); err != nil {
|
||||
if err := writeAllChunks(s.conn, header[:], payload); err != nil {
|
||||
s.closeWithError(err)
|
||||
return err
|
||||
}
|
||||
if len(payload) > 0 {
|
||||
if err := writeFull(s.conn, payload); err != nil {
|
||||
s.closeWithError(err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -315,17 +309,6 @@ func (s *Session) readLoop() {
|
||||
}
|
||||
}
|
||||
|
||||
func writeFull(w io.Writer, b []byte) error {
|
||||
for len(b) > 0 {
|
||||
n, err := w.Write(b)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b = b[n:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func trimASCII(b []byte) string {
|
||||
i := 0
|
||||
j := len(b)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package multiplex
|
||||
|
||||
import "io"
|
||||
|
||||
func writeAllChunks(w io.Writer, chunks ...[]byte) error {
|
||||
for _, chunk := range chunks {
|
||||
for len(chunk) > 0 {
|
||||
n, err := w.Write(chunk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return io.ErrShortWrite
|
||||
}
|
||||
chunk = chunk[n:]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -3,12 +3,9 @@ package sudoku
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
crypto_rand "crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math/rand"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
const IOBufferSize = 32 * 1024
|
||||
@@ -45,14 +42,17 @@ type Conn struct {
|
||||
table *Table
|
||||
reader *bufio.Reader
|
||||
recorder *bytes.Buffer
|
||||
recording bool
|
||||
recording atomic.Bool
|
||||
recordLock sync.Mutex
|
||||
|
||||
rawBuf []byte
|
||||
pendingData []byte
|
||||
hintBuf []byte
|
||||
pendingData pendingBuffer
|
||||
hintBuf [4]byte
|
||||
hintCount int
|
||||
writeMu sync.Mutex
|
||||
writeBuf []byte
|
||||
|
||||
rng *rand.Rand
|
||||
rng randomSource
|
||||
paddingThreshold uint64
|
||||
}
|
||||
|
||||
@@ -77,33 +77,28 @@ func (sc *Conn) CloseRead() error {
|
||||
}
|
||||
|
||||
func NewConn(c net.Conn, table *Table, pMin, pMax int, record bool) *Conn {
|
||||
var seedBytes [8]byte
|
||||
if _, err := crypto_rand.Read(seedBytes[:]); err != nil {
|
||||
binary.BigEndian.PutUint64(seedBytes[:], uint64(rand.Int63()))
|
||||
}
|
||||
seed := int64(binary.BigEndian.Uint64(seedBytes[:]))
|
||||
localRng := rand.New(rand.NewSource(seed))
|
||||
localRng := newSeededRand()
|
||||
|
||||
sc := &Conn{
|
||||
Conn: c,
|
||||
table: table,
|
||||
reader: bufio.NewReaderSize(c, IOBufferSize),
|
||||
rawBuf: make([]byte, IOBufferSize),
|
||||
pendingData: make([]byte, 0, 4096),
|
||||
hintBuf: make([]byte, 0, 4),
|
||||
pendingData: newPendingBuffer(4096),
|
||||
writeBuf: make([]byte, 0, 4096),
|
||||
rng: localRng,
|
||||
paddingThreshold: pickPaddingThreshold(localRng, pMin, pMax),
|
||||
}
|
||||
if record {
|
||||
sc.recorder = new(bytes.Buffer)
|
||||
sc.recording = true
|
||||
sc.recording.Store(true)
|
||||
}
|
||||
return sc
|
||||
}
|
||||
|
||||
func (sc *Conn) StopRecording() {
|
||||
sc.recordLock.Lock()
|
||||
sc.recording = false
|
||||
sc.recording.Store(false)
|
||||
sc.recorder = nil
|
||||
sc.recordLock.Unlock()
|
||||
}
|
||||
@@ -137,74 +132,50 @@ func (sc *Conn) Write(p []byte) (n int, err error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
outCapacity := len(p) * 6
|
||||
out := make([]byte, 0, outCapacity)
|
||||
pads := sc.table.PaddingPool
|
||||
padLen := len(pads)
|
||||
sc.writeMu.Lock()
|
||||
defer sc.writeMu.Unlock()
|
||||
|
||||
for _, b := range p {
|
||||
if shouldPad(sc.rng, sc.paddingThreshold) {
|
||||
out = append(out, pads[sc.rng.Intn(padLen)])
|
||||
}
|
||||
|
||||
puzzles := sc.table.EncodeTable[b]
|
||||
puzzle := puzzles[sc.rng.Intn(len(puzzles))]
|
||||
|
||||
perm := perm4[sc.rng.Intn(len(perm4))]
|
||||
for _, idx := range perm {
|
||||
if shouldPad(sc.rng, sc.paddingThreshold) {
|
||||
out = append(out, pads[sc.rng.Intn(padLen)])
|
||||
}
|
||||
out = append(out, puzzle[idx])
|
||||
}
|
||||
}
|
||||
|
||||
if shouldPad(sc.rng, sc.paddingThreshold) {
|
||||
out = append(out, pads[sc.rng.Intn(padLen)])
|
||||
}
|
||||
|
||||
return len(p), writeFull(sc.Conn, out)
|
||||
sc.writeBuf = encodeSudokuPayload(sc.writeBuf[:0], sc.table, sc.rng, sc.paddingThreshold, p)
|
||||
return len(p), writeFull(sc.Conn, sc.writeBuf)
|
||||
}
|
||||
|
||||
func (sc *Conn) Read(p []byte) (n int, err error) {
|
||||
if len(sc.pendingData) > 0 {
|
||||
n = copy(p, sc.pendingData)
|
||||
if n == len(sc.pendingData) {
|
||||
sc.pendingData = sc.pendingData[:0]
|
||||
} else {
|
||||
sc.pendingData = sc.pendingData[n:]
|
||||
}
|
||||
if n, ok := drainPending(p, &sc.pendingData); ok {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
for {
|
||||
if len(sc.pendingData) > 0 {
|
||||
if sc.pendingData.available() > 0 {
|
||||
break
|
||||
}
|
||||
|
||||
nr, rErr := sc.reader.Read(sc.rawBuf)
|
||||
if nr > 0 {
|
||||
chunk := sc.rawBuf[:nr]
|
||||
sc.recordLock.Lock()
|
||||
if sc.recording {
|
||||
sc.recorder.Write(chunk)
|
||||
if sc.recording.Load() {
|
||||
sc.recordLock.Lock()
|
||||
if sc.recording.Load() && sc.recorder != nil {
|
||||
sc.recorder.Write(chunk)
|
||||
}
|
||||
sc.recordLock.Unlock()
|
||||
}
|
||||
sc.recordLock.Unlock()
|
||||
|
||||
layout := sc.table.layout
|
||||
for _, b := range chunk {
|
||||
if !sc.table.layout.isHint(b) {
|
||||
if !layout.hintTable[b] {
|
||||
continue
|
||||
}
|
||||
|
||||
sc.hintBuf = append(sc.hintBuf, b)
|
||||
if len(sc.hintBuf) == 4 {
|
||||
key := packHintsToKey([4]byte{sc.hintBuf[0], sc.hintBuf[1], sc.hintBuf[2], sc.hintBuf[3]})
|
||||
sc.hintBuf[sc.hintCount] = b
|
||||
sc.hintCount++
|
||||
if sc.hintCount == len(sc.hintBuf) {
|
||||
key := packHintsToKey(sc.hintBuf)
|
||||
val, ok := sc.table.DecodeMap[key]
|
||||
if !ok {
|
||||
return 0, errors.New("INVALID_SUDOKU_MAP_MISS")
|
||||
return 0, ErrInvalidSudokuMapMiss
|
||||
}
|
||||
sc.pendingData = append(sc.pendingData, val)
|
||||
sc.hintBuf = sc.hintBuf[:0]
|
||||
sc.pendingData.appendByte(val)
|
||||
sc.hintCount = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -212,16 +183,11 @@ func (sc *Conn) Read(p []byte) (n int, err error) {
|
||||
if rErr != nil {
|
||||
return 0, rErr
|
||||
}
|
||||
if len(sc.pendingData) > 0 {
|
||||
if sc.pendingData.available() > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
n = copy(p, sc.pendingData)
|
||||
if n == len(sc.pendingData) {
|
||||
sc.pendingData = sc.pendingData[:0]
|
||||
} else {
|
||||
sc.pendingData = sc.pendingData[n:]
|
||||
}
|
||||
n, _ = drainPending(p, &sc.pendingData)
|
||||
return n, nil
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package sudoku
|
||||
|
||||
func encodeSudokuPayload(dst []byte, table *Table, rng randomSource, paddingThreshold uint64, p []byte) []byte {
|
||||
if len(p) == 0 {
|
||||
return dst[:0]
|
||||
}
|
||||
|
||||
outCapacity := len(p)*6 + 1
|
||||
if cap(dst) < outCapacity {
|
||||
dst = make([]byte, 0, outCapacity)
|
||||
}
|
||||
out := dst[:0]
|
||||
pads := table.PaddingPool
|
||||
padLen := len(pads)
|
||||
|
||||
for _, b := range p {
|
||||
if shouldPad(rng, paddingThreshold) {
|
||||
out = append(out, pads[rng.Intn(padLen)])
|
||||
}
|
||||
|
||||
puzzles := table.EncodeTable[b]
|
||||
puzzle := puzzles[rng.Intn(len(puzzles))]
|
||||
perm := perm4[rng.Intn(len(perm4))]
|
||||
for _, idx := range perm {
|
||||
if shouldPad(rng, paddingThreshold) {
|
||||
out = append(out, pads[rng.Intn(padLen)])
|
||||
}
|
||||
out = append(out, puzzle[idx])
|
||||
}
|
||||
}
|
||||
|
||||
if shouldPad(rng, paddingThreshold) {
|
||||
out = append(out, pads[rng.Intn(padLen)])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -14,17 +14,30 @@ type byteLayout struct {
|
||||
padMarker byte
|
||||
paddingPool []byte
|
||||
|
||||
encodeHint func(val, pos byte) byte
|
||||
encodeGroup func(group byte) byte
|
||||
decodeGroup func(b byte) (byte, bool)
|
||||
hintTable [256]bool
|
||||
encodeHint [4][16]byte
|
||||
encodeGroup [64]byte
|
||||
decodeGroup [256]byte
|
||||
groupValid [256]bool
|
||||
}
|
||||
|
||||
func (l *byteLayout) isHint(b byte) bool {
|
||||
if (b & l.hintMask) == l.hintValue {
|
||||
return true
|
||||
return l != nil && l.hintTable[b]
|
||||
}
|
||||
|
||||
func (l *byteLayout) hintByte(val, pos byte) byte {
|
||||
return l.encodeHint[val&0x03][pos&0x0F]
|
||||
}
|
||||
|
||||
func (l *byteLayout) groupByte(group byte) byte {
|
||||
return l.encodeGroup[group&0x3F]
|
||||
}
|
||||
|
||||
func (l *byteLayout) decodePackedGroup(b byte) (byte, bool) {
|
||||
if l == nil {
|
||||
return 0, false
|
||||
}
|
||||
// ASCII layout maps the single non-printable marker (0x7F) to '\n' on the wire.
|
||||
return l.name == "ascii" && b == '\n'
|
||||
return l.decodeGroup[b], l.groupValid[b]
|
||||
}
|
||||
|
||||
// resolveLayout picks the byte layout for a single traffic direction.
|
||||
@@ -50,38 +63,44 @@ func newASCIILayout() *byteLayout {
|
||||
for i := 0; i < 32; i++ {
|
||||
padding = append(padding, byte(0x20+i))
|
||||
}
|
||||
return &byteLayout{
|
||||
|
||||
layout := &byteLayout{
|
||||
name: "ascii",
|
||||
hintMask: 0x40,
|
||||
hintValue: 0x40,
|
||||
padMarker: 0x3F,
|
||||
paddingPool: padding,
|
||||
encodeHint: func(val, pos byte) byte {
|
||||
b := 0x40 | ((val & 0x03) << 4) | (pos & 0x0F)
|
||||
// Avoid DEL (0x7F) in prefer_ascii mode; map it to '\n' to reduce fingerprint.
|
||||
if b == 0x7F {
|
||||
return '\n'
|
||||
}
|
||||
return b
|
||||
},
|
||||
encodeGroup: func(group byte) byte {
|
||||
b := 0x40 | (group & 0x3F)
|
||||
// Avoid DEL (0x7F) in prefer_ascii mode; map it to '\n' to reduce fingerprint.
|
||||
if b == 0x7F {
|
||||
return '\n'
|
||||
}
|
||||
return b
|
||||
},
|
||||
decodeGroup: func(b byte) (byte, bool) {
|
||||
if b == '\n' {
|
||||
return 0x3F, true
|
||||
}
|
||||
if (b & 0x40) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
return b & 0x3F, true
|
||||
},
|
||||
}
|
||||
|
||||
for val := 0; val < 4; val++ {
|
||||
for pos := 0; pos < 16; pos++ {
|
||||
b := byte(0x40 | (byte(val) << 4) | byte(pos))
|
||||
if b == 0x7F {
|
||||
b = '\n'
|
||||
}
|
||||
layout.encodeHint[val][pos] = b
|
||||
}
|
||||
}
|
||||
for group := 0; group < 64; group++ {
|
||||
b := byte(0x40 | byte(group))
|
||||
if b == 0x7F {
|
||||
b = '\n'
|
||||
}
|
||||
layout.encodeGroup[group] = b
|
||||
}
|
||||
for b := 0; b < 256; b++ {
|
||||
wire := byte(b)
|
||||
if (wire & 0x40) == 0x40 {
|
||||
layout.hintTable[wire] = true
|
||||
layout.decodeGroup[wire] = wire & 0x3F
|
||||
layout.groupValid[wire] = true
|
||||
}
|
||||
}
|
||||
layout.hintTable['\n'] = true
|
||||
layout.decodeGroup['\n'] = 0x3F
|
||||
layout.groupValid['\n'] = true
|
||||
|
||||
return layout
|
||||
}
|
||||
|
||||
func newEntropyLayout() *byteLayout {
|
||||
@@ -90,26 +109,35 @@ func newEntropyLayout() *byteLayout {
|
||||
padding = append(padding, byte(0x80+i))
|
||||
padding = append(padding, byte(0x10+i))
|
||||
}
|
||||
return &byteLayout{
|
||||
|
||||
layout := &byteLayout{
|
||||
name: "entropy",
|
||||
hintMask: 0x90,
|
||||
hintValue: 0x00,
|
||||
padMarker: 0x80,
|
||||
paddingPool: padding,
|
||||
encodeHint: func(val, pos byte) byte {
|
||||
return ((val & 0x03) << 5) | (pos & 0x0F)
|
||||
},
|
||||
encodeGroup: func(group byte) byte {
|
||||
v := group & 0x3F
|
||||
return ((v & 0x30) << 1) | (v & 0x0F)
|
||||
},
|
||||
decodeGroup: func(b byte) (byte, bool) {
|
||||
if (b & 0x90) != 0 {
|
||||
return 0, false
|
||||
}
|
||||
return ((b >> 1) & 0x30) | (b & 0x0F), true
|
||||
},
|
||||
}
|
||||
|
||||
for val := 0; val < 4; val++ {
|
||||
for pos := 0; pos < 16; pos++ {
|
||||
layout.encodeHint[val][pos] = (byte(val) << 5) | byte(pos)
|
||||
}
|
||||
}
|
||||
for group := 0; group < 64; group++ {
|
||||
v := byte(group)
|
||||
layout.encodeGroup[group] = ((v & 0x30) << 1) | (v & 0x0F)
|
||||
}
|
||||
for b := 0; b < 256; b++ {
|
||||
wire := byte(b)
|
||||
if (wire & 0x90) != 0 {
|
||||
continue
|
||||
}
|
||||
layout.hintTable[wire] = true
|
||||
layout.decodeGroup[wire] = ((wire >> 1) & 0x30) | (wire & 0x0F)
|
||||
layout.groupValid[wire] = true
|
||||
}
|
||||
|
||||
return layout
|
||||
}
|
||||
|
||||
func newCustomLayout(pattern string) (*byteLayout, error) {
|
||||
@@ -162,26 +190,6 @@ func newCustomLayout(pattern string) (*byteLayout, error) {
|
||||
return out
|
||||
}
|
||||
|
||||
decodeGroup := func(b byte) (byte, bool) {
|
||||
if (b & xMask) != xMask {
|
||||
return 0, false
|
||||
}
|
||||
var val, pos byte
|
||||
if b&(1<<pBits[0]) != 0 {
|
||||
val |= 0x02
|
||||
}
|
||||
if b&(1<<pBits[1]) != 0 {
|
||||
val |= 0x01
|
||||
}
|
||||
for i, bit := range vBits {
|
||||
if b&(1<<bit) != 0 {
|
||||
pos |= 1 << (3 - uint8(i))
|
||||
}
|
||||
}
|
||||
group := (val << 4) | (pos & 0x0F)
|
||||
return group, true
|
||||
}
|
||||
|
||||
paddingSet := make(map[byte]struct{})
|
||||
var padding []byte
|
||||
for drop := range xBits {
|
||||
@@ -202,20 +210,46 @@ func newCustomLayout(pattern string) (*byteLayout, error) {
|
||||
return nil, fmt.Errorf("custom table produced empty padding pool")
|
||||
}
|
||||
|
||||
return &byteLayout{
|
||||
layout := &byteLayout{
|
||||
name: fmt.Sprintf("custom(%s)", cleaned),
|
||||
hintMask: xMask,
|
||||
hintValue: xMask,
|
||||
padMarker: padding[0],
|
||||
paddingPool: padding,
|
||||
encodeHint: func(val, pos byte) byte {
|
||||
return encodeBits(val, pos, -1)
|
||||
},
|
||||
encodeGroup: func(group byte) byte {
|
||||
val := (group >> 4) & 0x03
|
||||
pos := group & 0x0F
|
||||
return encodeBits(val, pos, -1)
|
||||
},
|
||||
decodeGroup: decodeGroup,
|
||||
}, nil
|
||||
}
|
||||
|
||||
for val := 0; val < 4; val++ {
|
||||
for pos := 0; pos < 16; pos++ {
|
||||
layout.encodeHint[val][pos] = encodeBits(byte(val), byte(pos), -1)
|
||||
}
|
||||
}
|
||||
for group := 0; group < 64; group++ {
|
||||
val := byte(group>>4) & 0x03
|
||||
pos := byte(group) & 0x0F
|
||||
layout.encodeGroup[group] = encodeBits(val, pos, -1)
|
||||
}
|
||||
for b := 0; b < 256; b++ {
|
||||
wire := byte(b)
|
||||
if (wire & xMask) != xMask {
|
||||
continue
|
||||
}
|
||||
layout.hintTable[wire] = true
|
||||
|
||||
var val, pos byte
|
||||
if wire&(1<<pBits[0]) != 0 {
|
||||
val |= 0x02
|
||||
}
|
||||
if wire&(1<<pBits[1]) != 0 {
|
||||
val |= 0x01
|
||||
}
|
||||
for i, bit := range vBits {
|
||||
if wire&(1<<bit) != 0 {
|
||||
pos |= 1 << (3 - uint8(i))
|
||||
}
|
||||
}
|
||||
layout.decodeGroup[wire] = (val << 4) | pos
|
||||
layout.groupValid[wire] = true
|
||||
}
|
||||
|
||||
return layout, nil
|
||||
}
|
||||
@@ -2,10 +2,7 @@ package sudoku
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
crypto_rand "crypto/rand"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
@@ -25,7 +22,7 @@ type PackedConn struct {
|
||||
|
||||
// Read-side buffers.
|
||||
rawBuf []byte
|
||||
pendingData []byte
|
||||
pendingData pendingBuffer
|
||||
|
||||
// Write-side state.
|
||||
writeMu sync.Mutex
|
||||
@@ -38,7 +35,7 @@ type PackedConn struct {
|
||||
readBits int
|
||||
|
||||
// Padding selection matches Conn's threshold-based model.
|
||||
rng *rand.Rand
|
||||
rng randomSource
|
||||
paddingThreshold uint64
|
||||
padMarker byte
|
||||
padPool []byte
|
||||
@@ -65,19 +62,14 @@ func (pc *PackedConn) CloseRead() error {
|
||||
}
|
||||
|
||||
func NewPackedConn(c net.Conn, table *Table, pMin, pMax int) *PackedConn {
|
||||
var seedBytes [8]byte
|
||||
if _, err := crypto_rand.Read(seedBytes[:]); err != nil {
|
||||
binary.BigEndian.PutUint64(seedBytes[:], uint64(rand.Int63()))
|
||||
}
|
||||
seed := int64(binary.BigEndian.Uint64(seedBytes[:]))
|
||||
localRng := rand.New(rand.NewSource(seed))
|
||||
localRng := newSeededRand()
|
||||
|
||||
pc := &PackedConn{
|
||||
Conn: c,
|
||||
table: table,
|
||||
reader: bufio.NewReaderSize(c, IOBufferSize),
|
||||
rawBuf: make([]byte, IOBufferSize),
|
||||
pendingData: make([]byte, 0, 4096),
|
||||
pendingData: newPendingBuffer(4096),
|
||||
writeBuf: make([]byte, 0, 4096),
|
||||
rng: localRng,
|
||||
paddingThreshold: pickPaddingThreshold(localRng, pMin, pMax),
|
||||
@@ -104,7 +96,7 @@ func (pc *PackedConn) maybeAddPadding(out []byte) []byte {
|
||||
|
||||
func (pc *PackedConn) appendGroup(out []byte, group byte) []byte {
|
||||
out = pc.maybeAddPadding(out)
|
||||
return append(out, pc.encodeGroup(group))
|
||||
return append(out, pc.table.layout.groupByte(group))
|
||||
}
|
||||
|
||||
func (pc *PackedConn) appendForcedPadding(out []byte) []byte {
|
||||
@@ -156,19 +148,6 @@ func (pc *PackedConn) writeProtectedPrefix(out []byte, p []byte) ([]byte, int) {
|
||||
return out, limit
|
||||
}
|
||||
|
||||
func (pc *PackedConn) drainPendingData(dst []byte) int {
|
||||
n := copy(dst, pc.pendingData)
|
||||
if n == len(pc.pendingData) {
|
||||
pc.pendingData = pc.pendingData[:0]
|
||||
return n
|
||||
}
|
||||
|
||||
remaining := len(pc.pendingData) - n
|
||||
copy(pc.pendingData, pc.pendingData[n:])
|
||||
pc.pendingData = pc.pendingData[:remaining]
|
||||
return n
|
||||
}
|
||||
|
||||
func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
@@ -282,7 +261,7 @@ func (pc *PackedConn) Flush() error {
|
||||
pc.bitBuf = 0
|
||||
pc.bitCount = 0
|
||||
|
||||
out = append(out, pc.encodeGroup(group&0x3F))
|
||||
out = append(out, pc.table.layout.groupByte(group&0x3F))
|
||||
out = append(out, pc.padMarker)
|
||||
}
|
||||
|
||||
@@ -301,14 +280,17 @@ func writeFull(w io.Writer, b []byte) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return io.ErrShortWrite
|
||||
}
|
||||
b = b[n:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pc *PackedConn) Read(p []byte) (int, error) {
|
||||
if len(pc.pendingData) > 0 {
|
||||
return pc.drainPendingData(p), nil
|
||||
if n, ok := drainPending(p, &pc.pendingData); ok {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
for {
|
||||
@@ -320,7 +302,7 @@ func (pc *PackedConn) Read(p []byte) (int, error) {
|
||||
layout := pc.table.layout
|
||||
|
||||
for _, b := range pc.rawBuf[:nr] {
|
||||
if !layout.isHint(b) {
|
||||
if !layout.hintTable[b] {
|
||||
if b == padMarker {
|
||||
rBuf = 0
|
||||
rBits = 0
|
||||
@@ -328,7 +310,7 @@ func (pc *PackedConn) Read(p []byte) (int, error) {
|
||||
continue
|
||||
}
|
||||
|
||||
group, ok := layout.decodeGroup(b)
|
||||
group, ok := layout.decodePackedGroup(b)
|
||||
if !ok {
|
||||
return 0, ErrInvalidSudokuMapMiss
|
||||
}
|
||||
@@ -339,7 +321,12 @@ func (pc *PackedConn) Read(p []byte) (int, error) {
|
||||
if rBits >= 8 {
|
||||
rBits -= 8
|
||||
val := byte(rBuf >> rBits)
|
||||
pc.pendingData = append(pc.pendingData, val)
|
||||
pc.pendingData.appendByte(val)
|
||||
if rBits == 0 {
|
||||
rBuf = 0
|
||||
} else {
|
||||
rBuf &= (uint64(1) << rBits) - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,24 +339,21 @@ func (pc *PackedConn) Read(p []byte) (int, error) {
|
||||
pc.readBitBuf = 0
|
||||
pc.readBits = 0
|
||||
}
|
||||
if len(pc.pendingData) > 0 {
|
||||
if pc.pendingData.available() > 0 {
|
||||
break
|
||||
}
|
||||
return 0, rErr
|
||||
}
|
||||
|
||||
if len(pc.pendingData) > 0 {
|
||||
if pc.pendingData.available() > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return pc.drainPendingData(p), nil
|
||||
n, _ := drainPending(p, &pc.pendingData)
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (pc *PackedConn) getPaddingByte() byte {
|
||||
return pc.padPool[pc.rng.Intn(len(pc.padPool))]
|
||||
}
|
||||
|
||||
func (pc *PackedConn) encodeGroup(group byte) byte {
|
||||
return pc.table.layout.encodeGroup(group)
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
package sudoku
|
||||
|
||||
import "math/rand"
|
||||
|
||||
const probOne = uint64(1) << 32
|
||||
|
||||
func pickPaddingThreshold(r *rand.Rand, pMin, pMax int) uint64 {
|
||||
func pickPaddingThreshold(r randomSource, pMin, pMax int) uint64 {
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
@@ -30,7 +28,7 @@ func pickPaddingThreshold(r *rand.Rand, pMin, pMax int) uint64 {
|
||||
return min + (u * (max - min) >> 32)
|
||||
}
|
||||
|
||||
func shouldPad(r *rand.Rand, threshold uint64) bool {
|
||||
func shouldPad(r randomSource, threshold uint64) bool {
|
||||
if threshold == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package sudoku
|
||||
|
||||
type pendingBuffer struct {
|
||||
data []byte
|
||||
off int
|
||||
}
|
||||
|
||||
func newPendingBuffer(capacity int) pendingBuffer {
|
||||
return pendingBuffer{data: make([]byte, 0, capacity)}
|
||||
}
|
||||
|
||||
func (p *pendingBuffer) available() int {
|
||||
if p == nil {
|
||||
return 0
|
||||
}
|
||||
return len(p.data) - p.off
|
||||
}
|
||||
|
||||
func (p *pendingBuffer) reset() {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
p.data = p.data[:0]
|
||||
p.off = 0
|
||||
}
|
||||
|
||||
func (p *pendingBuffer) ensureAppendCapacity(extra int) {
|
||||
if p == nil || extra <= 0 || p.off == 0 {
|
||||
return
|
||||
}
|
||||
if cap(p.data)-len(p.data) >= extra {
|
||||
return
|
||||
}
|
||||
|
||||
unread := len(p.data) - p.off
|
||||
copy(p.data[:unread], p.data[p.off:])
|
||||
p.data = p.data[:unread]
|
||||
p.off = 0
|
||||
}
|
||||
|
||||
func (p *pendingBuffer) appendByte(b byte) {
|
||||
p.ensureAppendCapacity(1)
|
||||
p.data = append(p.data, b)
|
||||
}
|
||||
|
||||
func drainPending(dst []byte, pending *pendingBuffer) (int, bool) {
|
||||
if pending == nil || pending.available() == 0 {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
n := copy(dst, pending.data[pending.off:])
|
||||
pending.off += n
|
||||
if pending.off == len(pending.data) {
|
||||
pending.reset()
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package sudoku
|
||||
|
||||
import (
|
||||
crypto_rand "crypto/rand"
|
||||
"encoding/binary"
|
||||
"time"
|
||||
)
|
||||
|
||||
type randomSource interface {
|
||||
Uint32() uint32
|
||||
Uint64() uint64
|
||||
Intn(n int) int
|
||||
}
|
||||
|
||||
type sudokuRand struct {
|
||||
state uint64
|
||||
}
|
||||
|
||||
func newSeededRand() *sudokuRand {
|
||||
seed := time.Now().UnixNano()
|
||||
var seedBytes [8]byte
|
||||
if _, err := crypto_rand.Read(seedBytes[:]); err == nil {
|
||||
seed = int64(binary.BigEndian.Uint64(seedBytes[:]))
|
||||
}
|
||||
return newSudokuRand(seed)
|
||||
}
|
||||
|
||||
func newSudokuRand(seed int64) *sudokuRand {
|
||||
state := uint64(seed)
|
||||
if state == 0 {
|
||||
state = 0x9e3779b97f4a7c15
|
||||
}
|
||||
return &sudokuRand{state: state}
|
||||
}
|
||||
|
||||
func (r *sudokuRand) Uint64() uint64 {
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
r.state += 0x9e3779b97f4a7c15
|
||||
z := r.state
|
||||
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9
|
||||
z = (z ^ (z >> 27)) * 0x94d049bb133111eb
|
||||
return z ^ (z >> 31)
|
||||
}
|
||||
|
||||
func (r *sudokuRand) Uint32() uint32 {
|
||||
return uint32(r.Uint64() >> 32)
|
||||
}
|
||||
|
||||
func (r *sudokuRand) Intn(n int) int {
|
||||
if n <= 1 {
|
||||
return 0
|
||||
}
|
||||
return int((uint64(r.Uint32()) * uint64(n)) >> 32)
|
||||
}
|
||||
@@ -146,7 +146,7 @@ func newSingleDirectionTable(key string, mode string, customPattern string) (*Ta
|
||||
if matchCount == 1 {
|
||||
// 唯一确定,生成最终编码字节
|
||||
for i, p := range rawParts {
|
||||
currentHints[i] = t.layout.encodeHint(p.val-1, p.pos)
|
||||
currentHints[i] = t.layout.hintByte(p.val-1, p.pos)
|
||||
}
|
||||
|
||||
t.EncodeTable[byteVal] = append(t.EncodeTable[byteVal], currentHints)
|
||||
|
||||
+60
-42
@@ -8,7 +8,6 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -37,42 +36,15 @@ func WriteDatagram(w io.Writer, addr string, payload []byte) error {
|
||||
binary.BigEndian.PutUint16(header[:2], uint16(len(addrBuf)))
|
||||
binary.BigEndian.PutUint16(header[2:], uint16(len(payload)))
|
||||
|
||||
if err := writeFull(w, header[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeFull(w, addrBuf); err != nil {
|
||||
return err
|
||||
}
|
||||
return writeFull(w, payload)
|
||||
return writeAllChunks(w, header[:], addrBuf, payload)
|
||||
}
|
||||
|
||||
// ReadDatagram parses a single UDP datagram frame from the reliable stream.
|
||||
func ReadDatagram(r io.Reader) (string, []byte, error) {
|
||||
var header [4]byte
|
||||
if _, err := io.ReadFull(r, header[:]); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
addrLen := int(binary.BigEndian.Uint16(header[:2]))
|
||||
payloadLen := int(binary.BigEndian.Uint16(header[2:]))
|
||||
|
||||
if addrLen <= 0 || addrLen > maxUoTPayload {
|
||||
return "", nil, fmt.Errorf("invalid address length: %d", addrLen)
|
||||
}
|
||||
if payloadLen < 0 || payloadLen > maxUoTPayload {
|
||||
return "", nil, fmt.Errorf("invalid payload length: %d", payloadLen)
|
||||
}
|
||||
|
||||
addrBuf := make([]byte, addrLen)
|
||||
if _, err := io.ReadFull(r, addrBuf); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
addr, err := DecodeAddress(bytes.NewReader(addrBuf))
|
||||
addr, payloadLen, err := readDatagramHeaderAndAddress(r)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("decode address: %w", err)
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
payload := make([]byte, payloadLen)
|
||||
if _, err := io.ReadFull(r, payload); err != nil {
|
||||
return "", nil, err
|
||||
@@ -93,26 +65,29 @@ func NewUoTPacketConn(conn net.Conn) *UoTPacketConn {
|
||||
|
||||
func (c *UoTPacketConn) ReadFrom(p []byte) (int, net.Addr, error) {
|
||||
for {
|
||||
addrStr, payload, err := ReadDatagram(c.conn)
|
||||
addrStr, payloadLen, err := readDatagramHeaderAndAddress(c.conn)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
if len(payload) > len(p) {
|
||||
udpAddr, err := parseDatagramUDPAddr(addrStr)
|
||||
if payloadLen > len(p) {
|
||||
if discardErr := discardBytes(c.conn, payloadLen); discardErr != nil {
|
||||
return 0, nil, discardErr
|
||||
}
|
||||
return 0, nil, io.ErrShortBuffer
|
||||
}
|
||||
|
||||
host, port, _ := net.SplitHostPort(addrStr)
|
||||
portInt, _ := strconv.ParseUint(port, 10, 16)
|
||||
ip, err := netip.ParseAddr(host)
|
||||
if err != nil { // disallow domain addr at here, just ignore
|
||||
if err != nil {
|
||||
if discardErr := discardBytes(c.conn, payloadLen); discardErr != nil {
|
||||
return 0, nil, discardErr
|
||||
}
|
||||
log.Debugln("[Sudoku][UoT] discard datagram with invalid address %s: %v", addrStr, err)
|
||||
continue
|
||||
}
|
||||
udpAddr := net.UDPAddrFromAddrPort(netip.AddrPortFrom(ip.Unmap(), uint16(portInt)))
|
||||
|
||||
copy(p, payload)
|
||||
return len(payload), udpAddr, nil
|
||||
if _, err := io.ReadFull(c.conn, p[:payloadLen]); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
return payloadLen, udpAddr, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,3 +122,46 @@ func (c *UoTPacketConn) SetReadDeadline(t time.Time) error {
|
||||
func (c *UoTPacketConn) SetWriteDeadline(t time.Time) error {
|
||||
return c.conn.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
func readDatagramHeaderAndAddress(r io.Reader) (string, int, error) {
|
||||
var header [4]byte
|
||||
if _, err := io.ReadFull(r, header[:]); err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
|
||||
addrLen := int(binary.BigEndian.Uint16(header[:2]))
|
||||
payloadLen := int(binary.BigEndian.Uint16(header[2:]))
|
||||
if addrLen <= 0 || addrLen > maxUoTPayload {
|
||||
return "", 0, fmt.Errorf("invalid address length: %d", addrLen)
|
||||
}
|
||||
if payloadLen < 0 || payloadLen > maxUoTPayload {
|
||||
return "", 0, fmt.Errorf("invalid payload length: %d", payloadLen)
|
||||
}
|
||||
|
||||
addrBuf := make([]byte, addrLen)
|
||||
if _, err := io.ReadFull(r, addrBuf); err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
|
||||
addr, err := DecodeAddress(bytes.NewReader(addrBuf))
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("decode address: %w", err)
|
||||
}
|
||||
return addr, payloadLen, nil
|
||||
}
|
||||
|
||||
func parseDatagramUDPAddr(addr string) (*net.UDPAddr, error) {
|
||||
addrPort, err := netip.ParseAddrPort(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return net.UDPAddrFromAddrPort(netip.AddrPortFrom(addrPort.Addr().Unmap(), addrPort.Port())), nil
|
||||
}
|
||||
|
||||
func discardBytes(r io.Reader, n int) error {
|
||||
if n <= 0 {
|
||||
return nil
|
||||
}
|
||||
_, err := io.CopyN(io.Discard, r, int64(n))
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package sudoku
|
||||
|
||||
import "io"
|
||||
|
||||
func writeAllChunks(w io.Writer, chunks ...[]byte) error {
|
||||
for _, chunk := range chunks {
|
||||
for len(chunk) > 0 {
|
||||
n, err := w.Write(chunk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return io.ErrShortWrite
|
||||
}
|
||||
chunk = chunk[n:]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+142
-50
@@ -6,12 +6,14 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/httputils"
|
||||
"github.com/metacubex/mihomo/common/once"
|
||||
"github.com/metacubex/mihomo/component/dialer"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/transport/vmess"
|
||||
|
||||
@@ -20,11 +22,11 @@ import (
|
||||
"golang.org/x/exp/slices"
|
||||
)
|
||||
|
||||
type ResolvUDPFunc func(ctx context.Context, server string) (netip.AddrPort, error)
|
||||
type DialOptionsFunc func() []dialer.Option
|
||||
|
||||
type ClientOptions struct {
|
||||
Dialer C.Dialer
|
||||
ResolvUDP ResolvUDPFunc
|
||||
DialOptions DialOptionsFunc // for quic
|
||||
Server string
|
||||
Username string
|
||||
Password string
|
||||
@@ -32,28 +34,33 @@ type ClientOptions struct {
|
||||
QUIC bool
|
||||
QUICCongestionControl string
|
||||
QUICCwnd int
|
||||
QUICBBRProfile string
|
||||
HealthCheck bool
|
||||
MaxConnections int
|
||||
MinStreams int
|
||||
MaxStreams int
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
ctx context.Context
|
||||
dialer C.Dialer
|
||||
resolv ResolvUDPFunc
|
||||
dialOptions DialOptionsFunc
|
||||
server string
|
||||
auth string
|
||||
roundTripper http.RoundTripper
|
||||
startOnce sync.Once
|
||||
healthCheck bool
|
||||
healthCheckTimer *time.Timer
|
||||
count atomic.Int64
|
||||
}
|
||||
|
||||
func NewClient(ctx context.Context, options ClientOptions) (client *Client, err error) {
|
||||
client = &Client{
|
||||
ctx: ctx,
|
||||
dialer: options.Dialer,
|
||||
resolv: options.ResolvUDP,
|
||||
server: options.Server,
|
||||
auth: buildAuth(options.Username, options.Password),
|
||||
ctx: ctx,
|
||||
dialer: options.Dialer,
|
||||
dialOptions: options.DialOptions,
|
||||
server: options.Server,
|
||||
auth: buildAuth(options.Username, options.Password),
|
||||
}
|
||||
if options.QUIC {
|
||||
if len(options.TLSConfig.NextProtos) == 0 {
|
||||
@@ -61,7 +68,7 @@ func NewClient(ctx context.Context, options ClientOptions) (client *Client, err
|
||||
} else if !slices.Contains(options.TLSConfig.NextProtos, "h3") {
|
||||
return nil, errors.New("require alpn h3")
|
||||
}
|
||||
err = client.quicRoundTripper(options.TLSConfig, options.QUICCongestionControl, options.QUICCwnd)
|
||||
err = client.quicRoundTripper(options.TLSConfig, options.QUICCongestionControl, options.QUICCwnd, options.QUICBBRProfile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -134,6 +141,10 @@ func (c *Client) roundTrip(request *http.Request, conn *httpConn) {
|
||||
writer: pipeWriter,
|
||||
created: make(chan struct{}),
|
||||
}
|
||||
c.count.Add(1)
|
||||
conn.closeFn = once.OnceFunc(func() {
|
||||
c.count.Add(-1)
|
||||
})
|
||||
ctx, cancel := context.WithCancel(c.ctx) // requestCtx must alive during conn not closed
|
||||
conn.cancelFn = cancel // cancel ctx when conn closed
|
||||
go func() {
|
||||
@@ -144,66 +155,51 @@ func (c *Client) roundTrip(request *http.Request, conn *httpConn) {
|
||||
if err != nil {
|
||||
_ = pipeWriter.CloseWithError(err)
|
||||
_ = pipeReader.CloseWithError(err)
|
||||
conn.setUp(nil, err)
|
||||
conn.setup(nil, err)
|
||||
} else if response.StatusCode != http.StatusOK {
|
||||
_ = response.Body.Close()
|
||||
err = fmt.Errorf("unexpected status code: %d", response.StatusCode)
|
||||
_ = pipeWriter.CloseWithError(err)
|
||||
_ = pipeReader.CloseWithError(err)
|
||||
conn.setUp(nil, err)
|
||||
conn.setup(nil, err)
|
||||
} else {
|
||||
c.resetHealthCheckTimer()
|
||||
conn.setUp(response.Body, nil)
|
||||
conn.setup(response.Body, nil)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (c *Client) Dial(ctx context.Context, host string) (net.Conn, error) {
|
||||
func (c *Client) newConnectRequest(host, userAgent string) *http.Request {
|
||||
request := &http.Request{
|
||||
Method: http.MethodConnect,
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: host,
|
||||
Host: c.server, // Use the proxy server authority so the pool keys reuse against the actual proxy endpoint.
|
||||
},
|
||||
Header: make(http.Header),
|
||||
Host: host,
|
||||
Host: host, // Send the actual CONNECT target as the Host header (:authority).
|
||||
}
|
||||
request.Header.Add("User-Agent", TCPUserAgent)
|
||||
request.Header.Add("User-Agent", userAgent)
|
||||
request.Header.Add("Proxy-Authorization", c.auth)
|
||||
return request
|
||||
}
|
||||
|
||||
func (c *Client) Dial(ctx context.Context, host string) (net.Conn, error) {
|
||||
request := c.newConnectRequest(host, TCPUserAgent)
|
||||
conn := &tcpConn{}
|
||||
c.roundTrip(request, &conn.httpConn)
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListenPacket(ctx context.Context) (net.PacketConn, error) {
|
||||
request := &http.Request{
|
||||
Method: http.MethodConnect,
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: UDPMagicAddress,
|
||||
},
|
||||
Header: make(http.Header),
|
||||
Host: UDPMagicAddress,
|
||||
}
|
||||
request.Header.Add("User-Agent", UDPUserAgent)
|
||||
request.Header.Add("Proxy-Authorization", c.auth)
|
||||
request := c.newConnectRequest(UDPMagicAddress, UDPUserAgent)
|
||||
conn := &clientPacketConn{}
|
||||
c.roundTrip(request, &conn.httpConn)
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListenICMP(ctx context.Context) (*IcmpConn, error) {
|
||||
request := &http.Request{
|
||||
Method: http.MethodConnect,
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: ICMPMagicAddress,
|
||||
},
|
||||
Header: make(http.Header),
|
||||
Host: ICMPMagicAddress,
|
||||
}
|
||||
request.Header.Add("User-Agent", ICMPUserAgent)
|
||||
request.Header.Add("Proxy-Authorization", c.auth)
|
||||
request := c.newConnectRequest(ICMPMagicAddress, ICMPUserAgent)
|
||||
conn := &IcmpConn{}
|
||||
c.roundTrip(request, &conn.httpConn)
|
||||
return conn, nil
|
||||
@@ -224,17 +220,7 @@ func (c *Client) ResetConnections() {
|
||||
|
||||
func (c *Client) HealthCheck(ctx context.Context) error {
|
||||
defer c.resetHealthCheckTimer()
|
||||
request := &http.Request{
|
||||
Method: http.MethodConnect,
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: HealthCheckMagicAddress,
|
||||
},
|
||||
Header: make(http.Header),
|
||||
Host: HealthCheckMagicAddress,
|
||||
}
|
||||
request.Header.Add("User-Agent", HealthCheckUserAgent)
|
||||
request.Header.Add("Proxy-Authorization", c.auth)
|
||||
request := c.newConnectRequest(HealthCheckMagicAddress, HealthCheckUserAgent)
|
||||
response, err := c.roundTripper.RoundTrip(request.WithContext(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -245,3 +231,109 @@ func (c *Client) HealthCheck(ctx context.Context) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type PoolClient struct {
|
||||
mutex sync.Mutex
|
||||
maxConnections int
|
||||
minStreams int
|
||||
maxStreams int
|
||||
ctx context.Context
|
||||
options ClientOptions
|
||||
clients []*Client
|
||||
}
|
||||
|
||||
func NewPoolClient(ctx context.Context, options ClientOptions) (*PoolClient, error) {
|
||||
maxConnections := options.MaxConnections
|
||||
minStreams := options.MinStreams
|
||||
maxStreams := options.MaxStreams
|
||||
if maxConnections == 0 && minStreams == 0 && maxStreams == 0 {
|
||||
maxConnections = 8
|
||||
minStreams = 5
|
||||
}
|
||||
client, err := NewClient(ctx, options) // reserve one client and verify the configuration
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &PoolClient{
|
||||
maxConnections: maxConnections,
|
||||
minStreams: minStreams,
|
||||
maxStreams: maxStreams,
|
||||
ctx: ctx,
|
||||
options: options,
|
||||
clients: []*Client{client},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *PoolClient) Dial(ctx context.Context, host string) (net.Conn, error) {
|
||||
transport, err := c.getClient()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return transport.Dial(ctx, host)
|
||||
}
|
||||
|
||||
func (c *PoolClient) ListenPacket(ctx context.Context) (net.PacketConn, error) {
|
||||
transport, err := c.getClient()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return transport.ListenPacket(ctx)
|
||||
}
|
||||
|
||||
func (c *PoolClient) ListenICMP(ctx context.Context) (*IcmpConn, error) {
|
||||
transport, err := c.getClient()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return transport.ListenICMP(ctx)
|
||||
}
|
||||
|
||||
func (c *PoolClient) Close() error {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
var errs []error
|
||||
for _, t := range c.clients {
|
||||
if err := t.Close(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
c.clients = nil
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func (c *PoolClient) getClient() (*Client, error) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
var transport *Client
|
||||
for _, t := range c.clients {
|
||||
if transport == nil || t.count.Load() < transport.count.Load() {
|
||||
transport = t
|
||||
}
|
||||
}
|
||||
if transport == nil {
|
||||
return c.newTransportLocked()
|
||||
}
|
||||
numStreams := int(transport.count.Load())
|
||||
if numStreams == 0 {
|
||||
return transport, nil
|
||||
}
|
||||
if c.maxConnections > 0 {
|
||||
if len(c.clients) >= c.maxConnections || numStreams < c.minStreams {
|
||||
return transport, nil
|
||||
}
|
||||
} else {
|
||||
if c.maxStreams > 0 && numStreams < c.maxStreams {
|
||||
return transport, nil
|
||||
}
|
||||
}
|
||||
return c.newTransportLocked()
|
||||
}
|
||||
|
||||
func (c *PoolClient) newTransportLocked() (*Client, error) {
|
||||
transport, err := NewClient(c.ctx, c.options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.clients = append(c.clients, transport)
|
||||
return transport, nil
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/netip"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/httputils"
|
||||
@@ -95,31 +96,39 @@ type httpConn struct {
|
||||
writer io.Writer
|
||||
flusher http.Flusher
|
||||
body io.ReadCloser
|
||||
setupOnce sync.Once
|
||||
created chan struct{}
|
||||
createErr error
|
||||
cancelFn func()
|
||||
closeFn func()
|
||||
httputils.NetAddr
|
||||
|
||||
// deadlines
|
||||
deadline *time.Timer
|
||||
}
|
||||
|
||||
func (h *httpConn) setUp(body io.ReadCloser, err error) {
|
||||
h.body = body
|
||||
h.createErr = err
|
||||
close(h.created)
|
||||
func (h *httpConn) setup(body io.ReadCloser, err error) {
|
||||
h.setupOnce.Do(func() {
|
||||
h.body = body
|
||||
h.createErr = err
|
||||
close(h.created)
|
||||
})
|
||||
if h.createErr != nil && body != nil { // conn already closed before setup
|
||||
_ = body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *httpConn) waitCreated() error {
|
||||
if h.body != nil || h.createErr != nil {
|
||||
return h.createErr
|
||||
}
|
||||
<-h.created
|
||||
if h.body != nil {
|
||||
return nil
|
||||
}
|
||||
return h.createErr
|
||||
}
|
||||
|
||||
func (h *httpConn) Close() error {
|
||||
var errorArr []error
|
||||
h.setup(nil, net.ErrClosed)
|
||||
if closer, ok := h.writer.(io.Closer); ok {
|
||||
errorArr = append(errorArr, closer.Close())
|
||||
}
|
||||
@@ -129,6 +138,9 @@ func (h *httpConn) Close() error {
|
||||
if h.cancelFn != nil {
|
||||
h.cancelFn()
|
||||
}
|
||||
if h.closeFn != nil {
|
||||
h.closeFn()
|
||||
}
|
||||
return errors.Join(errorArr...)
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
"github.com/metacubex/tls"
|
||||
)
|
||||
|
||||
func (c *Client) quicRoundTripper(tlsConfig *vmess.TLSConfig, congestionControlName string, cwnd int) error {
|
||||
func (c *Client) quicRoundTripper(tlsConfig *vmess.TLSConfig, congestionControlName string, cwnd int, bbrProfile string) error {
|
||||
stdConfig, err := tlsConfig.ToStdConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -30,24 +30,15 @@ func (c *Client) quicRoundTripper(tlsConfig *vmess.TLSConfig, congestionControlN
|
||||
Allow0RTT: false,
|
||||
},
|
||||
Dial: func(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *quic.Config) (*quic.Conn, error) {
|
||||
addrPort, err := c.resolv(ctx, c.server)
|
||||
err := tlsConfig.ECH.ClientHandle(ctx, tlsCfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = tlsConfig.ECH.ClientHandle(ctx, tlsCfg)
|
||||
_, quicConn, err := common.DialQuic(ctx, addr, c.dialOptions(), c.dialer, tlsCfg, cfg, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
packetConn, err := c.dialer.ListenPacket(ctx, "udp", "", addrPort)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
quicConn, err := quic.DialEarly(ctx, packetConn, net.UDPAddrFromAddrPort(addrPort), tlsCfg, cfg)
|
||||
if err != nil {
|
||||
_ = packetConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
common.SetCongestionController(quicConn, congestionControlName, cwnd)
|
||||
common.SetCongestionController(quicConn, congestionControlName, cwnd, bbrProfile)
|
||||
return quicConn, nil
|
||||
},
|
||||
}
|
||||
@@ -69,7 +60,7 @@ func (s *Service) configHTTP3Server(tlsConfig *tls.Config, udpConn net.PacketCon
|
||||
Handler: s,
|
||||
IdleTimeout: DefaultSessionTimeout,
|
||||
ConnContext: func(ctx context.Context, conn *quic.Conn) context.Context {
|
||||
common.SetCongestionController(conn, s.quicCongestionControl, s.quicCwnd)
|
||||
common.SetCongestionController(conn, s.quicCongestionControl, s.quicCwnd, s.quicBBRProfile)
|
||||
return ctx
|
||||
},
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/httputils"
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/http/h2c"
|
||||
@@ -18,13 +19,13 @@ import (
|
||||
E "github.com/metacubex/sing/common/exceptions"
|
||||
"github.com/metacubex/sing/common/logger"
|
||||
M "github.com/metacubex/sing/common/metadata"
|
||||
N "github.com/metacubex/sing/common/network"
|
||||
"github.com/metacubex/sing/common/network"
|
||||
"github.com/metacubex/tls"
|
||||
)
|
||||
|
||||
type Handler interface {
|
||||
N.TCPConnectionHandler
|
||||
N.UDPConnectionHandler
|
||||
network.TCPConnectionHandler
|
||||
network.UDPConnectionHandler
|
||||
}
|
||||
|
||||
type ICMPHandler interface {
|
||||
@@ -38,6 +39,7 @@ type ServiceOptions struct {
|
||||
ICMPHandler ICMPHandler
|
||||
QUICCongestionControl string
|
||||
QUICCwnd int
|
||||
QUICBBRProfile string
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
@@ -48,6 +50,7 @@ type Service struct {
|
||||
icmpHandler ICMPHandler
|
||||
quicCongestionControl string
|
||||
quicCwnd int
|
||||
quicBBRProfile string
|
||||
httpServer *http.Server
|
||||
h2Server *http.Http2Server
|
||||
h3Server *http3.Server
|
||||
@@ -64,6 +67,7 @@ func NewService(options ServiceOptions) *Service {
|
||||
icmpHandler: options.ICMPHandler,
|
||||
quicCongestionControl: options.QUICCongestionControl,
|
||||
quicCwnd: options.QUICCwnd,
|
||||
quicBBRProfile: options.QUICBBRProfile,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,7 +167,7 @@ func (s *Service) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
},
|
||||
}
|
||||
httputils.SetAddrFromRequest(&conn.NetAddr, request)
|
||||
conn.setUp(request.Body, nil)
|
||||
conn.setup(request.Body, nil)
|
||||
firstPacket := buf.NewPacket()
|
||||
destination, err := conn.ReadPacket(firstPacket)
|
||||
if err != nil {
|
||||
@@ -200,7 +204,7 @@ func (s *Service) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
},
|
||||
}
|
||||
httputils.SetAddrFromRequest(&conn.NetAddr, request)
|
||||
conn.setUp(request.Body, nil)
|
||||
conn.setup(request.Body, nil)
|
||||
s.icmpHandler.NewICMPConnection(ctx, conn)
|
||||
}
|
||||
case HealthCheckMagicAddress:
|
||||
@@ -223,8 +227,8 @@ func (s *Service) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
},
|
||||
}
|
||||
httputils.SetAddrFromRequest(&conn.NetAddr, request)
|
||||
conn.setUp(request.Body, nil)
|
||||
_ = s.handler.NewConnection(ctx, conn, M.Metadata{
|
||||
conn.setup(request.Body, nil)
|
||||
_ = s.handler.NewConnection(ctx, N.NewDeadlineConn(conn), M.Metadata{
|
||||
Protocol: "trusttunnel",
|
||||
Source: M.ParseSocksaddr(request.RemoteAddr),
|
||||
Destination: M.ParseSocksaddr(request.Host).Unwrap(),
|
||||
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user