mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-03-04 04:47:30 +00:00
Compare commits
181 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4277dc6eab | ||
|
|
0e228765fc | ||
|
|
f45ccc0761 | ||
|
|
9f4cd646c2 | ||
|
|
a9ecc627e6 | ||
|
|
50286678bf | ||
|
|
917c5fdd80 | ||
|
|
1457f83530 | ||
|
|
5ab8154e7e | ||
|
|
09be5cbc99 | ||
|
|
0738e18100 | ||
|
|
40f40f6d24 | ||
|
|
ad5bc51c77 | ||
|
|
75c16f9b87 | ||
|
|
d96d7651ca | ||
|
|
a5f25a2246 | ||
|
|
2b4741fbc7 | ||
|
|
f317baa8de | ||
|
|
5678131591 | ||
|
|
10f8ba4434 | ||
|
|
cacfefad4b | ||
|
|
0d4e57cb21 | ||
|
|
063836fe5d | ||
|
|
7b3c9e94e6 | ||
|
|
be3d121ec6 | ||
|
|
59fd3cffe3 | ||
|
|
39eda257a7 | ||
|
|
d3fea909e9 | ||
|
|
7eb70aeb4d | ||
|
|
846bdfa812 | ||
|
|
0b6ae6ffb8 | ||
|
|
71922dd0b1 | ||
|
|
5eb8958ff2 | ||
|
|
ac2506154f | ||
|
|
43bdc76f87 | ||
|
|
3195c678c7 | ||
|
|
bd43eca09d | ||
|
|
c504985b99 | ||
|
|
4243a74284 | ||
|
|
48e481d0a2 | ||
|
|
e749c7e492 | ||
|
|
c3ee921d30 | ||
|
|
df69a31e62 | ||
|
|
b7c02a5923 | ||
|
|
bfb6caeeaf | ||
|
|
30a913aad6 | ||
|
|
00e361c5ac | ||
|
|
56edd8f671 | ||
|
|
2b52809d2c | ||
|
|
5c3a9b1dfc | ||
|
|
fe88f0e437 | ||
|
|
87877d1b80 | ||
|
|
1bc3c16b59 | ||
|
|
ed1e7e32c7 | ||
|
|
5da9ccaa98 | ||
|
|
fd7ecc004f | ||
|
|
3ae4014b39 | ||
|
|
a50339bd5f | ||
|
|
7df1c26942 | ||
|
|
fc82a32a48 | ||
|
|
adf0ff588f | ||
|
|
b840eae4c6 | ||
|
|
619f34119e | ||
|
|
6d1c62bbf0 | ||
|
|
5dd883e790 | ||
|
|
a2b43faa0b | ||
|
|
8861eaf903 | ||
|
|
107e3e7630 | ||
|
|
81947304bc | ||
|
|
314c0bb34b | ||
|
|
89a097faa8 | ||
|
|
df01582996 | ||
|
|
8ff56b5bb8 | ||
|
|
2f8f139f7c | ||
|
|
b2280c85b7 | ||
|
|
002b8af94a | ||
|
|
99b274acbc | ||
|
|
d4ececae20 | ||
|
|
ff2071c1da | ||
|
|
189b7b9c5f | ||
|
|
a878254662 | ||
|
|
3566542d0e | ||
|
|
ca84ab1a94 | ||
|
|
d84f88b50f | ||
|
|
e3b69b8ae2 | ||
|
|
91a7ffaad2 | ||
|
|
16fadd2441 | ||
|
|
cff7df164f | ||
|
|
de38fa882c | ||
|
|
bd703b8ff2 | ||
|
|
72df27be44 | ||
|
|
f3e23b1128 | ||
|
|
19f7220c0b | ||
|
|
3249572dc1 | ||
|
|
ba09139bd7 | ||
|
|
90bf158e9f | ||
|
|
d1539e6c07 | ||
|
|
c893e3c462 | ||
|
|
b56e73a02a | ||
|
|
40f5c5b987 | ||
|
|
d48517b29d | ||
|
|
3b472f786e | ||
|
|
f3743fc7f9 | ||
|
|
56ed9019a6 | ||
|
|
3e0bd65135 | ||
|
|
e27d7c010f | ||
|
|
72d0948224 | ||
|
|
4542fc0991 | ||
|
|
914bc8a3e9 | ||
|
|
11f0983e5c | ||
|
|
89d7b8138a | ||
|
|
eae1f05e88 | ||
|
|
367a287153 | ||
|
|
06b5121d9e | ||
|
|
82517e6ba8 | ||
|
|
582e94ff4d | ||
|
|
0b4662e4b7 | ||
|
|
288899a473 | ||
|
|
5af7f4e847 | ||
|
|
d2ae94f20b | ||
|
|
d56a439a74 | ||
|
|
9c08e936f9 | ||
|
|
284b01ca38 | ||
|
|
2e94531c72 | ||
|
|
e1a5b93cce | ||
|
|
7fd5902e6b | ||
|
|
143fe84b8e | ||
|
|
80408855ac | ||
|
|
c80dd5d738 | ||
|
|
b3db113b1b | ||
|
|
dceb8ee535 | ||
|
|
31d3614060 | ||
|
|
5fdfde6a07 | ||
|
|
81c832ef9e | ||
|
|
012e448562 | ||
|
|
44d8a14629 | ||
|
|
7ad37ca0e3 | ||
|
|
f0ff6546e4 | ||
|
|
77c10d90f3 | ||
|
|
e0248faebd | ||
|
|
feedc9ec66 | ||
|
|
7754b46dc4 | ||
|
|
90d0ef033b | ||
|
|
5702d28cda | ||
|
|
0bb5568de9 | ||
|
|
37b02b18f7 | ||
|
|
cd9e9cd2c1 | ||
|
|
234a4bfc93 | ||
|
|
fad1a08378 | ||
|
|
04886761a2 | ||
|
|
823f59b5c7 | ||
|
|
974332c0cc | ||
|
|
8b9813079b | ||
|
|
fe4acebb8b | ||
|
|
69bf434e2c | ||
|
|
e867497315 | ||
|
|
3ec23c1fc5 | ||
|
|
d27340867f | ||
|
|
7eb16a098a | ||
|
|
f0bc68585a | ||
|
|
092e53586e | ||
|
|
41e3571e1d | ||
|
|
e58294198c | ||
|
|
0619c75276 | ||
|
|
78b4b11f26 | ||
|
|
8d9eb1e534 | ||
|
|
d2a5376cb8 | ||
|
|
f8295a02fd | ||
|
|
3d833ef6a8 | ||
|
|
1c7e011f87 | ||
|
|
9e7eaf720f | ||
|
|
6399347a63 | ||
|
|
23e3f12e88 | ||
|
|
985b884d85 | ||
|
|
93b48a94fc | ||
|
|
080d316059 | ||
|
|
0c384b1e42 | ||
|
|
324c0bde7d | ||
|
|
9e57e7d29b | ||
|
|
20658f6eac | ||
|
|
822ba5f0b5 |
8
.github/genReleaseNote.sh
vendored
8
.github/genReleaseNote.sh
vendored
@@ -18,15 +18,15 @@ if [ -z "$version_range" ]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
echo "## What's Changed" > release.md
|
echo "## What's Changed" > release.md
|
||||||
git log --pretty=format:"* %s by @%an" --grep="^feat" -i $version_range | sort -f | uniq >> release.md
|
git log --pretty=format:"* %h %s by @%an" --grep="^feat" -i $version_range | sort -f | uniq >> release.md
|
||||||
echo "" >> release.md
|
echo "" >> release.md
|
||||||
|
|
||||||
echo "## BUG & Fix" >> release.md
|
echo "## BUG & Fix" >> release.md
|
||||||
git log --pretty=format:"* %s by @%an" --grep="^fix" -i $version_range | sort -f | uniq >> release.md
|
git log --pretty=format:"* %h %s by @%an" --grep="^fix" -i $version_range | sort -f | uniq >> release.md
|
||||||
echo "" >> release.md
|
echo "" >> release.md
|
||||||
|
|
||||||
echo "## Maintenance" >> release.md
|
echo "## Maintenance" >> release.md
|
||||||
git log --pretty=format:"* %s by @%an" --grep="^chore\|^docs\|^refactor" -i $version_range | sort -f | uniq >> release.md
|
git log --pretty=format:"* %h %s by @%an" --grep="^chore\|^docs\|^refactor" -i $version_range | sort -f | uniq >> release.md
|
||||||
echo "" >> release.md
|
echo "" >> release.md
|
||||||
|
|
||||||
echo "**Full Changelog**: https://github.com/MetaCubeX/Clash.Meta/compare/$version_range" >> release.md
|
echo "**Full Changelog**: https://github.com/MetaCubeX/mihomo/compare/$version_range" >> release.md
|
||||||
|
|||||||
17
.github/mihomo.service
vendored
Normal file
17
.github/mihomo.service
vendored
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=mihomo Daemon, Another Clash Kernel.
|
||||||
|
After=network.target NetworkManager.service systemd-networkd.service iwd.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
LimitNPROC=500
|
||||||
|
LimitNOFILE=1000000
|
||||||
|
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SYS_TIME CAP_SYS_PTRACE CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE
|
||||||
|
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SYS_TIME CAP_SYS_PTRACE CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE
|
||||||
|
Restart=always
|
||||||
|
ExecStartPre=/usr/bin/sleep 2s
|
||||||
|
ExecStart=/usr/bin/mihomo -d /etc/mihomo
|
||||||
|
ExecReload=/bin/kill -HUP $MAINPID
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
54
.github/patch_go122/48042aa09c2f878c4faa576948b07fe625c4707a.diff
vendored
Normal file
54
.github/patch_go122/48042aa09c2f878c4faa576948b07fe625c4707a.diff
vendored
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
index 06e684c7116b4..b311a5c74684b 100644
|
||||||
|
--- a/src/syscall/exec_windows.go
|
||||||
|
+++ b/src/syscall/exec_windows.go
|
||||||
|
@@ -319,17 +319,6 @@ func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
- var maj, min, build uint32
|
||||||
|
- rtlGetNtVersionNumbers(&maj, &min, &build)
|
||||||
|
- isWin7 := maj < 6 || (maj == 6 && min <= 1)
|
||||||
|
- // NT kernel handles are divisible by 4, with the bottom 3 bits left as
|
||||||
|
- // a tag. The fully set tag correlates with the types of handles we're
|
||||||
|
- // concerned about here. Except, the kernel will interpret some
|
||||||
|
- // special handle values, like -1, -2, and so forth, so kernelbase.dll
|
||||||
|
- // checks to see that those bottom three bits are checked, but that top
|
||||||
|
- // bit is not checked.
|
||||||
|
- isLegacyWin7ConsoleHandle := func(handle Handle) bool { return isWin7 && handle&0x10000003 == 3 }
|
||||||
|
-
|
||||||
|
p, _ := GetCurrentProcess()
|
||||||
|
parentProcess := p
|
||||||
|
if sys.ParentProcess != 0 {
|
||||||
|
@@ -338,15 +327,7 @@ func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle
|
||||||
|
fd := make([]Handle, len(attr.Files))
|
||||||
|
for i := range attr.Files {
|
||||||
|
if attr.Files[i] > 0 {
|
||||||
|
- destinationProcessHandle := parentProcess
|
||||||
|
-
|
||||||
|
- // On Windows 7, console handles aren't real handles, and can only be duplicated
|
||||||
|
- // into the current process, not a parent one, which amounts to the same thing.
|
||||||
|
- if parentProcess != p && isLegacyWin7ConsoleHandle(Handle(attr.Files[i])) {
|
||||||
|
- destinationProcessHandle = p
|
||||||
|
- }
|
||||||
|
-
|
||||||
|
- err := DuplicateHandle(p, Handle(attr.Files[i]), destinationProcessHandle, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
+ err := DuplicateHandle(p, Handle(attr.Files[i]), parentProcess, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
@@ -377,14 +358,6 @@ func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle
|
||||||
|
|
||||||
|
fd = append(fd, sys.AdditionalInheritedHandles...)
|
||||||
|
|
||||||
|
- // On Windows 7, console handles aren't real handles, so don't pass them
|
||||||
|
- // through to PROC_THREAD_ATTRIBUTE_HANDLE_LIST.
|
||||||
|
- for i := range fd {
|
||||||
|
- if isLegacyWin7ConsoleHandle(fd[i]) {
|
||||||
|
- fd[i] = 0
|
||||||
|
- }
|
||||||
|
- }
|
||||||
|
-
|
||||||
|
// The presence of a NULL handle in the list is enough to cause PROC_THREAD_ATTRIBUTE_HANDLE_LIST
|
||||||
|
// to treat the entire list as empty, so remove NULL handles.
|
||||||
|
j := 0
|
||||||
158
.github/patch_go122/693def151adff1af707d82d28f55dba81ceb08e1.diff
vendored
Normal file
158
.github/patch_go122/693def151adff1af707d82d28f55dba81ceb08e1.diff
vendored
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
index 62738e2cb1a7d..d0dcc7cc71fc0 100644
|
||||||
|
--- a/src/crypto/rand/rand.go
|
||||||
|
+++ b/src/crypto/rand/rand.go
|
||||||
|
@@ -15,7 +15,7 @@ import "io"
|
||||||
|
// available, /dev/urandom otherwise.
|
||||||
|
// On OpenBSD and macOS, Reader uses getentropy(2).
|
||||||
|
// On other Unix-like systems, Reader reads from /dev/urandom.
|
||||||
|
-// On Windows systems, Reader uses the RtlGenRandom API.
|
||||||
|
+// On Windows systems, Reader uses the ProcessPrng API.
|
||||||
|
// On JS/Wasm, Reader uses the Web Crypto API.
|
||||||
|
// On WASIP1/Wasm, Reader uses random_get from wasi_snapshot_preview1.
|
||||||
|
var Reader io.Reader
|
||||||
|
diff --git a/src/crypto/rand/rand_windows.go b/src/crypto/rand/rand_windows.go
|
||||||
|
index 6c0655c72b692..7380f1f0f1e6e 100644
|
||||||
|
--- a/src/crypto/rand/rand_windows.go
|
||||||
|
+++ b/src/crypto/rand/rand_windows.go
|
||||||
|
@@ -15,11 +15,8 @@ func init() { Reader = &rngReader{} }
|
||||||
|
|
||||||
|
type rngReader struct{}
|
||||||
|
|
||||||
|
-func (r *rngReader) Read(b []byte) (n int, err error) {
|
||||||
|
- // RtlGenRandom only returns 1<<32-1 bytes at a time. We only read at
|
||||||
|
- // most 1<<31-1 bytes at a time so that this works the same on 32-bit
|
||||||
|
- // and 64-bit systems.
|
||||||
|
- if err := batched(windows.RtlGenRandom, 1<<31-1)(b); err != nil {
|
||||||
|
+func (r *rngReader) Read(b []byte) (int, error) {
|
||||||
|
+ if err := windows.ProcessPrng(b); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(b), nil
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
index ab4ad2ec64108..5854ca60b5cef 100644
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
@@ -373,7 +373,7 @@ func ErrorLoadingGetTempPath2() error {
|
||||||
|
//sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
|
||||||
|
//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle syscall.Handle, err error) = kernel32.CreateEventW
|
||||||
|
|
||||||
|
-//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
+//sys ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
|
||||||
|
type FILE_ID_BOTH_DIR_INFO struct {
|
||||||
|
NextEntryOffset uint32
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
index e3f6d8d2a2208..5a587ad4f146c 100644
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
@@ -37,13 +37,14 @@ func errnoErr(e syscall.Errno) error {
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
- modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
|
||||||
|
- modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
|
||||||
|
- modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
|
||||||
|
- modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
|
||||||
|
- modpsapi = syscall.NewLazyDLL(sysdll.Add("psapi.dll"))
|
||||||
|
- moduserenv = syscall.NewLazyDLL(sysdll.Add("userenv.dll"))
|
||||||
|
- modws2_32 = syscall.NewLazyDLL(sysdll.Add("ws2_32.dll"))
|
||||||
|
+ modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
|
||||||
|
+ modbcryptprimitives = syscall.NewLazyDLL(sysdll.Add("bcryptprimitives.dll"))
|
||||||
|
+ modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
|
||||||
|
+ modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
|
||||||
|
+ modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
|
||||||
|
+ modpsapi = syscall.NewLazyDLL(sysdll.Add("psapi.dll"))
|
||||||
|
+ moduserenv = syscall.NewLazyDLL(sysdll.Add("userenv.dll"))
|
||||||
|
+ modws2_32 = syscall.NewLazyDLL(sysdll.Add("ws2_32.dll"))
|
||||||
|
|
||||||
|
procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
|
||||||
|
procDuplicateTokenEx = modadvapi32.NewProc("DuplicateTokenEx")
|
||||||
|
@@ -55,7 +56,7 @@ var (
|
||||||
|
procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
+ procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procGetACP = modkernel32.NewProc("GetACP")
|
||||||
|
@@ -179,12 +180,12 @@ func SetTokenInformation(tokenHandle syscall.Token, tokenInformationClass uint32
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
+func ProcessPrng(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.Syscall(procSystemFunction036.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
+ r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
index 8ca8d7790909e..3772a864b2ff4 100644
|
||||||
|
--- a/src/runtime/os_windows.go
|
||||||
|
+++ b/src/runtime/os_windows.go
|
||||||
|
@@ -127,15 +127,8 @@ var (
|
||||||
|
_WriteFile,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use RtlGenRandom to generate cryptographically random data.
|
||||||
|
- // This approach has been recommended by Microsoft (see issue
|
||||||
|
- // 15589 for details).
|
||||||
|
- // The RtlGenRandom is not listed in advapi32.dll, instead
|
||||||
|
- // RtlGenRandom function can be found by searching for SystemFunction036.
|
||||||
|
- // Also some versions of Mingw cannot link to SystemFunction036
|
||||||
|
- // when building executable as Cgo. So load SystemFunction036
|
||||||
|
- // manually during runtime startup.
|
||||||
|
- _RtlGenRandom stdFunction
|
||||||
|
+ // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
+ _ProcessPrng stdFunction
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -151,11 +144,11 @@ var (
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
- advapi32dll = [...]uint16{'a', 'd', 'v', 'a', 'p', 'i', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
- ntdlldll = [...]uint16{'n', 't', 'd', 'l', 'l', '.', 'd', 'l', 'l', 0}
|
||||||
|
- powrprofdll = [...]uint16{'p', 'o', 'w', 'r', 'p', 'r', 'o', 'f', '.', 'd', 'l', 'l', 0}
|
||||||
|
- winmmdll = [...]uint16{'w', 'i', 'n', 'm', 'm', '.', 'd', 'l', 'l', 0}
|
||||||
|
- ws2_32dll = [...]uint16{'w', 's', '2', '_', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ bcryptprimitivesdll = [...]uint16{'b', 'c', 'r', 'y', 'p', 't', 'p', 'r', 'i', 'm', 'i', 't', 'i', 'v', 'e', 's', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ ntdlldll = [...]uint16{'n', 't', 'd', 'l', 'l', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ powrprofdll = [...]uint16{'p', 'o', 'w', 'r', 'p', 'r', 'o', 'f', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ winmmdll = [...]uint16{'w', 'i', 'n', 'm', 'm', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ ws2_32dll = [...]uint16{'w', 's', '2', '_', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Function to be called by windows CreateThread
|
||||||
|
@@ -251,11 +244,11 @@ func windowsLoadSystemLib(name []uint16) uintptr {
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOptionalSyscalls() {
|
||||||
|
- a32 := windowsLoadSystemLib(advapi32dll[:])
|
||||||
|
- if a32 == 0 {
|
||||||
|
- throw("advapi32.dll not found")
|
||||||
|
+ bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
+ if bcryptPrimitives == 0 {
|
||||||
|
+ throw("bcryptprimitives.dll not found")
|
||||||
|
}
|
||||||
|
- _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
+ _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
|
||||||
|
n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
if n32 == 0 {
|
||||||
|
@@ -531,7 +524,7 @@ func osinit() {
|
||||||
|
//go:nosplit
|
||||||
|
func readRandom(r []byte) int {
|
||||||
|
n := 0
|
||||||
|
- if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall2(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
return n
|
||||||
162
.github/patch_go122/7c1157f9544922e96945196b47b95664b1e39108.diff
vendored
Normal file
162
.github/patch_go122/7c1157f9544922e96945196b47b95664b1e39108.diff
vendored
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
diff --git a/src/net/hook_windows.go b/src/net/hook_windows.go
|
||||||
|
index ab8656cbbf343..28c49cc6de7e7 100644
|
||||||
|
--- a/src/net/hook_windows.go
|
||||||
|
+++ b/src/net/hook_windows.go
|
||||||
|
@@ -14,7 +14,6 @@ var (
|
||||||
|
testHookDialChannel = func() { time.Sleep(time.Millisecond) } // see golang.org/issue/5349
|
||||||
|
|
||||||
|
// Placeholders for socket system calls.
|
||||||
|
- socketFunc func(int, int, int) (syscall.Handle, error) = syscall.Socket
|
||||||
|
wsaSocketFunc func(int32, int32, int32, *syscall.WSAProtocolInfo, uint32, uint32) (syscall.Handle, error) = windows.WSASocket
|
||||||
|
connectFunc func(syscall.Handle, syscall.Sockaddr) error = syscall.Connect
|
||||||
|
listenFunc func(syscall.Handle, int) error = syscall.Listen
|
||||||
|
diff --git a/src/net/internal/socktest/main_test.go b/src/net/internal/socktest/main_test.go
|
||||||
|
index 0197feb3f199a..967ce6795aedb 100644
|
||||||
|
--- a/src/net/internal/socktest/main_test.go
|
||||||
|
+++ b/src/net/internal/socktest/main_test.go
|
||||||
|
@@ -2,7 +2,7 @@
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
-//go:build !js && !plan9 && !wasip1
|
||||||
|
+//go:build !js && !plan9 && !wasip1 && !windows
|
||||||
|
|
||||||
|
package socktest_test
|
||||||
|
|
||||||
|
diff --git a/src/net/internal/socktest/main_windows_test.go b/src/net/internal/socktest/main_windows_test.go
|
||||||
|
deleted file mode 100644
|
||||||
|
index df1cb97784b51..0000000000000
|
||||||
|
--- a/src/net/internal/socktest/main_windows_test.go
|
||||||
|
+++ /dev/null
|
||||||
|
@@ -1,22 +0,0 @@
|
||||||
|
-// Copyright 2015 The Go Authors. All rights reserved.
|
||||||
|
-// Use of this source code is governed by a BSD-style
|
||||||
|
-// license that can be found in the LICENSE file.
|
||||||
|
-
|
||||||
|
-package socktest_test
|
||||||
|
-
|
||||||
|
-import "syscall"
|
||||||
|
-
|
||||||
|
-var (
|
||||||
|
- socketFunc func(int, int, int) (syscall.Handle, error)
|
||||||
|
- closeFunc func(syscall.Handle) error
|
||||||
|
-)
|
||||||
|
-
|
||||||
|
-func installTestHooks() {
|
||||||
|
- socketFunc = sw.Socket
|
||||||
|
- closeFunc = sw.Closesocket
|
||||||
|
-}
|
||||||
|
-
|
||||||
|
-func uninstallTestHooks() {
|
||||||
|
- socketFunc = syscall.Socket
|
||||||
|
- closeFunc = syscall.Closesocket
|
||||||
|
-}
|
||||||
|
diff --git a/src/net/internal/socktest/sys_windows.go b/src/net/internal/socktest/sys_windows.go
|
||||||
|
index 8c1c862f33c9b..1c42e5c7f34b7 100644
|
||||||
|
--- a/src/net/internal/socktest/sys_windows.go
|
||||||
|
+++ b/src/net/internal/socktest/sys_windows.go
|
||||||
|
@@ -9,38 +9,6 @@ import (
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
-// Socket wraps syscall.Socket.
|
||||||
|
-func (sw *Switch) Socket(family, sotype, proto int) (s syscall.Handle, err error) {
|
||||||
|
- sw.once.Do(sw.init)
|
||||||
|
-
|
||||||
|
- so := &Status{Cookie: cookie(family, sotype, proto)}
|
||||||
|
- sw.fmu.RLock()
|
||||||
|
- f, _ := sw.fltab[FilterSocket]
|
||||||
|
- sw.fmu.RUnlock()
|
||||||
|
-
|
||||||
|
- af, err := f.apply(so)
|
||||||
|
- if err != nil {
|
||||||
|
- return syscall.InvalidHandle, err
|
||||||
|
- }
|
||||||
|
- s, so.Err = syscall.Socket(family, sotype, proto)
|
||||||
|
- if err = af.apply(so); err != nil {
|
||||||
|
- if so.Err == nil {
|
||||||
|
- syscall.Closesocket(s)
|
||||||
|
- }
|
||||||
|
- return syscall.InvalidHandle, err
|
||||||
|
- }
|
||||||
|
-
|
||||||
|
- sw.smu.Lock()
|
||||||
|
- defer sw.smu.Unlock()
|
||||||
|
- if so.Err != nil {
|
||||||
|
- sw.stats.getLocked(so.Cookie).OpenFailed++
|
||||||
|
- return syscall.InvalidHandle, so.Err
|
||||||
|
- }
|
||||||
|
- nso := sw.addLocked(s, family, sotype, proto)
|
||||||
|
- sw.stats.getLocked(nso.Cookie).Opened++
|
||||||
|
- return s, nil
|
||||||
|
-}
|
||||||
|
-
|
||||||
|
// WSASocket wraps [syscall.WSASocket].
|
||||||
|
func (sw *Switch) WSASocket(family, sotype, proto int32, protinfo *syscall.WSAProtocolInfo, group uint32, flags uint32) (s syscall.Handle, err error) {
|
||||||
|
sw.once.Do(sw.init)
|
||||||
|
diff --git a/src/net/main_windows_test.go b/src/net/main_windows_test.go
|
||||||
|
index 07f21b72eb1fc..bc024c0bbd82d 100644
|
||||||
|
--- a/src/net/main_windows_test.go
|
||||||
|
+++ b/src/net/main_windows_test.go
|
||||||
|
@@ -8,7 +8,6 @@ import "internal/poll"
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Placeholders for saving original socket system calls.
|
||||||
|
- origSocket = socketFunc
|
||||||
|
origWSASocket = wsaSocketFunc
|
||||||
|
origClosesocket = poll.CloseFunc
|
||||||
|
origConnect = connectFunc
|
||||||
|
@@ -18,7 +17,6 @@ var (
|
||||||
|
)
|
||||||
|
|
||||||
|
func installTestHooks() {
|
||||||
|
- socketFunc = sw.Socket
|
||||||
|
wsaSocketFunc = sw.WSASocket
|
||||||
|
poll.CloseFunc = sw.Closesocket
|
||||||
|
connectFunc = sw.Connect
|
||||||
|
@@ -28,7 +26,6 @@ func installTestHooks() {
|
||||||
|
}
|
||||||
|
|
||||||
|
func uninstallTestHooks() {
|
||||||
|
- socketFunc = origSocket
|
||||||
|
wsaSocketFunc = origWSASocket
|
||||||
|
poll.CloseFunc = origClosesocket
|
||||||
|
connectFunc = origConnect
|
||||||
|
diff --git a/src/net/sock_windows.go b/src/net/sock_windows.go
|
||||||
|
index fa11c7af2e727..5540135a2c43e 100644
|
||||||
|
--- a/src/net/sock_windows.go
|
||||||
|
+++ b/src/net/sock_windows.go
|
||||||
|
@@ -19,21 +19,6 @@ func maxListenerBacklog() int {
|
||||||
|
func sysSocket(family, sotype, proto int) (syscall.Handle, error) {
|
||||||
|
s, err := wsaSocketFunc(int32(family), int32(sotype), int32(proto),
|
||||||
|
nil, 0, windows.WSA_FLAG_OVERLAPPED|windows.WSA_FLAG_NO_HANDLE_INHERIT)
|
||||||
|
- if err == nil {
|
||||||
|
- return s, nil
|
||||||
|
- }
|
||||||
|
- // WSA_FLAG_NO_HANDLE_INHERIT flag is not supported on some
|
||||||
|
- // old versions of Windows, see
|
||||||
|
- // https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx
|
||||||
|
- // for details. Just use syscall.Socket, if windows.WSASocket failed.
|
||||||
|
-
|
||||||
|
- // See ../syscall/exec_unix.go for description of ForkLock.
|
||||||
|
- syscall.ForkLock.RLock()
|
||||||
|
- s, err = socketFunc(family, sotype, proto)
|
||||||
|
- if err == nil {
|
||||||
|
- syscall.CloseOnExec(s)
|
||||||
|
- }
|
||||||
|
- syscall.ForkLock.RUnlock()
|
||||||
|
if err != nil {
|
||||||
|
return syscall.InvalidHandle, os.NewSyscallError("socket", err)
|
||||||
|
}
|
||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
index 0a93bc0a80d4e..06e684c7116b4 100644
|
||||||
|
--- a/src/syscall/exec_windows.go
|
||||||
|
+++ b/src/syscall/exec_windows.go
|
||||||
|
@@ -14,6 +14,7 @@ import (
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
+// ForkLock is not used on Windows.
|
||||||
|
var ForkLock sync.RWMutex
|
||||||
|
|
||||||
|
// EscapeArg rewrites command line argument s as prescribed
|
||||||
620
.github/workflows/build.yml
vendored
620
.github/workflows/build.yml
vendored
@@ -1,6 +1,10 @@
|
|||||||
name: Build
|
name: Build
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
version:
|
||||||
|
description: "Tag version to release"
|
||||||
|
required: true
|
||||||
push:
|
push:
|
||||||
paths-ignore:
|
paths-ignore:
|
||||||
- "docs/**"
|
- "docs/**"
|
||||||
@@ -13,358 +17,437 @@ on:
|
|||||||
pull_request_target:
|
pull_request_target:
|
||||||
branches:
|
branches:
|
||||||
- Alpha
|
- Alpha
|
||||||
|
|
||||||
concurrency:
|
concurrency:
|
||||||
group: ${{ github.workflow }}-${{ github.ref }}
|
group: "${{ github.workflow }}-${{ github.ref }}"
|
||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
|
|
||||||
env:
|
env:
|
||||||
REGISTRY: docker.io
|
REGISTRY: docker.io
|
||||||
jobs:
|
jobs:
|
||||||
Build:
|
build:
|
||||||
permissions: write-all
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
matrix:
|
||||||
job:
|
jobs:
|
||||||
- {
|
- { goos: darwin, goarch: arm64, output: arm64 }
|
||||||
type: "WithoutCGO",
|
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-compatible }
|
||||||
target: "linux-amd64 linux-amd64-compatible",
|
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64 }
|
||||||
id: "1",
|
|
||||||
}
|
- { goos: linux, goarch: '386', output: '386' }
|
||||||
- {
|
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-compatible, test: test }
|
||||||
type: "WithoutCGO",
|
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64 }
|
||||||
target: "linux-armv5 linux-armv6 linux-armv7",
|
- { goos: linux, goarch: arm64, output: arm64 }
|
||||||
id: "2",
|
- { goos: linux, goarch: arm, goarm: '5', output: armv5 }
|
||||||
}
|
- { goos: linux, goarch: arm, goarm: '6', output: armv6 }
|
||||||
- {
|
- { goos: linux, goarch: arm, goarm: '7', output: armv7 }
|
||||||
type: "WithoutCGO",
|
- { goos: linux, goarch: mips, mips: hardfloat, output: mips-hardfloat }
|
||||||
target: "linux-arm64 linux-mips64 linux-mips64le",
|
- { goos: linux, goarch: mips, mips: softfloat, output: mips-softfloat }
|
||||||
id: "3",
|
- { goos: linux, goarch: mipsle, mips: hardfloat, output: mipsle-hardfloat }
|
||||||
}
|
- { goos: linux, goarch: mipsle, mips: softfloat, output: mipsle-softfloat }
|
||||||
- {
|
- { goos: linux, goarch: mips64, output: mips64 }
|
||||||
type: "WithoutCGO",
|
- { goos: linux, goarch: mips64le, output: mips64le }
|
||||||
target: "linux-mips-softfloat linux-mips-hardfloat linux-mipsle-softfloat linux-mipsle-hardfloat",
|
- { goos: linux, goarch: loong64, output: loong64-abi1, abi: '1' }
|
||||||
id: "4",
|
- { goos: linux, goarch: loong64, output: loong64-abi2, abi: '2' }
|
||||||
}
|
- { goos: linux, goarch: riscv64, output: riscv64 }
|
||||||
- { type: "WithoutCGO", target: "linux-386 linux-riscv64 linux-loong64", id: "5" }
|
- { goos: linux, goarch: s390x, output: s390x }
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
- { goos: windows, goarch: '386', output: '386' }
|
||||||
target: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible }
|
||||||
id: "6",
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64 }
|
||||||
}
|
- { goos: windows, goarch: arm, goarm: '7', output: armv7 }
|
||||||
- {
|
- { goos: windows, goarch: arm64, output: arm64 }
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "windows-amd64-compatible windows-amd64 windows-386",
|
- { goos: freebsd, goarch: '386', output: '386' }
|
||||||
id: "7",
|
- { goos: freebsd, goarch: amd64, goamd64: v1, output: amd64-compatible }
|
||||||
}
|
- { goos: freebsd, goarch: amd64, goamd64: v3, output: amd64 }
|
||||||
- {
|
- { goos: freebsd, goarch: arm64, output: arm64 }
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "windows-arm64 windows-arm32v7",
|
- { goos: android, goarch: '386', ndk: i686-linux-android34, output: '386' }
|
||||||
id: "8",
|
- { goos: android, goarch: amd64, ndk: x86_64-linux-android34, output: amd64 }
|
||||||
}
|
- { goos: android, goarch: arm, ndk: armv7a-linux-androideabi34, output: armv7 }
|
||||||
- {
|
- { goos: android, goarch: arm64, ndk: aarch64-linux-android34, output: arm64-v8 }
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "darwin-amd64 darwin-arm64 android-arm64",
|
# Go 1.21 can revert commit `9e4385` to work on Windows 7
|
||||||
id: "9",
|
# https://github.com/golang/go/issues/64622#issuecomment-1847475161
|
||||||
}
|
# (OR we can just use golang1.21.4 which unneeded any patch)
|
||||||
# only for test
|
- { goos: windows, goarch: '386', output: '386-go121', goversion: '1.21' }
|
||||||
- { type: "WithoutCGO-GO120", target: "linux-amd64 linux-amd64-compatible",id: "1" }
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible-go121, goversion: '1.21' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-go121, goversion: '1.21' }
|
||||||
|
|
||||||
# Go 1.20 is the last release that will run on any release of Windows 7, 8, Server 2008 and Server 2012. Go 1.21 will require at least Windows 10 or Server 2016.
|
# Go 1.20 is the last release that will run on any release of Windows 7, 8, Server 2008 and Server 2012. Go 1.21 will require at least Windows 10 or Server 2016.
|
||||||
- { type: "WithoutCGO-GO120", target: "windows-amd64-compatible windows-amd64 windows-386",id: "2" }
|
- { goos: windows, goarch: '386', output: '386-go120', goversion: '1.20' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible-go120, goversion: '1.20' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-go120, goversion: '1.20' }
|
||||||
|
|
||||||
# Go 1.20 is the last release that will run on macOS 10.13 High Sierra or 10.14 Mojave. Go 1.21 will require macOS 10.15 Catalina or later.
|
# Go 1.20 is the last release that will run on macOS 10.13 High Sierra or 10.14 Mojave. Go 1.21 will require macOS 10.15 Catalina or later.
|
||||||
- { type: "WithoutCGO-GO120", target: "darwin-amd64 darwin-arm64 android-arm64",id: "3" }
|
- { goos: darwin, goarch: arm64, output: arm64-go120, goversion: '1.20' }
|
||||||
# - { type: "WithCGO", target: "windows/*", id: "1" }
|
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-compatible-go120, goversion: '1.20' }
|
||||||
# - { type: "WithCGO", target: "linux/386", id: "2" }
|
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64-go120, goversion: '1.20' }
|
||||||
# - { type: "WithCGO", target: "linux/amd64", id: "3" }
|
|
||||||
# - { type: "WithCGO", target: "linux/arm64,linux/riscv64", id: "4" }
|
# only for test
|
||||||
# - { type: "WithCGO", target: "linux/arm,", id: "5" }
|
- { goos: linux, goarch: '386', output: '386-go120', goversion: '1.20' }
|
||||||
# - { type: "WithCGO", target: "linux/arm-6,linux/arm-7", id: "6" }
|
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-compatible-go120, goversion: '1.20', test: test }
|
||||||
# - { type: "WithCGO", target: "linux/mips,linux/mipsle", id: "7" }
|
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64-go120, goversion: '1.20' }
|
||||||
# - { type: "WithCGO", target: "linux/mips64", id: "8" }
|
|
||||||
# - { type: "WithCGO", target: "linux/mips64le", id: "9" }
|
|
||||||
# - { type: "WithCGO", target: "darwin-10.16/*", id: "10" }
|
|
||||||
# - { type: "WithCGO", target: "android", id: "11" }
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Check out code into the Go module directory
|
- uses: actions/checkout@v4
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set variables
|
- name: Set up Go
|
||||||
run: echo "VERSION=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
if: ${{ matrix.jobs.goversion == '' && matrix.jobs.goarch != 'loong64' }}
|
||||||
shell: bash
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.22'
|
||||||
|
|
||||||
- name: Set variables
|
- name: Set up Go
|
||||||
if: ${{github.ref_name=='Alpha'}}
|
if: ${{ matrix.jobs.goversion != '' && matrix.jobs.goarch != 'loong64' }}
|
||||||
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
uses: actions/setup-go@v5
|
||||||
shell: bash
|
with:
|
||||||
|
go-version: ${{ matrix.jobs.goversion }}
|
||||||
|
|
||||||
- name: Set variables
|
- name: Set up Go1.22 loongarch abi1
|
||||||
if: ${{github.ref_name=='Beta'}}
|
if: ${{ matrix.jobs.goarch == 'loong64' && matrix.jobs.abi == '1' }}
|
||||||
run: echo "VERSION=beta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
run: |
|
||||||
shell: bash
|
wget -q https://github.com/xishang0128/loongarch64-golang/releases/download/1.22.0/go1.22.0.linux-amd64-abi1.tar.gz
|
||||||
|
sudo tar zxf go1.22.0.linux-amd64-abi1.tar.gz -C /usr/local
|
||||||
|
echo "/usr/local/go/bin" >> $GITHUB_PATH
|
||||||
|
|
||||||
- name: Set variables
|
- name: Set up Go1.22 loongarch abi2
|
||||||
if: ${{github.ref_name=='Meta'}}
|
if: ${{ matrix.jobs.goarch == 'loong64' && matrix.jobs.abi == '2' }}
|
||||||
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
run: |
|
||||||
shell: bash
|
wget -q https://github.com/xishang0128/loongarch64-golang/releases/download/1.22.0/go1.22.0.linux-amd64-abi2.tar.gz
|
||||||
|
sudo tar zxf go1.22.0.linux-amd64-abi2.tar.gz -C /usr/local
|
||||||
|
echo "/usr/local/go/bin" >> $GITHUB_PATH
|
||||||
|
|
||||||
- name: Set variables
|
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||||
if: ${{github.ref_name=='' || github.ref_type=='tag'}}
|
# this patch file only works on golang1.22.x
|
||||||
run: echo "VERSION=$(git describe --tags)" >> $GITHUB_ENV
|
# that means after golang1.23 release it must be changed
|
||||||
shell: bash
|
# revert:
|
||||||
|
# 693def151adff1af707d82d28f55dba81ceb08e1: "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
# 7c1157f9544922e96945196b47b95664b1e39108: "net: remove sysSocket fallback for Windows 7"
|
||||||
|
# 48042aa09c2f878c4faa576948b07fe625c4707a: "syscall: remove Windows 7 console handle workaround"
|
||||||
|
- name: Revert Golang1.22 commit for Windows7/8
|
||||||
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '' }}
|
||||||
|
run: |
|
||||||
|
cd $(go env GOROOT)
|
||||||
|
patch --verbose -R -p 1 < $GITHUB_WORKSPACE/.github/patch_go122/693def151adff1af707d82d28f55dba81ceb08e1.diff
|
||||||
|
patch --verbose -R -p 1 < $GITHUB_WORKSPACE/.github/patch_go122/7c1157f9544922e96945196b47b95664b1e39108.diff
|
||||||
|
patch --verbose -R -p 1 < $GITHUB_WORKSPACE/.github/patch_go122/48042aa09c2f878c4faa576948b07fe625c4707a.diff
|
||||||
|
|
||||||
- name: Set ENV
|
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||||
run: |
|
- name: Revert Golang1.21 commit for Windows7/8
|
||||||
sudo timedatectl set-timezone "Asia/Shanghai"
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.21' }}
|
||||||
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
run: |
|
||||||
shell: bash
|
cd $(go env GOROOT)
|
||||||
|
curl https://github.com/golang/go/commit/9e43850a3298a9b8b1162ba0033d4c53f8637571.diff | patch --verbose -R -p 1
|
||||||
|
|
||||||
- name: Set ENV
|
- name: Set variables
|
||||||
run: |
|
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
||||||
echo "TAGS=with_gvisor,with_lwip" >> $GITHUB_ENV
|
run: echo "VERSION=${{ github.event.inputs.version }}" >> $GITHUB_ENV
|
||||||
echo "LDFLAGS=-X 'github.com/metacubex/mihomo/constant.Version=${VERSION}' -X 'github.com/metacubex/mihomo/constant.BuildTime=${BUILDTIME}' -w -s -buildid=" >> $GITHUB_ENV
|
shell: bash
|
||||||
echo "GOTOOLCHAIN=local" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Setup Go
|
- name: Set variables
|
||||||
if: ${{ matrix.job.type!='WithoutCGO-GO120' }}
|
if: ${{ github.event_name != 'workflow_dispatch' && github.ref_name == 'Alpha' }}
|
||||||
uses: actions/setup-go@v4
|
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
with:
|
shell: bash
|
||||||
go-version: "1.21"
|
|
||||||
check-latest: true
|
|
||||||
|
|
||||||
- name: Setup Go
|
- name: Set Time Variable
|
||||||
if: ${{ matrix.job.type=='WithoutCGO-GO120' }}
|
run: |
|
||||||
uses: actions/setup-go@v4
|
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
||||||
with:
|
echo "CGO_ENABLED=0" >> $GITHUB_ENV
|
||||||
go-version: "1.20"
|
echo "BUILDTAG=-extldflags --static" >> $GITHUB_ENV
|
||||||
check-latest: true
|
|
||||||
|
|
||||||
- name: Test
|
- name: Setup NDK
|
||||||
if: ${{ matrix.job.id=='1' && matrix.job.type!='WithCGO' }}
|
if: ${{ matrix.jobs.goos == 'android' }}
|
||||||
run: |
|
uses: nttld/setup-ndk@v1
|
||||||
go test ./...
|
id: setup-ndk
|
||||||
|
with:
|
||||||
|
ndk-version: r26c
|
||||||
|
|
||||||
- name: Build WithoutCGO
|
- name: Set NDK path
|
||||||
if: ${{ matrix.job.type!='WithCGO' }}
|
if: ${{ matrix.jobs.goos == 'android' }}
|
||||||
env:
|
run: |
|
||||||
NAME: mihomo
|
echo "CC=${{steps.setup-ndk.outputs.ndk-path}}/toolchains/llvm/prebuilt/linux-x86_64/bin/${{matrix.jobs.ndk}}-clang" >> $GITHUB_ENV
|
||||||
BINDIR: bin
|
echo "CGO_ENABLED=1" >> $GITHUB_ENV
|
||||||
run: make -j$(($(nproc) + 1)) ${{ matrix.job.target }}
|
echo "BUILDTAG=" >> $GITHUB_ENV
|
||||||
|
|
||||||
- uses: nttld/setup-ndk@v1
|
- name: Test
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
if: ${{ matrix.jobs.test == 'test' }}
|
||||||
id: setup-ndk
|
run: |
|
||||||
with:
|
go test ./...
|
||||||
ndk-version: r26b
|
|
||||||
add-to-path: true
|
|
||||||
|
|
||||||
- name: Build Android
|
- name: Update CA
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
run: |
|
||||||
env:
|
sudo apt-get install ca-certificates
|
||||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
sudo update-ca-certificates
|
||||||
run: |
|
cp -f /etc/ssl/certs/ca-certificates.crt component/ca/ca-certificates.crt
|
||||||
mkdir bin
|
|
||||||
CC=${ANDROID_NDK_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android33-clang
|
|
||||||
CGO_ENABLED=1 CC=${CC} GOARCH=arm64 GOOS=android go build -tags ${TAGS} -trimpath -ldflags "${LDFLAGS}" -o bin/${NAME}-android-arm64
|
|
||||||
|
|
||||||
- name: Set up xgo
|
- name: Build core
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
env:
|
||||||
run: |
|
GOOS: ${{matrix.jobs.goos}}
|
||||||
docker pull techknowlogick/xgo:latest
|
GOARCH: ${{matrix.jobs.goarch}}
|
||||||
go install src.techknowlogick.com/xgo@latest
|
GOAMD64: ${{matrix.jobs.goamd64}}
|
||||||
|
GOARM: ${{matrix.jobs.arm}}
|
||||||
|
GOMIPS: ${{matrix.jobs.mips}}
|
||||||
|
run: |
|
||||||
|
echo $CGO_ENABLED
|
||||||
|
go build -v -tags "with_gvisor" -trimpath -ldflags "${BUILDTAG} -X 'github.com/metacubex/mihomo/constant.Version=${VERSION}' -X 'github.com/metacubex/mihomo/constant.BuildTime=${BUILDTIME}' -w -s -buildid="
|
||||||
|
if [ "${{matrix.jobs.goos}}" = "windows" ]; then
|
||||||
|
cp mihomo.exe mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}.exe
|
||||||
|
zip -r mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.zip mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}.exe
|
||||||
|
else
|
||||||
|
cp mihomo mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}
|
||||||
|
gzip -c mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}} > mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.gz
|
||||||
|
rm mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}
|
||||||
|
fi
|
||||||
|
|
||||||
- name: Build by xgo
|
- name: Create DEB package
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
if: ${{ matrix.jobs.goos == 'linux' && !contains(matrix.jobs.goarch, 'mips') }}
|
||||||
env:
|
run: |
|
||||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
sudo apt-get install dpkg
|
||||||
run: |
|
if [ "${{matrix.jobs.abi}}" = "1" ]; then
|
||||||
mkdir bin
|
ARCH=loongarch64
|
||||||
xgo --targets="${{ matrix.job.target }}" --tags="${TAGS}" -ldflags="${LDFLAGS}" --out bin/${NAME} ./
|
elif [ "${{matrix.jobs.goarm}}" = "7" ]; then
|
||||||
|
ARCH=armhf
|
||||||
|
elif [ "${{matrix.jobs.goarch}}" = "arm" ]; then
|
||||||
|
ARCH=armel
|
||||||
|
else
|
||||||
|
ARCH=${{matrix.jobs.goarch}}
|
||||||
|
fi
|
||||||
|
PackageVersion=$(curl -s "https://api.github.com/repos/MetaCubeX/mihomo/releases/latest" | grep -o '"tag_name": "[^"]*' | grep -o '[^"]*$' | sed 's/v//g' )
|
||||||
|
if [ $(git branch | awk -F ' ' '{print $2}') = "Alpha" ]; then
|
||||||
|
PackageVersion="$(echo "${PackageVersion}" | awk -F '.' '{$NF = $NF + 1; print}' OFS='.')-${VERSION}"
|
||||||
|
fi
|
||||||
|
|
||||||
- name: Rename
|
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/DEBIAN
|
||||||
if: ${{ matrix.job.type=='WithCGO' }}
|
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/bin
|
||||||
run: |
|
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/mihomo
|
||||||
cd bin
|
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/systemd/system/
|
||||||
ls -la
|
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/share/licenses/mihomo
|
||||||
cp ../.github/rename-cgo.sh ./
|
|
||||||
bash ./rename-cgo.sh
|
|
||||||
rm ./rename-cgo.sh
|
|
||||||
ls -la
|
|
||||||
cd ..
|
|
||||||
|
|
||||||
- name: Rename
|
cp mihomo mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/bin/mihomo
|
||||||
if: ${{ matrix.job.type=='WithoutCGO-GO120' }}
|
cp LICENSE mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/share/licenses/mihomo/
|
||||||
run: |
|
cp .github/mihomo.service mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/systemd/system/
|
||||||
cd bin
|
|
||||||
ls -la
|
|
||||||
cp ../.github/rename-go120.sh ./
|
|
||||||
bash ./rename-go120.sh
|
|
||||||
rm ./rename-go120.sh
|
|
||||||
ls -la
|
|
||||||
cd ..
|
|
||||||
|
|
||||||
- name: Zip
|
cat > mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/mihomo/config.yaml <<EOF
|
||||||
if: ${{ success() }}
|
mixed-port: 7890
|
||||||
run: |
|
external-controller: 127.0.0.1:9090
|
||||||
cd bin
|
EOF
|
||||||
ls -la
|
|
||||||
chmod +x *
|
|
||||||
cp ../.github/release.sh ./
|
|
||||||
bash ./release.sh
|
|
||||||
rm ./release.sh
|
|
||||||
ls -la
|
|
||||||
cd ..
|
|
||||||
|
|
||||||
- name: Save version
|
cat > mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/DEBIAN/control <<EOF
|
||||||
run: echo ${VERSION} > bin/version.txt
|
Package: mihomo
|
||||||
shell: bash
|
Version: ${PackageVersion}
|
||||||
|
Section:
|
||||||
|
Priority: extra
|
||||||
|
Architecture: ${ARCH}
|
||||||
|
Maintainer: MetaCubeX <none@example.com>
|
||||||
|
Homepage: https://wiki.metacubex.one/
|
||||||
|
Description: The universal proxy platform.
|
||||||
|
EOF
|
||||||
|
|
||||||
- uses: actions/upload-artifact@v3
|
dpkg-deb -Z gzip --build mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
- name: Convert DEB to RPM
|
||||||
name: artifact
|
if: ${{ matrix.jobs.goos == 'linux' && !contains(matrix.jobs.goarch, 'mips') }}
|
||||||
path: bin/
|
run: |
|
||||||
|
sudo apt-get install -y alien
|
||||||
|
alien --to-rpm --scripts mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.deb
|
||||||
|
mv mihomo*.rpm mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.rpm
|
||||||
|
|
||||||
|
# - name: Convert DEB to PKG
|
||||||
|
# if: ${{ matrix.jobs.goos == 'linux' && !contains(matrix.jobs.goarch, 'mips') && !contains(matrix.jobs.goarch, 'loong64') }}
|
||||||
|
# run: |
|
||||||
|
# docker pull archlinux
|
||||||
|
# docker run --rm -v ./:/mnt archlinux bash -c "
|
||||||
|
# pacman -Syu pkgfile base-devel --noconfirm
|
||||||
|
# curl -L https://github.com/helixarch/debtap/raw/master/debtap > /usr/bin/debtap
|
||||||
|
# chmod 755 /usr/bin/debtap
|
||||||
|
# debtap -u
|
||||||
|
# debtap -Q /mnt/mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.deb
|
||||||
|
# "
|
||||||
|
# mv mihomo*.pkg.tar.zst mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.pkg.tar.zst
|
||||||
|
|
||||||
|
- name: Save version
|
||||||
|
run: |
|
||||||
|
echo ${VERSION} > version.txt
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Archive production artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: "${{ matrix.jobs.goos }}-${{ matrix.jobs.output }}"
|
||||||
|
path: |
|
||||||
|
mihomo*.gz
|
||||||
|
mihomo*.deb
|
||||||
|
mihomo*.rpm
|
||||||
|
mihomo*.zip
|
||||||
|
version.txt
|
||||||
|
|
||||||
Upload-Prerelease:
|
Upload-Prerelease:
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
if: ${{ github.ref_type == 'branch' && !startsWith(github.event_name, 'pull_request') }}
|
if: ${{ github.event_name != 'workflow_dispatch' && github.ref_type == 'branch' && !startsWith(github.event_name, 'pull_request') }}
|
||||||
needs: [Build]
|
needs: [build]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/download-artifact@v3
|
- name: Download all workflow run artifacts
|
||||||
with:
|
uses: actions/download-artifact@v4
|
||||||
name: artifact
|
with:
|
||||||
path: bin/
|
path: bin/
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
- name: Delete current release assets
|
||||||
run: ls -R
|
uses: 8Mi-Tech/delete-release-assets-action@main
|
||||||
working-directory: bin
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
tag: Prerelease-${{ github.ref_name }}
|
||||||
|
deleteOnlyFromDrafts: false
|
||||||
|
- name: Set Env
|
||||||
|
run: |
|
||||||
|
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
- name: Delete current release assets
|
- name: Tag Repo
|
||||||
uses: 8Mi-Tech/delete-release-assets-action@main
|
uses: richardsimko/update-tag@v1
|
||||||
with:
|
with:
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
tag: Prerelease-${{ github.ref_name }}
|
env:
|
||||||
deleteOnlyFromDrafts: false
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- run: |
|
||||||
|
cat > release.txt << 'EOF'
|
||||||
|
Release created at ${{ env.BUILDTIME }}
|
||||||
|
Synchronize ${{ github.ref_name }} branch code updates, keeping only the latest version
|
||||||
|
<br>
|
||||||
|
[我应该下载哪个文件? / Which file should I download?](https://github.com/MetaCubeX/mihomo/wiki/FAQ)
|
||||||
|
[二进制文件筛选 / Binary file selector](https://metacubex.github.io/Meta-Docs/startup/#_1)
|
||||||
|
[查看文档 / Docs](https://metacubex.github.io/Meta-Docs/)
|
||||||
|
EOF
|
||||||
|
|
||||||
- name: Set Env
|
- name: Upload Prerelease
|
||||||
run: |
|
uses: softprops/action-gh-release@v1
|
||||||
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
|
if: ${{ success() }}
|
||||||
shell: bash
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
- name: Tag Repo
|
files: |
|
||||||
uses: richardsimko/update-tag@v1.0.6
|
bin/*
|
||||||
with:
|
prerelease: true
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
generate_release_notes: true
|
||||||
env:
|
body_path: release.txt
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- run: |
|
|
||||||
cat > release.txt << 'EOF'
|
|
||||||
Release created at ${{ env.BUILDTIME }}
|
|
||||||
Synchronize ${{ github.ref_name }} branch code updates, keeping only the latest version
|
|
||||||
<br>
|
|
||||||
[我应该下载哪个文件? / Which file should I download?](https://github.com/MetaCubeX/mihomo/wiki/FAQ)
|
|
||||||
[二进制文件筛选 / Binary file selector] (https://metacubex.github.io/Meta-Docs/startup/#_1)
|
|
||||||
[查看文档 / Docs](https://metacubex.github.io/Meta-Docs/)
|
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Upload Prerelease
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
files: |
|
|
||||||
bin/*
|
|
||||||
prerelease: true
|
|
||||||
generate_release_notes: true
|
|
||||||
body_path: release.txt
|
|
||||||
|
|
||||||
Upload-Release:
|
Upload-Release:
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
if: ${{ github.ref_type=='tag' }}
|
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
||||||
needs: [Build]
|
needs: [build]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
ref: Meta
|
||||||
|
fetch-depth: '0'
|
||||||
|
fetch-tags: 'true'
|
||||||
|
|
||||||
- name: Get tags
|
- name: Get tags
|
||||||
run: |
|
run: |
|
||||||
echo "CURRENTVERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
|
echo "CURRENTVERSION=${{ github.event.inputs.version }}" >> $GITHUB_ENV
|
||||||
git fetch --tags
|
git fetch --tags
|
||||||
echo "PREVERSION=$(git describe --tags --abbrev=0 HEAD^)" >> $GITHUB_ENV
|
echo "PREVERSION=$(git describe --tags --abbrev=0 HEAD)" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Merge Alpha branch into Meta
|
||||||
|
run: |
|
||||||
|
git config --global user.email "github-actions[bot]@users.noreply.github.com"
|
||||||
|
git config --global user.name "github-actions[bot]"
|
||||||
|
git fetch origin Alpha:Alpha
|
||||||
|
git merge Alpha
|
||||||
|
git push origin Meta
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Tag the commit
|
||||||
|
run: |
|
||||||
|
git tag ${{ github.event.inputs.version }}
|
||||||
|
git push origin ${{ github.event.inputs.version }}
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
- name: Generate release notes
|
- name: Generate release notes
|
||||||
run: |
|
run: |
|
||||||
cp ./.github/genReleaseNote.sh ./
|
cp ./.github/genReleaseNote.sh ./
|
||||||
bash ./genReleaseNote.sh -v ${PREVERSION}...${CURRENTVERSION}
|
bash ./genReleaseNote.sh -v ${PREVERSION}...${CURRENTVERSION}
|
||||||
rm ./genReleaseNote.sh
|
rm ./genReleaseNote.sh
|
||||||
|
|
||||||
- uses: actions/download-artifact@v3
|
- uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: artifact
|
|
||||||
path: bin/
|
path: bin/
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
- name: Display structure of downloaded files
|
||||||
run: ls -R
|
run: ls -R
|
||||||
working-directory: bin
|
working-directory: bin
|
||||||
|
|
||||||
- name: Upload Release
|
- name: Upload Release
|
||||||
uses: softprops/action-gh-release@v1
|
uses: softprops/action-gh-release@v2
|
||||||
if: ${{ success() }}
|
if: ${{ success() }}
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ github.ref_name }}
|
tag_name: ${{ github.event.inputs.version }}
|
||||||
files: bin/*
|
files: bin/*
|
||||||
generate_release_notes: true
|
|
||||||
body_path: release.md
|
body_path: release.md
|
||||||
|
|
||||||
Docker:
|
Docker:
|
||||||
if: ${{ !startsWith(github.event_name, 'pull_request') }}
|
if: ${{ !startsWith(github.event_name, 'pull_request') }}
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
needs: [Build]
|
needs: [build]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- uses: actions/download-artifact@v3
|
- uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: artifact
|
|
||||||
path: bin/
|
path: bin/
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
- name: Display structure of downloaded files
|
||||||
run: ls -R
|
run: ls -R
|
||||||
working-directory: bin
|
working-directory: bin
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v2
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
- name: Setup Docker buildx
|
- name: Setup Docker buildx
|
||||||
uses: docker/setup-buildx-action@v2
|
uses: docker/setup-buildx-action@v3
|
||||||
with:
|
with:
|
||||||
version: latest
|
version: latest
|
||||||
|
|
||||||
# Extract metadata (tags, labels) for Docker
|
# Extract metadata (tags, labels) for Docker
|
||||||
# https://github.com/docker/metadata-action
|
# https://github.com/docker/metadata-action
|
||||||
- name: Extract Docker metadata
|
- name: Extract Docker metadata
|
||||||
id: meta
|
if: ${{ github.event_name != 'workflow_dispatch' }}
|
||||||
uses: docker/metadata-action@v4
|
id: meta_alpha
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
with:
|
with:
|
||||||
images: ${{ env.REGISTRY }}/${{ github.repository }}
|
images: '${{ env.REGISTRY }}/${{ github.repository }}'
|
||||||
|
|
||||||
|
# Extract metadata (tags, labels) for Docker
|
||||||
|
# https://github.com/docker/metadata-action
|
||||||
|
- name: Extract Docker metadata
|
||||||
|
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
||||||
|
id: meta_release
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: '${{ env.REGISTRY }}/${{ github.repository }}'
|
||||||
|
tags: |
|
||||||
|
${{ github.event.inputs.version }}
|
||||||
|
flavor: |
|
||||||
|
latest=true
|
||||||
|
labels: org.opencontainers.image.version=${{ github.event.inputs.version }}
|
||||||
|
|
||||||
- name: Show files
|
- name: Show files
|
||||||
run: |
|
run: |
|
||||||
ls .
|
ls .
|
||||||
ls bin/
|
ls bin/
|
||||||
|
|
||||||
- name: login to docker REGISTRY
|
- name: login to docker REGISTRY
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
@@ -375,7 +458,7 @@ jobs:
|
|||||||
# Build and push Docker image with Buildx (don't push on PR)
|
# Build and push Docker image with Buildx (don't push on PR)
|
||||||
# https://github.com/docker/build-push-action
|
# https://github.com/docker/build-push-action
|
||||||
- name: Build and push Docker image
|
- name: Build and push Docker image
|
||||||
id: build-and-push
|
if: ${{ github.event_name != 'workflow_dispatch' }}
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v5
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
@@ -386,5 +469,20 @@ jobs:
|
|||||||
linux/amd64
|
linux/amd64
|
||||||
linux/arm64
|
linux/arm64
|
||||||
linux/arm/v7
|
linux/arm/v7
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta_alpha.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta_alpha.outputs.labels }}
|
||||||
|
|
||||||
|
- name: Build and push Docker image
|
||||||
|
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./Dockerfile
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
platforms: |
|
||||||
|
linux/386
|
||||||
|
linux/amd64
|
||||||
|
linux/arm64
|
||||||
|
linux/arm/v7
|
||||||
|
tags: ${{ steps.meta_release.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta_release.outputs.labels }}
|
||||||
@@ -12,7 +12,7 @@ COPY docker/file-name.sh /mihomo/file-name.sh
|
|||||||
WORKDIR /mihomo
|
WORKDIR /mihomo
|
||||||
COPY bin/ bin/
|
COPY bin/ bin/
|
||||||
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
||||||
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.*"|awk NR==1` && echo $FILE_NAME && \
|
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.gz"|awk NR==1` && echo $FILE_NAME && \
|
||||||
mv bin/$FILE_NAME mihomo.gz && gzip -d mihomo.gz && echo "$FILE_NAME" > /mihomo-config/test
|
mv bin/$FILE_NAME mihomo.gz && gzip -d mihomo.gz && echo "$FILE_NAME" > /mihomo-config/test
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/mihomo"
|
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/mihomo"
|
||||||
|
|||||||
1
Makefile
1
Makefile
@@ -17,6 +17,7 @@ GOBUILD=CGO_ENABLED=0 go build -tags with_gvisor -trimpath -ldflags '-X "github.
|
|||||||
-w -s -buildid='
|
-w -s -buildid='
|
||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
|
darwin-amd64-compatible \
|
||||||
darwin-amd64 \
|
darwin-amd64 \
|
||||||
darwin-arm64 \
|
darwin-arm64 \
|
||||||
linux-amd64-compatible \
|
linux-amd64-compatible \
|
||||||
|
|||||||
@@ -98,4 +98,3 @@ API.
|
|||||||
|
|
||||||
This software is released under the GPL-3.0 license.
|
This software is released under the GPL-3.0 license.
|
||||||
|
|
||||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2FMetaCubeX%2Fmihomo?ref=badge_large)
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package adapter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
@@ -14,6 +15,7 @@ import (
|
|||||||
"github.com/metacubex/mihomo/common/atomic"
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
"github.com/metacubex/mihomo/common/queue"
|
"github.com/metacubex/mihomo/common/queue"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/puzpuzpuz/xsync/v3"
|
"github.com/puzpuzpuz/xsync/v3"
|
||||||
@@ -230,6 +232,7 @@ func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.In
|
|||||||
IdleConnTimeout: 90 * time.Second,
|
IdleConnTimeout: 90 * time.Second,
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
|
TLSClientConfig: ca.GetGlobalTLSConfig(&tls.Config{}),
|
||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{
|
client := http.Client{
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ func WithDstAddr(addr net.Addr) Addition {
|
|||||||
func WithSrcAddr(addr net.Addr) Addition {
|
func WithSrcAddr(addr net.Addr) Addition {
|
||||||
return func(metadata *C.Metadata) {
|
return func(metadata *C.Metadata) {
|
||||||
m := C.Metadata{}
|
m := C.Metadata{}
|
||||||
if err := m.SetRemoteAddr(addr);err ==nil{
|
if err := m.SetRemoteAddr(addr); err == nil {
|
||||||
metadata.SrcIP = m.DstIP
|
metadata.SrcIP = m.DstIP
|
||||||
metadata.SrcPort = m.DstPort
|
metadata.SrcPort = m.DstPort
|
||||||
}
|
}
|
||||||
@@ -57,7 +57,7 @@ func WithSrcAddr(addr net.Addr) Addition {
|
|||||||
func WithInAddr(addr net.Addr) Addition {
|
func WithInAddr(addr net.Addr) Addition {
|
||||||
return func(metadata *C.Metadata) {
|
return func(metadata *C.Metadata) {
|
||||||
m := C.Metadata{}
|
m := C.Metadata{}
|
||||||
if err := m.SetRemoteAddr(addr);err ==nil{
|
if err := m.SetRemoteAddr(addr); err == nil {
|
||||||
metadata.InIP = m.DstIP
|
metadata.InIP = m.DstIP
|
||||||
metadata.InPort = m.DstPort
|
metadata.InPort = m.DstPort
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ func NewHTTP(target socks5.Addr, srcConn net.Conn, conn net.Conn, additions ...A
|
|||||||
metadata.Type = C.HTTP
|
metadata.Type = C.HTTP
|
||||||
metadata.RawSrcAddr = srcConn.RemoteAddr()
|
metadata.RawSrcAddr = srcConn.RemoteAddr()
|
||||||
metadata.RawDstAddr = srcConn.LocalAddr()
|
metadata.RawDstAddr = srcConn.LocalAddr()
|
||||||
ApplyAdditions(metadata, WithSrcAddr(srcConn.RemoteAddr()), WithInAddr(conn.LocalAddr()))
|
ApplyAdditions(metadata, WithSrcAddr(srcConn.RemoteAddr()), WithInAddr(srcConn.LocalAddr()))
|
||||||
ApplyAdditions(metadata, additions...)
|
ApplyAdditions(metadata, additions...)
|
||||||
return conn, metadata
|
return conn, metadata
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,22 +3,10 @@ package inbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/sagernet/tfo-go"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
|
||||||
lc = tfo.ListenConfig{
|
|
||||||
DisableTFO: true,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
func SetTfo(open bool) {
|
|
||||||
lc.DisableTFO = !open
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetMPTCP(open bool) {
|
func SetMPTCP(open bool) {
|
||||||
setMultiPathTCP(&lc.ListenConfig, open)
|
setMultiPathTCP(getListenConfig(), open)
|
||||||
}
|
}
|
||||||
|
|
||||||
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
|
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
|
||||||
|
|||||||
23
adapter/inbound/listen_unix.go
Normal file
23
adapter/inbound/listen_unix.go
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
//go:build unix
|
||||||
|
|
||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/metacubex/tfo-go"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
lc = tfo.ListenConfig{
|
||||||
|
DisableTFO: true,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func SetTfo(open bool) {
|
||||||
|
lc.DisableTFO = !open
|
||||||
|
}
|
||||||
|
|
||||||
|
func getListenConfig() *net.ListenConfig {
|
||||||
|
return &lc.ListenConfig
|
||||||
|
}
|
||||||
15
adapter/inbound/listen_windows.go
Normal file
15
adapter/inbound/listen_windows.go
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
lc = net.ListenConfig{}
|
||||||
|
)
|
||||||
|
|
||||||
|
func SetTfo(open bool) {}
|
||||||
|
|
||||||
|
func getListenConfig() *net.ListenConfig {
|
||||||
|
return &lc
|
||||||
|
}
|
||||||
@@ -3,18 +3,22 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"os"
|
||||||
"net/netip"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
|
"github.com/metacubex/mihomo/component/loopback"
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/constant/features"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var DisableLoopBackDetector, _ = strconv.ParseBool(os.Getenv("DISABLE_LOOPBACK_DETECTOR"))
|
||||||
|
|
||||||
type Direct struct {
|
type Direct struct {
|
||||||
*Base
|
*Base
|
||||||
loopBack *loopBackDetector
|
loopBack *loopback.Detector
|
||||||
}
|
}
|
||||||
|
|
||||||
type DirectOption struct {
|
type DirectOption struct {
|
||||||
@@ -24,8 +28,10 @@ type DirectOption struct {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
if d.loopBack.CheckConn(metadata.SourceAddrPort()) {
|
if !features.CMFA && !DisableLoopBackDetector {
|
||||||
return nil, fmt.Errorf("reject loopback connection to: %s", metadata.RemoteAddress())
|
if err := d.loopBack.CheckConn(metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
||||||
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
||||||
@@ -38,8 +44,10 @@ func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
if d.loopBack.CheckPacketConn(metadata.SourceAddrPort()) {
|
if !features.CMFA && !DisableLoopBackDetector {
|
||||||
return nil, fmt.Errorf("reject loopback connection to: %s", metadata.RemoteAddress())
|
if err := d.loopBack.CheckPacketConn(metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// net.UDPConn.WriteTo only working with *net.UDPAddr, so we need a net.UDPAddr
|
// net.UDPConn.WriteTo only working with *net.UDPAddr, so we need a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
@@ -49,13 +57,17 @@ func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
}
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
pc, err := dialer.NewDialer(d.Base.DialOptions(opts...)...).ListenPacket(ctx, "udp", "", netip.AddrPortFrom(metadata.DstIP, metadata.DstPort))
|
pc, err := dialer.NewDialer(d.Base.DialOptions(opts...)...).ListenPacket(ctx, "udp", "", metadata.AddrPort())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return d.loopBack.NewPacketConn(newPacketConn(pc, d)), nil
|
return d.loopBack.NewPacketConn(newPacketConn(pc, d)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *Direct) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return true // tell DNSDialer don't send domain to DialContext, avoid lookback to DefaultResolver
|
||||||
|
}
|
||||||
|
|
||||||
func NewDirectWithOption(option DirectOption) *Direct {
|
func NewDirectWithOption(option DirectOption) *Direct {
|
||||||
return &Direct{
|
return &Direct{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
@@ -68,7 +80,7 @@ func NewDirectWithOption(option DirectOption) *Direct {
|
|||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
loopBack: newLoopBackDetector(),
|
loopBack: loopback.NewDetector(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,7 +92,7 @@ func NewDirect() *Direct {
|
|||||||
udp: true,
|
udp: true,
|
||||||
prefer: C.DualStack,
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
loopBack: newLoopBackDetector(),
|
loopBack: loopback.NewDetector(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,6 +104,6 @@ func NewCompatible() *Direct {
|
|||||||
udp: true,
|
udp: true,
|
||||||
prefer: C.DualStack,
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
loopBack: newLoopBackDetector(),
|
loopBack: loopback.NewDetector(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,68 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/callback"
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
|
|
||||||
"github.com/puzpuzpuz/xsync/v3"
|
|
||||||
)
|
|
||||||
|
|
||||||
type loopBackDetector struct {
|
|
||||||
connMap *xsync.MapOf[netip.AddrPort, struct{}]
|
|
||||||
packetConnMap *xsync.MapOf[netip.AddrPort, struct{}]
|
|
||||||
}
|
|
||||||
|
|
||||||
func newLoopBackDetector() *loopBackDetector {
|
|
||||||
return &loopBackDetector{
|
|
||||||
connMap: xsync.NewMapOf[netip.AddrPort, struct{}](),
|
|
||||||
packetConnMap: xsync.NewMapOf[netip.AddrPort, struct{}](),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *loopBackDetector) NewConn(conn C.Conn) C.Conn {
|
|
||||||
metadata := C.Metadata{}
|
|
||||||
if metadata.SetRemoteAddr(conn.LocalAddr()) != nil {
|
|
||||||
return conn
|
|
||||||
}
|
|
||||||
connAddr := metadata.AddrPort()
|
|
||||||
if !connAddr.IsValid() {
|
|
||||||
return conn
|
|
||||||
}
|
|
||||||
l.connMap.Store(connAddr, struct{}{})
|
|
||||||
return callback.NewCloseCallbackConn(conn, func() {
|
|
||||||
l.connMap.Delete(connAddr)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *loopBackDetector) NewPacketConn(conn C.PacketConn) C.PacketConn {
|
|
||||||
metadata := C.Metadata{}
|
|
||||||
if metadata.SetRemoteAddr(conn.LocalAddr()) != nil {
|
|
||||||
return conn
|
|
||||||
}
|
|
||||||
connAddr := metadata.AddrPort()
|
|
||||||
if !connAddr.IsValid() {
|
|
||||||
return conn
|
|
||||||
}
|
|
||||||
l.packetConnMap.Store(connAddr, struct{}{})
|
|
||||||
return callback.NewCloseCallbackPacketConn(conn, func() {
|
|
||||||
l.packetConnMap.Delete(connAddr)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *loopBackDetector) CheckConn(connAddr netip.AddrPort) bool {
|
|
||||||
if !connAddr.IsValid() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := l.connMap.Load(connAddr)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *loopBackDetector) CheckPacketConn(connAddr netip.AddrPort) bool {
|
|
||||||
if !connAddr.IsValid() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := l.packetConnMap.Load(connAddr)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
159
adapter/outbound/dns.go
Normal file
159
adapter/outbound/dns.go
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
"github.com/metacubex/mihomo/common/pool"
|
||||||
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Dns struct {
|
||||||
|
*Base
|
||||||
|
}
|
||||||
|
|
||||||
|
type DnsOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (d *Dns) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
left, right := N.Pipe()
|
||||||
|
go resolver.RelayDnsConn(context.Background(), right, 0)
|
||||||
|
return NewConn(left, d), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (d *Dns) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
log.Debugln("[DNS] hijack udp:%s from %s", metadata.RemoteAddress(), metadata.SourceAddrPort())
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
|
||||||
|
return newPacketConn(&dnsPacketConn{
|
||||||
|
response: make(chan dnsPacket, 1),
|
||||||
|
ctx: ctx,
|
||||||
|
cancel: cancel,
|
||||||
|
}, d), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type dnsPacket struct {
|
||||||
|
data []byte
|
||||||
|
put func()
|
||||||
|
addr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
// dnsPacketConn implements net.PacketConn
|
||||||
|
type dnsPacketConn struct {
|
||||||
|
response chan dnsPacket
|
||||||
|
ctx context.Context
|
||||||
|
cancel context.CancelFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dnsPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
select {
|
||||||
|
case packet := <-d.response:
|
||||||
|
return packet.data, packet.put, packet.addr, nil
|
||||||
|
case <-d.ctx.Done():
|
||||||
|
return nil, nil, nil, net.ErrClosed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dnsPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||||
|
select {
|
||||||
|
case packet := <-d.response:
|
||||||
|
n = copy(p, packet.data)
|
||||||
|
if packet.put != nil {
|
||||||
|
packet.put()
|
||||||
|
}
|
||||||
|
return n, packet.addr, nil
|
||||||
|
case <-d.ctx.Done():
|
||||||
|
return 0, nil, net.ErrClosed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dnsPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||||
|
select {
|
||||||
|
case <-d.ctx.Done():
|
||||||
|
return 0, net.ErrClosed
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(p) > resolver.SafeDnsPacketSize {
|
||||||
|
// wtf???
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := pool.Get(resolver.SafeDnsPacketSize)
|
||||||
|
put := func() { _ = pool.Put(buf) }
|
||||||
|
copy(buf, p) // avoid p be changed after WriteTo returned
|
||||||
|
|
||||||
|
go func() { // don't block the WriteTo function
|
||||||
|
ctx, cancel := context.WithTimeout(d.ctx, resolver.DefaultDnsRelayTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
buf, err = resolver.RelayDnsPacket(ctx, buf[:len(p)], buf)
|
||||||
|
if err != nil {
|
||||||
|
put()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
packet := dnsPacket{
|
||||||
|
data: buf,
|
||||||
|
put: put,
|
||||||
|
addr: addr,
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case d.response <- packet:
|
||||||
|
break
|
||||||
|
case <-d.ctx.Done():
|
||||||
|
put()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dnsPacketConn) Close() error {
|
||||||
|
d.cancel()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*dnsPacketConn) LocalAddr() net.Addr {
|
||||||
|
return &net.UDPAddr{
|
||||||
|
IP: net.IPv4(127, 0, 0, 1),
|
||||||
|
Port: 53,
|
||||||
|
Zone: "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*dnsPacketConn) SetDeadline(t time.Time) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*dnsPacketConn) SetReadDeadline(t time.Time) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*dnsPacketConn) SetWriteDeadline(t time.Time) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDnsWithOption(option DnsOption) *Dns {
|
||||||
|
return &Dns{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
tp: C.Dns,
|
||||||
|
udp: true,
|
||||||
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,16 +8,20 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
CN "github.com/metacubex/mihomo/common/net"
|
CN "github.com/metacubex/mihomo/common/net"
|
||||||
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
tuicCommon "github.com/metacubex/mihomo/transport/tuic/common"
|
tuicCommon "github.com/metacubex/mihomo/transport/tuic/common"
|
||||||
|
|
||||||
"github.com/metacubex/sing-quic/hysteria2"
|
"github.com/metacubex/sing-quic/hysteria2"
|
||||||
|
|
||||||
|
"github.com/metacubex/randv2"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -25,6 +29,9 @@ func init() {
|
|||||||
hysteria2.SetCongestionController = tuicCommon.SetCongestionController
|
hysteria2.SetCongestionController = tuicCommon.SetCongestionController
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const minHopInterval = 5
|
||||||
|
const defaultHopInterval = 30
|
||||||
|
|
||||||
type Hysteria2 struct {
|
type Hysteria2 struct {
|
||||||
*Base
|
*Base
|
||||||
|
|
||||||
@@ -37,7 +44,9 @@ type Hysteria2Option struct {
|
|||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port,omitempty"`
|
||||||
|
Ports string `proxy:"ports,omitempty"`
|
||||||
|
HopInterval int `proxy:"hop-interval,omitempty"`
|
||||||
Up string `proxy:"up,omitempty"`
|
Up string `proxy:"up,omitempty"`
|
||||||
Down string `proxy:"down,omitempty"`
|
Down string `proxy:"down,omitempty"`
|
||||||
Password string `proxy:"password,omitempty"`
|
Password string `proxy:"password,omitempty"`
|
||||||
@@ -129,7 +138,7 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
|||||||
clientOptions := hysteria2.ClientOptions{
|
clientOptions := hysteria2.ClientOptions{
|
||||||
Context: context.TODO(),
|
Context: context.TODO(),
|
||||||
Dialer: singDialer,
|
Dialer: singDialer,
|
||||||
ServerAddress: M.ParseSocksaddrHostPort(option.Server, uint16(option.Port)),
|
Logger: log.SingLogger,
|
||||||
SendBPS: StringToBps(option.Up),
|
SendBPS: StringToBps(option.Up),
|
||||||
ReceiveBPS: StringToBps(option.Down),
|
ReceiveBPS: StringToBps(option.Down),
|
||||||
SalamanderPassword: salamanderPassword,
|
SalamanderPassword: salamanderPassword,
|
||||||
@@ -138,6 +147,37 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
|||||||
UDPDisabled: false,
|
UDPDisabled: false,
|
||||||
CWND: option.CWND,
|
CWND: option.CWND,
|
||||||
UdpMTU: option.UdpMTU,
|
UdpMTU: option.UdpMTU,
|
||||||
|
ServerAddress: func(ctx context.Context) (*net.UDPAddr, error) {
|
||||||
|
return resolveUDPAddrWithPrefer(ctx, "udp", addr, C.NewDNSPrefer(option.IPVersion))
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
var ranges utils.IntRanges[uint16]
|
||||||
|
var serverAddress []string
|
||||||
|
if option.Ports != "" {
|
||||||
|
ranges, err = utils.NewUnsignedRanges[uint16](option.Ports)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ranges.Range(func(port uint16) bool {
|
||||||
|
serverAddress = append(serverAddress, net.JoinHostPort(option.Server, strconv.Itoa(int(port))))
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if len(serverAddress) > 0 {
|
||||||
|
clientOptions.ServerAddress = func(ctx context.Context) (*net.UDPAddr, error) {
|
||||||
|
return resolveUDPAddrWithPrefer(ctx, "udp", serverAddress[randv2.IntN(len(serverAddress))], C.NewDNSPrefer(option.IPVersion))
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.HopInterval == 0 {
|
||||||
|
option.HopInterval = defaultHopInterval
|
||||||
|
} else if option.HopInterval < minHopInterval {
|
||||||
|
option.HopInterval = minHopInterval
|
||||||
|
}
|
||||||
|
clientOptions.HopInterval = time.Duration(option.HopInterval) * time.Second
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if option.Port == 0 && len(serverAddress) == 0 {
|
||||||
|
return nil, errors.New("invalid port")
|
||||||
}
|
}
|
||||||
|
|
||||||
client, err := hysteria2.NewClient(clientOptions)
|
client, err := hysteria2.NewClient(clientOptions)
|
||||||
|
|||||||
@@ -166,12 +166,6 @@ func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if len(ss.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(ss.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ss.option.UDPOverTCP {
|
if ss.option.UDPOverTCP {
|
||||||
tcpConn, err := ss.DialContextWithDialer(ctx, dialer, metadata)
|
tcpConn, err := ss.DialContextWithDialer(ctx, dialer, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -179,6 +173,12 @@ func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dial
|
|||||||
}
|
}
|
||||||
return ss.ListenPacketOnStreamConn(ctx, tcpConn, metadata)
|
return ss.ListenPacketOnStreamConn(ctx, tcpConn, metadata)
|
||||||
}
|
}
|
||||||
|
if len(ss.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(ss.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -273,6 +273,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
if opts.TLS {
|
if opts.TLS {
|
||||||
v2rayOption.TLS = true
|
v2rayOption.TLS = true
|
||||||
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
||||||
|
v2rayOption.Fingerprint = opts.Fingerprint
|
||||||
}
|
}
|
||||||
} else if option.Plugin == shadowtls.Mode {
|
} else if option.Plugin == shadowtls.Mode {
|
||||||
obfsMode = shadowtls.Mode
|
obfsMode = shadowtls.Mode
|
||||||
|
|||||||
208
adapter/outbound/ssh.go
Normal file
208
adapter/outbound/ssh.go
Normal file
@@ -0,0 +1,208 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
|
||||||
|
"github.com/metacubex/randv2"
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Ssh struct {
|
||||||
|
*Base
|
||||||
|
|
||||||
|
option *SshOption
|
||||||
|
client *sshClient // using a standalone struct to avoid its inner loop invalidate the Finalizer
|
||||||
|
}
|
||||||
|
|
||||||
|
type SshOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UserName string `proxy:"username"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
|
PrivateKeyPassphrase string `proxy:"private-key-passphrase,omitempty"`
|
||||||
|
HostKey []string `proxy:"host-key,omitempty"`
|
||||||
|
HostKeyAlgorithms []string `proxy:"host-key-algorithms,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Ssh) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
|
var cDialer C.Dialer = dialer.NewDialer(s.Base.DialOptions(opts...)...)
|
||||||
|
if len(s.option.DialerProxy) > 0 {
|
||||||
|
cDialer, err = proxydialer.NewByName(s.option.DialerProxy, cDialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
client, err := s.client.connect(ctx, cDialer, s.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c, err := client.DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(N.NewRefConn(c, s), s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type sshClient struct {
|
||||||
|
config *ssh.ClientConfig
|
||||||
|
client *ssh.Client
|
||||||
|
cMutex sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *sshClient) connect(ctx context.Context, cDialer C.Dialer, addr string) (client *ssh.Client, err error) {
|
||||||
|
s.cMutex.Lock()
|
||||||
|
defer s.cMutex.Unlock()
|
||||||
|
if s.client != nil {
|
||||||
|
return s.client, nil
|
||||||
|
}
|
||||||
|
c, err := cDialer.DialContext(ctx, "tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
|
|
||||||
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
|
if ctx.Done() != nil {
|
||||||
|
done := N.SetupContextForConn(ctx, c)
|
||||||
|
defer done(&err)
|
||||||
|
}
|
||||||
|
|
||||||
|
clientConn, chans, reqs, err := ssh.NewClientConn(c, addr, s.config)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
client = ssh.NewClient(clientConn, chans, reqs)
|
||||||
|
|
||||||
|
s.client = client
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
_ = client.Wait() // wait shutdown
|
||||||
|
_ = client.Close()
|
||||||
|
s.cMutex.Lock()
|
||||||
|
defer s.cMutex.Unlock()
|
||||||
|
if s.client == client {
|
||||||
|
s.client = nil
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return client, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *sshClient) Close() error {
|
||||||
|
s.cMutex.Lock()
|
||||||
|
defer s.cMutex.Unlock()
|
||||||
|
if s.client != nil {
|
||||||
|
return s.client.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func closeSsh(s *Ssh) {
|
||||||
|
_ = s.client.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSsh(option SshOption) (*Ssh, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
|
config := ssh.ClientConfig{
|
||||||
|
User: option.UserName,
|
||||||
|
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
|
||||||
|
HostKeyAlgorithms: option.HostKeyAlgorithms,
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.PrivateKey != "" {
|
||||||
|
var b []byte
|
||||||
|
var err error
|
||||||
|
if strings.Contains(option.PrivateKey, "PRIVATE KEY") {
|
||||||
|
b = []byte(option.PrivateKey)
|
||||||
|
} else {
|
||||||
|
b, err = os.ReadFile(C.Path.Resolve(option.PrivateKey))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var pKey ssh.Signer
|
||||||
|
if option.PrivateKeyPassphrase != "" {
|
||||||
|
pKey, err = ssh.ParsePrivateKeyWithPassphrase(b, []byte(option.PrivateKeyPassphrase))
|
||||||
|
} else {
|
||||||
|
pKey, err = ssh.ParsePrivateKey(b)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
config.Auth = append(config.Auth, ssh.PublicKeys(pKey))
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.Password != "" {
|
||||||
|
config.Auth = append(config.Auth, ssh.Password(option.Password))
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.HostKey) != 0 {
|
||||||
|
keys := make([]ssh.PublicKey, len(option.HostKey))
|
||||||
|
for i, hostKey := range option.HostKey {
|
||||||
|
key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(hostKey))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("parse host key :%s", key)
|
||||||
|
}
|
||||||
|
keys[i] = key
|
||||||
|
}
|
||||||
|
config.HostKeyCallback = func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||||
|
serverKey := key.Marshal()
|
||||||
|
for _, hostKey := range keys {
|
||||||
|
if bytes.Equal(serverKey, hostKey.Marshal()) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("host key mismatch, server send :%s %s", key.Type(), base64.StdEncoding.EncodeToString(serverKey))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
version := "SSH-2.0-OpenSSH_"
|
||||||
|
if randv2.IntN(2) == 0 {
|
||||||
|
version += "7." + strconv.Itoa(randv2.IntN(10))
|
||||||
|
} else {
|
||||||
|
version += "8." + strconv.Itoa(randv2.IntN(9))
|
||||||
|
}
|
||||||
|
config.ClientVersion = version
|
||||||
|
|
||||||
|
outbound := &Ssh{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Ssh,
|
||||||
|
udp: false,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
},
|
||||||
|
option: &option,
|
||||||
|
client: &sshClient{
|
||||||
|
config: &config,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
runtime.SetFinalizer(outbound, closeSsh)
|
||||||
|
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -15,6 +16,7 @@ import (
|
|||||||
tlsC "github.com/metacubex/mihomo/component/tls"
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/transport/gun"
|
"github.com/metacubex/mihomo/transport/gun"
|
||||||
|
"github.com/metacubex/mihomo/transport/shadowsocks/core"
|
||||||
"github.com/metacubex/mihomo/transport/trojan"
|
"github.com/metacubex/mihomo/transport/trojan"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -29,6 +31,8 @@ type Trojan struct {
|
|||||||
transport *gun.TransportWrap
|
transport *gun.TransportWrap
|
||||||
|
|
||||||
realityConfig *tlsC.RealityConfig
|
realityConfig *tlsC.RealityConfig
|
||||||
|
|
||||||
|
ssCipher core.Cipher
|
||||||
}
|
}
|
||||||
|
|
||||||
type TrojanOption struct {
|
type TrojanOption struct {
|
||||||
@@ -46,9 +50,17 @@ type TrojanOption struct {
|
|||||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
|
SSOpts TrojanSSOption `proxy:"ss-opts,omitempty"`
|
||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TrojanSSOption from https://github.com/p4gefau1t/trojan-go/blob/v0.10.6/tunnel/shadowsocks/config.go#L5
|
||||||
|
type TrojanSSOption struct {
|
||||||
|
Enabled bool `proxy:"enabled,omitempty"`
|
||||||
|
Method string `proxy:"method,omitempty"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
func (t *Trojan) plainStream(ctx context.Context, c net.Conn) (net.Conn, error) {
|
func (t *Trojan) plainStream(ctx context.Context, c net.Conn) (net.Conn, error) {
|
||||||
if t.option.Network == "ws" {
|
if t.option.Network == "ws" {
|
||||||
host, port, _ := net.SplitHostPort(t.addr)
|
host, port, _ := net.SplitHostPort(t.addr)
|
||||||
@@ -95,6 +107,10 @@ func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.
|
|||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if t.ssCipher != nil {
|
||||||
|
c = t.ssCipher.StreamConn(c)
|
||||||
|
}
|
||||||
|
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
return c, err
|
return c, err
|
||||||
@@ -112,6 +128,10 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if t.ssCipher != nil {
|
||||||
|
c = t.ssCipher.StreamConn(c)
|
||||||
|
}
|
||||||
|
|
||||||
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
||||||
c.Close()
|
c.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -161,6 +181,11 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
|
if t.ssCipher != nil {
|
||||||
|
c = t.ssCipher.StreamConn(c)
|
||||||
|
}
|
||||||
|
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -193,6 +218,10 @@ func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if t.ssCipher != nil {
|
||||||
|
c = t.ssCipher.StreamConn(c)
|
||||||
|
}
|
||||||
|
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -257,6 +286,20 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
}
|
}
|
||||||
tOption.Reality = t.realityConfig
|
tOption.Reality = t.realityConfig
|
||||||
|
|
||||||
|
if option.SSOpts.Enabled {
|
||||||
|
if option.SSOpts.Password == "" {
|
||||||
|
return nil, errors.New("empty password")
|
||||||
|
}
|
||||||
|
if option.SSOpts.Method == "" {
|
||||||
|
option.SSOpts.Method = "AES-128-GCM"
|
||||||
|
}
|
||||||
|
ciph, err := core.PickCipher(option.SSOpts.Method, nil, option.SSOpts.Password)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
t.ssCipher = ciph
|
||||||
|
}
|
||||||
|
|
||||||
if option.Network == "grpc" {
|
if option.Network == "grpc" {
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|||||||
@@ -373,7 +373,7 @@ func (v *Vless) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metada
|
|||||||
}, M.SocksaddrFromNet(metadata.UDPAddr())),
|
}, M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||||
), v), nil
|
), v), nil
|
||||||
}
|
}
|
||||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return newPacketConn(N.NewThreadSafePacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}), v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
|||||||
@@ -179,6 +179,7 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
tlsOpts := mihomoVMess.TLSConfig{
|
tlsOpts := mihomoVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
FingerPrint: v.option.Fingerprint,
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Reality: v.realityConfig,
|
Reality: v.realityConfig,
|
||||||
@@ -208,6 +209,7 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
tlsOpts := &mihomoVMess.TLSConfig{
|
tlsOpts := &mihomoVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
FingerPrint: v.option.Fingerprint,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Reality: v.realityConfig,
|
Reality: v.realityConfig,
|
||||||
NextProtos: v.option.ALPN,
|
NextProtos: v.option.ALPN,
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
CN "github.com/metacubex/mihomo/common/net"
|
CN "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
@@ -37,16 +39,29 @@ type WireGuard struct {
|
|||||||
device *device.Device
|
device *device.Device
|
||||||
tunDevice wireguard.Device
|
tunDevice wireguard.Device
|
||||||
dialer proxydialer.SingDialer
|
dialer proxydialer.SingDialer
|
||||||
startOnce sync.Once
|
|
||||||
startErr error
|
|
||||||
resolver *dns.Resolver
|
resolver *dns.Resolver
|
||||||
refP *refProxyAdapter
|
refP *refProxyAdapter
|
||||||
|
|
||||||
|
initOk atomic.Bool
|
||||||
|
initMutex sync.Mutex
|
||||||
|
initErr error
|
||||||
|
option WireGuardOption
|
||||||
|
connectAddr M.Socksaddr
|
||||||
|
localPrefixes []netip.Prefix
|
||||||
|
|
||||||
|
serverAddrMap map[M.Socksaddr]netip.AddrPort
|
||||||
|
serverAddrTime atomic.TypedValue[time.Time]
|
||||||
|
serverAddrMutex sync.Mutex
|
||||||
|
|
||||||
|
closeCh chan struct{} // for test
|
||||||
}
|
}
|
||||||
|
|
||||||
type WireGuardOption struct {
|
type WireGuardOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
WireGuardPeerOption
|
WireGuardPeerOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
|
Ip string `proxy:"ip,omitempty"`
|
||||||
|
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||||
PrivateKey string `proxy:"private-key"`
|
PrivateKey string `proxy:"private-key"`
|
||||||
Workers int `proxy:"workers,omitempty"`
|
Workers int `proxy:"workers,omitempty"`
|
||||||
MTU int `proxy:"mtu,omitempty"`
|
MTU int `proxy:"mtu,omitempty"`
|
||||||
@@ -57,13 +72,13 @@ type WireGuardOption struct {
|
|||||||
|
|
||||||
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
||||||
Dns []string `proxy:"dns,omitempty"`
|
Dns []string `proxy:"dns,omitempty"`
|
||||||
|
|
||||||
|
RefreshServerIPInterval int `proxy:"refresh-server-ip-interval,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type WireGuardPeerOption struct {
|
type WireGuardPeerOption struct {
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Ip string `proxy:"ip,omitempty"`
|
|
||||||
Ipv6 string `proxy:"ipv6,omitempty"`
|
|
||||||
PublicKey string `proxy:"public-key,omitempty"`
|
PublicKey string `proxy:"public-key,omitempty"`
|
||||||
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
||||||
Reserved []uint8 `proxy:"reserved,omitempty"`
|
Reserved []uint8 `proxy:"reserved,omitempty"`
|
||||||
@@ -98,7 +113,7 @@ func (option WireGuardPeerOption) Addr() M.Socksaddr {
|
|||||||
return M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
return M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (option WireGuardPeerOption) Prefixes() ([]netip.Prefix, error) {
|
func (option WireGuardOption) Prefixes() ([]netip.Prefix, error) {
|
||||||
localPrefixes := make([]netip.Prefix, 0, 2)
|
localPrefixes := make([]netip.Prefix, 0, 2)
|
||||||
if len(option.Ip) > 0 {
|
if len(option.Ip) > 0 {
|
||||||
if !strings.Contains(option.Ip, "/") {
|
if !strings.Contains(option.Ip, "/") {
|
||||||
@@ -149,125 +164,83 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
copy(reserved[:], option.Reserved)
|
copy(reserved[:], option.Reserved)
|
||||||
}
|
}
|
||||||
var isConnect bool
|
var isConnect bool
|
||||||
var connectAddr M.Socksaddr
|
|
||||||
if len(option.Peers) < 2 {
|
if len(option.Peers) < 2 {
|
||||||
isConnect = true
|
isConnect = true
|
||||||
if len(option.Peers) == 1 {
|
if len(option.Peers) == 1 {
|
||||||
connectAddr = option.Peers[0].Addr()
|
outbound.connectAddr = option.Peers[0].Addr()
|
||||||
} else {
|
} else {
|
||||||
connectAddr = option.Addr()
|
outbound.connectAddr = option.Addr()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
outbound.bind = wireguard.NewClientBind(context.Background(), wgSingErrorHandler{outbound.Name()}, outbound.dialer, isConnect, connectAddr, reserved)
|
outbound.bind = wireguard.NewClientBind(context.Background(), wgSingErrorHandler{outbound.Name()}, outbound.dialer, isConnect, outbound.connectAddr.AddrPort(), reserved)
|
||||||
|
|
||||||
var localPrefixes []netip.Prefix
|
var err error
|
||||||
|
outbound.localPrefixes, err = option.Prefixes()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
var privateKey string
|
|
||||||
{
|
{
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode private key")
|
return nil, E.Cause(err, "decode private key")
|
||||||
}
|
}
|
||||||
privateKey = hex.EncodeToString(bytes)
|
option.PrivateKey = hex.EncodeToString(bytes)
|
||||||
}
|
}
|
||||||
ipcConf := "private_key=" + privateKey
|
|
||||||
if peersLen := len(option.Peers); peersLen > 0 {
|
if len(option.Peers) > 0 {
|
||||||
localPrefixes = make([]netip.Prefix, 0, peersLen*2)
|
for i := range option.Peers {
|
||||||
for i, peer := range option.Peers {
|
peer := &option.Peers[i] // we need modify option here
|
||||||
var peerPublicKey, preSharedKey string
|
bytes, err := base64.StdEncoding.DecodeString(peer.PublicKey)
|
||||||
{
|
if err != nil {
|
||||||
bytes, err := base64.StdEncoding.DecodeString(peer.PublicKey)
|
return nil, E.Cause(err, "decode public key for peer ", i)
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode public key for peer ", i)
|
|
||||||
}
|
|
||||||
peerPublicKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
}
|
||||||
|
peer.PublicKey = hex.EncodeToString(bytes)
|
||||||
|
|
||||||
if peer.PreSharedKey != "" {
|
if peer.PreSharedKey != "" {
|
||||||
bytes, err := base64.StdEncoding.DecodeString(peer.PreSharedKey)
|
bytes, err := base64.StdEncoding.DecodeString(peer.PreSharedKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode pre shared key for peer ", i)
|
return nil, E.Cause(err, "decode pre shared key for peer ", i)
|
||||||
}
|
}
|
||||||
preSharedKey = hex.EncodeToString(bytes)
|
peer.PreSharedKey = hex.EncodeToString(bytes)
|
||||||
}
|
|
||||||
destination := peer.Addr()
|
|
||||||
ipcConf += "\npublic_key=" + peerPublicKey
|
|
||||||
ipcConf += "\nendpoint=" + destination.String()
|
|
||||||
if preSharedKey != "" {
|
|
||||||
ipcConf += "\npreshared_key=" + preSharedKey
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(peer.AllowedIPs) == 0 {
|
if len(peer.AllowedIPs) == 0 {
|
||||||
return nil, E.New("missing allowed_ips for peer ", i)
|
return nil, E.New("missing allowed_ips for peer ", i)
|
||||||
}
|
}
|
||||||
for _, allowedIP := range peer.AllowedIPs {
|
|
||||||
ipcConf += "\nallowed_ip=" + allowedIP
|
|
||||||
}
|
|
||||||
if len(peer.Reserved) > 0 {
|
if len(peer.Reserved) > 0 {
|
||||||
if len(peer.Reserved) != 3 {
|
if len(peer.Reserved) != 3 {
|
||||||
return nil, E.New("invalid reserved value for peer ", i, ", required 3 bytes, got ", len(peer.Reserved))
|
return nil, E.New("invalid reserved value for peer ", i, ", required 3 bytes, got ", len(peer.Reserved))
|
||||||
}
|
}
|
||||||
copy(reserved[:], option.Reserved)
|
|
||||||
outbound.bind.SetReservedForEndpoint(destination, reserved)
|
|
||||||
}
|
}
|
||||||
prefixes, err := peer.Prefixes()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
localPrefixes = append(localPrefixes, prefixes...)
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
var peerPublicKey, preSharedKey string
|
|
||||||
{
|
{
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode peer public key")
|
return nil, E.Cause(err, "decode peer public key")
|
||||||
}
|
}
|
||||||
peerPublicKey = hex.EncodeToString(bytes)
|
option.PublicKey = hex.EncodeToString(bytes)
|
||||||
}
|
}
|
||||||
if option.PreSharedKey != "" {
|
if option.PreSharedKey != "" {
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode pre shared key")
|
return nil, E.Cause(err, "decode pre shared key")
|
||||||
}
|
}
|
||||||
preSharedKey = hex.EncodeToString(bytes)
|
option.PreSharedKey = hex.EncodeToString(bytes)
|
||||||
}
|
|
||||||
ipcConf += "\npublic_key=" + peerPublicKey
|
|
||||||
ipcConf += "\nendpoint=" + connectAddr.String()
|
|
||||||
if preSharedKey != "" {
|
|
||||||
ipcConf += "\npreshared_key=" + preSharedKey
|
|
||||||
}
|
|
||||||
var err error
|
|
||||||
localPrefixes, err = option.Prefixes()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var has4, has6 bool
|
|
||||||
for _, address := range localPrefixes {
|
|
||||||
if address.Addr().Is4() {
|
|
||||||
has4 = true
|
|
||||||
} else {
|
|
||||||
has6 = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if has4 {
|
|
||||||
ipcConf += "\nallowed_ip=0.0.0.0/0"
|
|
||||||
}
|
|
||||||
if has6 {
|
|
||||||
ipcConf += "\nallowed_ip=::/0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
outbound.option = option
|
||||||
|
|
||||||
if option.PersistentKeepalive != 0 {
|
|
||||||
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", option.PersistentKeepalive)
|
|
||||||
}
|
|
||||||
mtu := option.MTU
|
mtu := option.MTU
|
||||||
if mtu == 0 {
|
if mtu == 0 {
|
||||||
mtu = 1408
|
mtu = 1408
|
||||||
}
|
}
|
||||||
if len(localPrefixes) == 0 {
|
if len(outbound.localPrefixes) == 0 {
|
||||||
return nil, E.New("missing local address")
|
return nil, E.New("missing local address")
|
||||||
}
|
}
|
||||||
var err error
|
outbound.tunDevice, err = wireguard.NewStackDevice(outbound.localPrefixes, uint32(mtu))
|
||||||
outbound.tunDevice, err = wireguard.NewStackDevice(localPrefixes, uint32(mtu))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "create WireGuard device")
|
return nil, E.Cause(err, "create WireGuard device")
|
||||||
}
|
}
|
||||||
@@ -279,17 +252,9 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
||||||
},
|
},
|
||||||
}, option.Workers)
|
}, option.Workers)
|
||||||
if debug.Enabled {
|
|
||||||
log.SingLogger.Trace(fmt.Sprintf("[WG](%s) created wireguard ipc conf: \n %s", option.Name, ipcConf))
|
|
||||||
}
|
|
||||||
err = outbound.device.IpcSet(ipcConf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "setup wireguard")
|
|
||||||
}
|
|
||||||
//err = outbound.tunDevice.Start()
|
|
||||||
|
|
||||||
var has6 bool
|
var has6 bool
|
||||||
for _, address := range localPrefixes {
|
for _, address := range outbound.localPrefixes {
|
||||||
if !address.Addr().Unmap().Is4() {
|
if !address.Addr().Unmap().Is4() {
|
||||||
has6 = true
|
has6 = true
|
||||||
break
|
break
|
||||||
@@ -315,22 +280,194 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
return outbound, nil
|
return outbound, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) resolve(ctx context.Context, address M.Socksaddr) (netip.AddrPort, error) {
|
||||||
|
if address.Addr.IsValid() {
|
||||||
|
return address.AddrPort(), nil
|
||||||
|
}
|
||||||
|
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", address.String(), w.prefer)
|
||||||
|
if err != nil {
|
||||||
|
return netip.AddrPort{}, err
|
||||||
|
}
|
||||||
|
// net.ResolveUDPAddr maybe return 4in6 address, so unmap at here
|
||||||
|
addrPort := udpAddr.AddrPort()
|
||||||
|
return netip.AddrPortFrom(addrPort.Addr().Unmap(), addrPort.Port()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) init(ctx context.Context) error {
|
||||||
|
err := w.init0(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
w.updateServerAddr(ctx)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) init0(ctx context.Context) error {
|
||||||
|
if w.initOk.Load() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
w.initMutex.Lock()
|
||||||
|
defer w.initMutex.Unlock()
|
||||||
|
// double check like sync.Once
|
||||||
|
if w.initOk.Load() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if w.initErr != nil {
|
||||||
|
return w.initErr
|
||||||
|
}
|
||||||
|
|
||||||
|
w.bind.ResetReservedForEndpoint()
|
||||||
|
w.serverAddrMap = make(map[M.Socksaddr]netip.AddrPort)
|
||||||
|
ipcConf, err := w.genIpcConf(ctx, false)
|
||||||
|
if err != nil {
|
||||||
|
// !!! do not set initErr here !!!
|
||||||
|
// let us can retry domain resolve in next time
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if debug.Enabled {
|
||||||
|
log.SingLogger.Trace(fmt.Sprintf("[WG](%s) created wireguard ipc conf: \n %s", w.option.Name, ipcConf))
|
||||||
|
}
|
||||||
|
err = w.device.IpcSet(ipcConf)
|
||||||
|
if err != nil {
|
||||||
|
w.initErr = E.Cause(err, "setup wireguard")
|
||||||
|
return w.initErr
|
||||||
|
}
|
||||||
|
w.serverAddrTime.Store(time.Now())
|
||||||
|
|
||||||
|
err = w.tunDevice.Start()
|
||||||
|
if err != nil {
|
||||||
|
w.initErr = err
|
||||||
|
return w.initErr
|
||||||
|
}
|
||||||
|
|
||||||
|
w.initOk.Store(true)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) updateServerAddr(ctx context.Context) {
|
||||||
|
if w.option.RefreshServerIPInterval != 0 && time.Since(w.serverAddrTime.Load()) > time.Second*time.Duration(w.option.RefreshServerIPInterval) {
|
||||||
|
if w.serverAddrMutex.TryLock() {
|
||||||
|
defer w.serverAddrMutex.Unlock()
|
||||||
|
ipcConf, err := w.genIpcConf(ctx, true)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("[WG](%s)UpdateServerAddr failed to generate wireguard ipc conf: %s", w.option.Name, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = w.device.IpcSet(ipcConf)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("[WG](%s)UpdateServerAddr failed to update wireguard ipc conf: %s", w.option.Name, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.serverAddrTime.Store(time.Now())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) genIpcConf(ctx context.Context, updateOnly bool) (string, error) {
|
||||||
|
ipcConf := ""
|
||||||
|
if !updateOnly {
|
||||||
|
ipcConf += "private_key=" + w.option.PrivateKey + "\n"
|
||||||
|
}
|
||||||
|
if len(w.option.Peers) > 0 {
|
||||||
|
for i, peer := range w.option.Peers {
|
||||||
|
peerAddr := peer.Addr()
|
||||||
|
destination, err := w.resolve(ctx, peerAddr)
|
||||||
|
if err != nil {
|
||||||
|
return "", E.Cause(err, "resolve endpoint domain for peer ", i)
|
||||||
|
}
|
||||||
|
if w.serverAddrMap[peerAddr] != destination {
|
||||||
|
w.serverAddrMap[peerAddr] = destination
|
||||||
|
} else if updateOnly {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(w.option.Peers) == 1 { // must call SetConnectAddr if isConnect == true
|
||||||
|
w.bind.SetConnectAddr(destination)
|
||||||
|
}
|
||||||
|
ipcConf += "public_key=" + peer.PublicKey + "\n"
|
||||||
|
if updateOnly {
|
||||||
|
ipcConf += "update_only=true\n"
|
||||||
|
}
|
||||||
|
ipcConf += "endpoint=" + destination.String() + "\n"
|
||||||
|
if len(peer.Reserved) > 0 {
|
||||||
|
var reserved [3]uint8
|
||||||
|
copy(reserved[:], w.option.Reserved)
|
||||||
|
w.bind.SetReservedForEndpoint(destination, reserved)
|
||||||
|
}
|
||||||
|
if updateOnly {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if peer.PreSharedKey != "" {
|
||||||
|
ipcConf += "preshared_key=" + peer.PreSharedKey + "\n"
|
||||||
|
}
|
||||||
|
for _, allowedIP := range peer.AllowedIPs {
|
||||||
|
ipcConf += "allowed_ip=" + allowedIP + "\n"
|
||||||
|
}
|
||||||
|
if w.option.PersistentKeepalive != 0 {
|
||||||
|
ipcConf += fmt.Sprintf("persistent_keepalive_interval=%d\n", w.option.PersistentKeepalive)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
destination, err := w.resolve(ctx, w.connectAddr)
|
||||||
|
if err != nil {
|
||||||
|
return "", E.Cause(err, "resolve endpoint domain")
|
||||||
|
}
|
||||||
|
if w.serverAddrMap[w.connectAddr] != destination {
|
||||||
|
w.serverAddrMap[w.connectAddr] = destination
|
||||||
|
} else if updateOnly {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
w.bind.SetConnectAddr(destination) // must call SetConnectAddr if isConnect == true
|
||||||
|
ipcConf += "public_key=" + w.option.PublicKey + "\n"
|
||||||
|
if updateOnly {
|
||||||
|
ipcConf += "update_only=true\n"
|
||||||
|
}
|
||||||
|
ipcConf += "endpoint=" + destination.String() + "\n"
|
||||||
|
if updateOnly {
|
||||||
|
return ipcConf, nil
|
||||||
|
}
|
||||||
|
if w.option.PreSharedKey != "" {
|
||||||
|
ipcConf += "preshared_key=" + w.option.PreSharedKey + "\n"
|
||||||
|
}
|
||||||
|
var has4, has6 bool
|
||||||
|
for _, address := range w.localPrefixes {
|
||||||
|
if address.Addr().Is4() {
|
||||||
|
has4 = true
|
||||||
|
} else {
|
||||||
|
has6 = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if has4 {
|
||||||
|
ipcConf += "allowed_ip=0.0.0.0/0\n"
|
||||||
|
}
|
||||||
|
if has6 {
|
||||||
|
ipcConf += "allowed_ip=::/0\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
if w.option.PersistentKeepalive != 0 {
|
||||||
|
ipcConf += fmt.Sprintf("persistent_keepalive_interval=%d\n", w.option.PersistentKeepalive)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ipcConf, nil
|
||||||
|
}
|
||||||
|
|
||||||
func closeWireGuard(w *WireGuard) {
|
func closeWireGuard(w *WireGuard) {
|
||||||
if w.device != nil {
|
if w.device != nil {
|
||||||
w.device.Close()
|
w.device.Close()
|
||||||
}
|
}
|
||||||
_ = common.Close(w.tunDevice)
|
_ = common.Close(w.tunDevice)
|
||||||
|
if w.closeCh != nil {
|
||||||
|
close(w.closeCh)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
options := w.Base.DialOptions(opts...)
|
options := w.Base.DialOptions(opts...)
|
||||||
w.dialer.SetDialer(dialer.NewDialer(options...))
|
w.dialer.SetDialer(dialer.NewDialer(options...))
|
||||||
var conn net.Conn
|
var conn net.Conn
|
||||||
w.startOnce.Do(func() {
|
if err = w.init(ctx); err != nil {
|
||||||
w.startErr = w.tunDevice.Start()
|
return nil, err
|
||||||
})
|
|
||||||
if w.startErr != nil {
|
|
||||||
return nil, w.startErr
|
|
||||||
}
|
}
|
||||||
if !metadata.Resolved() || w.resolver != nil {
|
if !metadata.Resolved() || w.resolver != nil {
|
||||||
r := resolver.DefaultResolver
|
r := resolver.DefaultResolver
|
||||||
@@ -358,13 +495,7 @@ func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
|||||||
options := w.Base.DialOptions(opts...)
|
options := w.Base.DialOptions(opts...)
|
||||||
w.dialer.SetDialer(dialer.NewDialer(options...))
|
w.dialer.SetDialer(dialer.NewDialer(options...))
|
||||||
var pc net.PacketConn
|
var pc net.PacketConn
|
||||||
w.startOnce.Do(func() {
|
if err = w.init(ctx); err != nil {
|
||||||
w.startErr = w.tunDevice.Start()
|
|
||||||
})
|
|
||||||
if w.startErr != nil {
|
|
||||||
return nil, w.startErr
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if (!metadata.Resolved() || w.resolver != nil) && metadata.Host != "" {
|
if (!metadata.Resolved() || w.resolver != nil) && metadata.Host != "" {
|
||||||
|
|||||||
44
adapter/outbound/wireguard_test.go
Normal file
44
adapter/outbound/wireguard_test.go
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
//go:build with_gvisor
|
||||||
|
|
||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWireGuardGC(t *testing.T) {
|
||||||
|
option := WireGuardOption{}
|
||||||
|
option.Server = "162.159.192.1"
|
||||||
|
option.Port = 2408
|
||||||
|
option.PrivateKey = "iOx7749AdqH3IqluG7+0YbGKd0m1mcEXAfGRzpy9rG8="
|
||||||
|
option.PublicKey = "bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo="
|
||||||
|
option.Ip = "172.16.0.2"
|
||||||
|
option.Ipv6 = "2606:4700:110:8d29:be92:3a6a:f4:c437"
|
||||||
|
option.Reserved = []uint8{51, 69, 125}
|
||||||
|
wg, err := NewWireGuard(option)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
closeCh := make(chan struct{})
|
||||||
|
wg.closeCh = closeCh
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
||||||
|
defer cancel()
|
||||||
|
err = wg.init(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
// must do a small sleep before test GC
|
||||||
|
// because it maybe deadlocks if w.device.Close call too fast after w.device.Start
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
wg = nil
|
||||||
|
runtime.GC()
|
||||||
|
select {
|
||||||
|
case <-closeCh:
|
||||||
|
return
|
||||||
|
case <-ctx.Done():
|
||||||
|
t.Error("timeout not GC")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -164,6 +164,8 @@ func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
option.ExcludeType,
|
||||||
|
option.TestTimeout,
|
||||||
|
option.MaxFailedTimes,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
|
|||||||
@@ -31,20 +31,24 @@ type GroupBase struct {
|
|||||||
failedTesting atomic.Bool
|
failedTesting atomic.Bool
|
||||||
proxies [][]C.Proxy
|
proxies [][]C.Proxy
|
||||||
versions []atomic.Uint32
|
versions []atomic.Uint32
|
||||||
|
TestTimeout int
|
||||||
|
maxFailedTimes int
|
||||||
}
|
}
|
||||||
|
|
||||||
type GroupBaseOption struct {
|
type GroupBaseOption struct {
|
||||||
outbound.BaseOption
|
outbound.BaseOption
|
||||||
filter string
|
filter string
|
||||||
excludeFilter string
|
excludeFilter string
|
||||||
excludeType string
|
excludeType string
|
||||||
providers []provider.ProxyProvider
|
TestTimeout int
|
||||||
|
maxFailedTimes int
|
||||||
|
providers []provider.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||||
var excludeFilterReg *regexp2.Regexp
|
var excludeFilterReg *regexp2.Regexp
|
||||||
if opt.excludeFilter != "" {
|
if opt.excludeFilter != "" {
|
||||||
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, 0)
|
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, regexp2.None)
|
||||||
}
|
}
|
||||||
var excludeTypeArray []string
|
var excludeTypeArray []string
|
||||||
if opt.excludeType != "" {
|
if opt.excludeType != "" {
|
||||||
@@ -54,7 +58,7 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|||||||
var filterRegs []*regexp2.Regexp
|
var filterRegs []*regexp2.Regexp
|
||||||
if opt.filter != "" {
|
if opt.filter != "" {
|
||||||
for _, filter := range strings.Split(opt.filter, "`") {
|
for _, filter := range strings.Split(opt.filter, "`") {
|
||||||
filterReg := regexp2.MustCompile(filter, 0)
|
filterReg := regexp2.MustCompile(filter, regexp2.None)
|
||||||
filterRegs = append(filterRegs, filterReg)
|
filterRegs = append(filterRegs, filterReg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -66,6 +70,15 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|||||||
excludeTypeArray: excludeTypeArray,
|
excludeTypeArray: excludeTypeArray,
|
||||||
providers: opt.providers,
|
providers: opt.providers,
|
||||||
failedTesting: atomic.NewBool(false),
|
failedTesting: atomic.NewBool(false),
|
||||||
|
TestTimeout: opt.TestTimeout,
|
||||||
|
maxFailedTimes: opt.maxFailedTimes,
|
||||||
|
}
|
||||||
|
|
||||||
|
if gb.TestTimeout == 0 {
|
||||||
|
gb.TestTimeout = 5000
|
||||||
|
}
|
||||||
|
if gb.maxFailedTimes == 0 {
|
||||||
|
gb.maxFailedTimes = 5
|
||||||
}
|
}
|
||||||
|
|
||||||
gb.proxies = make([][]C.Proxy, len(opt.providers))
|
gb.proxies = make([][]C.Proxy, len(opt.providers))
|
||||||
@@ -113,7 +126,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
for _, filterReg := range gb.filterRegs {
|
for _, filterReg := range gb.filterRegs {
|
||||||
for _, p := range proxies {
|
for _, p := range proxies {
|
||||||
name := p.Name()
|
name := p.Name()
|
||||||
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
if mat, _ := filterReg.MatchString(name); mat {
|
||||||
if _, ok := proxiesSet[name]; !ok {
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
proxiesSet[name] = struct{}{}
|
proxiesSet[name] = struct{}{}
|
||||||
newProxies = append(newProxies, p)
|
newProxies = append(newProxies, p)
|
||||||
@@ -137,7 +150,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
for _, filterReg := range gb.filterRegs {
|
for _, filterReg := range gb.filterRegs {
|
||||||
for _, p := range proxies {
|
for _, p := range proxies {
|
||||||
name := p.Name()
|
name := p.Name()
|
||||||
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
if mat, _ := filterReg.MatchString(name); mat {
|
||||||
if _, ok := proxiesSet[name]; !ok {
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
proxiesSet[name] = struct{}{}
|
proxiesSet[name] = struct{}{}
|
||||||
newProxies = append(newProxies, p)
|
newProxies = append(newProxies, p)
|
||||||
@@ -178,7 +191,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
var newProxies []C.Proxy
|
var newProxies []C.Proxy
|
||||||
for _, p := range proxies {
|
for _, p := range proxies {
|
||||||
name := p.Name()
|
name := p.Name()
|
||||||
if mat, _ := gb.excludeFilterReg.FindStringMatch(name); mat != nil {
|
if mat, _ := gb.excludeFilterReg.MatchString(name); mat {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
newProxies = append(newProxies, p)
|
newProxies = append(newProxies, p)
|
||||||
@@ -240,13 +253,13 @@ func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
|||||||
log.Debugln("ProxyGroup: %s first failed", gb.Name())
|
log.Debugln("ProxyGroup: %s first failed", gb.Name())
|
||||||
gb.failedTime = time.Now()
|
gb.failedTime = time.Now()
|
||||||
} else {
|
} else {
|
||||||
if time.Since(gb.failedTime) > gb.failedTimeoutInterval() {
|
if time.Since(gb.failedTime) > time.Duration(gb.TestTimeout)*time.Millisecond {
|
||||||
gb.failedTimes = 0
|
gb.failedTimes = 0
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
||||||
if gb.failedTimes >= gb.maxFailedTimes() {
|
if gb.failedTimes >= gb.maxFailedTimes {
|
||||||
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
||||||
gb.healthCheck()
|
gb.healthCheck()
|
||||||
}
|
}
|
||||||
@@ -275,20 +288,8 @@ func (gb *GroupBase) healthCheck() {
|
|||||||
gb.failedTimes = 0
|
gb.failedTimes = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) failedIntervalTime() int64 {
|
|
||||||
return 5 * time.Second.Milliseconds()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) onDialSuccess() {
|
func (gb *GroupBase) onDialSuccess() {
|
||||||
if !gb.failedTesting.Load() {
|
if !gb.failedTesting.Load() {
|
||||||
gb.failedTimes = 0
|
gb.failedTimes = 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) maxFailedTimes() int {
|
|
||||||
return 5
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) failedTimeoutInterval() time.Duration {
|
|
||||||
return 5 * time.Second
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -266,6 +266,8 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
option.ExcludeType,
|
||||||
|
option.TestTimeout,
|
||||||
|
option.MaxFailedTimes,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter/outbound"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/metacubex/mihomo/adapter/provider"
|
"github.com/metacubex/mihomo/adapter/provider"
|
||||||
"github.com/metacubex/mihomo/common/structure"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
@@ -29,6 +31,7 @@ type GroupCommonOption struct {
|
|||||||
URL string `group:"url,omitempty"`
|
URL string `group:"url,omitempty"`
|
||||||
Interval int `group:"interval,omitempty"`
|
Interval int `group:"interval,omitempty"`
|
||||||
TestTimeout int `group:"timeout,omitempty"`
|
TestTimeout int `group:"timeout,omitempty"`
|
||||||
|
MaxFailedTimes int `group:"max-failed-times,omitempty"`
|
||||||
Lazy bool `group:"lazy,omitempty"`
|
Lazy bool `group:"lazy,omitempty"`
|
||||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
Filter string `group:"filter,omitempty"`
|
Filter string `group:"filter,omitempty"`
|
||||||
@@ -64,20 +67,30 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
groupOption.IncludeAllProviders = true
|
groupOption.IncludeAllProviders = true
|
||||||
groupOption.IncludeAllProxies = true
|
groupOption.IncludeAllProxies = true
|
||||||
}
|
}
|
||||||
var GroupUse []string
|
|
||||||
var GroupProxies []string
|
|
||||||
if groupOption.IncludeAllProviders {
|
if groupOption.IncludeAllProviders {
|
||||||
GroupUse = append(GroupUse, AllProviders...)
|
groupOption.Use = append(groupOption.Use, AllProviders...)
|
||||||
} else {
|
|
||||||
GroupUse = groupOption.Use
|
|
||||||
}
|
}
|
||||||
if groupOption.IncludeAllProxies {
|
if groupOption.IncludeAllProxies {
|
||||||
GroupProxies = append(groupOption.Proxies, AllProxies...)
|
if groupOption.Filter != "" {
|
||||||
} else {
|
var filterRegs []*regexp2.Regexp
|
||||||
GroupProxies = groupOption.Proxies
|
for _, filter := range strings.Split(groupOption.Filter, "`") {
|
||||||
|
filterReg := regexp2.MustCompile(filter, regexp2.None)
|
||||||
|
filterRegs = append(filterRegs, filterReg)
|
||||||
|
}
|
||||||
|
for _, p := range AllProxies {
|
||||||
|
for _, filterReg := range filterRegs {
|
||||||
|
if mat, _ := filterReg.MatchString(p); mat {
|
||||||
|
groupOption.Proxies = append(groupOption.Proxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
groupOption.Proxies = append(groupOption.Proxies, AllProxies...)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(GroupProxies) == 0 && len(GroupUse) == 0 {
|
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, errMissProxy)
|
return nil, fmt.Errorf("%s: %w", groupName, errMissProxy)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,17 +104,32 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
status = "*"
|
status = "*"
|
||||||
}
|
}
|
||||||
groupOption.ExpectedStatus = status
|
groupOption.ExpectedStatus = status
|
||||||
testUrl := groupOption.URL
|
|
||||||
|
|
||||||
if groupOption.Type != "select" && groupOption.Type != "relay" {
|
if len(groupOption.Use) != 0 {
|
||||||
if groupOption.URL == "" {
|
PDs, err := getProviders(providersMap, groupOption.Use)
|
||||||
groupOption.URL = C.DefaultTestURL
|
if err != nil {
|
||||||
testUrl = groupOption.URL
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// if test URL is empty, use the first health check URL of providers
|
||||||
|
if groupOption.URL == "" {
|
||||||
|
for _, pd := range PDs {
|
||||||
|
if pd.HealthCheckURL() != "" {
|
||||||
|
groupOption.URL = pd.HealthCheckURL()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if groupOption.URL == "" {
|
||||||
|
groupOption.URL = C.DefaultTestURL
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
addTestUrlToProviders(PDs, groupOption.URL, expectedStatus, groupOption.Filter, uint(groupOption.Interval))
|
||||||
|
}
|
||||||
|
providers = append(providers, PDs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(GroupProxies) != 0 {
|
if len(groupOption.Proxies) != 0 {
|
||||||
ps, err := getProxies(proxyMap, GroupProxies)
|
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
@@ -110,38 +138,28 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
return nil, fmt.Errorf("%s: %w", groupName, errDuplicateProvider)
|
return nil, fmt.Errorf("%s: %w", groupName, errDuplicateProvider)
|
||||||
}
|
}
|
||||||
|
|
||||||
// select don't need health check
|
if groupOption.URL == "" {
|
||||||
|
groupOption.URL = C.DefaultTestURL
|
||||||
|
}
|
||||||
|
|
||||||
|
// select don't need auto health check
|
||||||
if groupOption.Type != "select" && groupOption.Type != "relay" {
|
if groupOption.Type != "select" && groupOption.Type != "relay" {
|
||||||
if groupOption.Interval == 0 {
|
if groupOption.Interval == 0 {
|
||||||
groupOption.Interval = 300
|
groupOption.Interval = 300
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
hc := provider.NewHealthCheck(ps, testUrl, uint(groupOption.TestTimeout), uint(groupOption.Interval), groupOption.Lazy, expectedStatus)
|
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.TestTimeout), uint(groupOption.Interval), groupOption.Lazy, expectedStatus)
|
||||||
|
|
||||||
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
providers = append(providers, pd)
|
providers = append([]types.ProxyProvider{pd}, providers...)
|
||||||
providersMap[groupName] = pd
|
providersMap[groupName] = pd
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(GroupUse) != 0 {
|
|
||||||
list, err := getProviders(providersMap, GroupUse)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// different proxy groups use different test URL
|
|
||||||
addTestUrlToProviders(list, testUrl, expectedStatus, groupOption.Filter, uint(groupOption.Interval))
|
|
||||||
|
|
||||||
providers = append(providers, list...)
|
|
||||||
} else {
|
|
||||||
groupOption.Filter = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
var group C.ProxyAdapter
|
var group C.ProxyAdapter
|
||||||
switch groupOption.Type {
|
switch groupOption.Type {
|
||||||
case "url-test":
|
case "url-test":
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
"github.com/metacubex/mihomo/constant/provider"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Relay struct {
|
type Relay struct {
|
||||||
@@ -149,6 +150,7 @@ func (r *Relay) Addr() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
||||||
|
log.Warnln("The group [%s] with relay type is deprecated, please using dialer-proxy instead", option.Name)
|
||||||
return &Relay{
|
return &Relay{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
outbound.BaseOption{
|
outbound.BaseOption{
|
||||||
@@ -160,6 +162,8 @@ func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Re
|
|||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
|
5000,
|
||||||
|
5,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
Hidden: option.Hidden,
|
Hidden: option.Hidden,
|
||||||
|
|||||||
@@ -114,6 +114,8 @@ func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
option.ExcludeType,
|
||||||
|
option.TestTimeout,
|
||||||
|
option.MaxFailedTimes,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
selected: "COMPATIBLE",
|
selected: "COMPATIBLE",
|
||||||
|
|||||||
@@ -235,6 +235,8 @@ func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, o
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
option.ExcludeType,
|
||||||
|
option.TestTimeout,
|
||||||
|
option.MaxFailedTimes,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
|
|||||||
@@ -120,6 +120,13 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy = outbound.NewDirectWithOption(*directOption)
|
proxy = outbound.NewDirectWithOption(*directOption)
|
||||||
|
case "dns":
|
||||||
|
dnsOptions := &outbound.DnsOption{}
|
||||||
|
err = decoder.Decode(mapping, dnsOptions)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = outbound.NewDnsWithOption(*dnsOptions)
|
||||||
case "reject":
|
case "reject":
|
||||||
rejectOption := &outbound.RejectOption{}
|
rejectOption := &outbound.RejectOption{}
|
||||||
err = decoder.Decode(mapping, rejectOption)
|
err = decoder.Decode(mapping, rejectOption)
|
||||||
@@ -127,6 +134,13 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy = outbound.NewRejectWithOption(*rejectOption)
|
proxy = outbound.NewRejectWithOption(*rejectOption)
|
||||||
|
case "ssh":
|
||||||
|
sshOption := &outbound.SshOption{}
|
||||||
|
err = decoder.Decode(mapping, sshOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewSsh(*sshOption)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -181,14 +181,14 @@ func (hc *HealthCheck) execute(b *batch.Batch[bool], url, uid string, option *ex
|
|||||||
filters = append(filters, filter)
|
filters = append(filters, filter)
|
||||||
}
|
}
|
||||||
|
|
||||||
filterReg = regexp2.MustCompile(strings.Join(filters, "|"), 0)
|
filterReg = regexp2.MustCompile(strings.Join(filters, "|"), regexp2.None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, proxy := range hc.proxies {
|
for _, proxy := range hc.proxies {
|
||||||
// skip proxies that do not require health check
|
// skip proxies that do not require health check
|
||||||
if filterReg != nil {
|
if filterReg != nil {
|
||||||
if match, _ := filterReg.FindStringMatch(proxy.Name()); match == nil {
|
if match, _ := filterReg.MatchString(proxy.Name()); !match {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -211,8 +211,8 @@ func (hc *HealthCheck) close() {
|
|||||||
|
|
||||||
func NewHealthCheck(proxies []C.Proxy, url string, timeout uint, interval uint, lazy bool, expectedStatus utils.IntRanges[uint16]) *HealthCheck {
|
func NewHealthCheck(proxies []C.Proxy, url string, timeout uint, interval uint, lazy bool, expectedStatus utils.IntRanges[uint16]) *HealthCheck {
|
||||||
if url == "" {
|
if url == "" {
|
||||||
// expectedStatus = nil
|
expectedStatus = nil
|
||||||
url = C.DefaultTestURL
|
interval = 0
|
||||||
}
|
}
|
||||||
if timeout == 0 {
|
if timeout == 0 {
|
||||||
timeout = 5000
|
timeout = 5000
|
||||||
|
|||||||
@@ -28,28 +28,35 @@ type healthCheckSchema struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type OverrideSchema struct {
|
type OverrideSchema struct {
|
||||||
UDP *bool `provider:"udp,omitempty"`
|
TFO *bool `provider:"tfo,omitempty"`
|
||||||
Up *string `provider:"up,omitempty"`
|
MPTcp *bool `provider:"mptcp,omitempty"`
|
||||||
Down *string `provider:"down,omitempty"`
|
UDP *bool `provider:"udp,omitempty"`
|
||||||
DialerProxy *string `provider:"dialer-proxy,omitempty"`
|
UDPOverTCP *bool `provider:"udp-over-tcp,omitempty"`
|
||||||
SkipCertVerify *bool `provider:"skip-cert-verify,omitempty"`
|
Up *string `provider:"up,omitempty"`
|
||||||
Interface *string `provider:"interface-name,omitempty"`
|
Down *string `provider:"down,omitempty"`
|
||||||
RoutingMark *int `provider:"routing-mark,omitempty"`
|
DialerProxy *string `provider:"dialer-proxy,omitempty"`
|
||||||
IPVersion *string `provider:"ip-version,omitempty"`
|
SkipCertVerify *bool `provider:"skip-cert-verify,omitempty"`
|
||||||
|
Interface *string `provider:"interface-name,omitempty"`
|
||||||
|
RoutingMark *int `provider:"routing-mark,omitempty"`
|
||||||
|
IPVersion *string `provider:"ip-version,omitempty"`
|
||||||
|
AdditionalPrefix *string `provider:"additional-prefix,omitempty"`
|
||||||
|
AdditionalSuffix *string `provider:"additional-suffix,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type proxyProviderSchema struct {
|
type proxyProviderSchema struct {
|
||||||
Type string `provider:"type"`
|
Type string `provider:"type"`
|
||||||
Path string `provider:"path,omitempty"`
|
Path string `provider:"path,omitempty"`
|
||||||
URL string `provider:"url,omitempty"`
|
URL string `provider:"url,omitempty"`
|
||||||
|
Proxy string `provider:"proxy,omitempty"`
|
||||||
Interval int `provider:"interval,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
||||||
ExcludeType string `provider:"exclude-type,omitempty"`
|
ExcludeType string `provider:"exclude-type,omitempty"`
|
||||||
DialerProxy string `provider:"dialer-proxy,omitempty"`
|
DialerProxy string `provider:"dialer-proxy,omitempty"`
|
||||||
|
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
Override OverrideSchema `provider:"override,omitempty"`
|
Override OverrideSchema `provider:"override,omitempty"`
|
||||||
|
Header map[string][]string `provider:"header,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
||||||
@@ -84,16 +91,14 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
path := C.Path.Resolve(schema.Path)
|
path := C.Path.Resolve(schema.Path)
|
||||||
vehicle = resource.NewFileVehicle(path)
|
vehicle = resource.NewFileVehicle(path)
|
||||||
case "http":
|
case "http":
|
||||||
|
path := C.Path.GetPathByHash("proxies", schema.URL)
|
||||||
if schema.Path != "" {
|
if schema.Path != "" {
|
||||||
path := C.Path.Resolve(schema.Path)
|
path = C.Path.Resolve(schema.Path)
|
||||||
if !features.CMFA && !C.Path.IsSafePath(path) {
|
if !features.CMFA && !C.Path.IsSafePath(path) {
|
||||||
return nil, fmt.Errorf("%w: %s", errSubPath, path)
|
return nil, fmt.Errorf("%w: %s", errSubPath, path)
|
||||||
}
|
}
|
||||||
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
|
||||||
} else {
|
|
||||||
path := C.Path.GetPathByHash("proxies", schema.URL)
|
|
||||||
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
|
||||||
}
|
}
|
||||||
|
vehicle = resource.NewHTTPVehicle(schema.URL, path, schema.Proxy, schema.Header)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"reflect"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -46,18 +47,13 @@ type proxySetProvider struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
expectedStatus := "*"
|
|
||||||
if pp.healthCheck.expectedStatus != nil {
|
|
||||||
expectedStatus = pp.healthCheck.expectedStatus.ToString()
|
|
||||||
}
|
|
||||||
|
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"name": pp.Name(),
|
"name": pp.Name(),
|
||||||
"type": pp.Type().String(),
|
"type": pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
"proxies": pp.Proxies(),
|
||||||
"testUrl": pp.healthCheck.url,
|
"testUrl": pp.healthCheck.url,
|
||||||
"expectedStatus": expectedStatus,
|
"expectedStatus": pp.healthCheck.expectedStatus.String(),
|
||||||
"updatedAt": pp.UpdatedAt,
|
"updatedAt": pp.UpdatedAt,
|
||||||
"subscriptionInfo": pp.subscriptionInfo,
|
"subscriptionInfo": pp.subscriptionInfo,
|
||||||
})
|
})
|
||||||
@@ -106,6 +102,10 @@ func (pp *proxySetProvider) Touch() {
|
|||||||
pp.healthCheck.touch()
|
pp.healthCheck.touch()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) HealthCheckURL() string {
|
||||||
|
return pp.healthCheck.url
|
||||||
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
func (pp *proxySetProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||||
pp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
pp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
||||||
}
|
}
|
||||||
@@ -125,8 +125,8 @@ func (pp *proxySetProvider) getSubscriptionInfo() {
|
|||||||
go func() {
|
go func() {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
resp, err := mihomoHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
resp, err := mihomoHttp.HttpRequestWithProxy(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
||||||
http.MethodGet, http.Header{"User-Agent": {C.UA}}, nil)
|
http.MethodGet, http.Header{"User-Agent": {C.UA}}, nil, pp.Vehicle().Proxy())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -134,8 +134,8 @@ func (pp *proxySetProvider) getSubscriptionInfo() {
|
|||||||
|
|
||||||
userInfoStr := strings.TrimSpace(resp.Header.Get("subscription-userinfo"))
|
userInfoStr := strings.TrimSpace(resp.Header.Get("subscription-userinfo"))
|
||||||
if userInfoStr == "" {
|
if userInfoStr == "" {
|
||||||
resp2, err := mihomoHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
resp2, err := mihomoHttp.HttpRequestWithProxy(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
||||||
http.MethodGet, http.Header{"User-Agent": {"Quantumultx"}}, nil)
|
http.MethodGet, http.Header{"User-Agent": {"Quantumultx"}}, nil, pp.Vehicle().Proxy())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -170,7 +170,7 @@ func stopProxyProvider(pd *ProxySetProvider) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, excludeType string, dialerProxy string, override OverrideSchema, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, excludeType string, dialerProxy string, override OverrideSchema, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
excludeFilterReg, err := regexp2.Compile(excludeFilter, regexp2.None)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
||||||
}
|
}
|
||||||
@@ -181,7 +181,7 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, exc
|
|||||||
|
|
||||||
var filterRegs []*regexp2.Regexp
|
var filterRegs []*regexp2.Regexp
|
||||||
for _, filter := range strings.Split(filter, "`") {
|
for _, filter := range strings.Split(filter, "`") {
|
||||||
filterReg, err := regexp2.Compile(filter, 0)
|
filterReg, err := regexp2.Compile(filter, regexp2.None)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
}
|
}
|
||||||
@@ -217,18 +217,13 @@ type compatibleProvider struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
expectedStatus := "*"
|
|
||||||
if cp.healthCheck.expectedStatus != nil {
|
|
||||||
expectedStatus = cp.healthCheck.expectedStatus.ToString()
|
|
||||||
}
|
|
||||||
|
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"name": cp.Name(),
|
"name": cp.Name(),
|
||||||
"type": cp.Type().String(),
|
"type": cp.Type().String(),
|
||||||
"vehicleType": cp.VehicleType().String(),
|
"vehicleType": cp.VehicleType().String(),
|
||||||
"proxies": cp.Proxies(),
|
"proxies": cp.Proxies(),
|
||||||
"testUrl": cp.healthCheck.url,
|
"testUrl": cp.healthCheck.url,
|
||||||
"expectedStatus": expectedStatus,
|
"expectedStatus": cp.healthCheck.expectedStatus.String(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -271,6 +266,10 @@ func (cp *compatibleProvider) Touch() {
|
|||||||
cp.healthCheck.touch()
|
cp.healthCheck.touch()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) HealthCheckURL() string {
|
||||||
|
return cp.healthCheck.url
|
||||||
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
func (cp *compatibleProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||||
cp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
cp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
||||||
}
|
}
|
||||||
@@ -358,12 +357,12 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if len(excludeFilter) > 0 {
|
if len(excludeFilter) > 0 {
|
||||||
if mat, _ := excludeFilterReg.FindStringMatch(name); mat != nil {
|
if mat, _ := excludeFilterReg.MatchString(name); mat {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(filter) > 0 {
|
if len(filter) > 0 {
|
||||||
if mat, _ := filterReg.FindStringMatch(name); mat == nil {
|
if mat, _ := filterReg.MatchString(name); !mat {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -375,29 +374,23 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
|||||||
mapping["dialer-proxy"] = dialerProxy
|
mapping["dialer-proxy"] = dialerProxy
|
||||||
}
|
}
|
||||||
|
|
||||||
if override.UDP != nil {
|
val := reflect.ValueOf(override)
|
||||||
mapping["udp"] = *override.UDP
|
for i := 0; i < val.NumField(); i++ {
|
||||||
}
|
field := val.Field(i)
|
||||||
if override.Up != nil {
|
if field.IsNil() {
|
||||||
mapping["up"] = *override.Up
|
continue
|
||||||
}
|
}
|
||||||
if override.Down != nil {
|
fieldName := strings.Split(val.Type().Field(i).Tag.Get("provider"), ",")[0]
|
||||||
mapping["down"] = *override.Down
|
switch fieldName {
|
||||||
}
|
case "additional-prefix":
|
||||||
if override.DialerProxy != nil {
|
name := mapping["name"].(string)
|
||||||
mapping["dialer-proxy"] = *override.DialerProxy
|
mapping["name"] = *field.Interface().(*string) + name
|
||||||
}
|
case "additional-suffix":
|
||||||
if override.SkipCertVerify != nil {
|
name := mapping["name"].(string)
|
||||||
mapping["skip-cert-verify"] = *override.SkipCertVerify
|
mapping["name"] = name + *field.Interface().(*string)
|
||||||
}
|
default:
|
||||||
if override.Interface != nil {
|
mapping[fieldName] = field.Elem().Interface()
|
||||||
mapping["interface-name"] = *override.Interface
|
}
|
||||||
}
|
|
||||||
if override.RoutingMark != nil {
|
|
||||||
mapping["routing-mark"] = *override.RoutingMark
|
|
||||||
}
|
|
||||||
if override.IPVersion != nil {
|
|
||||||
mapping["ip-version"] = *override.IPVersion
|
|
||||||
}
|
}
|
||||||
|
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
|
|||||||
21
android_tz.go
Normal file
21
android_tz.go
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
// Copyright 2014 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// kanged from https://github.com/golang/mobile/blob/c713f31d574bb632a93f169b2cc99c9e753fef0e/app/android.go#L89
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
// #include <time.h>
|
||||||
|
import "C"
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
var currentT C.time_t
|
||||||
|
var currentTM C.struct_tm
|
||||||
|
C.time(¤tT)
|
||||||
|
C.localtime_r(¤tT, ¤tTM)
|
||||||
|
tzOffset := int(currentTM.tm_gmtoff)
|
||||||
|
tz := C.GoString(currentTM.tm_zone)
|
||||||
|
time.Local = time.FixedZone(tz, tzOffset)
|
||||||
|
}
|
||||||
@@ -15,28 +15,39 @@ type TypedValue[T any] struct {
|
|||||||
value atomic.Value
|
value atomic.Value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// tValue is a struct with determined type to resolve atomic.Value usages with interface types
|
||||||
|
// https://github.com/golang/go/issues/22550
|
||||||
|
//
|
||||||
|
// The intention to have an atomic value store for errors. However, running this code panics:
|
||||||
|
// panic: sync/atomic: store of inconsistently typed value into Value
|
||||||
|
// This is because atomic.Value requires that the underlying concrete type be the same (which is a reasonable expectation for its implementation).
|
||||||
|
// When going through the atomic.Value.Store method call, the fact that both these are of the error interface is lost.
|
||||||
|
type tValue[T any] struct {
|
||||||
|
value T
|
||||||
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) Load() T {
|
func (t *TypedValue[T]) Load() T {
|
||||||
value := t.value.Load()
|
value := t.value.Load()
|
||||||
if value == nil {
|
if value == nil {
|
||||||
return DefaultValue[T]()
|
return DefaultValue[T]()
|
||||||
}
|
}
|
||||||
return value.(T)
|
return value.(tValue[T]).value
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) Store(value T) {
|
func (t *TypedValue[T]) Store(value T) {
|
||||||
t.value.Store(value)
|
t.value.Store(tValue[T]{value})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) Swap(new T) T {
|
func (t *TypedValue[T]) Swap(new T) T {
|
||||||
old := t.value.Swap(new)
|
old := t.value.Swap(tValue[T]{new})
|
||||||
if old == nil {
|
if old == nil {
|
||||||
return DefaultValue[T]()
|
return DefaultValue[T]()
|
||||||
}
|
}
|
||||||
return old.(T)
|
return old.(tValue[T]).value
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) CompareAndSwap(old, new T) bool {
|
func (t *TypedValue[T]) CompareAndSwap(old, new T) bool {
|
||||||
return t.value.CompareAndSwap(old, new)
|
return t.value.CompareAndSwap(tValue[T]{old}, tValue[T]{new})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) MarshalJSON() ([]byte, error) {
|
func (t *TypedValue[T]) MarshalJSON() ([]byte, error) {
|
||||||
|
|||||||
@@ -330,15 +330,38 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
|
|
||||||
vmess["h2-opts"] = h2Opts
|
vmess["h2-opts"] = h2Opts
|
||||||
|
|
||||||
case "ws":
|
case "ws", "httpupgrade":
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
wsOpts := make(map[string]any)
|
wsOpts := make(map[string]any)
|
||||||
wsOpts["path"] = []string{"/"}
|
wsOpts["path"] = "/"
|
||||||
if host, ok := values["host"]; ok && host != "" {
|
if host, ok := values["host"]; ok && host != "" {
|
||||||
headers["Host"] = host.(string)
|
headers["Host"] = host.(string)
|
||||||
}
|
}
|
||||||
if path, ok := values["path"]; ok && path != "" {
|
if path, ok := values["path"]; ok && path != "" {
|
||||||
wsOpts["path"] = path.(string)
|
path := path.(string)
|
||||||
|
pathURL, err := url.Parse(path)
|
||||||
|
if err == nil {
|
||||||
|
query := pathURL.Query()
|
||||||
|
if earlyData := query.Get("ed"); earlyData != "" {
|
||||||
|
med, err := strconv.Atoi(earlyData)
|
||||||
|
if err == nil {
|
||||||
|
switch network {
|
||||||
|
case "ws":
|
||||||
|
wsOpts["max-early-data"] = med
|
||||||
|
wsOpts["early-data-header-name"] = "Sec-WebSocket-Protocol"
|
||||||
|
case "httpupgrade":
|
||||||
|
wsOpts["v2ray-http-upgrade-fast-open"] = true
|
||||||
|
}
|
||||||
|
query.Del("ed")
|
||||||
|
pathURL.RawQuery = query.Encode()
|
||||||
|
path = pathURL.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
||||||
|
wsOpts["early-data-header-name"] = earlyDataHeader
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wsOpts["path"] = path
|
||||||
}
|
}
|
||||||
wsOpts["headers"] = headers
|
wsOpts["headers"] = headers
|
||||||
vmess["ws-opts"] = wsOpts
|
vmess["ws-opts"] = wsOpts
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ import (
|
|||||||
|
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
|
||||||
|
"github.com/metacubex/randv2"
|
||||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var hostsSuffix = []string{
|
var hostsSuffix = []string{
|
||||||
@@ -302,11 +302,11 @@ func RandHost() string {
|
|||||||
prefix += string(buf[6:8]) + "-"
|
prefix += string(buf[6:8]) + "-"
|
||||||
prefix += string(buf[len(buf)-8:])
|
prefix += string(buf[len(buf)-8:])
|
||||||
|
|
||||||
return prefix + hostsSuffix[fastrand.Intn(hostsLen)]
|
return prefix + hostsSuffix[randv2.IntN(hostsLen)]
|
||||||
}
|
}
|
||||||
|
|
||||||
func RandUserAgent() string {
|
func RandUserAgent() string {
|
||||||
return userAgents[fastrand.Intn(uaLen)]
|
return userAgents[randv2.IntN(uaLen)]
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetUserAgent(header http.Header) {
|
func SetUserAgent(header http.Header) {
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
h2Opts["headers"] = headers
|
h2Opts["headers"] = headers
|
||||||
proxy["h2-opts"] = h2Opts
|
proxy["h2-opts"] = h2Opts
|
||||||
|
|
||||||
case "ws":
|
case "ws", "httpupgrade":
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
wsOpts := make(map[string]any)
|
wsOpts := make(map[string]any)
|
||||||
headers["User-Agent"] = RandUserAgent()
|
headers["User-Agent"] = RandUserAgent()
|
||||||
@@ -113,7 +113,13 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("bad WebSocket max early data size: %v", err)
|
return fmt.Errorf("bad WebSocket max early data size: %v", err)
|
||||||
}
|
}
|
||||||
wsOpts["max-early-data"] = med
|
switch network {
|
||||||
|
case "ws":
|
||||||
|
wsOpts["max-early-data"] = med
|
||||||
|
wsOpts["early-data-header-name"] = "Sec-WebSocket-Protocol"
|
||||||
|
case "httpupgrade":
|
||||||
|
wsOpts["v2ray-http-upgrade-fast-open"] = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
||||||
wsOpts["early-data-header-name"] = earlyDataHeader
|
wsOpts["early-data-header-name"] = earlyDataHeader
|
||||||
|
|||||||
@@ -26,6 +26,11 @@ type Conn struct {
|
|||||||
resultCh chan *connReadResult
|
resultCh chan *connReadResult
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func IsConn(conn any) bool {
|
||||||
|
_, ok := conn.(*Conn)
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
func NewConn(conn net.Conn) *Conn {
|
func NewConn(conn net.Conn) *Conn {
|
||||||
c := &Conn{
|
c := &Conn{
|
||||||
ExtendedConn: bufio.NewExtendedConn(conn),
|
ExtendedConn: bufio.NewExtendedConn(conn),
|
||||||
|
|||||||
@@ -215,3 +215,8 @@ func (p *pipe) waitReadBuffer() (buffer *buf.Buffer, err error) {
|
|||||||
return nil, os.ErrDeadlineExceeded
|
return nil, os.ErrDeadlineExceeded
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func IsPipe(conn any) bool {
|
||||||
|
_, ok := conn.(*pipe)
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,10 +3,9 @@ package net
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
|
||||||
"unsafe"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/buf"
|
"github.com/metacubex/mihomo/common/buf"
|
||||||
|
"github.com/metacubex/mihomo/common/once"
|
||||||
)
|
)
|
||||||
|
|
||||||
type earlyConn struct {
|
type earlyConn struct {
|
||||||
@@ -44,8 +43,7 @@ func (conn *earlyConn) Upstream() any {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (conn *earlyConn) Success() bool {
|
func (conn *earlyConn) Success() bool {
|
||||||
// atomic visit sync.Once.done
|
return once.Done(&conn.resOnce) && conn.resErr == nil
|
||||||
return atomic.LoadUint32((*uint32)(unsafe.Pointer(&conn.resOnce))) == 1 && conn.resErr == nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (conn *earlyConn) ReaderReplaceable() bool {
|
func (conn *earlyConn) ReaderReplaceable() bool {
|
||||||
|
|||||||
@@ -23,6 +23,12 @@ type ExtendedReader = network.ExtendedReader
|
|||||||
var WriteBuffer = bufio.WriteBuffer
|
var WriteBuffer = bufio.WriteBuffer
|
||||||
|
|
||||||
func NewDeadlineConn(conn net.Conn) ExtendedConn {
|
func NewDeadlineConn(conn net.Conn) ExtendedConn {
|
||||||
|
if deadline.IsPipe(conn) || deadline.IsPipe(network.UnwrapReader(conn)) {
|
||||||
|
return NewExtendedConn(conn) // pipe always have correctly deadline implement
|
||||||
|
}
|
||||||
|
if deadline.IsConn(conn) || deadline.IsConn(network.UnwrapReader(conn)) {
|
||||||
|
return NewExtendedConn(conn) // was a *deadline.Conn
|
||||||
|
}
|
||||||
return deadline.NewConn(conn)
|
return deadline.NewConn(conn)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
26
common/once/once_go120.go
Normal file
26
common/once/once_go120.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
//go:build !go1.22
|
||||||
|
|
||||||
|
package once
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Once struct {
|
||||||
|
done uint32
|
||||||
|
m sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func Done(once *sync.Once) bool {
|
||||||
|
// atomic visit sync.Once.done
|
||||||
|
return atomic.LoadUint32((*uint32)(unsafe.Pointer(once))) == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func Reset(once *sync.Once) {
|
||||||
|
o := (*Once)(unsafe.Pointer(once))
|
||||||
|
o.m.Lock()
|
||||||
|
defer o.m.Unlock()
|
||||||
|
atomic.StoreUint32(&o.done, 0)
|
||||||
|
}
|
||||||
26
common/once/once_go122.go
Normal file
26
common/once/once_go122.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
//go:build go1.22
|
||||||
|
|
||||||
|
package once
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Once struct {
|
||||||
|
done atomic.Uint32
|
||||||
|
m sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func Done(once *sync.Once) bool {
|
||||||
|
// atomic visit sync.Once.done
|
||||||
|
return (*atomic.Uint32)(unsafe.Pointer(once)).Load() == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func Reset(once *sync.Once) {
|
||||||
|
o := (*Once)(unsafe.Pointer(once))
|
||||||
|
o.m.Lock()
|
||||||
|
defer o.m.Unlock()
|
||||||
|
o.done.Store(0)
|
||||||
|
}
|
||||||
@@ -3,8 +3,8 @@ package pool
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/metacubex/randv2"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAllocGet(t *testing.T) {
|
func TestAllocGet(t *testing.T) {
|
||||||
@@ -43,6 +43,6 @@ func TestAllocPutThenGet(t *testing.T) {
|
|||||||
|
|
||||||
func BenchmarkMSB(b *testing.B) {
|
func BenchmarkMSB(b *testing.B) {
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
msb(fastrand.Int())
|
msb(randv2.Int())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
50
common/utils/callback.go
Normal file
50
common/utils/callback.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
list "github.com/bahlo/generic-list-go"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Callback[T any] struct {
|
||||||
|
list list.List[func(T)]
|
||||||
|
mutex sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCallback[T any]() *Callback[T] {
|
||||||
|
return &Callback[T]{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Callback[T]) Register(item func(T)) io.Closer {
|
||||||
|
c.mutex.RLock()
|
||||||
|
defer c.mutex.RUnlock()
|
||||||
|
element := c.list.PushBack(item)
|
||||||
|
return &callbackCloser[T]{
|
||||||
|
element: element,
|
||||||
|
callback: c,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Callback[T]) Emit(item T) {
|
||||||
|
c.mutex.RLock()
|
||||||
|
defer c.mutex.RUnlock()
|
||||||
|
for element := c.list.Front(); element != nil; element = element.Next() {
|
||||||
|
go element.Value(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type callbackCloser[T any] struct {
|
||||||
|
element *list.Element[func(T)]
|
||||||
|
callback *Callback[T]
|
||||||
|
once sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *callbackCloser[T]) Close() error {
|
||||||
|
c.once.Do(func() {
|
||||||
|
c.callback.mutex.Lock()
|
||||||
|
defer c.callback.mutex.Unlock()
|
||||||
|
c.callback.list.Remove(c.element)
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -20,6 +20,8 @@ func newIntRanges[T constraints.Integer](expected string, parseFn func(string) (
|
|||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// support: 200,302 or 200,204,401-429,501-503
|
||||||
|
expected = strings.ReplaceAll(expected, ",", "/")
|
||||||
list := strings.Split(expected, "/")
|
list := strings.Split(expected, "/")
|
||||||
if len(list) > 28 {
|
if len(list) > 28 {
|
||||||
return nil, fmt.Errorf("%w, too many ranges to use, maximum support 28 ranges", errIntRanges)
|
return nil, fmt.Errorf("%w, too many ranges to use, maximum support 28 ranges", errIntRanges)
|
||||||
@@ -47,9 +49,9 @@ func newIntRangesFromList[T constraints.Integer](list []string, parseFn func(str
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch statusLen {
|
switch statusLen {
|
||||||
case 1:
|
case 1: // Port range
|
||||||
ranges = append(ranges, NewRange(T(start), T(start)))
|
ranges = append(ranges, NewRange(T(start), T(start)))
|
||||||
case 2:
|
case 2: // Single port
|
||||||
end, err := parseFn(strings.Trim(status[1], "[ ]"))
|
end, err := parseFn(strings.Trim(status[1], "[ ]"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errIntRanges
|
return nil, errIntRanges
|
||||||
@@ -108,7 +110,7 @@ func (ranges IntRanges[T]) Check(status T) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ranges IntRanges[T]) ToString() string {
|
func (ranges IntRanges[T]) String() string {
|
||||||
if len(ranges) == 0 {
|
if len(ranges) == 0 {
|
||||||
return "*"
|
return "*"
|
||||||
}
|
}
|
||||||
@@ -130,3 +132,17 @@ func (ranges IntRanges[T]) ToString() string {
|
|||||||
|
|
||||||
return strings.Join(terms, "/")
|
return strings.Join(terms, "/")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ranges IntRanges[T]) Range(f func(t T) bool) {
|
||||||
|
if len(ranges) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, r := range ranges {
|
||||||
|
for i := r.Start(); i <= r.End(); i++ {
|
||||||
|
if !f(i) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,19 +2,39 @@ package utils
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gofrs/uuid/v5"
|
"github.com/gofrs/uuid/v5"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
"github.com/metacubex/randv2"
|
||||||
)
|
)
|
||||||
|
|
||||||
type fastRandReader struct{}
|
type unsafeRandReader struct{}
|
||||||
|
|
||||||
func (r fastRandReader) Read(p []byte) (int, error) {
|
func (r unsafeRandReader) Read(p []byte) (n int, err error) {
|
||||||
return fastrand.Read(p)
|
// modify from https://github.com/golang/go/blob/587c3847da81aa7cfc3b3db2677c8586c94df13a/src/runtime/rand.go#L70-L89
|
||||||
|
// Inspired by wyrand.
|
||||||
|
n = len(p)
|
||||||
|
v := randv2.Uint64()
|
||||||
|
for len(p) > 0 {
|
||||||
|
v ^= 0xa0761d6478bd642f
|
||||||
|
v *= 0xe7037ed1a0b428db
|
||||||
|
size := 8
|
||||||
|
if len(p) < 8 {
|
||||||
|
size = len(p)
|
||||||
|
}
|
||||||
|
for i := 0; i < size; i++ {
|
||||||
|
p[i] ^= byte(v >> (8 * i))
|
||||||
|
}
|
||||||
|
p = p[size:]
|
||||||
|
v = v>>32 | v<<32
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var UnsafeUUIDGenerator = uuid.NewGenWithOptions(uuid.WithRandomReader(fastRandReader{}))
|
var UnsafeRandReader = unsafeRandReader{}
|
||||||
|
|
||||||
|
var UnsafeUUIDGenerator = uuid.NewGenWithOptions(uuid.WithRandomReader(UnsafeRandReader))
|
||||||
|
|
||||||
func NewUUIDV1() uuid.UUID {
|
func NewUUIDV1() uuid.UUID {
|
||||||
u, _ := UnsafeUUIDGenerator.NewV1() // fastrand.Read wouldn't cause error, so ignore err is safe
|
u, _ := UnsafeUUIDGenerator.NewV1() // unsafeRandReader wouldn't cause error, so ignore err is safe
|
||||||
return u
|
return u
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,7 +43,7 @@ func NewUUIDV3(ns uuid.UUID, name string) uuid.UUID {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewUUIDV4() uuid.UUID {
|
func NewUUIDV4() uuid.UUID {
|
||||||
u, _ := UnsafeUUIDGenerator.NewV4() // fastrand.Read wouldn't cause error, so ignore err is safe
|
u, _ := UnsafeUUIDGenerator.NewV4() // unsafeRandReader wouldn't cause error, so ignore err is safe
|
||||||
return u
|
return u
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,12 +52,12 @@ func NewUUIDV5(ns uuid.UUID, name string) uuid.UUID {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewUUIDV6() uuid.UUID {
|
func NewUUIDV6() uuid.UUID {
|
||||||
u, _ := UnsafeUUIDGenerator.NewV6() // fastrand.Read wouldn't cause error, so ignore err is safe
|
u, _ := UnsafeUUIDGenerator.NewV6() // unsafeRandReader wouldn't cause error, so ignore err is safe
|
||||||
return u
|
return u
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewUUIDV7() uuid.UUID {
|
func NewUUIDV7() uuid.UUID {
|
||||||
u, _ := UnsafeUUIDGenerator.NewV7() // fastrand.Read wouldn't cause error, so ignore err is safe
|
u, _ := UnsafeUUIDGenerator.NewV7() // unsafeRandReader wouldn't cause error, so ignore err is safe
|
||||||
return u
|
return u
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
0
component/ca/ca-certificates.crt
Normal file
0
component/ca/ca-certificates.crt
Normal file
@@ -5,12 +5,16 @@ import (
|
|||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
|
_ "embed"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
var trustCerts []*x509.Certificate
|
var trustCerts []*x509.Certificate
|
||||||
@@ -18,6 +22,11 @@ var globalCertPool *x509.CertPool
|
|||||||
var mutex sync.RWMutex
|
var mutex sync.RWMutex
|
||||||
var errNotMatch = errors.New("certificate fingerprints do not match")
|
var errNotMatch = errors.New("certificate fingerprints do not match")
|
||||||
|
|
||||||
|
//go:embed ca-certificates.crt
|
||||||
|
var _CaCertificates []byte
|
||||||
|
var DisableEmbedCa, _ = strconv.ParseBool(os.Getenv("DISABLE_EMBED_CA"))
|
||||||
|
var DisableSystemCa, _ = strconv.ParseBool(os.Getenv("DISABLE_SYSTEM_CA"))
|
||||||
|
|
||||||
func AddCertificate(certificate string) error {
|
func AddCertificate(certificate string) error {
|
||||||
mutex.Lock()
|
mutex.Lock()
|
||||||
defer mutex.Unlock()
|
defer mutex.Unlock()
|
||||||
@@ -34,13 +43,20 @@ func AddCertificate(certificate string) error {
|
|||||||
|
|
||||||
func initializeCertPool() {
|
func initializeCertPool() {
|
||||||
var err error
|
var err error
|
||||||
globalCertPool, err = x509.SystemCertPool()
|
if DisableSystemCa {
|
||||||
if err != nil {
|
|
||||||
globalCertPool = x509.NewCertPool()
|
globalCertPool = x509.NewCertPool()
|
||||||
|
} else {
|
||||||
|
globalCertPool, err = x509.SystemCertPool()
|
||||||
|
if err != nil {
|
||||||
|
globalCertPool = x509.NewCertPool()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for _, cert := range trustCerts {
|
for _, cert := range trustCerts {
|
||||||
globalCertPool.AddCert(cert)
|
globalCertPool.AddCert(cert)
|
||||||
}
|
}
|
||||||
|
if !DisableEmbedCa {
|
||||||
|
globalCertPool.AppendCertsFromPEM(_CaCertificates)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func ResetCertificate() {
|
func ResetCertificate() {
|
||||||
@@ -51,9 +67,6 @@ func ResetCertificate() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getCertPool() *x509.CertPool {
|
func getCertPool() *x509.CertPool {
|
||||||
if len(trustCerts) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if globalCertPool == nil {
|
if globalCertPool == nil {
|
||||||
mutex.Lock()
|
mutex.Lock()
|
||||||
defer mutex.Unlock()
|
defer mutex.Unlock()
|
||||||
@@ -103,7 +116,7 @@ func GetTLSConfig(tlsConfig *tls.Config, fingerprint string, customCA string, cu
|
|||||||
var certificate []byte
|
var certificate []byte
|
||||||
var err error
|
var err error
|
||||||
if len(customCA) > 0 {
|
if len(customCA) > 0 {
|
||||||
certificate, err = os.ReadFile(customCA)
|
certificate, err = os.ReadFile(C.Path.Resolve(customCA))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("load ca error: %w", err)
|
return nil, fmt.Errorf("load ca error: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
14
component/ca/fix_windows.go
Normal file
14
component/ca/fix_windows.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package ca
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/metacubex/mihomo/constant/features"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
// crypto/x509: certificate validation in Windows fails to validate IP in SAN
|
||||||
|
// https://github.com/golang/go/issues/37176
|
||||||
|
// As far as I can tell this is still the case on most older versions of Windows (but seems to be fixed in 10)
|
||||||
|
if features.WindowsMajorVersion < 10 && len(_CaCertificates) > 0 {
|
||||||
|
DisableSystemCa = true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -43,12 +43,12 @@ func (set *IpCidrSet) IsContainForString(ipString string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (set *IpCidrSet) IsContain(ip netip.Addr) bool {
|
func (set *IpCidrSet) IsContain(ip netip.Addr) bool {
|
||||||
return set.toIPSet().Contains(ip.WithZone(""))
|
return set.ToIPSet().Contains(ip.WithZone(""))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (set *IpCidrSet) Merge() error {
|
func (set *IpCidrSet) Merge() error {
|
||||||
var b netipx.IPSetBuilder
|
var b netipx.IPSetBuilder
|
||||||
b.AddSet(set.toIPSet())
|
b.AddSet(set.ToIPSet())
|
||||||
i, err := b.IPSet()
|
i, err := b.IPSet()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -57,7 +57,9 @@ func (set *IpCidrSet) Merge() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (set *IpCidrSet) toIPSet() *netipx.IPSet {
|
// ToIPSet not safe convert to *netipx.IPSet
|
||||||
|
// be careful, must be used after Merge
|
||||||
|
func (set *IpCidrSet) ToIPSet() *netipx.IPSet {
|
||||||
return (*netipx.IPSet)(unsafe.Pointer(set))
|
return (*netipx.IPSet)(unsafe.Pointer(set))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package dhcp
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
@@ -24,5 +25,5 @@ func ListenDHCPClient(ctx context.Context, ifaceName string) (net.PacketConn, er
|
|||||||
options = append(options, dialer.WithFallbackBind(true))
|
options = append(options, dialer.WithFallbackBind(true))
|
||||||
}
|
}
|
||||||
|
|
||||||
return dialer.ListenPacket(ctx, "udp4", listenAddr, options...)
|
return dialer.ListenPacket(ctx, "udp4", listenAddr, netip.AddrPortFrom(netip.AddrFrom4([4]byte{255, 255, 255, 255}), 67), options...)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ func LookupLocalAddrFromIfaceName(ifaceName string, network string, destination
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
destination = destination.Unmap()
|
||||||
|
|
||||||
var addr netip.Prefix
|
var addr netip.Prefix
|
||||||
switch network {
|
switch network {
|
||||||
@@ -23,7 +24,7 @@ func LookupLocalAddrFromIfaceName(ifaceName string, network string, destination
|
|||||||
addr, err = ifaceObj.PickIPv6Addr(destination)
|
addr, err = ifaceObj.PickIPv6Addr(destination)
|
||||||
default:
|
default:
|
||||||
if destination.IsValid() {
|
if destination.IsValid() {
|
||||||
if destination.Is4() || destination.Is4In6() {
|
if destination.Is4() {
|
||||||
addr, err = ifaceObj.PickIPv4Addr(destination)
|
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||||
} else {
|
} else {
|
||||||
addr, err = ifaceObj.PickIPv6Addr(destination)
|
addr, err = ifaceObj.PickIPv6Addr(destination)
|
||||||
@@ -74,7 +75,7 @@ func fallbackBindIfaceToDialer(ifaceName string, dialer *net.Dialer, network str
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func fallbackBindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, address string) (string, error) {
|
func fallbackBindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, address string, rAddrPort netip.AddrPort) (string, error) {
|
||||||
_, port, err := net.SplitHostPort(address)
|
_, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
port = "0"
|
port = "0"
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.A
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string, rAddrPort netip.AddrPort) (string, error) {
|
||||||
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.A
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string, rAddrPort netip.AddrPort) (string, error) {
|
||||||
addControlToListenConfig(lc, bindControl(ifaceName))
|
addControlToListenConfig(lc, bindControl(ifaceName))
|
||||||
|
|
||||||
return address, nil
|
return address, nil
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, network string, des
|
|||||||
return fallbackBindIfaceToDialer(ifaceName, dialer, network, destination)
|
return fallbackBindIfaceToDialer(ifaceName, dialer, network, destination)
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, network, address string) (string, error) {
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, network, address string, rAddrPort netip.AddrPort) (string, error) {
|
||||||
return fallbackBindIfaceToListenConfig(ifaceName, lc, network, address)
|
return fallbackBindIfaceToListenConfig(ifaceName, lc, network, address, rAddrPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseNetwork(network string, addr netip.Addr) string {
|
func ParseNetwork(network string, addr netip.Addr) string {
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ func bind6(handle syscall.Handle, ifaceIdx int) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindControl(ifaceIdx int) controlFn {
|
func bindControl(ifaceIdx int, rAddrPort netip.AddrPort) controlFn {
|
||||||
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
||||||
addrPort, err := netip.ParseAddrPort(address)
|
addrPort, err := netip.ParseAddrPort(address)
|
||||||
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
||||||
@@ -55,7 +55,7 @@ func bindControl(ifaceIdx int) controlFn {
|
|||||||
innerErr = bind4err
|
innerErr = bind4err
|
||||||
case "udp6":
|
case "udp6":
|
||||||
// golang will set network to udp6 when listenUDP on wildcard ip (eg: ":0", "")
|
// golang will set network to udp6 when listenUDP on wildcard ip (eg: ":0", "")
|
||||||
if (!addrPort.Addr().IsValid() || addrPort.Addr().IsUnspecified()) && bind6err != nil {
|
if (!addrPort.Addr().IsValid() || addrPort.Addr().IsUnspecified()) && bind6err != nil && rAddrPort.Addr().Unmap().Is4() {
|
||||||
// try bind ipv6, if failed, ignore. it's a workaround for windows disable interface ipv6
|
// try bind ipv6, if failed, ignore. it's a workaround for windows disable interface ipv6
|
||||||
if bind4err != nil {
|
if bind4err != nil {
|
||||||
innerErr = fmt.Errorf("%w (%s)", bind6err, bind4err)
|
innerErr = fmt.Errorf("%w (%s)", bind6err, bind4err)
|
||||||
@@ -76,23 +76,23 @@ func bindControl(ifaceIdx int) controlFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.Addr) error {
|
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, destination netip.Addr) error {
|
||||||
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
addControlToDialer(dialer, bindControl(ifaceObj.Index))
|
addControlToDialer(dialer, bindControl(ifaceObj.Index, netip.AddrPortFrom(destination, 0)))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string, rAddrPort netip.AddrPort) (string, error) {
|
||||||
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
addControlToListenConfig(lc, bindControl(ifaceObj.Index))
|
addControlToListenConfig(lc, bindControl(ifaceObj.Index, rAddrPort))
|
||||||
return address, nil
|
return address, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,12 +7,14 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
"github.com/metacubex/mihomo/constant/features"
|
"github.com/metacubex/mihomo/constant/features"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -24,6 +26,7 @@ type dialFunc func(ctx context.Context, network string, ips []netip.Addr, port s
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
dialMux sync.Mutex
|
dialMux sync.Mutex
|
||||||
|
IP4PEnable bool
|
||||||
actualSingleStackDialContext = serialSingleStackDialContext
|
actualSingleStackDialContext = serialSingleStackDialContext
|
||||||
actualDualStackDialContext = serialDualStackDialContext
|
actualDualStackDialContext = serialDualStackDialContext
|
||||||
tcpConcurrent = false
|
tcpConcurrent = false
|
||||||
@@ -75,7 +78,7 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func ListenPacket(ctx context.Context, network, address string, options ...Option) (net.PacketConn, error) {
|
func ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort, options ...Option) (net.PacketConn, error) {
|
||||||
if features.CMFA && DefaultSocketHook != nil {
|
if features.CMFA && DefaultSocketHook != nil {
|
||||||
return listenPacketHooked(ctx, network, address)
|
return listenPacketHooked(ctx, network, address)
|
||||||
}
|
}
|
||||||
@@ -88,7 +91,7 @@ func ListenPacket(ctx context.Context, network, address string, options ...Optio
|
|||||||
if cfg.fallbackBind {
|
if cfg.fallbackBind {
|
||||||
bind = fallbackBindIfaceToListenConfig
|
bind = fallbackBindIfaceToListenConfig
|
||||||
}
|
}
|
||||||
addr, err := bind(cfg.interfaceName, lc, network, address)
|
addr, err := bind(cfg.interfaceName, lc, network, address, rAddrPort)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -128,7 +131,11 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
|||||||
return dialContextHooked(ctx, network, destination, port)
|
return dialContextHooked(ctx, network, destination, port)
|
||||||
}
|
}
|
||||||
|
|
||||||
address := net.JoinHostPort(destination.String(), port)
|
var address string
|
||||||
|
if IP4PEnable {
|
||||||
|
destination, port = lookupIP4P(destination, port)
|
||||||
|
}
|
||||||
|
address = net.JoinHostPort(destination.String(), port)
|
||||||
|
|
||||||
netDialer := opt.netDialer
|
netDialer := opt.netDialer
|
||||||
switch netDialer.(type) {
|
switch netDialer.(type) {
|
||||||
@@ -157,7 +164,7 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
|||||||
if opt.mpTcp {
|
if opt.mpTcp {
|
||||||
setMultiPathTCP(dialer)
|
setMultiPathTCP(dialer)
|
||||||
}
|
}
|
||||||
if opt.tfo {
|
if opt.tfo && !DisableTFO {
|
||||||
return dialTFO(ctx, *dialer, network, address)
|
return dialTFO(ctx, *dialer, network, address)
|
||||||
}
|
}
|
||||||
return dialer.DialContext(ctx, network, address)
|
return dialer.DialContext(ctx, network, address)
|
||||||
@@ -371,15 +378,33 @@ func (d Dialer) DialContext(ctx context.Context, network, address string) (net.C
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d Dialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
func (d Dialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
||||||
opt := WithOption(d.Opt)
|
opt := d.Opt // make a copy
|
||||||
if rAddrPort.Addr().Unmap().IsLoopback() {
|
if rAddrPort.Addr().Unmap().IsLoopback() {
|
||||||
// avoid "The requested address is not valid in its context."
|
// avoid "The requested address is not valid in its context."
|
||||||
opt = WithInterface("")
|
WithInterface("")(&opt)
|
||||||
}
|
}
|
||||||
return ListenPacket(ctx, ParseNetwork(network, rAddrPort.Addr()), address, opt)
|
return ListenPacket(ctx, ParseNetwork(network, rAddrPort.Addr()), address, rAddrPort, WithOption(opt))
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDialer(options ...Option) Dialer {
|
func NewDialer(options ...Option) Dialer {
|
||||||
opt := applyOptions(options...)
|
opt := applyOptions(options...)
|
||||||
return Dialer{Opt: *opt}
|
return Dialer{Opt: *opt}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetIP4PEnable(enableIP4PConvert bool) {
|
||||||
|
IP4PEnable = enableIP4PConvert
|
||||||
|
}
|
||||||
|
|
||||||
|
// kanged from https://github.com/heiher/frp/blob/ip4p/client/ip4p.go
|
||||||
|
|
||||||
|
func lookupIP4P(addr netip.Addr, port string) (netip.Addr, string) {
|
||||||
|
ip := addr.AsSlice()
|
||||||
|
if ip[0] == 0x20 && ip[1] == 0x01 &&
|
||||||
|
ip[2] == 0x00 && ip[3] == 0x00 {
|
||||||
|
addr = netip.AddrFrom4([4]byte{ip[12], ip[13], ip[14], ip[15]})
|
||||||
|
port = strconv.Itoa(int(ip[10])<<8 + int(ip[11]))
|
||||||
|
log.Debugln("Convert IP4P address %s to %s", ip, net.JoinHostPort(addr.String(), port))
|
||||||
|
return addr, port
|
||||||
|
}
|
||||||
|
return addr, port
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,8 +5,6 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/tfo-go"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type tfoConn struct {
|
type tfoConn struct {
|
||||||
@@ -122,16 +120,3 @@ func (c *tfoConn) ReaderReplaceable() bool {
|
|||||||
func (c *tfoConn) WriterReplaceable() bool {
|
func (c *tfoConn) WriterReplaceable() bool {
|
||||||
return c.Conn != nil
|
return c.Conn != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func dialTFO(ctx context.Context, netDialer net.Dialer, network, address string) (net.Conn, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultTCPTimeout)
|
|
||||||
dialer := tfo.Dialer{Dialer: netDialer, DisableTFO: false}
|
|
||||||
return &tfoConn{
|
|
||||||
dialed: make(chan bool, 1),
|
|
||||||
cancel: cancel,
|
|
||||||
ctx: ctx,
|
|
||||||
dialFn: func(ctx context.Context, earlyData []byte) (net.Conn, error) {
|
|
||||||
return dialer.DialContext(ctx, network, address, earlyData)
|
|
||||||
},
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|||||||
25
component/dialer/tfo_unix.go
Normal file
25
component/dialer/tfo_unix.go
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
//go:build unix
|
||||||
|
|
||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/metacubex/tfo-go"
|
||||||
|
)
|
||||||
|
|
||||||
|
const DisableTFO = false
|
||||||
|
|
||||||
|
func dialTFO(ctx context.Context, netDialer net.Dialer, network, address string) (net.Conn, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), DefaultTCPTimeout)
|
||||||
|
dialer := tfo.Dialer{Dialer: netDialer, DisableTFO: false}
|
||||||
|
return &tfoConn{
|
||||||
|
dialed: make(chan bool, 1),
|
||||||
|
cancel: cancel,
|
||||||
|
ctx: ctx,
|
||||||
|
dialFn: func(ctx context.Context, earlyData []byte) (net.Conn, error) {
|
||||||
|
return dialer.DialContext(ctx, network, address, earlyData)
|
||||||
|
},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
12
component/dialer/tfo_windows.go
Normal file
12
component/dialer/tfo_windows.go
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
const DisableTFO = true
|
||||||
|
|
||||||
|
func dialTFO(ctx context.Context, netDialer net.Dialer, network, address string) (net.Conn, error) {
|
||||||
|
return netDialer.DialContext(ctx, network, address)
|
||||||
|
}
|
||||||
@@ -14,8 +14,11 @@ import (
|
|||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
var initGeoSite bool
|
var (
|
||||||
var initGeoIP int
|
initGeoSite bool
|
||||||
|
initGeoIP int
|
||||||
|
initASN bool
|
||||||
|
)
|
||||||
|
|
||||||
func InitGeoSite() error {
|
func InitGeoSite() error {
|
||||||
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
|
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
|
||||||
@@ -113,7 +116,7 @@ func InitGeoIP() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if initGeoIP != 2 {
|
if initGeoIP != 2 {
|
||||||
if !mmdb.Verify() {
|
if !mmdb.Verify(C.Path.MMDB()) {
|
||||||
log.Warnln("MMDB invalid, remove and download")
|
log.Warnln("MMDB invalid, remove and download")
|
||||||
if err := os.Remove(C.Path.MMDB()); err != nil {
|
if err := os.Remove(C.Path.MMDB()); err != nil {
|
||||||
return fmt.Errorf("can't remove invalid MMDB: %s", err.Error())
|
return fmt.Errorf("can't remove invalid MMDB: %s", err.Error())
|
||||||
@@ -126,3 +129,27 @@ func InitGeoIP() error {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func InitASN() error {
|
||||||
|
if _, err := os.Stat(C.Path.ASN()); os.IsNotExist(err) {
|
||||||
|
log.Infoln("Can't find ASN.mmdb, start download")
|
||||||
|
if err := mmdb.DownloadASN(C.Path.ASN()); err != nil {
|
||||||
|
return fmt.Errorf("can't download ASN.mmdb: %s", err.Error())
|
||||||
|
}
|
||||||
|
log.Infoln("Download ASN.mmdb finish")
|
||||||
|
initASN = false
|
||||||
|
}
|
||||||
|
if !initASN {
|
||||||
|
if !mmdb.Verify(C.Path.ASN()) {
|
||||||
|
log.Warnln("ASN invalid, remove and download")
|
||||||
|
if err := os.Remove(C.Path.ASN()); err != nil {
|
||||||
|
return fmt.Errorf("can't remove invalid ASN: %s", err.Error())
|
||||||
|
}
|
||||||
|
if err := mmdb.DownloadASN(C.Path.ASN()); err != nil {
|
||||||
|
return fmt.Errorf("can't download ASN: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
initASN = true
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,19 +3,37 @@ package geodata
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"golang.org/x/sync/singleflight"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/sync/singleflight"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/geodata/router"
|
"github.com/metacubex/mihomo/component/geodata/router"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
var geoLoaderName = "memconservative"
|
var (
|
||||||
var geoSiteMatcher = "succinct"
|
geoMode bool
|
||||||
|
AutoUpdate bool
|
||||||
|
UpdateInterval int
|
||||||
|
geoLoaderName = "memconservative"
|
||||||
|
geoSiteMatcher = "succinct"
|
||||||
|
)
|
||||||
|
|
||||||
// geoLoaderName = "standard"
|
// geoLoaderName = "standard"
|
||||||
|
|
||||||
|
func GeodataMode() bool {
|
||||||
|
return geoMode
|
||||||
|
}
|
||||||
|
|
||||||
|
func GeoAutoUpdate() bool {
|
||||||
|
return AutoUpdate
|
||||||
|
}
|
||||||
|
|
||||||
|
func GeoUpdateInterval() int {
|
||||||
|
return UpdateInterval
|
||||||
|
}
|
||||||
|
|
||||||
func LoaderName() string {
|
func LoaderName() string {
|
||||||
return geoLoaderName
|
return geoLoaderName
|
||||||
}
|
}
|
||||||
@@ -24,6 +42,16 @@ func SiteMatcherName() string {
|
|||||||
return geoSiteMatcher
|
return geoSiteMatcher
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func SetGeodataMode(newGeodataMode bool) {
|
||||||
|
geoMode = newGeodataMode
|
||||||
|
}
|
||||||
|
func SetGeoAutoUpdate(newAutoUpdate bool) {
|
||||||
|
AutoUpdate = newAutoUpdate
|
||||||
|
}
|
||||||
|
func SetGeoUpdateInterval(newGeoUpdateInterval int) {
|
||||||
|
UpdateInterval = newGeoUpdateInterval
|
||||||
|
}
|
||||||
|
|
||||||
func SetLoader(newLoader string) {
|
func SetLoader(newLoader string) {
|
||||||
if newLoader == "memc" {
|
if newLoader == "memc" {
|
||||||
newLoader = "memconservative"
|
newLoader = "memconservative"
|
||||||
|
|||||||
@@ -17,7 +17,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func HttpRequest(ctx context.Context, url, method string, header map[string][]string, body io.Reader) (*http.Response, error) {
|
func HttpRequest(ctx context.Context, url, method string, header map[string][]string, body io.Reader) (*http.Response, error) {
|
||||||
UA := C.UA
|
return HttpRequestWithProxy(ctx, url, method, header, body, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func HttpRequestWithProxy(ctx context.Context, url, method string, header map[string][]string, body io.Reader, specialProxy string) (*http.Response, error) {
|
||||||
method = strings.ToUpper(method)
|
method = strings.ToUpper(method)
|
||||||
urlRes, err := URL.Parse(url)
|
urlRes, err := URL.Parse(url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -32,7 +35,7 @@ func HttpRequest(ctx context.Context, url, method string, header map[string][]st
|
|||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := header["User-Agent"]; !ok {
|
if _, ok := header["User-Agent"]; !ok {
|
||||||
req.Header.Set("User-Agent", UA)
|
req.Header.Set("User-Agent", C.UA)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -54,7 +57,7 @@ func HttpRequest(ctx context.Context, url, method string, header map[string][]st
|
|||||||
TLSHandshakeTimeout: 10 * time.Second,
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
if conn, err := inner.HandleTcp(address); err == nil {
|
if conn, err := inner.HandleTcp(address, specialProxy); err == nil {
|
||||||
return conn, nil
|
return conn, nil
|
||||||
} else {
|
} else {
|
||||||
d := net.Dialer{}
|
d := net.Dialer{}
|
||||||
@@ -66,5 +69,4 @@ func HttpRequest(ctx context.Context, url, method string, header map[string][]st
|
|||||||
|
|
||||||
client := http.Client{Transport: transport}
|
client := http.Client{Transport: transport}
|
||||||
return client.Do(req)
|
return client.Do(req)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/singledo"
|
"github.com/metacubex/mihomo/common/singledo"
|
||||||
@@ -12,8 +11,9 @@ import (
|
|||||||
|
|
||||||
type Interface struct {
|
type Interface struct {
|
||||||
Index int
|
Index int
|
||||||
|
MTU int
|
||||||
Name string
|
Name string
|
||||||
Addrs []netip.Prefix
|
Addresses []netip.Prefix
|
||||||
HardwareAddr net.HardwareAddr
|
HardwareAddr net.HardwareAddr
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ var (
|
|||||||
|
|
||||||
var interfaces = singledo.NewSingle[map[string]*Interface](time.Second * 20)
|
var interfaces = singledo.NewSingle[map[string]*Interface](time.Second * 20)
|
||||||
|
|
||||||
func ResolveInterface(name string) (*Interface, error) {
|
func Interfaces() (map[string]*Interface, error) {
|
||||||
value, err, _ := interfaces.Do(func() (map[string]*Interface, error) {
|
value, err, _ := interfaces.Do(func() (map[string]*Interface, error) {
|
||||||
ifaces, err := net.Interfaces()
|
ifaces, err := net.Interfaces()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -38,45 +38,48 @@ func ResolveInterface(name string) (*Interface, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// if not available device like Meta, dummy0, docker0, etc.
|
|
||||||
if (iface.Flags&net.FlagMulticast == 0) || (iface.Flags&net.FlagPointToPoint != 0) || (iface.Flags&net.FlagRunning == 0) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
ipNets := make([]netip.Prefix, 0, len(addrs))
|
ipNets := make([]netip.Prefix, 0, len(addrs))
|
||||||
for _, addr := range addrs {
|
for _, addr := range addrs {
|
||||||
ipNet := addr.(*net.IPNet)
|
var pf netip.Prefix
|
||||||
ip, _ := netip.AddrFromSlice(ipNet.IP)
|
switch ipNet := addr.(type) {
|
||||||
|
case *net.IPNet:
|
||||||
//unavailable IPv6 Address
|
ip, _ := netip.AddrFromSlice(ipNet.IP)
|
||||||
if ip.Is6() && strings.HasPrefix(ip.String(), "fe80") {
|
ones, bits := ipNet.Mask.Size()
|
||||||
continue
|
if bits == 32 {
|
||||||
}
|
ip = ip.Unmap()
|
||||||
|
}
|
||||||
ones, bits := ipNet.Mask.Size()
|
pf = netip.PrefixFrom(ip, ones)
|
||||||
if bits == 32 {
|
case *net.IPAddr:
|
||||||
|
ip, _ := netip.AddrFromSlice(ipNet.IP)
|
||||||
ip = ip.Unmap()
|
ip = ip.Unmap()
|
||||||
|
pf = netip.PrefixFrom(ip, ip.BitLen())
|
||||||
|
}
|
||||||
|
if pf.IsValid() {
|
||||||
|
ipNets = append(ipNets, pf)
|
||||||
}
|
}
|
||||||
|
|
||||||
pf := netip.PrefixFrom(ip, ones)
|
|
||||||
ipNets = append(ipNets, pf)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
r[iface.Name] = &Interface{
|
r[iface.Name] = &Interface{
|
||||||
Index: iface.Index,
|
Index: iface.Index,
|
||||||
|
MTU: iface.MTU,
|
||||||
Name: iface.Name,
|
Name: iface.Name,
|
||||||
Addrs: ipNets,
|
Addresses: ipNets,
|
||||||
HardwareAddr: iface.HardwareAddr,
|
HardwareAddr: iface.HardwareAddr,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return r, nil
|
return r, nil
|
||||||
})
|
})
|
||||||
|
return value, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveInterface(name string) (*Interface, error) {
|
||||||
|
ifaces, err := Interfaces()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
ifaces := value
|
|
||||||
iface, ok := ifaces[name]
|
iface, ok := ifaces[name]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, ErrIfaceNotFound
|
return nil, ErrIfaceNotFound
|
||||||
@@ -85,6 +88,21 @@ func ResolveInterface(name string) (*Interface, error) {
|
|||||||
return iface, nil
|
return iface, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func IsLocalIp(ip netip.Addr) (bool, error) {
|
||||||
|
ifaces, err := Interfaces()
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
for _, iface := range ifaces {
|
||||||
|
for _, addr := range iface.Addresses {
|
||||||
|
if addr.Contains(ip) {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
func FlushCache() {
|
func FlushCache() {
|
||||||
interfaces.Reset()
|
interfaces.Reset()
|
||||||
}
|
}
|
||||||
@@ -104,7 +122,7 @@ func (iface *Interface) PickIPv6Addr(destination netip.Addr) (netip.Prefix, erro
|
|||||||
func (iface *Interface) pickIPAddr(destination netip.Addr, accept func(addr netip.Prefix) bool) (netip.Prefix, error) {
|
func (iface *Interface) pickIPAddr(destination netip.Addr, accept func(addr netip.Prefix) bool) (netip.Prefix, error) {
|
||||||
var fallback netip.Prefix
|
var fallback netip.Prefix
|
||||||
|
|
||||||
for _, addr := range iface.Addrs {
|
for _, addr := range iface.Addresses {
|
||||||
if !accept(addr) {
|
if !accept(addr) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
89
component/loopback/detector.go
Normal file
89
component/loopback/detector.go
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
package loopback
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/common/callback"
|
||||||
|
"github.com/metacubex/mihomo/component/iface"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
|
||||||
|
"github.com/puzpuzpuz/xsync/v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrReject = errors.New("reject loopback connection")
|
||||||
|
|
||||||
|
type Detector struct {
|
||||||
|
connMap *xsync.MapOf[netip.AddrPort, struct{}]
|
||||||
|
packetConnMap *xsync.MapOf[uint16, struct{}]
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDetector() *Detector {
|
||||||
|
return &Detector{
|
||||||
|
connMap: xsync.NewMapOf[netip.AddrPort, struct{}](),
|
||||||
|
packetConnMap: xsync.NewMapOf[uint16, struct{}](),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Detector) NewConn(conn C.Conn) C.Conn {
|
||||||
|
metadata := C.Metadata{}
|
||||||
|
if metadata.SetRemoteAddr(conn.LocalAddr()) != nil {
|
||||||
|
return conn
|
||||||
|
}
|
||||||
|
connAddr := metadata.AddrPort()
|
||||||
|
if !connAddr.IsValid() {
|
||||||
|
return conn
|
||||||
|
}
|
||||||
|
l.connMap.Store(connAddr, struct{}{})
|
||||||
|
return callback.NewCloseCallbackConn(conn, func() {
|
||||||
|
l.connMap.Delete(connAddr)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Detector) NewPacketConn(conn C.PacketConn) C.PacketConn {
|
||||||
|
metadata := C.Metadata{}
|
||||||
|
if metadata.SetRemoteAddr(conn.LocalAddr()) != nil {
|
||||||
|
return conn
|
||||||
|
}
|
||||||
|
connAddr := metadata.AddrPort()
|
||||||
|
if !connAddr.IsValid() {
|
||||||
|
return conn
|
||||||
|
}
|
||||||
|
port := connAddr.Port()
|
||||||
|
l.packetConnMap.Store(port, struct{}{})
|
||||||
|
return callback.NewCloseCallbackPacketConn(conn, func() {
|
||||||
|
l.packetConnMap.Delete(port)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Detector) CheckConn(metadata *C.Metadata) error {
|
||||||
|
connAddr := metadata.SourceAddrPort()
|
||||||
|
if !connAddr.IsValid() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if _, ok := l.connMap.Load(connAddr); ok {
|
||||||
|
return fmt.Errorf("%w to: %s", ErrReject, metadata.RemoteAddress())
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Detector) CheckPacketConn(metadata *C.Metadata) error {
|
||||||
|
connAddr := metadata.SourceAddrPort()
|
||||||
|
if !connAddr.IsValid() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
isLocalIp, err := iface.IsLocalIp(connAddr.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !isLocalIp && !connAddr.Addr().IsLoopback() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := l.packetConnMap.Load(connAddr.Port()); ok {
|
||||||
|
return fmt.Errorf("%w to: %s", ErrReject, metadata.RemoteAddress())
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
mihomoOnce "github.com/metacubex/mihomo/common/once"
|
||||||
mihomoHttp "github.com/metacubex/mihomo/component/http"
|
mihomoHttp "github.com/metacubex/mihomo/component/http"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
@@ -24,56 +25,58 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
reader Reader
|
IPreader IPReader
|
||||||
once sync.Once
|
ASNreader ASNReader
|
||||||
|
IPonce sync.Once
|
||||||
|
ASNonce sync.Once
|
||||||
)
|
)
|
||||||
|
|
||||||
func LoadFromBytes(buffer []byte) {
|
func LoadFromBytes(buffer []byte) {
|
||||||
once.Do(func() {
|
IPonce.Do(func() {
|
||||||
mmdb, err := maxminddb.FromBytes(buffer)
|
mmdb, err := maxminddb.FromBytes(buffer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalln("Can't load mmdb: %s", err.Error())
|
log.Fatalln("Can't load mmdb: %s", err.Error())
|
||||||
}
|
}
|
||||||
reader = Reader{Reader: mmdb}
|
IPreader = IPReader{Reader: mmdb}
|
||||||
switch mmdb.Metadata.DatabaseType {
|
switch mmdb.Metadata.DatabaseType {
|
||||||
case "sing-geoip":
|
case "sing-geoip":
|
||||||
reader.databaseType = typeSing
|
IPreader.databaseType = typeSing
|
||||||
case "Meta-geoip0":
|
case "Meta-geoip0":
|
||||||
reader.databaseType = typeMetaV0
|
IPreader.databaseType = typeMetaV0
|
||||||
default:
|
default:
|
||||||
reader.databaseType = typeMaxmind
|
IPreader.databaseType = typeMaxmind
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func Verify() bool {
|
func Verify(path string) bool {
|
||||||
instance, err := maxminddb.Open(C.Path.MMDB())
|
instance, err := maxminddb.Open(path)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
instance.Close()
|
instance.Close()
|
||||||
}
|
}
|
||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func Instance() Reader {
|
func IPInstance() IPReader {
|
||||||
once.Do(func() {
|
IPonce.Do(func() {
|
||||||
mmdbPath := C.Path.MMDB()
|
mmdbPath := C.Path.MMDB()
|
||||||
log.Debugln("Load MMDB file: %s", mmdbPath)
|
log.Infoln("Load MMDB file: %s", mmdbPath)
|
||||||
mmdb, err := maxminddb.Open(mmdbPath)
|
mmdb, err := maxminddb.Open(mmdbPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalln("Can't load MMDB: %s", err.Error())
|
log.Fatalln("Can't load MMDB: %s", err.Error())
|
||||||
}
|
}
|
||||||
reader = Reader{Reader: mmdb}
|
IPreader = IPReader{Reader: mmdb}
|
||||||
switch mmdb.Metadata.DatabaseType {
|
switch mmdb.Metadata.DatabaseType {
|
||||||
case "sing-geoip":
|
case "sing-geoip":
|
||||||
reader.databaseType = typeSing
|
IPreader.databaseType = typeSing
|
||||||
case "Meta-geoip0":
|
case "Meta-geoip0":
|
||||||
reader.databaseType = typeMetaV0
|
IPreader.databaseType = typeMetaV0
|
||||||
default:
|
default:
|
||||||
reader.databaseType = typeMaxmind
|
IPreader.databaseType = typeMaxmind
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
return reader
|
return IPreader
|
||||||
}
|
}
|
||||||
|
|
||||||
func DownloadMMDB(path string) (err error) {
|
func DownloadMMDB(path string) (err error) {
|
||||||
@@ -94,3 +97,44 @@ func DownloadMMDB(path string) (err error) {
|
|||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ASNInstance() ASNReader {
|
||||||
|
ASNonce.Do(func() {
|
||||||
|
ASNPath := C.Path.ASN()
|
||||||
|
log.Infoln("Load ASN file: %s", ASNPath)
|
||||||
|
asn, err := maxminddb.Open(ASNPath)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalln("Can't load ASN: %s", err.Error())
|
||||||
|
}
|
||||||
|
ASNreader = ASNReader{Reader: asn}
|
||||||
|
})
|
||||||
|
|
||||||
|
return ASNreader
|
||||||
|
}
|
||||||
|
|
||||||
|
func DownloadASN(path string) (err error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
||||||
|
defer cancel()
|
||||||
|
resp, err := mihomoHttp.HttpRequest(ctx, C.ASNUrl, http.MethodGet, http.Header{"User-Agent": {C.UA}}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
_, err = io.Copy(f, resp.Body)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReloadIP() {
|
||||||
|
mihomoOnce.Reset(&IPonce)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReloadASN() {
|
||||||
|
mihomoOnce.Reset(&ASNonce)
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,14 +5,14 @@ package mmdb
|
|||||||
import "github.com/oschwald/maxminddb-golang"
|
import "github.com/oschwald/maxminddb-golang"
|
||||||
|
|
||||||
func InstallOverride(override *maxminddb.Reader) {
|
func InstallOverride(override *maxminddb.Reader) {
|
||||||
newReader := Reader{Reader: override}
|
newReader := IPReader{Reader: override}
|
||||||
switch override.Metadata.DatabaseType {
|
switch override.Metadata.DatabaseType {
|
||||||
case "sing-geoip":
|
case "sing-geoip":
|
||||||
reader.databaseType = typeSing
|
IPreader.databaseType = typeSing
|
||||||
case "Meta-geoip0":
|
case "Meta-geoip0":
|
||||||
reader.databaseType = typeMetaV0
|
IPreader.databaseType = typeMetaV0
|
||||||
default:
|
default:
|
||||||
reader.databaseType = typeMaxmind
|
IPreader.databaseType = typeMaxmind
|
||||||
}
|
}
|
||||||
reader = newReader
|
IPreader = newReader
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,9 @@ package mmdb
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/oschwald/maxminddb-golang"
|
"github.com/oschwald/maxminddb-golang"
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type geoip2Country struct {
|
type geoip2Country struct {
|
||||||
@@ -14,12 +14,21 @@ type geoip2Country struct {
|
|||||||
} `maxminddb:"country"`
|
} `maxminddb:"country"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Reader struct {
|
type IPReader struct {
|
||||||
*maxminddb.Reader
|
*maxminddb.Reader
|
||||||
databaseType
|
databaseType
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Reader) LookupCode(ipAddress net.IP) []string {
|
type ASNReader struct {
|
||||||
|
*maxminddb.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
type ASNResult struct {
|
||||||
|
AutonomousSystemNumber uint32 `maxminddb:"autonomous_system_number"`
|
||||||
|
AutonomousSystemOrganization string `maxminddb:"autonomous_system_organization"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r IPReader) LookupCode(ipAddress net.IP) []string {
|
||||||
switch r.databaseType {
|
switch r.databaseType {
|
||||||
case typeMaxmind:
|
case typeMaxmind:
|
||||||
var country geoip2Country
|
var country geoip2Country
|
||||||
@@ -27,7 +36,7 @@ func (r Reader) LookupCode(ipAddress net.IP) []string {
|
|||||||
if country.Country.IsoCode == "" {
|
if country.Country.IsoCode == "" {
|
||||||
return []string{}
|
return []string{}
|
||||||
}
|
}
|
||||||
return []string{country.Country.IsoCode}
|
return []string{strings.ToLower(country.Country.IsoCode)}
|
||||||
|
|
||||||
case typeSing:
|
case typeSing:
|
||||||
var code string
|
var code string
|
||||||
@@ -44,9 +53,11 @@ func (r Reader) LookupCode(ipAddress net.IP) []string {
|
|||||||
case string:
|
case string:
|
||||||
return []string{record}
|
return []string{record}
|
||||||
case []any: // lookup returned type of slice is []any
|
case []any: // lookup returned type of slice is []any
|
||||||
return common.Map(record, func(it any) string {
|
result := make([]string, 0, len(record))
|
||||||
return it.(string)
|
for _, item := range record {
|
||||||
})
|
result = append(result, item.(string))
|
||||||
|
}
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
return []string{}
|
return []string{}
|
||||||
|
|
||||||
@@ -54,3 +65,9 @@ func (r Reader) LookupCode(ipAddress net.IP) []string {
|
|||||||
panic(fmt.Sprint("unknown geoip database type:", r.databaseType))
|
panic(fmt.Sprint("unknown geoip database type:", r.databaseType))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r ASNReader) LookupASN(ip net.IP) ASNResult {
|
||||||
|
var result ASNResult
|
||||||
|
r.Lookup(ip, &result)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|||||||
22
component/power/event.go
Normal file
22
component/power/event.go
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package power
|
||||||
|
|
||||||
|
type Type uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
SUSPEND Type = iota
|
||||||
|
RESUME
|
||||||
|
RESUMEAUTOMATIC // Because the user is not present, most applications should do nothing.
|
||||||
|
)
|
||||||
|
|
||||||
|
func (t Type) String() string {
|
||||||
|
switch t {
|
||||||
|
case SUSPEND:
|
||||||
|
return "SUSPEND"
|
||||||
|
case RESUME:
|
||||||
|
return "RESUME"
|
||||||
|
case RESUMEAUTOMATIC:
|
||||||
|
return "RESUMEAUTOMATIC"
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
9
component/power/event_other.go
Normal file
9
component/power/event_other.go
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package power
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
func NewEventListener(cb func(Type)) (func(), error) {
|
||||||
|
return nil, errors.New("not support on this platform")
|
||||||
|
}
|
||||||
74
component/power/event_windows.go
Normal file
74
component/power/event_windows.go
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
package power
|
||||||
|
|
||||||
|
// modify from https://github.com/golang/go/blob/b634f6fdcbebee23b7da709a243f3db217b64776/src/runtime/os_windows.go#L257
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
libPowrProf = windows.NewLazySystemDLL("powrprof.dll")
|
||||||
|
powerRegisterSuspendResumeNotification = libPowrProf.NewProc("PowerRegisterSuspendResumeNotification")
|
||||||
|
powerUnregisterSuspendResumeNotification = libPowrProf.NewProc("PowerUnregisterSuspendResumeNotification")
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewEventListener(cb func(Type)) (func(), error) {
|
||||||
|
if err := powerRegisterSuspendResumeNotification.Find(); err != nil {
|
||||||
|
return nil, err // Running on Windows 7, where we don't need it anyway.
|
||||||
|
}
|
||||||
|
if err := powerUnregisterSuspendResumeNotification.Find(); err != nil {
|
||||||
|
return nil, err // Running on Windows 7, where we don't need it anyway.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Defines the type of event
|
||||||
|
const (
|
||||||
|
PBT_APMSUSPEND uint32 = 4
|
||||||
|
PBT_APMRESUMESUSPEND uint32 = 7
|
||||||
|
PBT_APMRESUMEAUTOMATIC uint32 = 18
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
_DEVICE_NOTIFY_CALLBACK = 2
|
||||||
|
)
|
||||||
|
type _DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS struct {
|
||||||
|
callback uintptr
|
||||||
|
context uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
var fn interface{} = func(context uintptr, changeType uint32, setting uintptr) uintptr {
|
||||||
|
switch changeType {
|
||||||
|
case PBT_APMSUSPEND:
|
||||||
|
cb(SUSPEND)
|
||||||
|
case PBT_APMRESUMESUSPEND:
|
||||||
|
cb(RESUME)
|
||||||
|
case PBT_APMRESUMEAUTOMATIC:
|
||||||
|
cb(RESUMEAUTOMATIC)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
params := _DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS{
|
||||||
|
callback: windows.NewCallback(fn),
|
||||||
|
}
|
||||||
|
handle := uintptr(0)
|
||||||
|
|
||||||
|
_, _, err := powerRegisterSuspendResumeNotification.Call(
|
||||||
|
_DEVICE_NOTIFY_CALLBACK,
|
||||||
|
uintptr(unsafe.Pointer(¶ms)),
|
||||||
|
uintptr(unsafe.Pointer(&handle)),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return func() {
|
||||||
|
_, _, _ = powerUnregisterSuspendResumeNotification.Call(
|
||||||
|
uintptr(unsafe.Pointer(&handle)),
|
||||||
|
)
|
||||||
|
runtime.KeepAlive(params)
|
||||||
|
runtime.KeepAlive(handle)
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -2,19 +2,23 @@ package process
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"context"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"syscall"
|
"syscall"
|
||||||
"unicode"
|
"unicode"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
"github.com/mdlayher/netlink"
|
"github.com/mdlayher/netlink"
|
||||||
|
tun "github.com/metacubex/sing-tun"
|
||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -59,6 +63,19 @@ type inetDiagResponse struct {
|
|||||||
INode uint32
|
INode uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type MyCallback struct{}
|
||||||
|
|
||||||
|
var (
|
||||||
|
packageManager tun.PackageManager
|
||||||
|
once sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
|
func (cb *MyCallback) OnPackagesUpdated(packageCount int, sharedCount int) {}
|
||||||
|
|
||||||
|
func (cb *MyCallback) NewError(ctx context.Context, err error) {
|
||||||
|
log.Warnln("%s", err)
|
||||||
|
}
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, srcPort int) (uint32, string, error) {
|
func findProcessName(network string, ip netip.Addr, srcPort int) (uint32, string, error) {
|
||||||
uid, inode, err := resolveSocketByNetlink(network, ip, srcPort)
|
uid, inode, err := resolveSocketByNetlink(network, ip, srcPort)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -162,12 +179,7 @@ func resolveProcessNameByProcSearch(inode, uid uint32) (string, error) {
|
|||||||
}
|
}
|
||||||
if runtime.GOOS == "android" {
|
if runtime.GOOS == "android" {
|
||||||
if bytes.Equal(buffer[:n], socket) {
|
if bytes.Equal(buffer[:n], socket) {
|
||||||
cmdline, err := os.ReadFile(path.Join(processPath, "cmdline"))
|
return findPackageName(uid), nil
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return splitCmdline(cmdline), nil
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if bytes.Equal(buffer[:n], socket) {
|
if bytes.Equal(buffer[:n], socket) {
|
||||||
@@ -181,17 +193,28 @@ func resolveProcessNameByProcSearch(inode, uid uint32) (string, error) {
|
|||||||
return "", fmt.Errorf("process of uid(%d),inode(%d) not found", uid, inode)
|
return "", fmt.Errorf("process of uid(%d),inode(%d) not found", uid, inode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func splitCmdline(cmdline []byte) string {
|
func findPackageName(uid uint32) string {
|
||||||
cmdline = bytes.Trim(cmdline, " ")
|
once.Do(func() {
|
||||||
|
callback := &MyCallback{}
|
||||||
idx := bytes.IndexFunc(cmdline, func(r rune) bool {
|
var err error
|
||||||
return unicode.IsControl(r) || unicode.IsSpace(r) || r == ':'
|
packageManager, err = tun.NewPackageManager(callback)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("%s", err)
|
||||||
|
}
|
||||||
|
err = packageManager.Start()
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("%s", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
if idx == -1 {
|
if sharedPackage, loaded := packageManager.SharedPackageByID(uid % 100000); loaded {
|
||||||
return filepath.Base(string(cmdline))
|
return sharedPackage
|
||||||
}
|
}
|
||||||
return filepath.Base(string(cmdline[:idx]))
|
if packageName, loaded := packageManager.PackageByID(uid % 100000); loaded {
|
||||||
|
return packageName
|
||||||
|
}
|
||||||
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func isPid(s string) bool {
|
func isPid(s string) bool {
|
||||||
|
|||||||
@@ -3,12 +3,20 @@ package resolver
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
_ "unsafe"
|
_ "unsafe"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
"github.com/metacubex/mihomo/component/resolver/hosts"
|
||||||
"github.com/metacubex/mihomo/component/trie"
|
"github.com/metacubex/mihomo/component/trie"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
"github.com/metacubex/randv2"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
DisableSystemHosts, _ = strconv.ParseBool(os.Getenv("DISABLE_SYSTEM_HOSTS"))
|
||||||
|
UseSystemHosts bool
|
||||||
)
|
)
|
||||||
|
|
||||||
type Hosts struct {
|
type Hosts struct {
|
||||||
@@ -21,11 +29,6 @@ func NewHosts(hosts *trie.DomainTrie[HostValue]) Hosts {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// lookupStaticHost looks up the addresses and the canonical name for the given host from /etc/hosts.
|
|
||||||
//
|
|
||||||
//go:linkname lookupStaticHost net.lookupStaticHost
|
|
||||||
func lookupStaticHost(host string) ([]string, string)
|
|
||||||
|
|
||||||
// Return the search result and whether to match the parameter `isDomain`
|
// Return the search result and whether to match the parameter `isDomain`
|
||||||
func (h *Hosts) Search(domain string, isDomain bool) (*HostValue, bool) {
|
func (h *Hosts) Search(domain string, isDomain bool) (*HostValue, bool) {
|
||||||
if value := h.DomainTrie.Search(domain); value != nil {
|
if value := h.DomainTrie.Search(domain); value != nil {
|
||||||
@@ -47,8 +50,9 @@ func (h *Hosts) Search(domain string, isDomain bool) (*HostValue, bool) {
|
|||||||
|
|
||||||
return &hostValue, false
|
return &hostValue, false
|
||||||
}
|
}
|
||||||
if !isDomain {
|
|
||||||
addr, _ := lookupStaticHost(domain)
|
if !isDomain && !DisableSystemHosts && UseSystemHosts {
|
||||||
|
addr, _ := hosts.LookupStaticHost(domain)
|
||||||
if hostValue, err := NewHostValue(addr); err == nil {
|
if hostValue, err := NewHostValue(addr); err == nil {
|
||||||
return &hostValue, true
|
return &hostValue, true
|
||||||
}
|
}
|
||||||
@@ -121,5 +125,5 @@ func (hv HostValue) RandIP() (netip.Addr, error) {
|
|||||||
if hv.IsDomain {
|
if hv.IsDomain {
|
||||||
return netip.Addr{}, errors.New("value type is error")
|
return netip.Addr{}, errors.New("value type is error")
|
||||||
}
|
}
|
||||||
return hv.IPs[fastrand.Intn(len(hv.IPs))], nil
|
return hv.IPs[randv2.IntN(len(hv.IPs))], nil
|
||||||
}
|
}
|
||||||
|
|||||||
309
component/resolver/hosts/hosts.go
Normal file
309
component/resolver/hosts/hosts.go
Normal file
@@ -0,0 +1,309 @@
|
|||||||
|
package hosts
|
||||||
|
|
||||||
|
// this file copy and modify from golang's std net/hosts.go
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var hostsFilePath = "/etc/hosts"
|
||||||
|
|
||||||
|
const cacheMaxAge = 5 * time.Second
|
||||||
|
|
||||||
|
func parseLiteralIP(addr string) string {
|
||||||
|
ip, err := netip.ParseAddr(addr)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return ip.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
type byName struct {
|
||||||
|
addrs []string
|
||||||
|
canonicalName string
|
||||||
|
}
|
||||||
|
|
||||||
|
// hosts contains known host entries.
|
||||||
|
var hosts struct {
|
||||||
|
sync.Mutex
|
||||||
|
|
||||||
|
// Key for the list of literal IP addresses must be a host
|
||||||
|
// name. It would be part of DNS labels, a FQDN or an absolute
|
||||||
|
// FQDN.
|
||||||
|
// For now the key is converted to lower case for convenience.
|
||||||
|
byName map[string]byName
|
||||||
|
|
||||||
|
// Key for the list of host names must be a literal IP address
|
||||||
|
// including IPv6 address with zone identifier.
|
||||||
|
// We don't support old-classful IP address notation.
|
||||||
|
byAddr map[string][]string
|
||||||
|
|
||||||
|
expire time.Time
|
||||||
|
path string
|
||||||
|
mtime time.Time
|
||||||
|
size int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func readHosts() {
|
||||||
|
now := time.Now()
|
||||||
|
hp := hostsFilePath
|
||||||
|
|
||||||
|
if now.Before(hosts.expire) && hosts.path == hp && len(hosts.byName) > 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
mtime, size, err := stat(hp)
|
||||||
|
if err == nil && hosts.path == hp && hosts.mtime.Equal(mtime) && hosts.size == size {
|
||||||
|
hosts.expire = now.Add(cacheMaxAge)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hs := make(map[string]byName)
|
||||||
|
is := make(map[string][]string)
|
||||||
|
|
||||||
|
file, err := open(hp)
|
||||||
|
if err != nil {
|
||||||
|
if !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, fs.ErrPermission) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if file != nil {
|
||||||
|
defer file.close()
|
||||||
|
for line, ok := file.readLine(); ok; line, ok = file.readLine() {
|
||||||
|
if i := strings.IndexByte(line, '#'); i >= 0 {
|
||||||
|
// Discard comments.
|
||||||
|
line = line[0:i]
|
||||||
|
}
|
||||||
|
f := getFields(line)
|
||||||
|
if len(f) < 2 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
addr := parseLiteralIP(f[0])
|
||||||
|
if addr == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var canonical string
|
||||||
|
for i := 1; i < len(f); i++ {
|
||||||
|
name := absDomainName(f[i])
|
||||||
|
h := []byte(f[i])
|
||||||
|
lowerASCIIBytes(h)
|
||||||
|
key := absDomainName(string(h))
|
||||||
|
|
||||||
|
if i == 1 {
|
||||||
|
canonical = key
|
||||||
|
}
|
||||||
|
|
||||||
|
is[addr] = append(is[addr], name)
|
||||||
|
|
||||||
|
if v, ok := hs[key]; ok {
|
||||||
|
hs[key] = byName{
|
||||||
|
addrs: append(v.addrs, addr),
|
||||||
|
canonicalName: v.canonicalName,
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
hs[key] = byName{
|
||||||
|
addrs: []string{addr},
|
||||||
|
canonicalName: canonical,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Update the data cache.
|
||||||
|
hosts.expire = now.Add(cacheMaxAge)
|
||||||
|
hosts.path = hp
|
||||||
|
hosts.byName = hs
|
||||||
|
hosts.byAddr = is
|
||||||
|
hosts.mtime = mtime
|
||||||
|
hosts.size = size
|
||||||
|
}
|
||||||
|
|
||||||
|
// LookupStaticHost looks up the addresses and the canonical name for the given host from /etc/hosts.
|
||||||
|
func LookupStaticHost(host string) ([]string, string) {
|
||||||
|
hosts.Lock()
|
||||||
|
defer hosts.Unlock()
|
||||||
|
readHosts()
|
||||||
|
if len(hosts.byName) != 0 {
|
||||||
|
if hasUpperCase(host) {
|
||||||
|
lowerHost := []byte(host)
|
||||||
|
lowerASCIIBytes(lowerHost)
|
||||||
|
host = string(lowerHost)
|
||||||
|
}
|
||||||
|
if byName, ok := hosts.byName[absDomainName(host)]; ok {
|
||||||
|
ipsCp := make([]string, len(byName.addrs))
|
||||||
|
copy(ipsCp, byName.addrs)
|
||||||
|
return ipsCp, byName.canonicalName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// LookupStaticAddr looks up the hosts for the given address from /etc/hosts.
|
||||||
|
func LookupStaticAddr(addr string) []string {
|
||||||
|
hosts.Lock()
|
||||||
|
defer hosts.Unlock()
|
||||||
|
readHosts()
|
||||||
|
addr = parseLiteralIP(addr)
|
||||||
|
if addr == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if len(hosts.byAddr) != 0 {
|
||||||
|
if hosts, ok := hosts.byAddr[addr]; ok {
|
||||||
|
hostsCp := make([]string, len(hosts))
|
||||||
|
copy(hostsCp, hosts)
|
||||||
|
return hostsCp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func stat(name string) (mtime time.Time, size int64, err error) {
|
||||||
|
st, err := os.Stat(name)
|
||||||
|
if err != nil {
|
||||||
|
return time.Time{}, 0, err
|
||||||
|
}
|
||||||
|
return st.ModTime(), st.Size(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type file struct {
|
||||||
|
file *os.File
|
||||||
|
data []byte
|
||||||
|
atEOF bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *file) close() { f.file.Close() }
|
||||||
|
|
||||||
|
func (f *file) getLineFromData() (s string, ok bool) {
|
||||||
|
data := f.data
|
||||||
|
i := 0
|
||||||
|
for i = 0; i < len(data); i++ {
|
||||||
|
if data[i] == '\n' {
|
||||||
|
s = string(data[0:i])
|
||||||
|
ok = true
|
||||||
|
// move data
|
||||||
|
i++
|
||||||
|
n := len(data) - i
|
||||||
|
copy(data[0:], data[i:])
|
||||||
|
f.data = data[0:n]
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if f.atEOF && len(f.data) > 0 {
|
||||||
|
// EOF, return all we have
|
||||||
|
s = string(data)
|
||||||
|
f.data = f.data[0:0]
|
||||||
|
ok = true
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *file) readLine() (s string, ok bool) {
|
||||||
|
if s, ok = f.getLineFromData(); ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(f.data) < cap(f.data) {
|
||||||
|
ln := len(f.data)
|
||||||
|
n, err := io.ReadFull(f.file, f.data[ln:cap(f.data)])
|
||||||
|
if n >= 0 {
|
||||||
|
f.data = f.data[0 : ln+n]
|
||||||
|
}
|
||||||
|
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||||
|
f.atEOF = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s, ok = f.getLineFromData()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *file) stat() (mtime time.Time, size int64, err error) {
|
||||||
|
st, err := f.file.Stat()
|
||||||
|
if err != nil {
|
||||||
|
return time.Time{}, 0, err
|
||||||
|
}
|
||||||
|
return st.ModTime(), st.Size(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func open(name string) (*file, error) {
|
||||||
|
fd, err := os.Open(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &file{fd, make([]byte, 0, 64*1024), false}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getFields(s string) []string { return splitAtBytes(s, " \r\t\n") }
|
||||||
|
|
||||||
|
// Count occurrences in s of any bytes in t.
|
||||||
|
func countAnyByte(s string, t string) int {
|
||||||
|
n := 0
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
if strings.IndexByte(t, s[i]) >= 0 {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// Split s at any bytes in t.
|
||||||
|
func splitAtBytes(s string, t string) []string {
|
||||||
|
a := make([]string, 1+countAnyByte(s, t))
|
||||||
|
n := 0
|
||||||
|
last := 0
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
if strings.IndexByte(t, s[i]) >= 0 {
|
||||||
|
if last < i {
|
||||||
|
a[n] = s[last:i]
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
last = i + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if last < len(s) {
|
||||||
|
a[n] = s[last:]
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
return a[0:n]
|
||||||
|
}
|
||||||
|
|
||||||
|
// lowerASCIIBytes makes x ASCII lowercase in-place.
|
||||||
|
func lowerASCIIBytes(x []byte) {
|
||||||
|
for i, b := range x {
|
||||||
|
if 'A' <= b && b <= 'Z' {
|
||||||
|
x[i] += 'a' - 'A'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// hasUpperCase tells whether the given string contains at least one upper-case.
|
||||||
|
func hasUpperCase(s string) bool {
|
||||||
|
for i := range s {
|
||||||
|
if 'A' <= s[i] && s[i] <= 'Z' {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// absDomainName returns an absolute domain name which ends with a
|
||||||
|
// trailing dot to match pure Go reverse resolver and all other lookup
|
||||||
|
// routines.
|
||||||
|
// See golang.org/issue/12189.
|
||||||
|
// But we don't want to add dots for local names from /etc/hosts.
|
||||||
|
// It's hard to tell so we settle on the heuristic that names without dots
|
||||||
|
// (like "localhost" or "myhost") do not get trailing dots, but any other
|
||||||
|
// names do.
|
||||||
|
func absDomainName(s string) string {
|
||||||
|
if strings.IndexByte(s, '.') != -1 && s[len(s)-1] != '.' {
|
||||||
|
s += "."
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
13
component/resolver/hosts/hosts_windows.go
Normal file
13
component/resolver/hosts/hosts_windows.go
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
package hosts
|
||||||
|
|
||||||
|
// this file copy and modify from golang's std net/hook_windows.go
|
||||||
|
|
||||||
|
import (
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
if dir, err := windows.GetSystemDirectory(); err == nil {
|
||||||
|
hostsFilePath = dir + "/Drivers/etc/hosts"
|
||||||
|
}
|
||||||
|
}
|
||||||
96
component/resolver/relay.go
Normal file
96
component/resolver/relay.go
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
package resolver
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/binary"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/common/pool"
|
||||||
|
|
||||||
|
D "github.com/miekg/dns"
|
||||||
|
)
|
||||||
|
|
||||||
|
const DefaultDnsReadTimeout = time.Second * 10
|
||||||
|
const DefaultDnsRelayTimeout = time.Second * 5
|
||||||
|
|
||||||
|
const SafeDnsPacketSize = 2 * 1024 // safe size which is 1232 from https://dnsflagday.net/2020/, so 2048 is enough
|
||||||
|
|
||||||
|
func RelayDnsConn(ctx context.Context, conn net.Conn, readTimeout time.Duration) error {
|
||||||
|
buff := pool.Get(pool.UDPBufferSize)
|
||||||
|
defer func() {
|
||||||
|
_ = pool.Put(buff)
|
||||||
|
_ = conn.Close()
|
||||||
|
}()
|
||||||
|
for {
|
||||||
|
if readTimeout > 0 {
|
||||||
|
_ = conn.SetReadDeadline(time.Now().Add(readTimeout))
|
||||||
|
}
|
||||||
|
|
||||||
|
length := uint16(0)
|
||||||
|
if err := binary.Read(conn, binary.BigEndian, &length); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if int(length) > len(buff) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := io.ReadFull(conn, buff[:length])
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
err = func() error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, DefaultDnsRelayTimeout)
|
||||||
|
defer cancel()
|
||||||
|
inData := buff[:n]
|
||||||
|
msg, err := relayDnsPacket(ctx, inData, buff, 0)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = binary.Write(conn, binary.BigEndian, uint16(len(msg)))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = conn.Write(msg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func relayDnsPacket(ctx context.Context, payload []byte, target []byte, maxSize int) ([]byte, error) {
|
||||||
|
msg := &D.Msg{}
|
||||||
|
if err := msg.Unpack(payload); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
r, err := ServeMsg(ctx, msg)
|
||||||
|
if err != nil {
|
||||||
|
m := new(D.Msg)
|
||||||
|
m.SetRcode(msg, D.RcodeServerFailure)
|
||||||
|
return m.PackBuffer(target)
|
||||||
|
}
|
||||||
|
|
||||||
|
r.SetRcode(msg, r.Rcode)
|
||||||
|
if maxSize > 0 {
|
||||||
|
r.Truncate(maxSize)
|
||||||
|
}
|
||||||
|
r.Compress = true
|
||||||
|
return r.PackBuffer(target)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RelayDnsPacket will truncate udp message up to SafeDnsPacketSize
|
||||||
|
func RelayDnsPacket(ctx context.Context, payload []byte, target []byte) ([]byte, error) {
|
||||||
|
return relayDnsPacket(ctx, payload, target, SafeDnsPacketSize)
|
||||||
|
}
|
||||||
@@ -12,8 +12,8 @@ import (
|
|||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/trie"
|
"github.com/metacubex/mihomo/component/trie"
|
||||||
|
|
||||||
|
"github.com/metacubex/randv2"
|
||||||
"github.com/miekg/dns"
|
"github.com/miekg/dns"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -93,7 +93,7 @@ func ResolveIPv4WithResolver(ctx context.Context, host string, r Resolver) (neti
|
|||||||
} else if len(ips) == 0 {
|
} else if len(ips) == 0 {
|
||||||
return netip.Addr{}, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
return netip.Addr{}, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
||||||
}
|
}
|
||||||
return ips[fastrand.Intn(len(ips))], nil
|
return ips[randv2.IntN(len(ips))], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIPv4 with a host, return ipv4
|
// ResolveIPv4 with a host, return ipv4
|
||||||
@@ -149,7 +149,7 @@ func ResolveIPv6WithResolver(ctx context.Context, host string, r Resolver) (neti
|
|||||||
} else if len(ips) == 0 {
|
} else if len(ips) == 0 {
|
||||||
return netip.Addr{}, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
return netip.Addr{}, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
||||||
}
|
}
|
||||||
return ips[fastrand.Intn(len(ips))], nil
|
return ips[randv2.IntN(len(ips))], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ResolveIPv6(ctx context.Context, host string) (netip.Addr, error) {
|
func ResolveIPv6(ctx context.Context, host string) (netip.Addr, error) {
|
||||||
@@ -200,9 +200,9 @@ func ResolveIPWithResolver(ctx context.Context, host string, r Resolver) (netip.
|
|||||||
}
|
}
|
||||||
ipv4s, ipv6s := SortationAddr(ips)
|
ipv4s, ipv6s := SortationAddr(ips)
|
||||||
if len(ipv4s) > 0 {
|
if len(ipv4s) > 0 {
|
||||||
return ipv4s[fastrand.Intn(len(ipv4s))], nil
|
return ipv4s[randv2.IntN(len(ipv4s))], nil
|
||||||
}
|
}
|
||||||
return ipv6s[fastrand.Intn(len(ipv6s))], nil
|
return ipv6s[randv2.IntN(len(ipv6s))], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIP with a host, return ip and priority return TypeA
|
// ResolveIP with a host, return ip and priority return TypeA
|
||||||
@@ -213,11 +213,7 @@ func ResolveIP(ctx context.Context, host string) (netip.Addr, error) {
|
|||||||
// ResolveIPv4ProxyServerHost proxies server host only
|
// ResolveIPv4ProxyServerHost proxies server host only
|
||||||
func ResolveIPv4ProxyServerHost(ctx context.Context, host string) (netip.Addr, error) {
|
func ResolveIPv4ProxyServerHost(ctx context.Context, host string) (netip.Addr, error) {
|
||||||
if ProxyServerHostResolver != nil {
|
if ProxyServerHostResolver != nil {
|
||||||
if ip, err := ResolveIPv4WithResolver(ctx, host, ProxyServerHostResolver); err != nil {
|
return ResolveIPv4WithResolver(ctx, host, ProxyServerHostResolver)
|
||||||
return ResolveIPv4(ctx, host)
|
|
||||||
} else {
|
|
||||||
return ip, nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return ResolveIPv4(ctx, host)
|
return ResolveIPv4(ctx, host)
|
||||||
}
|
}
|
||||||
@@ -225,11 +221,7 @@ func ResolveIPv4ProxyServerHost(ctx context.Context, host string) (netip.Addr, e
|
|||||||
// ResolveIPv6ProxyServerHost proxies server host only
|
// ResolveIPv6ProxyServerHost proxies server host only
|
||||||
func ResolveIPv6ProxyServerHost(ctx context.Context, host string) (netip.Addr, error) {
|
func ResolveIPv6ProxyServerHost(ctx context.Context, host string) (netip.Addr, error) {
|
||||||
if ProxyServerHostResolver != nil {
|
if ProxyServerHostResolver != nil {
|
||||||
if ip, err := ResolveIPv6WithResolver(ctx, host, ProxyServerHostResolver); err != nil {
|
return ResolveIPv6WithResolver(ctx, host, ProxyServerHostResolver)
|
||||||
return ResolveIPv6(ctx, host)
|
|
||||||
} else {
|
|
||||||
return ip, nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return ResolveIPv6(ctx, host)
|
return ResolveIPv6(ctx, host)
|
||||||
}
|
}
|
||||||
@@ -237,11 +229,7 @@ func ResolveIPv6ProxyServerHost(ctx context.Context, host string) (netip.Addr, e
|
|||||||
// ResolveProxyServerHost proxies server host only
|
// ResolveProxyServerHost proxies server host only
|
||||||
func ResolveProxyServerHost(ctx context.Context, host string) (netip.Addr, error) {
|
func ResolveProxyServerHost(ctx context.Context, host string) (netip.Addr, error) {
|
||||||
if ProxyServerHostResolver != nil {
|
if ProxyServerHostResolver != nil {
|
||||||
if ip, err := ResolveIPWithResolver(ctx, host, ProxyServerHostResolver); err != nil {
|
return ResolveIPWithResolver(ctx, host, ProxyServerHostResolver)
|
||||||
return ResolveIP(ctx, host)
|
|
||||||
} else {
|
|
||||||
return ip, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return ResolveIP(ctx, host)
|
return ResolveIP(ctx, host)
|
||||||
}
|
}
|
||||||
|
|||||||
39
component/resolver/system.go
Normal file
39
component/resolver/system.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package resolver
|
||||||
|
|
||||||
|
import "sync"
|
||||||
|
|
||||||
|
var blacklist struct {
|
||||||
|
Map map[string]struct{}
|
||||||
|
Mutex sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
blacklist.Map = make(map[string]struct{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddSystemDnsBlacklist(names ...string) {
|
||||||
|
blacklist.Mutex.Lock()
|
||||||
|
defer blacklist.Mutex.Unlock()
|
||||||
|
for _, name := range names {
|
||||||
|
blacklist.Map[name] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func RemoveSystemDnsBlacklist(names ...string) {
|
||||||
|
blacklist.Mutex.Lock()
|
||||||
|
defer blacklist.Mutex.Unlock()
|
||||||
|
for _, name := range names {
|
||||||
|
delete(blacklist.Map, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsSystemDnsBlacklisted(names ...string) bool {
|
||||||
|
blacklist.Mutex.Lock()
|
||||||
|
defer blacklist.Mutex.Unlock()
|
||||||
|
for _, name := range names {
|
||||||
|
if _, ok := blacklist.Map[name]; ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -28,13 +28,19 @@ func (f *FileVehicle) Read() ([]byte, error) {
|
|||||||
return os.ReadFile(f.path)
|
return os.ReadFile(f.path)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Proxy() string {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
func NewFileVehicle(path string) *FileVehicle {
|
func NewFileVehicle(path string) *FileVehicle {
|
||||||
return &FileVehicle{path: path}
|
return &FileVehicle{path: path}
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPVehicle struct {
|
type HTTPVehicle struct {
|
||||||
url string
|
url string
|
||||||
path string
|
path string
|
||||||
|
proxy string
|
||||||
|
header http.Header
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *HTTPVehicle) Url() string {
|
func (h *HTTPVehicle) Url() string {
|
||||||
@@ -49,10 +55,14 @@ func (h *HTTPVehicle) Path() string {
|
|||||||
return h.path
|
return h.path
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Proxy() string {
|
||||||
|
return h.proxy
|
||||||
|
}
|
||||||
|
|
||||||
func (h *HTTPVehicle) Read() ([]byte, error) {
|
func (h *HTTPVehicle) Read() ([]byte, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
resp, err := mihomoHttp.HttpRequest(ctx, h.url, http.MethodGet, nil, nil)
|
resp, err := mihomoHttp.HttpRequestWithProxy(ctx, h.url, http.MethodGet, h.header, nil, h.proxy)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -67,6 +77,6 @@ func (h *HTTPVehicle) Read() ([]byte, error) {
|
|||||||
return buf, nil
|
return buf, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHTTPVehicle(url string, path string) *HTTPVehicle {
|
func NewHTTPVehicle(url string, path string, proxy string, header http.Header) *HTTPVehicle {
|
||||||
return &HTTPVehicle{url, path}
|
return &HTTPVehicle{url, path, proxy, header}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,8 +12,10 @@ type SlowDown struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *SlowDown) Wait(ctx context.Context) (err error) {
|
func (s *SlowDown) Wait(ctx context.Context) (err error) {
|
||||||
|
timer := time.NewTimer(s.backoff.Duration())
|
||||||
|
defer timer.Stop()
|
||||||
select {
|
select {
|
||||||
case <-time.After(s.backoff.Duration()):
|
case <-timer.C:
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
err = ctx.Err()
|
err = ctx.Err()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -116,14 +116,13 @@ func (sd *SnifferDispatcher) TCPSniff(conn *N.BufferedConn, metadata *C.Metadata
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (sd *SnifferDispatcher) replaceDomain(metadata *C.Metadata, host string, overrideDest bool) {
|
func (sd *SnifferDispatcher) replaceDomain(metadata *C.Metadata, host string, overrideDest bool) {
|
||||||
// show log early, since the following code may mutate `metadata.Host`
|
|
||||||
log.Debugln("[Sniffer] Sniff %s [%s]-->[%s] success, replace domain [%s]-->[%s]",
|
|
||||||
metadata.NetWork,
|
|
||||||
metadata.SourceDetail(),
|
|
||||||
metadata.RemoteAddress(),
|
|
||||||
metadata.Host, host)
|
|
||||||
metadata.SniffHost = host
|
metadata.SniffHost = host
|
||||||
if overrideDest {
|
if overrideDest {
|
||||||
|
log.Debugln("[Sniffer] Sniff %s [%s]-->[%s] success, replace domain [%s]-->[%s]",
|
||||||
|
metadata.NetWork,
|
||||||
|
metadata.SourceDetail(),
|
||||||
|
metadata.RemoteAddress(),
|
||||||
|
metadata.Host, host)
|
||||||
metadata.Host = host
|
metadata.Host = host
|
||||||
}
|
}
|
||||||
metadata.DNSMode = C.DNSNormal
|
metadata.DNSMode = C.DNSNormal
|
||||||
|
|||||||
@@ -16,17 +16,14 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"reflect"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
"unsafe"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
"github.com/metacubex/mihomo/ntp"
|
"github.com/metacubex/mihomo/ntp"
|
||||||
|
|
||||||
utls "github.com/sagernet/utls"
|
"github.com/metacubex/randv2"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
utls "github.com/metacubex/utls"
|
||||||
"golang.org/x/crypto/chacha20poly1305"
|
"golang.org/x/crypto/chacha20poly1305"
|
||||||
"golang.org/x/crypto/hkdf"
|
"golang.org/x/crypto/hkdf"
|
||||||
"golang.org/x/net/http2"
|
"golang.org/x/net/http2"
|
||||||
@@ -39,9 +36,6 @@ type RealityConfig struct {
|
|||||||
ShortID [RealityMaxShortIDLen]byte
|
ShortID [RealityMaxShortIDLen]byte
|
||||||
}
|
}
|
||||||
|
|
||||||
//go:linkname aesgcmPreferred crypto/tls.aesgcmPreferred
|
|
||||||
func aesgcmPreferred(ciphers []uint16) bool
|
|
||||||
|
|
||||||
func GetRealityConn(ctx context.Context, conn net.Conn, ClientFingerprint string, tlsConfig *tls.Config, realityConfig *RealityConfig) (net.Conn, error) {
|
func GetRealityConn(ctx context.Context, conn net.Conn, ClientFingerprint string, tlsConfig *tls.Config, realityConfig *RealityConfig) (net.Conn, error) {
|
||||||
retry := 0
|
retry := 0
|
||||||
for fingerprint, exists := GetFingerprint(ClientFingerprint); exists; retry++ {
|
for fingerprint, exists := GetFingerprint(ClientFingerprint); exists; retry++ {
|
||||||
@@ -102,7 +96,7 @@ func GetRealityConn(ctx context.Context, conn net.Conn, ClientFingerprint string
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
var aeadCipher cipher.AEAD
|
var aeadCipher cipher.AEAD
|
||||||
if aesgcmPreferred(hello.CipherSuites) {
|
if utls.AesgcmPreferred(hello.CipherSuites) {
|
||||||
aesBlock, _ := aes.NewCipher(authKey)
|
aesBlock, _ := aes.NewCipher(authKey)
|
||||||
aeadCipher, _ = cipher.NewGCM(aesBlock)
|
aeadCipher, _ = cipher.NewGCM(aesBlock)
|
||||||
} else {
|
} else {
|
||||||
@@ -139,15 +133,18 @@ func realityClientFallback(uConn net.Conn, serverName string, fingerprint utls.C
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
request, _ := http.NewRequest("GET", "https://"+serverName, nil)
|
request, err := http.NewRequest("GET", "https://"+serverName, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
request.Header.Set("User-Agent", fingerprint.Client)
|
request.Header.Set("User-Agent", fingerprint.Client)
|
||||||
request.AddCookie(&http.Cookie{Name: "padding", Value: strings.Repeat("0", fastrand.Intn(32)+30)})
|
request.AddCookie(&http.Cookie{Name: "padding", Value: strings.Repeat("0", randv2.IntN(32)+30)})
|
||||||
response, err := client.Do(request)
|
response, err := client.Do(request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
//_, _ = io.Copy(io.Discard, response.Body)
|
//_, _ = io.Copy(io.Discard, response.Body)
|
||||||
time.Sleep(time.Duration(5+fastrand.Int63n(10)) * time.Second)
|
time.Sleep(time.Duration(5+randv2.IntN(10)) * time.Second)
|
||||||
response.Body.Close()
|
response.Body.Close()
|
||||||
client.CloseIdleConnections()
|
client.CloseIdleConnections()
|
||||||
}
|
}
|
||||||
@@ -159,11 +156,12 @@ type realityVerifier struct {
|
|||||||
verified bool
|
verified bool
|
||||||
}
|
}
|
||||||
|
|
||||||
var pOffset = utils.MustOK(reflect.TypeOf((*utls.Conn)(nil)).Elem().FieldByName("peerCertificates")).Offset
|
//var pOffset = utils.MustOK(reflect.TypeOf((*utls.Conn)(nil)).Elem().FieldByName("peerCertificates")).Offset
|
||||||
|
|
||||||
func (c *realityVerifier) VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
func (c *realityVerifier) VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||||
//p, _ := reflect.TypeOf(c.Conn).Elem().FieldByName("peerCertificates")
|
//p, _ := reflect.TypeOf(c.Conn).Elem().FieldByName("peerCertificates")
|
||||||
certs := *(*[]*x509.Certificate)(unsafe.Add(unsafe.Pointer(c.Conn), pOffset))
|
//certs := *(*[]*x509.Certificate)(unsafe.Add(unsafe.Pointer(c.Conn), pOffset))
|
||||||
|
certs := c.Conn.PeerCertificates()
|
||||||
if pub, ok := certs[0].PublicKey.(ed25519.PublicKey); ok {
|
if pub, ok := certs[0].PublicKey.(ed25519.PublicKey); ok {
|
||||||
h := hmac.New(sha512.New, c.authKey)
|
h := hmac.New(sha512.New, c.authKey)
|
||||||
h.Write(pub)
|
h.Write(pub)
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import (
|
|||||||
|
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
|
utls "github.com/metacubex/utls"
|
||||||
"github.com/mroth/weightedrand/v2"
|
"github.com/mroth/weightedrand/v2"
|
||||||
utls "github.com/sagernet/utls"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type UConn struct {
|
type UConn struct {
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
mihomoHttp "github.com/metacubex/mihomo/component/http"
|
mihomoHttp "github.com/metacubex/mihomo/component/http"
|
||||||
"github.com/metacubex/mihomo/constant"
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
@@ -52,6 +51,10 @@ func init() {
|
|||||||
if runtime.GOARCH == "amd64" && cpuid.CPU.X64Level() < 3 {
|
if runtime.GOARCH == "amd64" && cpuid.CPU.X64Level() < 3 {
|
||||||
amd64Compatible = "-compatible"
|
amd64Compatible = "-compatible"
|
||||||
}
|
}
|
||||||
|
if !strings.HasPrefix(C.Version, "alpha") {
|
||||||
|
baseURL = "https://github.com/MetaCubeX/mihomo/releases/latest/download/mihomo"
|
||||||
|
versionURL = "https://github.com/MetaCubeX/mihomo/releases/latest/download/version.txt"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type updateError struct {
|
type updateError struct {
|
||||||
@@ -64,7 +67,7 @@ func (e *updateError) Error() string {
|
|||||||
|
|
||||||
// Update performs the auto-updater. It returns an error if the updater failed.
|
// Update performs the auto-updater. It returns an error if the updater failed.
|
||||||
// If firstRun is true, it assumes the configuration file doesn't exist.
|
// If firstRun is true, it assumes the configuration file doesn't exist.
|
||||||
func Update(execPath string) (err error) {
|
func UpdateCore(execPath string) (err error) {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock()
|
||||||
|
|
||||||
@@ -73,9 +76,9 @@ func Update(execPath string) (err error) {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Infoln("current version %s, latest version %s", constant.Version, latestVersion)
|
log.Infoln("current version %s, latest version %s", C.Version, latestVersion)
|
||||||
|
|
||||||
if latestVersion == constant.Version {
|
if latestVersion == C.Version {
|
||||||
err := &updateError{Message: "already using latest version"}
|
err := &updateError{Message: "already using latest version"}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -137,6 +140,8 @@ func prepare(exePath string) (err error) {
|
|||||||
|
|
||||||
if runtime.GOOS == "windows" {
|
if runtime.GOOS == "windows" {
|
||||||
updateExeName = "mihomo" + "-" + runtime.GOOS + "-" + runtime.GOARCH + amd64Compatible + ".exe"
|
updateExeName = "mihomo" + "-" + runtime.GOOS + "-" + runtime.GOARCH + amd64Compatible + ".exe"
|
||||||
|
} else if runtime.GOOS == "android" && runtime.GOARCH == "arm64" {
|
||||||
|
updateExeName = "mihomo-android-arm64-v8"
|
||||||
} else {
|
} else {
|
||||||
updateExeName = "mihomo" + "-" + runtime.GOOS + "-" + runtime.GOARCH + amd64Compatible
|
updateExeName = "mihomo" + "-" + runtime.GOOS + "-" + runtime.GOARCH + amd64Compatible
|
||||||
}
|
}
|
||||||
@@ -440,7 +445,11 @@ func updateDownloadURL() {
|
|||||||
middle = fmt.Sprintf("-%s-%s%s-%s", runtime.GOOS, runtime.GOARCH, goarm, latestVersion)
|
middle = fmt.Sprintf("-%s-%s%s-%s", runtime.GOOS, runtime.GOARCH, goarm, latestVersion)
|
||||||
} else if runtime.GOARCH == "arm64" {
|
} else if runtime.GOARCH == "arm64" {
|
||||||
//-linux-arm64-alpha-e552b54.gz
|
//-linux-arm64-alpha-e552b54.gz
|
||||||
middle = fmt.Sprintf("-%s-%s-%s", runtime.GOOS, runtime.GOARCH, latestVersion)
|
if runtime.GOOS == "android" {
|
||||||
|
middle = fmt.Sprintf("-%s-%s-v8-%s", runtime.GOOS, runtime.GOARCH, latestVersion)
|
||||||
|
} else {
|
||||||
|
middle = fmt.Sprintf("-%s-%s-%s", runtime.GOOS, runtime.GOARCH, latestVersion)
|
||||||
|
}
|
||||||
} else if isMIPS(runtime.GOARCH) && gomips != "" {
|
} else if isMIPS(runtime.GOARCH) && gomips != "" {
|
||||||
middle = fmt.Sprintf("-%s-%s-%s-%s", runtime.GOOS, runtime.GOARCH, gomips, latestVersion)
|
middle = fmt.Sprintf("-%s-%s-%s-%s", runtime.GOOS, runtime.GOARCH, gomips, latestVersion)
|
||||||
} else {
|
} else {
|
||||||
176
component/updater/update_geo.go
Normal file
176
component/updater/update_geo.go
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
package updater
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
|
"github.com/metacubex/mihomo/component/geodata"
|
||||||
|
_ "github.com/metacubex/mihomo/component/geodata/standard"
|
||||||
|
"github.com/metacubex/mihomo/component/mmdb"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
|
"github.com/oschwald/maxminddb-golang"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
UpdatingGeo atomic.Bool
|
||||||
|
)
|
||||||
|
|
||||||
|
func updateGeoDatabases() error {
|
||||||
|
defer runtime.GC()
|
||||||
|
geoLoader, err := geodata.GetGeoDataLoader("standard")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if C.GeodataMode {
|
||||||
|
data, err := downloadForBytes(C.GeoIpUrl)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoIP database file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err = geoLoader.LoadIPByBytes(data, "cn"); err != nil {
|
||||||
|
return fmt.Errorf("invalid GeoIP database file: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = saveFile(data, C.Path.GeoIP()); err != nil {
|
||||||
|
return fmt.Errorf("can't save GeoIP database file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
defer mmdb.ReloadIP()
|
||||||
|
data, err := downloadForBytes(C.MmdbUrl)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("can't download MMDB database file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
instance, err := maxminddb.FromBytes(data)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid MMDB database file: %s", err)
|
||||||
|
}
|
||||||
|
_ = instance.Close()
|
||||||
|
|
||||||
|
mmdb.IPInstance().Reader.Close() // mmdb is loaded with mmap, so it needs to be closed before overwriting the file
|
||||||
|
if err = saveFile(data, C.Path.MMDB()); err != nil {
|
||||||
|
return fmt.Errorf("can't save MMDB database file: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if C.ASNEnable {
|
||||||
|
defer mmdb.ReloadASN()
|
||||||
|
data, err := downloadForBytes(C.ASNUrl)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("can't download ASN database file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
instance, err := maxminddb.FromBytes(data)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid ASN database file: %s", err)
|
||||||
|
}
|
||||||
|
_ = instance.Close()
|
||||||
|
|
||||||
|
mmdb.ASNInstance().Reader.Close()
|
||||||
|
if err = saveFile(data, C.Path.ASN()); err != nil {
|
||||||
|
return fmt.Errorf("can't save ASN database file: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := downloadForBytes(C.GeoSiteUrl)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoSite database file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err = geoLoader.LoadSiteByBytes(data, "cn"); err != nil {
|
||||||
|
return fmt.Errorf("invalid GeoSite database file: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = saveFile(data, C.Path.GeoSite()); err != nil {
|
||||||
|
return fmt.Errorf("can't save GeoSite database file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
geodata.ClearCache()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var ErrGetDatabaseUpdateSkip = errors.New("GEO database is updating, skip")
|
||||||
|
|
||||||
|
func UpdateGeoDatabases() error {
|
||||||
|
log.Infoln("[GEO] Start updating GEO database")
|
||||||
|
|
||||||
|
if UpdatingGeo.Load() {
|
||||||
|
return ErrGetDatabaseUpdateSkip
|
||||||
|
}
|
||||||
|
|
||||||
|
UpdatingGeo.Store(true)
|
||||||
|
defer UpdatingGeo.Store(false)
|
||||||
|
|
||||||
|
log.Infoln("[GEO] Updating GEO database")
|
||||||
|
|
||||||
|
if err := updateGeoDatabases(); err != nil {
|
||||||
|
log.Errorln("[GEO] update GEO database error: %s", err.Error())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getUpdateTime() (err error, time time.Time) {
|
||||||
|
var fileInfo os.FileInfo
|
||||||
|
if C.GeodataMode {
|
||||||
|
fileInfo, err = os.Stat(C.Path.GeoIP())
|
||||||
|
if err != nil {
|
||||||
|
return err, time
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fileInfo, err = os.Stat(C.Path.MMDB())
|
||||||
|
if err != nil {
|
||||||
|
return err, time
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, fileInfo.ModTime()
|
||||||
|
}
|
||||||
|
|
||||||
|
func RegisterGeoUpdater(onSuccess func()) {
|
||||||
|
if C.GeoUpdateInterval <= 0 {
|
||||||
|
log.Errorln("[GEO] Invalid update interval: %d", C.GeoUpdateInterval)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
ticker := time.NewTicker(time.Duration(C.GeoUpdateInterval) * time.Hour)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
err, lastUpdate := getUpdateTime()
|
||||||
|
if err != nil {
|
||||||
|
log.Errorln("[GEO] Get GEO database update time error: %s", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Infoln("[GEO] last update time %s", lastUpdate)
|
||||||
|
if lastUpdate.Add(time.Duration(C.GeoUpdateInterval) * time.Hour).Before(time.Now()) {
|
||||||
|
log.Infoln("[GEO] Database has not been updated for %v, update now", time.Duration(C.GeoUpdateInterval)*time.Hour)
|
||||||
|
if err := UpdateGeoDatabases(); err != nil {
|
||||||
|
log.Errorln("[GEO] Failed to update GEO database: %s", err.Error())
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
onSuccess()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for range ticker.C {
|
||||||
|
log.Infoln("[GEO] updating database every %d hours", C.GeoUpdateInterval)
|
||||||
|
if err := UpdateGeoDatabases(); err != nil {
|
||||||
|
log.Errorln("[GEO] Failed to update GEO database: %s", err.Error())
|
||||||
|
} else {
|
||||||
|
onSuccess()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package config
|
package updater
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"archive/zip"
|
"archive/zip"
|
||||||
@@ -29,7 +29,7 @@ func UpdateUI() error {
|
|||||||
xdMutex.Lock()
|
xdMutex.Lock()
|
||||||
defer xdMutex.Unlock()
|
defer xdMutex.Unlock()
|
||||||
|
|
||||||
err := prepare()
|
err := prepare_ui()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -64,7 +64,7 @@ func UpdateUI() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func prepare() error {
|
func prepare_ui() error {
|
||||||
if ExternalUIPath == "" || ExternalUIURL == "" {
|
if ExternalUIPath == "" || ExternalUIURL == "" {
|
||||||
return ErrIncompleteConf
|
return ErrIncompleteConf
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,35 @@
|
|||||||
package updater
|
package updater
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
mihomoHttp "github.com/metacubex/mihomo/component/http"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
|
||||||
"golang.org/x/exp/constraints"
|
"golang.org/x/exp/constraints"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func downloadForBytes(url string) ([]byte, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
||||||
|
defer cancel()
|
||||||
|
resp, err := mihomoHttp.HttpRequest(ctx, url, http.MethodGet, http.Header{"User-Agent": {C.UA}}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
return io.ReadAll(resp.Body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func saveFile(bytes []byte, path string) error {
|
||||||
|
return os.WriteFile(path, bytes, 0o644)
|
||||||
|
}
|
||||||
|
|
||||||
// LimitReachedError records the limit and the operation that caused it.
|
// LimitReachedError records the limit and the operation that caused it.
|
||||||
type LimitReachedError struct {
|
type LimitReachedError struct {
|
||||||
Limit int64
|
Limit int64
|
||||||
256
config/config.go
256
config/config.go
@@ -28,6 +28,7 @@ import (
|
|||||||
SNIFF "github.com/metacubex/mihomo/component/sniffer"
|
SNIFF "github.com/metacubex/mihomo/component/sniffer"
|
||||||
tlsC "github.com/metacubex/mihomo/component/tls"
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
"github.com/metacubex/mihomo/component/trie"
|
"github.com/metacubex/mihomo/component/trie"
|
||||||
|
"github.com/metacubex/mihomo/component/updater"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/constant/features"
|
"github.com/metacubex/mihomo/constant/features"
|
||||||
providerTypes "github.com/metacubex/mihomo/constant/provider"
|
providerTypes "github.com/metacubex/mihomo/constant/provider"
|
||||||
@@ -91,10 +92,11 @@ type Inbound struct {
|
|||||||
|
|
||||||
// Controller config
|
// Controller config
|
||||||
type Controller struct {
|
type Controller struct {
|
||||||
ExternalController string `json:"-"`
|
ExternalController string `json:"-"`
|
||||||
ExternalControllerTLS string `json:"-"`
|
ExternalControllerTLS string `json:"-"`
|
||||||
ExternalUI string `json:"-"`
|
ExternalControllerUnix string `json:"-"`
|
||||||
Secret string `json:"-"`
|
ExternalUI string `json:"-"`
|
||||||
|
Secret string `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NTP config
|
// NTP config
|
||||||
@@ -113,6 +115,7 @@ type DNS struct {
|
|||||||
PreferH3 bool `yaml:"prefer-h3"`
|
PreferH3 bool `yaml:"prefer-h3"`
|
||||||
IPv6 bool `yaml:"ipv6"`
|
IPv6 bool `yaml:"ipv6"`
|
||||||
IPv6Timeout uint `yaml:"ipv6-timeout"`
|
IPv6Timeout uint `yaml:"ipv6-timeout"`
|
||||||
|
UseSystemHosts bool `yaml:"use-system-hosts"`
|
||||||
NameServer []dns.NameServer `yaml:"nameserver"`
|
NameServer []dns.NameServer `yaml:"nameserver"`
|
||||||
Fallback []dns.NameServer `yaml:"fallback"`
|
Fallback []dns.NameServer `yaml:"fallback"`
|
||||||
FallbackFilter FallbackFilter `yaml:"fallback-filter"`
|
FallbackFilter FallbackFilter `yaml:"fallback-filter"`
|
||||||
@@ -152,6 +155,7 @@ type IPTables struct {
|
|||||||
Enable bool `yaml:"enable" json:"enable"`
|
Enable bool `yaml:"enable" json:"enable"`
|
||||||
InboundInterface string `yaml:"inbound-interface" json:"inbound-interface"`
|
InboundInterface string `yaml:"inbound-interface" json:"inbound-interface"`
|
||||||
Bypass []string `yaml:"bypass" json:"bypass"`
|
Bypass []string `yaml:"bypass" json:"bypass"`
|
||||||
|
DnsRedirect bool `yaml:"dns-redirect" json:"dns-redirect"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Sniffer struct {
|
type Sniffer struct {
|
||||||
@@ -168,6 +172,7 @@ type Experimental struct {
|
|||||||
Fingerprints []string `yaml:"fingerprints"`
|
Fingerprints []string `yaml:"fingerprints"`
|
||||||
QUICGoDisableGSO bool `yaml:"quic-go-disable-gso"`
|
QUICGoDisableGSO bool `yaml:"quic-go-disable-gso"`
|
||||||
QUICGoDisableECN bool `yaml:"quic-go-disable-ecn"`
|
QUICGoDisableECN bool `yaml:"quic-go-disable-ecn"`
|
||||||
|
IP4PEnable bool `yaml:"dialer-ip4p-convert"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Config is mihomo config manager
|
// Config is mihomo config manager
|
||||||
@@ -206,6 +211,8 @@ type RawDNS struct {
|
|||||||
IPv6 bool `yaml:"ipv6" json:"ipv6"`
|
IPv6 bool `yaml:"ipv6" json:"ipv6"`
|
||||||
IPv6Timeout uint `yaml:"ipv6-timeout" json:"ipv6-timeout"`
|
IPv6Timeout uint `yaml:"ipv6-timeout" json:"ipv6-timeout"`
|
||||||
UseHosts bool `yaml:"use-hosts" json:"use-hosts"`
|
UseHosts bool `yaml:"use-hosts" json:"use-hosts"`
|
||||||
|
UseSystemHosts bool `yaml:"use-system-hosts" json:"use-system-hosts"`
|
||||||
|
RespectRules bool `yaml:"respect-rules" json:"respect-rules"`
|
||||||
NameServer []string `yaml:"nameserver" json:"nameserver"`
|
NameServer []string `yaml:"nameserver" json:"nameserver"`
|
||||||
Fallback []string `yaml:"fallback" json:"fallback"`
|
Fallback []string `yaml:"fallback" json:"fallback"`
|
||||||
FallbackFilter RawFallbackFilter `yaml:"fallback-filter" json:"fallback-filter"`
|
FallbackFilter RawFallbackFilter `yaml:"fallback-filter" json:"fallback-filter"`
|
||||||
@@ -239,30 +246,39 @@ type RawTun struct {
|
|||||||
DNSHijack []string `yaml:"dns-hijack" json:"dns-hijack"`
|
DNSHijack []string `yaml:"dns-hijack" json:"dns-hijack"`
|
||||||
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
||||||
AutoDetectInterface bool `yaml:"auto-detect-interface"`
|
AutoDetectInterface bool `yaml:"auto-detect-interface"`
|
||||||
RedirectToTun []string `yaml:"-" json:"-"`
|
|
||||||
|
|
||||||
MTU uint32 `yaml:"mtu" json:"mtu,omitempty"`
|
MTU uint32 `yaml:"mtu" json:"mtu,omitempty"`
|
||||||
GSO bool `yaml:"gso" json:"gso,omitempty"`
|
GSO bool `yaml:"gso" json:"gso,omitempty"`
|
||||||
GSOMaxSize uint32 `yaml:"gso-max-size" json:"gso-max-size,omitempty"`
|
GSOMaxSize uint32 `yaml:"gso-max-size" json:"gso-max-size,omitempty"`
|
||||||
//Inet4Address []netip.Prefix `yaml:"inet4-address" json:"inet4_address,omitempty"`
|
//Inet4Address []netip.Prefix `yaml:"inet4-address" json:"inet4_address,omitempty"`
|
||||||
Inet6Address []netip.Prefix `yaml:"inet6-address" json:"inet6_address,omitempty"`
|
Inet6Address []netip.Prefix `yaml:"inet6-address" json:"inet6_address,omitempty"`
|
||||||
StrictRoute bool `yaml:"strict-route" json:"strict_route,omitempty"`
|
IPRoute2TableIndex int `yaml:"iproute2-table-index" json:"iproute2_table_index,omitempty"`
|
||||||
|
IPRoute2RuleIndex int `yaml:"iproute2-rule-index" json:"iproute2_rule_index,omitempty"`
|
||||||
|
AutoRedirect bool `yaml:"auto-redirect" json:"auto_redirect,omitempty"`
|
||||||
|
AutoRedirectInputMark uint32 `yaml:"auto-redirect-input-mark" json:"auto_redirect_input_mark,omitempty"`
|
||||||
|
AutoRedirectOutputMark uint32 `yaml:"auto-redirect-output-mark" json:"auto_redirect_output_mark,omitempty"`
|
||||||
|
StrictRoute bool `yaml:"strict-route" json:"strict_route,omitempty"`
|
||||||
|
RouteAddress []netip.Prefix `yaml:"route-address" json:"route_address,omitempty"`
|
||||||
|
RouteAddressSet []string `yaml:"route-address-set" json:"route_address_set,omitempty"`
|
||||||
|
RouteExcludeAddress []netip.Prefix `yaml:"route-exclude-address" json:"route_exclude_address,omitempty"`
|
||||||
|
RouteExcludeAddressSet []string `yaml:"route-exclude-address-set" json:"route_exclude_address_set,omitempty"`
|
||||||
|
IncludeInterface []string `yaml:"include-interface" json:"include-interface,omitempty"`
|
||||||
|
ExcludeInterface []string `yaml:"exclude-interface" json:"exclude-interface,omitempty"`
|
||||||
|
IncludeUID []uint32 `yaml:"include-uid" json:"include_uid,omitempty"`
|
||||||
|
IncludeUIDRange []string `yaml:"include-uid-range" json:"include_uid_range,omitempty"`
|
||||||
|
ExcludeUID []uint32 `yaml:"exclude-uid" json:"exclude_uid,omitempty"`
|
||||||
|
ExcludeUIDRange []string `yaml:"exclude-uid-range" json:"exclude_uid_range,omitempty"`
|
||||||
|
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"`
|
||||||
|
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"`
|
||||||
|
|
||||||
Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4_route_address,omitempty"`
|
Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4_route_address,omitempty"`
|
||||||
Inet6RouteAddress []netip.Prefix `yaml:"inet6-route-address" json:"inet6_route_address,omitempty"`
|
Inet6RouteAddress []netip.Prefix `yaml:"inet6-route-address" json:"inet6_route_address,omitempty"`
|
||||||
Inet4RouteExcludeAddress []netip.Prefix `yaml:"inet4-route-exclude-address" json:"inet4_route_exclude_address,omitempty"`
|
Inet4RouteExcludeAddress []netip.Prefix `yaml:"inet4-route-exclude-address" json:"inet4_route_exclude_address,omitempty"`
|
||||||
Inet6RouteExcludeAddress []netip.Prefix `yaml:"inet6-route-exclude-address" json:"inet6_route_exclude_address,omitempty"`
|
Inet6RouteExcludeAddress []netip.Prefix `yaml:"inet6-route-exclude-address" json:"inet6_route_exclude_address,omitempty"`
|
||||||
IncludeInterface []string `yaml:"include-interface" json:"include-interface,omitempty"`
|
|
||||||
ExcludeInterface []string `yaml:"exclude-interface" json:"exclude-interface,omitempty"`
|
|
||||||
IncludeUID []uint32 `yaml:"include-uid" json:"include_uid,omitempty"`
|
|
||||||
IncludeUIDRange []string `yaml:"include-uid-range" json:"include_uid_range,omitempty"`
|
|
||||||
ExcludeUID []uint32 `yaml:"exclude-uid" json:"exclude_uid,omitempty"`
|
|
||||||
ExcludeUIDRange []string `yaml:"exclude-uid-range" json:"exclude_uid_range,omitempty"`
|
|
||||||
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"`
|
|
||||||
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"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type RawTuicServer struct {
|
type RawTuicServer struct {
|
||||||
@@ -301,6 +317,7 @@ type RawConfig struct {
|
|||||||
LogLevel log.LogLevel `yaml:"log-level" json:"log-level"`
|
LogLevel log.LogLevel `yaml:"log-level" json:"log-level"`
|
||||||
IPv6 bool `yaml:"ipv6" json:"ipv6"`
|
IPv6 bool `yaml:"ipv6" json:"ipv6"`
|
||||||
ExternalController string `yaml:"external-controller"`
|
ExternalController string `yaml:"external-controller"`
|
||||||
|
ExternalControllerUnix string `yaml:"external-controller-unix"`
|
||||||
ExternalControllerTLS string `yaml:"external-controller-tls"`
|
ExternalControllerTLS string `yaml:"external-controller-tls"`
|
||||||
ExternalUI string `yaml:"external-ui"`
|
ExternalUI string `yaml:"external-ui"`
|
||||||
ExternalUIURL string `yaml:"external-ui-url" json:"external-ui-url"`
|
ExternalUIURL string `yaml:"external-ui-url" json:"external-ui-url"`
|
||||||
@@ -346,6 +363,7 @@ type RawConfig struct {
|
|||||||
type GeoXUrl struct {
|
type GeoXUrl struct {
|
||||||
GeoIp string `yaml:"geoip" json:"geoip"`
|
GeoIp string `yaml:"geoip" json:"geoip"`
|
||||||
Mmdb string `yaml:"mmdb" json:"mmdb"`
|
Mmdb string `yaml:"mmdb" json:"mmdb"`
|
||||||
|
ASN string `yaml:"asn" json:"asn"`
|
||||||
GeoSite string `yaml:"geosite" json:"geosite"`
|
GeoSite string `yaml:"geosite" json:"geosite"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -409,7 +427,7 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
ProxyGroup: []map[string]any{},
|
ProxyGroup: []map[string]any{},
|
||||||
TCPConcurrent: false,
|
TCPConcurrent: false,
|
||||||
FindProcessMode: P.FindProcessStrict,
|
FindProcessMode: P.FindProcessStrict,
|
||||||
GlobalUA: "clash.meta",
|
GlobalUA: "clash.meta/" + C.Version,
|
||||||
Tun: RawTun{
|
Tun: RawTun{
|
||||||
Enable: false,
|
Enable: false,
|
||||||
Device: "",
|
Device: "",
|
||||||
@@ -440,6 +458,7 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
Enable: false,
|
Enable: false,
|
||||||
InboundInterface: "lo",
|
InboundInterface: "lo",
|
||||||
Bypass: []string{},
|
Bypass: []string{},
|
||||||
|
DnsRedirect: true,
|
||||||
},
|
},
|
||||||
NTP: RawNTP{
|
NTP: RawNTP{
|
||||||
Enable: false,
|
Enable: false,
|
||||||
@@ -449,12 +468,13 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
Interval: 30,
|
Interval: 30,
|
||||||
},
|
},
|
||||||
DNS: RawDNS{
|
DNS: RawDNS{
|
||||||
Enable: false,
|
Enable: false,
|
||||||
IPv6: false,
|
IPv6: false,
|
||||||
UseHosts: true,
|
UseHosts: true,
|
||||||
IPv6Timeout: 100,
|
UseSystemHosts: true,
|
||||||
EnhancedMode: C.DNSMapping,
|
IPv6Timeout: 100,
|
||||||
FakeIPRange: "198.18.0.1/16",
|
EnhancedMode: C.DNSMapping,
|
||||||
|
FakeIPRange: "198.18.0.1/16",
|
||||||
FallbackFilter: RawFallbackFilter{
|
FallbackFilter: RawFallbackFilter{
|
||||||
GeoIP: true,
|
GeoIP: true,
|
||||||
GeoIPCode: "CN",
|
GeoIPCode: "CN",
|
||||||
@@ -477,6 +497,11 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
"www.msftconnecttest.com",
|
"www.msftconnecttest.com",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
Experimental: Experimental{
|
||||||
|
// https://github.com/quic-go/quic-go/issues/4178
|
||||||
|
// Quic-go currently cannot automatically fall back on platforms that do not support ecn, so this feature is turned off by default.
|
||||||
|
QUICGoDisableECN: true,
|
||||||
|
},
|
||||||
Sniffer: RawSniffer{
|
Sniffer: RawSniffer{
|
||||||
Enable: false,
|
Enable: false,
|
||||||
Sniffing: []string{},
|
Sniffing: []string{},
|
||||||
@@ -492,6 +517,7 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
},
|
},
|
||||||
GeoXUrl: GeoXUrl{
|
GeoXUrl: GeoXUrl{
|
||||||
Mmdb: "https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.metadb",
|
Mmdb: "https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.metadb",
|
||||||
|
ASN: "https://github.com/xishang0128/geoip/releases/download/latest/GeoLite2-ASN.mmdb",
|
||||||
GeoIp: "https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.dat",
|
GeoIp: "https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.dat",
|
||||||
GeoSite: "https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geosite.dat",
|
GeoSite: "https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geosite.dat",
|
||||||
},
|
},
|
||||||
@@ -546,13 +572,13 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
}
|
}
|
||||||
config.RuleProviders = ruleProviders
|
config.RuleProviders = ruleProviders
|
||||||
|
|
||||||
subRules, err := parseSubRules(rawCfg, proxies)
|
subRules, err := parseSubRules(rawCfg, proxies, ruleProviders)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
config.SubRules = subRules
|
config.SubRules = subRules
|
||||||
|
|
||||||
rules, err := parseRules(rawCfg.Rule, proxies, subRules, "rules")
|
rules, err := parseRules(rawCfg.Rule, proxies, ruleProviders, subRules, "rules")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -607,6 +633,9 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func parseGeneral(cfg *RawConfig) (*General, error) {
|
func parseGeneral(cfg *RawConfig) (*General, error) {
|
||||||
|
geodata.SetGeodataMode(cfg.GeodataMode)
|
||||||
|
geodata.SetGeoAutoUpdate(cfg.GeoAutoUpdate)
|
||||||
|
geodata.SetGeoUpdateInterval(cfg.GeoUpdateInterval)
|
||||||
geodata.SetLoader(cfg.GeodataLoader)
|
geodata.SetLoader(cfg.GeodataLoader)
|
||||||
geodata.SetSiteMatcher(cfg.GeositeMatcher)
|
geodata.SetSiteMatcher(cfg.GeositeMatcher)
|
||||||
C.GeoAutoUpdate = cfg.GeoAutoUpdate
|
C.GeoAutoUpdate = cfg.GeoAutoUpdate
|
||||||
@@ -614,37 +643,37 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
|||||||
C.GeoIpUrl = cfg.GeoXUrl.GeoIp
|
C.GeoIpUrl = cfg.GeoXUrl.GeoIp
|
||||||
C.GeoSiteUrl = cfg.GeoXUrl.GeoSite
|
C.GeoSiteUrl = cfg.GeoXUrl.GeoSite
|
||||||
C.MmdbUrl = cfg.GeoXUrl.Mmdb
|
C.MmdbUrl = cfg.GeoXUrl.Mmdb
|
||||||
|
C.ASNUrl = cfg.GeoXUrl.ASN
|
||||||
C.GeodataMode = cfg.GeodataMode
|
C.GeodataMode = cfg.GeodataMode
|
||||||
C.UA = cfg.GlobalUA
|
C.UA = cfg.GlobalUA
|
||||||
if cfg.KeepAliveInterval != 0 {
|
if cfg.KeepAliveInterval != 0 {
|
||||||
N.KeepAliveInterval = time.Duration(cfg.KeepAliveInterval) * time.Second
|
N.KeepAliveInterval = time.Duration(cfg.KeepAliveInterval) * time.Second
|
||||||
}
|
}
|
||||||
|
|
||||||
ExternalUIPath = cfg.ExternalUI
|
updater.ExternalUIPath = cfg.ExternalUI
|
||||||
// checkout externalUI exist
|
// checkout externalUI exist
|
||||||
if ExternalUIPath != "" {
|
if updater.ExternalUIPath != "" {
|
||||||
ExternalUIPath = C.Path.Resolve(ExternalUIPath)
|
updater.ExternalUIPath = C.Path.Resolve(updater.ExternalUIPath)
|
||||||
if _, err := os.Stat(ExternalUIPath); os.IsNotExist(err) {
|
if _, err := os.Stat(updater.ExternalUIPath); os.IsNotExist(err) {
|
||||||
defaultUIpath := path.Join(C.Path.HomeDir(), "ui")
|
defaultUIpath := path.Join(C.Path.HomeDir(), "ui")
|
||||||
log.Warnln("external-ui: %s does not exist, creating folder in %s", ExternalUIPath, defaultUIpath)
|
log.Warnln("external-ui: %s does not exist, creating folder in %s", updater.ExternalUIPath, defaultUIpath)
|
||||||
if err := os.MkdirAll(defaultUIpath, os.ModePerm); err != nil {
|
if err := os.MkdirAll(defaultUIpath, os.ModePerm); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
ExternalUIPath = defaultUIpath
|
updater.ExternalUIPath = defaultUIpath
|
||||||
cfg.ExternalUI = defaultUIpath
|
cfg.ExternalUI = defaultUIpath
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// checkout UIpath/name exist
|
// checkout UIpath/name exist
|
||||||
if cfg.ExternalUIName != "" {
|
if cfg.ExternalUIName != "" {
|
||||||
ExternalUIName = cfg.ExternalUIName
|
updater.ExternalUIName = cfg.ExternalUIName
|
||||||
} else {
|
} else {
|
||||||
ExternalUIFolder = ExternalUIPath
|
updater.ExternalUIFolder = updater.ExternalUIPath
|
||||||
}
|
}
|
||||||
if cfg.ExternalUIURL != "" {
|
if cfg.ExternalUIURL != "" {
|
||||||
ExternalUIURL = cfg.ExternalUIURL
|
updater.ExternalUIURL = cfg.ExternalUIURL
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg.Tun.RedirectToTun = cfg.EBpf.RedirectToTun
|
|
||||||
return &General{
|
return &General{
|
||||||
Inbound: Inbound{
|
Inbound: Inbound{
|
||||||
Port: cfg.Port,
|
Port: cfg.Port,
|
||||||
@@ -663,10 +692,11 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
|||||||
InboundMPTCP: cfg.InboundMPTCP,
|
InboundMPTCP: cfg.InboundMPTCP,
|
||||||
},
|
},
|
||||||
Controller: Controller{
|
Controller: Controller{
|
||||||
ExternalController: cfg.ExternalController,
|
ExternalController: cfg.ExternalController,
|
||||||
ExternalUI: cfg.ExternalUI,
|
ExternalUI: cfg.ExternalUI,
|
||||||
Secret: cfg.Secret,
|
Secret: cfg.Secret,
|
||||||
ExternalControllerTLS: cfg.ExternalControllerTLS,
|
ExternalControllerUnix: cfg.ExternalControllerUnix,
|
||||||
|
ExternalControllerTLS: cfg.ExternalControllerTLS,
|
||||||
},
|
},
|
||||||
UnifiedDelay: cfg.UnifiedDelay,
|
UnifiedDelay: cfg.UnifiedDelay,
|
||||||
Mode: cfg.Mode,
|
Mode: cfg.Mode,
|
||||||
@@ -694,8 +724,11 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
groupsConfig := cfg.ProxyGroup
|
groupsConfig := cfg.ProxyGroup
|
||||||
providersConfig := cfg.ProxyProvider
|
providersConfig := cfg.ProxyProvider
|
||||||
|
|
||||||
var proxyList []string
|
var (
|
||||||
var AllProxies []string
|
proxyList []string
|
||||||
|
AllProxies []string
|
||||||
|
hasGlobal bool
|
||||||
|
)
|
||||||
proxiesList := list.New()
|
proxiesList := list.New()
|
||||||
groupsList := list.New()
|
groupsList := list.New()
|
||||||
|
|
||||||
@@ -728,6 +761,9 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
if !existName {
|
if !existName {
|
||||||
return nil, nil, fmt.Errorf("proxy group %d: missing name", idx)
|
return nil, nil, fmt.Errorf("proxy group %d: missing name", idx)
|
||||||
}
|
}
|
||||||
|
if groupName == "GLOBAL" {
|
||||||
|
hasGlobal = true
|
||||||
|
}
|
||||||
proxyList = append(proxyList, groupName)
|
proxyList = append(proxyList, groupName)
|
||||||
groupsList.PushBack(mapping)
|
groupsList.PushBack(mapping)
|
||||||
}
|
}
|
||||||
@@ -779,13 +815,15 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
pd, _ := provider.NewCompatibleProvider(provider.ReservedName, ps, hc)
|
pd, _ := provider.NewCompatibleProvider(provider.ReservedName, ps, hc)
|
||||||
providersMap[provider.ReservedName] = pd
|
providersMap[provider.ReservedName] = pd
|
||||||
|
|
||||||
global := outboundgroup.NewSelector(
|
if !hasGlobal {
|
||||||
&outboundgroup.GroupCommonOption{
|
global := outboundgroup.NewSelector(
|
||||||
Name: "GLOBAL",
|
&outboundgroup.GroupCommonOption{
|
||||||
},
|
Name: "GLOBAL",
|
||||||
[]providerTypes.ProxyProvider{pd},
|
},
|
||||||
)
|
[]providerTypes.ProxyProvider{pd},
|
||||||
proxies["GLOBAL"] = adapter.NewProxy(global)
|
)
|
||||||
|
proxies["GLOBAL"] = adapter.NewProxy(global)
|
||||||
|
}
|
||||||
ProxiesList = proxiesList
|
ProxiesList = proxiesList
|
||||||
GroupsList = groupsList
|
GroupsList = groupsList
|
||||||
if ParsingProxiesCallback != nil {
|
if ParsingProxiesCallback != nil {
|
||||||
@@ -814,6 +852,7 @@ func parseListeners(cfg *RawConfig) (listeners map[string]C.InboundListener, err
|
|||||||
}
|
}
|
||||||
|
|
||||||
func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]providerTypes.RuleProvider, err error) {
|
func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]providerTypes.RuleProvider, err error) {
|
||||||
|
RP.SetTunnel(T.Tunnel)
|
||||||
ruleProviders = map[string]providerTypes.RuleProvider{}
|
ruleProviders = map[string]providerTypes.RuleProvider{}
|
||||||
// parse rule provider
|
// parse rule provider
|
||||||
for name, mapping := range cfg.RuleProvider {
|
for name, mapping := range cfg.RuleProvider {
|
||||||
@@ -823,12 +862,11 @@ func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]providerTypes.
|
|||||||
}
|
}
|
||||||
|
|
||||||
ruleProviders[name] = rp
|
ruleProviders[name] = rp
|
||||||
RP.SetRuleProvider(rp)
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseSubRules(cfg *RawConfig, proxies map[string]C.Proxy) (subRules map[string][]C.Rule, err error) {
|
func parseSubRules(cfg *RawConfig, proxies map[string]C.Proxy, ruleProviders map[string]providerTypes.RuleProvider) (subRules map[string][]C.Rule, err error) {
|
||||||
subRules = map[string][]C.Rule{}
|
subRules = map[string][]C.Rule{}
|
||||||
for name := range cfg.SubRules {
|
for name := range cfg.SubRules {
|
||||||
subRules[name] = make([]C.Rule, 0)
|
subRules[name] = make([]C.Rule, 0)
|
||||||
@@ -838,7 +876,7 @@ func parseSubRules(cfg *RawConfig, proxies map[string]C.Proxy) (subRules map[str
|
|||||||
return nil, fmt.Errorf("sub-rule name is empty")
|
return nil, fmt.Errorf("sub-rule name is empty")
|
||||||
}
|
}
|
||||||
var rules []C.Rule
|
var rules []C.Rule
|
||||||
rules, err = parseRules(rawRules, proxies, subRules, fmt.Sprintf("sub-rules[%s]", name))
|
rules, err = parseRules(rawRules, proxies, ruleProviders, subRules, fmt.Sprintf("sub-rules[%s]", name))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -891,7 +929,7 @@ func verifySubRuleCircularReferences(n string, subRules map[string][]C.Rule, arr
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRules(rulesConfig []string, proxies map[string]C.Proxy, subRules map[string][]C.Rule, format string) ([]C.Rule, error) {
|
func parseRules(rulesConfig []string, proxies map[string]C.Proxy, ruleProviders map[string]providerTypes.RuleProvider, subRules map[string][]C.Rule, format string) ([]C.Rule, error) {
|
||||||
var rules []C.Rule
|
var rules []C.Rule
|
||||||
|
|
||||||
// parse rules
|
// parse rules
|
||||||
@@ -906,7 +944,7 @@ func parseRules(rulesConfig []string, proxies map[string]C.Proxy, subRules map[s
|
|||||||
|
|
||||||
l := len(rule)
|
l := len(rule)
|
||||||
|
|
||||||
if ruleName == "NOT" || ruleName == "OR" || ruleName == "AND" || ruleName == "SUB-RULE" {
|
if ruleName == "NOT" || ruleName == "OR" || ruleName == "AND" || ruleName == "SUB-RULE" || ruleName == "DOMAIN-REGEX" || ruleName == "PROCESS-NAME-REGEX" || ruleName == "PROCESS-PATH-REGEX" {
|
||||||
target = rule[l-1]
|
target = rule[l-1]
|
||||||
payload = strings.Join(rule[1:l-1], ",")
|
payload = strings.Join(rule[1:l-1], ",")
|
||||||
} else {
|
} else {
|
||||||
@@ -940,6 +978,12 @@ func parseRules(rulesConfig []string, proxies map[string]C.Proxy, subRules map[s
|
|||||||
return nil, fmt.Errorf("%s[%d] [%s] error: %s", format, idx, line, parseErr.Error())
|
return nil, fmt.Errorf("%s[%d] [%s] error: %s", format, idx, line, parseErr.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, name := range parsed.ProviderNames() {
|
||||||
|
if _, ok := ruleProviders[name]; !ok {
|
||||||
|
return nil, fmt.Errorf("%s[%d] [%s] error: rule set [%s] not found", format, idx, line, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
rules = append(rules, parsed)
|
rules = append(rules, parsed)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1009,10 +1053,20 @@ func hostWithDefaultPort(host string, defPort string) (string, error) {
|
|||||||
return net.JoinHostPort(hostname, port), nil
|
return net.JoinHostPort(hostname, port), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseNameServer(servers []string, preferH3 bool) ([]dns.NameServer, error) {
|
func parseNameServer(servers []string, respectRules bool, preferH3 bool) ([]dns.NameServer, error) {
|
||||||
var nameservers []dns.NameServer
|
var nameservers []dns.NameServer
|
||||||
|
|
||||||
for idx, server := range servers {
|
for idx, server := range servers {
|
||||||
|
if strings.HasPrefix(server, "dhcp://") {
|
||||||
|
nameservers = append(
|
||||||
|
nameservers,
|
||||||
|
dns.NameServer{
|
||||||
|
Net: "dhcp",
|
||||||
|
Addr: server[len("dhcp://"):],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
server = parsePureDNSServer(server)
|
server = parsePureDNSServer(server)
|
||||||
u, err := url.Parse(server)
|
u, err := url.Parse(server)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1055,9 +1109,6 @@ func parseNameServer(servers []string, preferH3 bool) ([]dns.NameServer, error)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case "dhcp":
|
|
||||||
addr = u.Host
|
|
||||||
dnsNetType = "dhcp" // UDP from DHCP
|
|
||||||
case "quic":
|
case "quic":
|
||||||
addr, err = hostWithDefaultPort(u.Host, "853")
|
addr, err = hostWithDefaultPort(u.Host, "853")
|
||||||
dnsNetType = "quic" // DNS over QUIC
|
dnsNetType = "quic" // DNS over QUIC
|
||||||
@@ -1084,6 +1135,10 @@ func parseNameServer(servers []string, preferH3 bool) ([]dns.NameServer, error)
|
|||||||
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if respectRules && len(proxyName) == 0 {
|
||||||
|
proxyName = dns.RespectRules
|
||||||
|
}
|
||||||
|
|
||||||
nameservers = append(
|
nameservers = append(
|
||||||
nameservers,
|
nameservers,
|
||||||
dns.NameServer{
|
dns.NameServer{
|
||||||
@@ -1100,7 +1155,7 @@ func parseNameServer(servers []string, preferH3 bool) ([]dns.NameServer, error)
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
dns.ParseNameServer = func(servers []string) ([]dns.NameServer, error) { // using by wireguard
|
dns.ParseNameServer = func(servers []string) ([]dns.NameServer, error) { // using by wireguard
|
||||||
return parseNameServer(servers, false)
|
return parseNameServer(servers, false, false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1126,7 +1181,8 @@ func parsePureDNSServer(server string) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
func parseNameServerPolicy(nsPolicy *orderedmap.OrderedMap[string, any], ruleProviders map[string]providerTypes.RuleProvider, preferH3 bool) (*orderedmap.OrderedMap[string, []dns.NameServer], error) {
|
|
||||||
|
func parseNameServerPolicy(nsPolicy *orderedmap.OrderedMap[string, any], ruleProviders map[string]providerTypes.RuleProvider, respectRules bool, preferH3 bool) (*orderedmap.OrderedMap[string, []dns.NameServer], error) {
|
||||||
policy := orderedmap.New[string, []dns.NameServer]()
|
policy := orderedmap.New[string, []dns.NameServer]()
|
||||||
updatedPolicy := orderedmap.New[string, any]()
|
updatedPolicy := orderedmap.New[string, any]()
|
||||||
re := regexp.MustCompile(`[a-zA-Z0-9\-]+\.[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?`)
|
re := regexp.MustCompile(`[a-zA-Z0-9\-]+\.[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?`)
|
||||||
@@ -1172,7 +1228,7 @@ func parseNameServerPolicy(nsPolicy *orderedmap.OrderedMap[string, any], rulePro
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
nameservers, err := parseNameServer(servers, preferH3)
|
nameservers, err := parseNameServer(servers, respectRules, preferH3)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -1266,39 +1322,44 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie[resolver.HostValue], rul
|
|||||||
return nil, fmt.Errorf("if DNS configuration is turned on, NameServer cannot be empty")
|
return nil, fmt.Errorf("if DNS configuration is turned on, NameServer cannot be empty")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if cfg.RespectRules && len(cfg.ProxyServerNameserver) == 0 {
|
||||||
|
return nil, fmt.Errorf("if “respect-rules” is turned on, “proxy-server-nameserver” cannot be empty")
|
||||||
|
}
|
||||||
|
|
||||||
dnsCfg := &DNS{
|
dnsCfg := &DNS{
|
||||||
Enable: cfg.Enable,
|
Enable: cfg.Enable,
|
||||||
Listen: cfg.Listen,
|
Listen: cfg.Listen,
|
||||||
PreferH3: cfg.PreferH3,
|
PreferH3: cfg.PreferH3,
|
||||||
IPv6Timeout: cfg.IPv6Timeout,
|
IPv6Timeout: cfg.IPv6Timeout,
|
||||||
IPv6: cfg.IPv6,
|
IPv6: cfg.IPv6,
|
||||||
EnhancedMode: cfg.EnhancedMode,
|
UseSystemHosts: cfg.UseSystemHosts,
|
||||||
|
EnhancedMode: cfg.EnhancedMode,
|
||||||
FallbackFilter: FallbackFilter{
|
FallbackFilter: FallbackFilter{
|
||||||
IPCIDR: []netip.Prefix{},
|
IPCIDR: []netip.Prefix{},
|
||||||
GeoSite: []router.DomainMatcher{},
|
GeoSite: []router.DomainMatcher{},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
var err error
|
var err error
|
||||||
if dnsCfg.NameServer, err = parseNameServer(cfg.NameServer, cfg.PreferH3); err != nil {
|
if dnsCfg.NameServer, err = parseNameServer(cfg.NameServer, cfg.RespectRules, cfg.PreferH3); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if dnsCfg.Fallback, err = parseNameServer(cfg.Fallback, cfg.PreferH3); err != nil {
|
if dnsCfg.Fallback, err = parseNameServer(cfg.Fallback, cfg.RespectRules, cfg.PreferH3); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if dnsCfg.NameServerPolicy, err = parseNameServerPolicy(cfg.NameServerPolicy, ruleProviders, cfg.PreferH3); err != nil {
|
if dnsCfg.NameServerPolicy, err = parseNameServerPolicy(cfg.NameServerPolicy, ruleProviders, cfg.RespectRules, cfg.PreferH3); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if dnsCfg.ProxyServerNameserver, err = parseNameServer(cfg.ProxyServerNameserver, cfg.PreferH3); err != nil {
|
if dnsCfg.ProxyServerNameserver, err = parseNameServer(cfg.ProxyServerNameserver, false, cfg.PreferH3); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(cfg.DefaultNameserver) == 0 {
|
if len(cfg.DefaultNameserver) == 0 {
|
||||||
return nil, errors.New("default nameserver should have at least one nameserver")
|
return nil, errors.New("default nameserver should have at least one nameserver")
|
||||||
}
|
}
|
||||||
if dnsCfg.DefaultNameserver, err = parseNameServer(cfg.DefaultNameserver, cfg.PreferH3); err != nil {
|
if dnsCfg.DefaultNameserver, err = parseNameServer(cfg.DefaultNameserver, false, cfg.PreferH3); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
// check default nameserver is pure ip addr
|
// check default nameserver is pure ip addr
|
||||||
@@ -1415,30 +1476,39 @@ func parseTun(rawTun RawTun, general *General) error {
|
|||||||
DNSHijack: rawTun.DNSHijack,
|
DNSHijack: rawTun.DNSHijack,
|
||||||
AutoRoute: rawTun.AutoRoute,
|
AutoRoute: rawTun.AutoRoute,
|
||||||
AutoDetectInterface: rawTun.AutoDetectInterface,
|
AutoDetectInterface: rawTun.AutoDetectInterface,
|
||||||
RedirectToTun: rawTun.RedirectToTun,
|
|
||||||
|
|
||||||
MTU: rawTun.MTU,
|
MTU: rawTun.MTU,
|
||||||
GSO: rawTun.GSO,
|
GSO: rawTun.GSO,
|
||||||
GSOMaxSize: rawTun.GSOMaxSize,
|
GSOMaxSize: rawTun.GSOMaxSize,
|
||||||
Inet4Address: []netip.Prefix{tunAddressPrefix},
|
Inet4Address: []netip.Prefix{tunAddressPrefix},
|
||||||
Inet6Address: rawTun.Inet6Address,
|
Inet6Address: rawTun.Inet6Address,
|
||||||
StrictRoute: rawTun.StrictRoute,
|
IPRoute2TableIndex: rawTun.IPRoute2TableIndex,
|
||||||
|
IPRoute2RuleIndex: rawTun.IPRoute2RuleIndex,
|
||||||
|
AutoRedirect: rawTun.AutoRedirect,
|
||||||
|
AutoRedirectInputMark: rawTun.AutoRedirectInputMark,
|
||||||
|
AutoRedirectOutputMark: rawTun.AutoRedirectOutputMark,
|
||||||
|
StrictRoute: rawTun.StrictRoute,
|
||||||
|
RouteAddress: rawTun.RouteAddress,
|
||||||
|
RouteAddressSet: rawTun.RouteAddressSet,
|
||||||
|
RouteExcludeAddress: rawTun.RouteExcludeAddress,
|
||||||
|
RouteExcludeAddressSet: rawTun.RouteExcludeAddressSet,
|
||||||
|
IncludeInterface: rawTun.IncludeInterface,
|
||||||
|
ExcludeInterface: rawTun.ExcludeInterface,
|
||||||
|
IncludeUID: rawTun.IncludeUID,
|
||||||
|
IncludeUIDRange: rawTun.IncludeUIDRange,
|
||||||
|
ExcludeUID: rawTun.ExcludeUID,
|
||||||
|
ExcludeUIDRange: rawTun.ExcludeUIDRange,
|
||||||
|
IncludeAndroidUser: rawTun.IncludeAndroidUser,
|
||||||
|
IncludePackage: rawTun.IncludePackage,
|
||||||
|
ExcludePackage: rawTun.ExcludePackage,
|
||||||
|
EndpointIndependentNat: rawTun.EndpointIndependentNat,
|
||||||
|
UDPTimeout: rawTun.UDPTimeout,
|
||||||
|
FileDescriptor: rawTun.FileDescriptor,
|
||||||
|
|
||||||
Inet4RouteAddress: rawTun.Inet4RouteAddress,
|
Inet4RouteAddress: rawTun.Inet4RouteAddress,
|
||||||
Inet6RouteAddress: rawTun.Inet6RouteAddress,
|
Inet6RouteAddress: rawTun.Inet6RouteAddress,
|
||||||
Inet4RouteExcludeAddress: rawTun.Inet4RouteExcludeAddress,
|
Inet4RouteExcludeAddress: rawTun.Inet4RouteExcludeAddress,
|
||||||
Inet6RouteExcludeAddress: rawTun.Inet6RouteExcludeAddress,
|
Inet6RouteExcludeAddress: rawTun.Inet6RouteExcludeAddress,
|
||||||
IncludeInterface: rawTun.IncludeInterface,
|
|
||||||
ExcludeInterface: rawTun.ExcludeInterface,
|
|
||||||
IncludeUID: rawTun.IncludeUID,
|
|
||||||
IncludeUIDRange: rawTun.IncludeUIDRange,
|
|
||||||
ExcludeUID: rawTun.ExcludeUID,
|
|
||||||
ExcludeUIDRange: rawTun.ExcludeUIDRange,
|
|
||||||
IncludeAndroidUser: rawTun.IncludeAndroidUser,
|
|
||||||
IncludePackage: rawTun.IncludePackage,
|
|
||||||
ExcludePackage: rawTun.ExcludePackage,
|
|
||||||
EndpointIndependentNat: rawTun.EndpointIndependentNat,
|
|
||||||
UDPTimeout: rawTun.UDPTimeout,
|
|
||||||
FileDescriptor: rawTun.FileDescriptor,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -1,67 +0,0 @@
|
|||||||
package config
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"runtime"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/geodata"
|
|
||||||
_ "github.com/metacubex/mihomo/component/geodata/standard"
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
|
|
||||||
"github.com/oschwald/maxminddb-golang"
|
|
||||||
)
|
|
||||||
|
|
||||||
func UpdateGeoDatabases() error {
|
|
||||||
defer runtime.GC()
|
|
||||||
geoLoader, err := geodata.GetGeoDataLoader("standard")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if C.GeodataMode {
|
|
||||||
data, err := downloadForBytes(C.GeoIpUrl)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("can't download GeoIP database file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err = geoLoader.LoadIPByBytes(data, "cn"); err != nil {
|
|
||||||
return fmt.Errorf("invalid GeoIP database file: %s", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = saveFile(data, C.Path.GeoIP()); err != nil {
|
|
||||||
return fmt.Errorf("can't save GeoIP database file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
data, err := downloadForBytes(C.MmdbUrl)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("can't download MMDB database file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
instance, err := maxminddb.FromBytes(data)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("invalid MMDB database file: %s", err)
|
|
||||||
}
|
|
||||||
_ = instance.Close()
|
|
||||||
if err = saveFile(data, C.Path.MMDB()); err != nil {
|
|
||||||
return fmt.Errorf("can't save MMDB database file: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := downloadForBytes(C.GeoSiteUrl)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("can't download GeoSite database file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err = geoLoader.LoadSiteByBytes(data, "cn"); err != nil {
|
|
||||||
return fmt.Errorf("invalid GeoSite database file: %s", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = saveFile(data, C.Path.GeoSite()); err != nil {
|
|
||||||
return fmt.Errorf("can't save GeoSite database file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
geodata.ClearCache()
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,38 +1,15 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter/outboundgroup"
|
"github.com/metacubex/mihomo/adapter/outboundgroup"
|
||||||
"github.com/metacubex/mihomo/common/structure"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
mihomoHttp "github.com/metacubex/mihomo/component/http"
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func downloadForBytes(url string) ([]byte, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
|
||||||
defer cancel()
|
|
||||||
resp, err := mihomoHttp.HttpRequest(ctx, url, http.MethodGet, http.Header{"User-Agent": {C.UA}}, nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
return io.ReadAll(resp.Body)
|
|
||||||
}
|
|
||||||
|
|
||||||
func saveFile(bytes []byte, path string) error {
|
|
||||||
return os.WriteFile(path, bytes, 0o644)
|
|
||||||
}
|
|
||||||
|
|
||||||
func trimArr(arr []string) (r []string) {
|
func trimArr(arr []string) (r []string) {
|
||||||
for _, e := range arr {
|
for _, e := range arr {
|
||||||
r = append(r, strings.Trim(e, " "))
|
r = append(r, strings.Trim(e, " "))
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ const (
|
|||||||
RejectDrop
|
RejectDrop
|
||||||
Compatible
|
Compatible
|
||||||
Pass
|
Pass
|
||||||
|
Dns
|
||||||
|
|
||||||
Relay
|
Relay
|
||||||
Selector
|
Selector
|
||||||
@@ -40,6 +41,7 @@ const (
|
|||||||
Hysteria2
|
Hysteria2
|
||||||
WireGuard
|
WireGuard
|
||||||
Tuic
|
Tuic
|
||||||
|
Ssh
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -184,6 +186,8 @@ func (at AdapterType) String() string {
|
|||||||
return "Compatible"
|
return "Compatible"
|
||||||
case Pass:
|
case Pass:
|
||||||
return "Pass"
|
return "Pass"
|
||||||
|
case Dns:
|
||||||
|
return "Dns"
|
||||||
case Shadowsocks:
|
case Shadowsocks:
|
||||||
return "Shadowsocks"
|
return "Shadowsocks"
|
||||||
case ShadowsocksR:
|
case ShadowsocksR:
|
||||||
@@ -219,7 +223,8 @@ func (at AdapterType) String() string {
|
|||||||
return "URLTest"
|
return "URLTest"
|
||||||
case LoadBalance:
|
case LoadBalance:
|
||||||
return "LoadBalance"
|
return "LoadBalance"
|
||||||
|
case Ssh:
|
||||||
|
return "Ssh"
|
||||||
default:
|
default:
|
||||||
return "Unknown"
|
return "Unknown"
|
||||||
}
|
}
|
||||||
|
|||||||
5
constant/features/version.go
Normal file
5
constant/features/version.go
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
package features
|
||||||
|
|
||||||
|
var WindowsMajorVersion uint32
|
||||||
|
var WindowsMinorVersion uint32
|
||||||
|
var WindowsBuildNumber uint32
|
||||||
10
constant/features/version_windows.go
Normal file
10
constant/features/version_windows.go
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package features
|
||||||
|
|
||||||
|
import "golang.org/x/sys/windows"
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
version := windows.RtlGetVersion()
|
||||||
|
WindowsMajorVersion = version.MajorVersion
|
||||||
|
WindowsMinorVersion = version.MinorVersion
|
||||||
|
WindowsBuildNumber = version.BuildNumber
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
package constant
|
package constant
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
ASNEnable bool
|
||||||
GeodataMode bool
|
GeodataMode bool
|
||||||
GeoAutoUpdate bool
|
GeoAutoUpdate bool
|
||||||
GeoUpdateInterval int
|
GeoUpdateInterval int
|
||||||
GeoIpUrl string
|
GeoIpUrl string
|
||||||
MmdbUrl string
|
MmdbUrl string
|
||||||
GeoSiteUrl string
|
GeoSiteUrl string
|
||||||
|
ASNUrl string
|
||||||
)
|
)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user