mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-03-04 04:47:30 +00:00
Compare commits
142 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
||||||
585
.github/workflows/build.yml
vendored
585
.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,7 +17,6 @@ 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
|
||||||
@@ -21,344 +24,420 @@ concurrency:
|
|||||||
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} ./
|
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
|
||||||
|
|
||||||
|
- name: Set Docker tags and labels based on trigger
|
||||||
|
id: set-meta
|
||||||
|
run: |
|
||||||
|
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||||
|
echo "tags=${{ github.event.inputs.version }}" >> $GITHUB_ENV
|
||||||
|
echo "labels=org.opencontainers.image.version=${{ github.event.inputs.version }}" >> $GITHUB_ENV
|
||||||
|
else
|
||||||
|
echo "tags=${{ steps.meta.outputs.tags }}" >> $GITHUB_ENV
|
||||||
|
echo "labels=${{ steps.meta.outputs.labels }}" >> $GITHUB_ENV
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
# 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
|
id: meta
|
||||||
uses: docker/metadata-action@v4
|
uses: docker/metadata-action@v5
|
||||||
with:
|
with:
|
||||||
images: ${{ env.REGISTRY }}/${{ github.repository }}
|
images: ${{ env.REGISTRY }}/${{ github.repository }}
|
||||||
|
tags: ${{ env.tags }}
|
||||||
|
labels: ${{ env.labels }}
|
||||||
|
|
||||||
|
|
||||||
- name: Show files
|
- name: Show files
|
||||||
run: |
|
run: |
|
||||||
@@ -387,4 +466,4 @@ jobs:
|
|||||||
linux/arm64
|
linux/arm64
|
||||||
linux/arm/v7
|
linux/arm/v7
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/sagernet/tfo-go"
|
"github.com/metacubex/tfo-go"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|||||||
@@ -3,18 +3,18 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
|
||||||
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"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Direct struct {
|
type Direct struct {
|
||||||
*Base
|
*Base
|
||||||
loopBack *loopBackDetector
|
loopBack *loopback.Detector
|
||||||
}
|
}
|
||||||
|
|
||||||
type DirectOption struct {
|
type DirectOption struct {
|
||||||
@@ -24,8 +24,8 @@ 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 err := d.loopBack.CheckConn(metadata); err != nil {
|
||||||
return nil, fmt.Errorf("reject loopback connection to: %s", metadata.RemoteAddress())
|
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 +38,8 @@ 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 err := d.loopBack.CheckPacketConn(metadata); err != nil {
|
||||||
return nil, fmt.Errorf("reject loopback connection to: %s", metadata.RemoteAddress())
|
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() {
|
||||||
@@ -68,7 +68,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 +80,7 @@ func NewDirect() *Direct {
|
|||||||
udp: true,
|
udp: true,
|
||||||
prefer: C.DualStack,
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
loopBack: newLoopBackDetector(),
|
loopBack: loopback.NewDetector(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,6 +92,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,23 +8,30 @@ 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"
|
||||||
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
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[fastrand.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/zhangyunhao116/fastrand"
|
||||||
|
"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 fastrand.Intn(2) == 0 {
|
||||||
|
version += "7." + strconv.Itoa(fastrand.Intn(10))
|
||||||
|
} else {
|
||||||
|
version += "8." + strconv.Itoa(fastrand.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
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"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 +38,25 @@ 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
|
||||||
|
|
||||||
|
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"`
|
||||||
@@ -62,8 +72,6 @@ type WireGuardOption struct {
|
|||||||
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 +106,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 +157,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 +245,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 +273,125 @@ 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 {
|
||||||
|
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()
|
||||||
|
ipcConf := "private_key=" + w.option.PrivateKey
|
||||||
|
if len(w.option.Peers) > 0 {
|
||||||
|
for i, peer := range w.option.Peers {
|
||||||
|
destination, err := w.resolve(ctx, peer.Addr())
|
||||||
|
if err != nil {
|
||||||
|
// !!! do not set initErr here !!!
|
||||||
|
// let us can retry domain resolve in next time
|
||||||
|
return E.Cause(err, "resolve endpoint domain for peer ", i)
|
||||||
|
}
|
||||||
|
ipcConf += "\npublic_key=" + peer.PublicKey
|
||||||
|
ipcConf += "\nendpoint=" + destination.String()
|
||||||
|
if peer.PreSharedKey != "" {
|
||||||
|
ipcConf += "\npreshared_key=" + peer.PreSharedKey
|
||||||
|
}
|
||||||
|
for _, allowedIP := range peer.AllowedIPs {
|
||||||
|
ipcConf += "\nallowed_ip=" + allowedIP
|
||||||
|
}
|
||||||
|
if len(peer.Reserved) > 0 {
|
||||||
|
var reserved [3]uint8
|
||||||
|
copy(reserved[:], w.option.Reserved)
|
||||||
|
w.bind.SetReservedForEndpoint(destination, reserved)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ipcConf += "\npublic_key=" + w.option.PublicKey
|
||||||
|
destination, err := w.resolve(ctx, w.connectAddr)
|
||||||
|
if err != nil {
|
||||||
|
// !!! do not set initErr here !!!
|
||||||
|
// let us can retry domain resolve in next time
|
||||||
|
return E.Cause(err, "resolve endpoint domain")
|
||||||
|
}
|
||||||
|
w.bind.SetConnectAddr(destination)
|
||||||
|
ipcConf += "\nendpoint=" + destination.String()
|
||||||
|
if w.option.PreSharedKey != "" {
|
||||||
|
ipcConf += "\npreshared_key=" + w.option.PreSharedKey
|
||||||
|
}
|
||||||
|
var has4, has6 bool
|
||||||
|
for _, address := range w.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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if w.option.PersistentKeepalive != 0 {
|
||||||
|
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", w.option.PersistentKeepalive)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
err = w.tunDevice.Start()
|
||||||
|
if err != nil {
|
||||||
|
w.initErr = err
|
||||||
|
return w.initErr
|
||||||
|
}
|
||||||
|
|
||||||
|
w.initOk.Store(true)
|
||||||
|
return 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 +419,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":
|
||||||
|
|||||||
@@ -160,6 +160,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,32 @@ type healthCheckSchema struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type OverrideSchema struct {
|
type OverrideSchema struct {
|
||||||
UDP *bool `provider:"udp,omitempty"`
|
UDP *bool `provider:"udp,omitempty"`
|
||||||
Up *string `provider:"up,omitempty"`
|
Up *string `provider:"up,omitempty"`
|
||||||
Down *string `provider:"down,omitempty"`
|
Down *string `provider:"down,omitempty"`
|
||||||
DialerProxy *string `provider:"dialer-proxy,omitempty"`
|
DialerProxy *string `provider:"dialer-proxy,omitempty"`
|
||||||
SkipCertVerify *bool `provider:"skip-cert-verify,omitempty"`
|
SkipCertVerify *bool `provider:"skip-cert-verify,omitempty"`
|
||||||
Interface *string `provider:"interface-name,omitempty"`
|
Interface *string `provider:"interface-name,omitempty"`
|
||||||
RoutingMark *int `provider:"routing-mark,omitempty"`
|
RoutingMark *int `provider:"routing-mark,omitempty"`
|
||||||
IPVersion *string `provider:"ip-version,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 +88,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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,18 +46,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 +101,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 +124,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 +133,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 +169,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 +180,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 +216,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 +265,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 +356,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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -399,6 +397,14 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
|||||||
if override.IPVersion != nil {
|
if override.IPVersion != nil {
|
||||||
mapping["ip-version"] = *override.IPVersion
|
mapping["ip-version"] = *override.IPVersion
|
||||||
}
|
}
|
||||||
|
if override.AdditionalPrefix != nil {
|
||||||
|
name := mapping["name"].(string)
|
||||||
|
mapping["name"] = *override.AdditionalPrefix + name
|
||||||
|
}
|
||||||
|
if override.AdditionalSuffix != nil {
|
||||||
|
name := mapping["name"].(string)
|
||||||
|
mapping["name"] = name + *override.AdditionalSuffix
|
||||||
|
}
|
||||||
|
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
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,7 +330,7 @@ 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"] = []string{"/"}
|
||||||
@@ -338,7 +338,30 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
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
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
@@ -376,10 +383,28 @@ func (d Dialer) ListenPacket(ctx context.Context, network, address string, rAddr
|
|||||||
// avoid "The requested address is not valid in its context."
|
// avoid "The requested address is not valid in its context."
|
||||||
opt = WithInterface("")
|
opt = WithInterface("")
|
||||||
}
|
}
|
||||||
return ListenPacket(ctx, ParseNetwork(network, rAddrPort.Addr()), address, opt)
|
return ListenPacket(ctx, ParseNetwork(network, rAddrPort.Addr()), address, rAddrPort, 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
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,9 +6,11 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/tfo-go"
|
"github.com/metacubex/tfo-go"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var DisableTFO = false
|
||||||
|
|
||||||
type tfoConn struct {
|
type tfoConn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
closed bool
|
closed bool
|
||||||
|
|||||||
11
component/dialer/tfo_windows.go
Normal file
11
component/dialer/tfo_windows.go
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import "github.com/metacubex/mihomo/constant/features"
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
// According to MSDN, this option is available since Windows 10, 1607
|
||||||
|
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms738596(v=vs.85).aspx
|
||||||
|
if features.WindowsMajorVersion < 10 || (features.WindowsMajorVersion == 10 && features.WindowsBuildNumber < 14393) {
|
||||||
|
DisableTFO = true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
@@ -24,7 +23,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,28 +37,26 @@ 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{
|
||||||
@@ -72,11 +69,15 @@ func ResolveInterface(name string) (*Interface, error) {
|
|||||||
|
|
||||||
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 +86,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.Addrs {
|
||||||
|
if addr.Contains(ip) {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
func FlushCache() {
|
func FlushCache() {
|
||||||
interfaces.Reset()
|
interfaces.Reset()
|
||||||
}
|
}
|
||||||
|
|||||||
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
|
||||||
|
}
|
||||||
@@ -3,14 +3,22 @@ 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/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
DisableSystemHosts, _ = strconv.ParseBool(os.Getenv("DISABLE_SYSTEM_HOSTS"))
|
||||||
|
UseSystemHosts bool
|
||||||
|
)
|
||||||
|
|
||||||
type Hosts struct {
|
type Hosts struct {
|
||||||
*trie.DomainTrie[HostValue]
|
*trie.DomainTrie[HostValue]
|
||||||
}
|
}
|
||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|||||||
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)
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,16 +16,13 @@ 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"
|
utls "github.com/metacubex/utls"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
"github.com/zhangyunhao116/fastrand"
|
||||||
"golang.org/x/crypto/chacha20poly1305"
|
"golang.org/x/crypto/chacha20poly1305"
|
||||||
"golang.org/x/crypto/hkdf"
|
"golang.org/x/crypto/hkdf"
|
||||||
@@ -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,7 +133,10 @@ 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", fastrand.Intn(32)+30)})
|
||||||
response, err := client.Do(request)
|
response, err := client.Do(request)
|
||||||
@@ -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 {
|
||||||
171
component/updater/update_geo.go
Normal file
171
component/updater/update_geo.go
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateGeoDatabases(updateNotification chan struct{}) error {
|
||||||
|
log.Infoln("[GEO] Start updating GEO database")
|
||||||
|
|
||||||
|
if UpdatingGeo.Load() {
|
||||||
|
return errors.New("GEO database is updating, skip")
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
updateNotification <- struct{}{}
|
||||||
|
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(updateNotification chan struct{}) {
|
||||||
|
if C.GeoUpdateInterval <= 0 {
|
||||||
|
log.Errorln("[GEO] Invalid update interval: %d", C.GeoUpdateInterval)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ticker := time.NewTicker(time.Duration(C.GeoUpdateInterval) * time.Hour)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
log.Infoln("[GEO] update GEO database every %d hours", C.GeoUpdateInterval)
|
||||||
|
go func() {
|
||||||
|
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(updateNotification); err != nil {
|
||||||
|
log.Errorln("[GEO] Failed to update GEO database: %s", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for range ticker.C {
|
||||||
|
if err := UpdateGeoDatabases(updateNotification); err != nil {
|
||||||
|
log.Errorln("[GEO] Failed to update GEO database: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -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,7 @@ 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"`
|
||||||
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"`
|
||||||
@@ -263,6 +269,7 @@ type RawTun struct {
|
|||||||
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint_independent_nat,omitempty"`
|
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint_independent_nat,omitempty"`
|
||||||
UDPTimeout int64 `yaml:"udp-timeout" json:"udp_timeout,omitempty"`
|
UDPTimeout int64 `yaml:"udp-timeout" json:"udp_timeout,omitempty"`
|
||||||
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
|
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
|
||||||
|
TableIndex int `yaml:"table-index" json:"table-index"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type RawTuicServer struct {
|
type RawTuicServer struct {
|
||||||
@@ -301,6 +308,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 +354,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 +418,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 +449,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 +459,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 +488,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 +508,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",
|
||||||
},
|
},
|
||||||
@@ -607,6 +624,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,34 +634,35 @@ 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
|
cfg.Tun.RedirectToTun = cfg.EBpf.RedirectToTun
|
||||||
@@ -663,10 +684,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,
|
||||||
@@ -906,7 +928,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 {
|
||||||
@@ -1267,12 +1289,13 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie[resolver.HostValue], rul
|
|||||||
}
|
}
|
||||||
|
|
||||||
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{},
|
||||||
@@ -1439,6 +1462,7 @@ func parseTun(rawTun RawTun, general *General) error {
|
|||||||
EndpointIndependentNat: rawTun.EndpointIndependentNat,
|
EndpointIndependentNat: rawTun.EndpointIndependentNat,
|
||||||
UDPTimeout: rawTun.UDPTimeout,
|
UDPTimeout: rawTun.UDPTimeout,
|
||||||
FileDescriptor: rawTun.FileDescriptor,
|
FileDescriptor: rawTun.FileDescriptor,
|
||||||
|
TableIndex: rawTun.TableIndex,
|
||||||
}
|
}
|
||||||
|
|
||||||
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.MinorVersion
|
||||||
|
}
|
||||||
@@ -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
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -133,6 +133,8 @@ type Metadata struct {
|
|||||||
Type Type `json:"type"`
|
Type Type `json:"type"`
|
||||||
SrcIP netip.Addr `json:"sourceIP"`
|
SrcIP netip.Addr `json:"sourceIP"`
|
||||||
DstIP netip.Addr `json:"destinationIP"`
|
DstIP netip.Addr `json:"destinationIP"`
|
||||||
|
DstGeoIP []string `json:"destinationGeoIP"` // can be nil if never queried, empty slice if got no result
|
||||||
|
DstIPASN string `json:"destinationIPASN"`
|
||||||
SrcPort uint16 `json:"sourcePort,string"` // `,string` is used to compatible with old version json output
|
SrcPort uint16 `json:"sourcePort,string"` // `,string` is used to compatible with old version json output
|
||||||
DstPort uint16 `json:"destinationPort,string"` // `,string` is used to compatible with old version json output
|
DstPort uint16 `json:"destinationPort,string"` // `,string` is used to compatible with old version json output
|
||||||
InIP netip.Addr `json:"inboundIP"`
|
InIP netip.Addr `json:"inboundIP"`
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ const Name = "mihomo"
|
|||||||
var (
|
var (
|
||||||
GeositeName = "GeoSite.dat"
|
GeositeName = "GeoSite.dat"
|
||||||
GeoipName = "GeoIP.dat"
|
GeoipName = "GeoIP.dat"
|
||||||
|
ASNName = "ASN.mmdb"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Path is used to get the configuration path
|
// Path is used to get the configuration path
|
||||||
@@ -112,6 +113,25 @@ func (p *path) MMDB() string {
|
|||||||
return P.Join(p.homeDir, "geoip.metadb")
|
return P.Join(p.homeDir, "geoip.metadb")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (p *path) ASN() string {
|
||||||
|
files, err := os.ReadDir(p.homeDir)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
for _, fi := range files {
|
||||||
|
if fi.IsDir() {
|
||||||
|
// 目录则直接跳过
|
||||||
|
continue
|
||||||
|
} else {
|
||||||
|
if strings.EqualFold(fi.Name(), "ASN.mmdb") {
|
||||||
|
ASNName = fi.Name()
|
||||||
|
return P.Join(p.homeDir, fi.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return P.Join(p.homeDir, ASNName)
|
||||||
|
}
|
||||||
|
|
||||||
func (p *path) OldCache() string {
|
func (p *path) OldCache() string {
|
||||||
return P.Join(p.homeDir, ".cache")
|
return P.Join(p.homeDir, ".cache")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ func (v VehicleType) String() string {
|
|||||||
type Vehicle interface {
|
type Vehicle interface {
|
||||||
Read() ([]byte, error)
|
Read() ([]byte, error)
|
||||||
Path() string
|
Path() string
|
||||||
|
Proxy() string
|
||||||
Type() VehicleType
|
Type() VehicleType
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,6 +74,7 @@ type ProxyProvider interface {
|
|||||||
HealthCheck()
|
HealthCheck()
|
||||||
Version() uint32
|
Version() uint32
|
||||||
RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint)
|
RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint)
|
||||||
|
HealthCheckURL() string
|
||||||
}
|
}
|
||||||
|
|
||||||
// RuleProvider interface
|
// RuleProvider interface
|
||||||
|
|||||||
@@ -5,8 +5,12 @@ const (
|
|||||||
Domain RuleType = iota
|
Domain RuleType = iota
|
||||||
DomainSuffix
|
DomainSuffix
|
||||||
DomainKeyword
|
DomainKeyword
|
||||||
|
DomainRegex
|
||||||
GEOSITE
|
GEOSITE
|
||||||
GEOIP
|
GEOIP
|
||||||
|
SrcGEOIP
|
||||||
|
IPASN
|
||||||
|
SrcIPASN
|
||||||
IPCIDR
|
IPCIDR
|
||||||
SrcIPCIDR
|
SrcIPCIDR
|
||||||
IPSuffix
|
IPSuffix
|
||||||
@@ -18,8 +22,10 @@ const (
|
|||||||
InUser
|
InUser
|
||||||
InName
|
InName
|
||||||
InType
|
InType
|
||||||
Process
|
ProcessName
|
||||||
ProcessPath
|
ProcessPath
|
||||||
|
ProcessNameRegex
|
||||||
|
ProcessPathRegex
|
||||||
RuleSet
|
RuleSet
|
||||||
Network
|
Network
|
||||||
Uid
|
Uid
|
||||||
@@ -40,10 +46,18 @@ func (rt RuleType) String() string {
|
|||||||
return "DomainSuffix"
|
return "DomainSuffix"
|
||||||
case DomainKeyword:
|
case DomainKeyword:
|
||||||
return "DomainKeyword"
|
return "DomainKeyword"
|
||||||
|
case DomainRegex:
|
||||||
|
return "DomainRegex"
|
||||||
case GEOSITE:
|
case GEOSITE:
|
||||||
return "GeoSite"
|
return "GeoSite"
|
||||||
case GEOIP:
|
case GEOIP:
|
||||||
return "GeoIP"
|
return "GeoIP"
|
||||||
|
case SrcGEOIP:
|
||||||
|
return "SrcGeoIP"
|
||||||
|
case IPASN:
|
||||||
|
return "IPASN"
|
||||||
|
case SrcIPASN:
|
||||||
|
return "SrcIPASN"
|
||||||
case IPCIDR:
|
case IPCIDR:
|
||||||
return "IPCIDR"
|
return "IPCIDR"
|
||||||
case SrcIPCIDR:
|
case SrcIPCIDR:
|
||||||
@@ -64,10 +78,14 @@ func (rt RuleType) String() string {
|
|||||||
return "InName"
|
return "InName"
|
||||||
case InType:
|
case InType:
|
||||||
return "InType"
|
return "InType"
|
||||||
case Process:
|
case ProcessName:
|
||||||
return "Process"
|
return "ProcessName"
|
||||||
case ProcessPath:
|
case ProcessPath:
|
||||||
return "ProcessPath"
|
return "ProcessPath"
|
||||||
|
case ProcessNameRegex:
|
||||||
|
return "ProcessNameRegex"
|
||||||
|
case ProcessPathRegex:
|
||||||
|
return "ProcessPathRegex"
|
||||||
case MATCH:
|
case MATCH:
|
||||||
return "Match"
|
return "Match"
|
||||||
case RuleSet:
|
case RuleSet:
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"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/log"
|
||||||
|
|
||||||
D "github.com/miekg/dns"
|
D "github.com/miekg/dns"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
"github.com/zhangyunhao116/fastrand"
|
||||||
@@ -77,7 +78,9 @@ func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error)
|
|||||||
options = append(options, dialer.WithInterface(c.iface))
|
options = append(options, dialer.WithInterface(c.iface))
|
||||||
}
|
}
|
||||||
|
|
||||||
conn, err := getDialHandler(c.r, c.proxyAdapter, c.proxyName, options...)(ctx, network, net.JoinHostPort(ip.String(), c.port))
|
dialHandler := getDialHandler(c.r, c.proxyAdapter, c.proxyName, options...)
|
||||||
|
addr := net.JoinHostPort(ip.String(), c.port)
|
||||||
|
conn, err := dialHandler(ctx, network, addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -97,12 +100,31 @@ func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error)
|
|||||||
conn = tls.Client(conn, ca.GetGlobalTLSConfig(c.Client.TLSConfig))
|
conn = tls.Client(conn, ca.GetGlobalTLSConfig(c.Client.TLSConfig))
|
||||||
}
|
}
|
||||||
|
|
||||||
msg, _, err := c.Client.ExchangeWithConn(m, &D.Conn{
|
dConn := &D.Conn{
|
||||||
Conn: conn,
|
Conn: conn,
|
||||||
UDPSize: c.Client.UDPSize,
|
UDPSize: c.Client.UDPSize,
|
||||||
TsigSecret: c.Client.TsigSecret,
|
TsigSecret: c.Client.TsigSecret,
|
||||||
TsigProvider: c.Client.TsigProvider,
|
TsigProvider: c.Client.TsigProvider,
|
||||||
})
|
}
|
||||||
|
|
||||||
|
msg, _, err := c.Client.ExchangeWithConn(m, dConn)
|
||||||
|
|
||||||
|
// Resolvers MUST resend queries over TCP if they receive a truncated UDP response (with TC=1 set)!
|
||||||
|
if msg != nil && msg.Truncated && c.Client.Net == "" {
|
||||||
|
tcpClient := *c.Client // copy a client
|
||||||
|
tcpClient.Net = "tcp"
|
||||||
|
network = "tcp"
|
||||||
|
log.Debugln("[DNS] Truncated reply from %s:%s for %s over UDP, retrying over TCP", c.host, c.port, m.Question[0].String())
|
||||||
|
dConn.Conn, err = dialHandler(ctx, network, addr)
|
||||||
|
if err != nil {
|
||||||
|
ch <- result{msg, err}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
_ = conn.Close()
|
||||||
|
}()
|
||||||
|
msg, _, err = tcpClient.ExchangeWithConn(m, dConn)
|
||||||
|
}
|
||||||
|
|
||||||
ch <- result{msg, err}
|
ch <- result{msg, err}
|
||||||
}()
|
}()
|
||||||
|
|||||||
@@ -515,7 +515,7 @@ func (doh *dnsOverHTTPS) createTransportH3(
|
|||||||
},
|
},
|
||||||
DisableCompression: true,
|
DisableCompression: true,
|
||||||
TLSClientConfig: tlsConfig,
|
TLSClientConfig: tlsConfig,
|
||||||
QuicConfig: doh.getQUICConfig(),
|
QUICConfig: doh.getQUICConfig(),
|
||||||
}
|
}
|
||||||
|
|
||||||
return &http3Transport{baseTransport: rt}, nil
|
return &http3Transport{baseTransport: rt}, nil
|
||||||
@@ -709,7 +709,8 @@ func (doh *dnsOverHTTPS) tlsDial(ctx context.Context, dialContext dialHandler, n
|
|||||||
err = conn.SetDeadline(time.Now().Add(dialTimeout))
|
err = conn.SetDeadline(time.Now().Add(dialTimeout))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Must not happen in normal circumstances.
|
// Must not happen in normal circumstances.
|
||||||
panic(fmt.Errorf("cannot set deadline: %w", err))
|
log.Errorln("cannot set deadline: %v", err)
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = conn.Handshake()
|
err = conn.Handshake()
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ var geoIPMatcher *router.GeoIPMatcher
|
|||||||
|
|
||||||
func (gf *geoipFilter) Match(ip netip.Addr) bool {
|
func (gf *geoipFilter) Match(ip netip.Addr) bool {
|
||||||
if !C.GeodataMode {
|
if !C.GeodataMode {
|
||||||
codes := mmdb.Instance().LookupCode(ip.AsSlice())
|
codes := mmdb.IPInstance().LookupCode(ip.AsSlice())
|
||||||
for _, code := range codes {
|
for _, code := range codes {
|
||||||
if !strings.EqualFold(code, gf.code) && !ip.IsPrivate() {
|
if !strings.EqualFold(code, gf.code) && !ip.IsPrivate() {
|
||||||
return true
|
return true
|
||||||
|
|||||||
@@ -324,7 +324,7 @@ func (r *Resolver) ipExchange(ctx context.Context, m *D.Msg) (msg *D.Msg, err er
|
|||||||
func (r *Resolver) lookupIP(ctx context.Context, host string, dnsType uint16) (ips []netip.Addr, err error) {
|
func (r *Resolver) lookupIP(ctx context.Context, host string, dnsType uint16) (ips []netip.Addr, err error) {
|
||||||
ip, err := netip.ParseAddr(host)
|
ip, err := netip.ParseAddr(host)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
isIPv4 := ip.Is4()
|
isIPv4 := ip.Is4() || ip.Is4In6()
|
||||||
if dnsType == D.TypeAAAA && !isIPv4 {
|
if dnsType == D.TypeAAAA && !isIPv4 {
|
||||||
return []netip.Addr{ip}, nil
|
return []netip.Addr{ip}, nil
|
||||||
} else if dnsType == D.TypeA && isIPv4 {
|
} else if dnsType == D.TypeA && isIPv4 {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
D "github.com/miekg/dns"
|
D "github.com/miekg/dns"
|
||||||
@@ -39,6 +40,9 @@ func (c *systemClient) getDnsClients() ([]dnsClient, error) {
|
|||||||
if nameservers, err = dnsReadConfig(); err == nil {
|
if nameservers, err = dnsReadConfig(); err == nil {
|
||||||
log.Debugln("[DNS] system dns update to %s", nameservers)
|
log.Debugln("[DNS] system dns update to %s", nameservers)
|
||||||
for _, addr := range nameservers {
|
for _, addr := range nameservers {
|
||||||
|
if resolver.IsSystemDnsBlacklisted(addr) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
if _, ok := c.dnsClients[addr]; !ok {
|
if _, ok := c.dnsClients[addr]; !ok {
|
||||||
clients := transform(
|
clients := transform(
|
||||||
[]NameServer{{
|
[]NameServer{{
|
||||||
|
|||||||
152
docs/config.yaml
152
docs/config.yaml
@@ -8,15 +8,15 @@ mixed-port: 10801 # HTTP(S) 和 SOCKS 代理混合端口
|
|||||||
|
|
||||||
allow-lan: true # 允许局域网连接
|
allow-lan: true # 允许局域网连接
|
||||||
bind-address: "*" # 绑定 IP 地址,仅作用于 allow-lan 为 true,'*'表示所有地址
|
bind-address: "*" # 绑定 IP 地址,仅作用于 allow-lan 为 true,'*'表示所有地址
|
||||||
authentication: # http,socks入口的验证用户名,密码
|
authentication: # http,socks 入口的验证用户名,密码
|
||||||
- "username:password"
|
- "username:password"
|
||||||
skip-auth-prefixes: # 设置跳过验证的IP段
|
skip-auth-prefixes: # 设置跳过验证的 IP 段
|
||||||
- 127.0.0.1/8
|
- 127.0.0.1/8
|
||||||
- ::1/128
|
- ::1/128
|
||||||
lan-allowed-ips: # 允许连接的 IP 地址段,仅作用于 allow-lan 为 true, 默认值为0.0.0.0/0和::/0
|
lan-allowed-ips: # 允许连接的 IP 地址段,仅作用于 allow-lan 为 true, 默认值为 0.0.0.0/0 和::/0
|
||||||
- 0.0.0.0/0
|
- 0.0.0.0/0
|
||||||
- ::/0
|
- ::/0
|
||||||
lan-disallowed-ips: # 禁止连接的 IP 地址段, 黑名单优先级高于白名单, 默认值为空
|
lan-disallowed-ips: # 禁止连接的 IP 地址段,黑名单优先级高于白名单,默认值为空
|
||||||
- 192.168.0.3/32
|
- 192.168.0.3/32
|
||||||
|
|
||||||
# find-process-mode has 3 values:always, strict, off
|
# find-process-mode has 3 values:always, strict, off
|
||||||
@@ -58,6 +58,11 @@ external-controller: 0.0.0.0:9093 # RESTful API 监听地址
|
|||||||
external-controller-tls: 0.0.0.0:9443 # RESTful API HTTPS 监听地址,需要配置 tls 部分配置文件
|
external-controller-tls: 0.0.0.0:9443 # RESTful API HTTPS 监听地址,需要配置 tls 部分配置文件
|
||||||
# secret: "123456" # `Authorization:Bearer ${secret}`
|
# secret: "123456" # `Authorization:Bearer ${secret}`
|
||||||
|
|
||||||
|
# RESTful API Unix socket 监听地址( windows版本大于17063也可以使用,即大于等于1803/RS4版本即可使用 )
|
||||||
|
# !!!注意: 从Unix socket访问api接口不会验证secret, 如果开启请自行保证安全问题 !!!
|
||||||
|
# 测试方法: curl -v --unix-socket "mihomo.sock" http://localhost/
|
||||||
|
external-controller-unix: mihomo.sock
|
||||||
|
|
||||||
# tcp-concurrent: true # TCP 并发连接所有 IP, 将使用最快握手的 TCP
|
# tcp-concurrent: true # TCP 并发连接所有 IP, 将使用最快握手的 TCP
|
||||||
|
|
||||||
# 配置 WEB UI 目录,使用 http://{{external-controller}}/ui 访问
|
# 配置 WEB UI 目录,使用 http://{{external-controller}}/ui 访问
|
||||||
@@ -109,9 +114,9 @@ tun:
|
|||||||
# auto-detect-interface: true # 自动识别出口网卡
|
# auto-detect-interface: true # 自动识别出口网卡
|
||||||
# auto-route: true # 配置路由表
|
# auto-route: true # 配置路由表
|
||||||
# mtu: 9000 # 最大传输单元
|
# mtu: 9000 # 最大传输单元
|
||||||
# gso: false # 启用通用分段卸载, 仅支持 Linux
|
# gso: false # 启用通用分段卸载,仅支持 Linux
|
||||||
# gso-max-size: 65536 # 通用分段卸载包的最大大小
|
# gso-max-size: 65536 # 通用分段卸载包的最大大小
|
||||||
# strict-route: true # 将所有连接路由到tun来防止泄漏,但你的设备将无法其他设备被访问
|
# strict-route: true # 将所有连接路由到 tun 来防止泄漏,但你的设备将无法其他设备被访问
|
||||||
inet4-route-address: # 启用 auto-route 时使用自定义路由而不是默认路由
|
inet4-route-address: # 启用 auto-route 时使用自定义路由而不是默认路由
|
||||||
- 0.0.0.0/1
|
- 0.0.0.0/1
|
||||||
- 128.0.0.0/1
|
- 128.0.0.0/1
|
||||||
@@ -119,9 +124,9 @@ tun:
|
|||||||
- "::/1"
|
- "::/1"
|
||||||
- "8000::/1"
|
- "8000::/1"
|
||||||
# endpoint-independent-nat: false # 启用独立于端点的 NAT
|
# endpoint-independent-nat: false # 启用独立于端点的 NAT
|
||||||
# include-interface: # 限制被路由的接口。默认不限制, 与 `exclude-interface` 冲突
|
# include-interface: # 限制被路由的接口。默认不限制,与 `exclude-interface` 冲突
|
||||||
# - "lan0"
|
# - "lan0"
|
||||||
# exclude-interface: # 排除路由的接口, 与 `include-interface` 冲突
|
# exclude-interface: # 排除路由的接口,与 `include-interface` 冲突
|
||||||
# - "lan1"
|
# - "lan1"
|
||||||
# include-uid: # UID 规则仅在 Linux 下被支持,并且需要 auto-route
|
# include-uid: # UID 规则仅在 Linux 下被支持,并且需要 auto-route
|
||||||
# - 0
|
# - 0
|
||||||
@@ -143,7 +148,7 @@ tun:
|
|||||||
# exclude-package: # 排除被路由的 Android 应用包名
|
# exclude-package: # 排除被路由的 Android 应用包名
|
||||||
# - com.android.captiveportallogin
|
# - com.android.captiveportallogin
|
||||||
|
|
||||||
#ebpf配置
|
#ebpf 配置
|
||||||
ebpf:
|
ebpf:
|
||||||
auto-redir: # redirect 模式,仅支持 TCP
|
auto-redir: # redirect 模式,仅支持 TCP
|
||||||
- eth0
|
- eth0
|
||||||
@@ -200,7 +205,7 @@ tunnels: # one line config
|
|||||||
target: target.com
|
target: target.com
|
||||||
proxy: proxy
|
proxy: proxy
|
||||||
|
|
||||||
# DNS配置
|
# DNS 配置
|
||||||
dns:
|
dns:
|
||||||
cache-algorithm: arc
|
cache-algorithm: arc
|
||||||
enable: false # 关闭将使用系统 DNS
|
enable: false # 关闭将使用系统 DNS
|
||||||
@@ -208,7 +213,7 @@ dns:
|
|||||||
listen: 0.0.0.0:53 # 开启 DNS 服务器监听
|
listen: 0.0.0.0:53 # 开启 DNS 服务器监听
|
||||||
# ipv6: false # false 将返回 AAAA 的空结果
|
# ipv6: false # false 将返回 AAAA 的空结果
|
||||||
# ipv6-timeout: 300 # 单位:ms,内部双栈并发时,向上游查询 AAAA 时,等待 AAAA 的时间,默认 100ms
|
# ipv6-timeout: 300 # 单位:ms,内部双栈并发时,向上游查询 AAAA 时,等待 AAAA 的时间,默认 100ms
|
||||||
# 用于解析 nameserver,fallback 以及其他DNS服务器配置的,DNS 服务域名
|
# 用于解析 nameserver,fallback 以及其他 DNS 服务器配置的,DNS 服务域名
|
||||||
# 只能使用纯 IP 地址,可使用加密 DNS
|
# 只能使用纯 IP 地址,可使用加密 DNS
|
||||||
default-nameserver:
|
default-nameserver:
|
||||||
- 114.114.114.114
|
- 114.114.114.114
|
||||||
@@ -222,12 +227,12 @@ dns:
|
|||||||
|
|
||||||
# use-hosts: true # 查询 hosts
|
# use-hosts: true # 查询 hosts
|
||||||
|
|
||||||
# 配置不使用fake-ip的域名
|
# 配置不使用 fake-ip 的域名
|
||||||
# fake-ip-filter:
|
# fake-ip-filter:
|
||||||
# - '*.lan'
|
# - '*.lan'
|
||||||
# - localhost.ptlogin2.qq.com
|
# - localhost.ptlogin2.qq.com
|
||||||
|
|
||||||
# DNS主要域名配置
|
# DNS 主要域名配置
|
||||||
# 支持 UDP,TCP,DoT,DoH,DoQ
|
# 支持 UDP,TCP,DoT,DoH,DoQ
|
||||||
# 这部分为主要 DNS 配置,影响所有直连,确保使用对大陆解析精准的 DNS
|
# 这部分为主要 DNS 配置,影响所有直连,确保使用对大陆解析精准的 DNS
|
||||||
nameserver:
|
nameserver:
|
||||||
@@ -239,7 +244,7 @@ dns:
|
|||||||
- https://mozilla.cloudflare-dns.com/dns-query#DNS&h3=true # 指定策略组和使用 HTTP/3
|
- https://mozilla.cloudflare-dns.com/dns-query#DNS&h3=true # 指定策略组和使用 HTTP/3
|
||||||
- dhcp://en0 # dns from dhcp
|
- dhcp://en0 # dns from dhcp
|
||||||
- quic://dns.adguard.com:784 # DNS over QUIC
|
- quic://dns.adguard.com:784 # DNS over QUIC
|
||||||
# - '8.8.8.8#en0' # 兼容指定DNS出口网卡
|
# - '8.8.8.8#en0' # 兼容指定 DNS 出口网卡
|
||||||
|
|
||||||
# 当配置 fallback 时,会查询 nameserver 中返回的 IP 是否为 CN,非必要配置
|
# 当配置 fallback 时,会查询 nameserver 中返回的 IP 是否为 CN,非必要配置
|
||||||
# 当不是 CN,则使用 fallback 中的 DNS 查询结果
|
# 当不是 CN,则使用 fallback 中的 DNS 查询结果
|
||||||
@@ -249,7 +254,6 @@ dns:
|
|||||||
# - 'tcp://1.1.1.1#ProxyGroupName' # 指定 DNS 过代理查询,ProxyGroupName 为策略组名或节点名,过代理配置优先于配置出口网卡,当找不到策略组或节点名则设置为出口网卡
|
# - 'tcp://1.1.1.1#ProxyGroupName' # 指定 DNS 过代理查询,ProxyGroupName 为策略组名或节点名,过代理配置优先于配置出口网卡,当找不到策略组或节点名则设置为出口网卡
|
||||||
|
|
||||||
# 专用于节点域名解析的 DNS 服务器,非必要配置项
|
# 专用于节点域名解析的 DNS 服务器,非必要配置项
|
||||||
# 配置服务器若查询失败将使用 nameserver,非并发查询
|
|
||||||
# proxy-server-nameserver:
|
# proxy-server-nameserver:
|
||||||
# - https://dns.google/dns-query
|
# - https://dns.google/dns-query
|
||||||
# - tls://one.one.one.one
|
# - tls://one.one.one.one
|
||||||
@@ -338,7 +342,7 @@ proxies: # socks5
|
|||||||
# udp-over-tcp: false
|
# udp-over-tcp: false
|
||||||
# ip-version: ipv4 # 设置节点使用 IP 版本,可选:dual,ipv4,ipv6,ipv4-prefer,ipv6-prefer。默认使用 dual
|
# ip-version: ipv4 # 设置节点使用 IP 版本,可选:dual,ipv4,ipv6,ipv4-prefer,ipv6-prefer。默认使用 dual
|
||||||
# ipv4:仅使用 IPv4 ipv6:仅使用 IPv6
|
# ipv4:仅使用 IPv4 ipv6:仅使用 IPv6
|
||||||
# ipv4-prefer:优先使用 IPv4 对于 TCP 会进行双栈解析,并发链接但是优先使用 IPv4 链接,
|
# ipv4-prefer:优先使用 IPv4 对于 TCP 会进行双栈解析,并发链接但是优先使用 IPv4 链接,
|
||||||
# UDP 则为双栈解析,获取结果中的第一个 IPv4
|
# UDP 则为双栈解析,获取结果中的第一个 IPv4
|
||||||
# ipv6-prefer 同 ipv4-prefer
|
# ipv6-prefer 同 ipv4-prefer
|
||||||
# 现有协议都支持此参数,TCP 效果仅在开启 tcp-concurrent 生效
|
# 现有协议都支持此参数,TCP 效果仅在开启 tcp-concurrent 生效
|
||||||
@@ -350,7 +354,7 @@ proxies: # socks5
|
|||||||
# max-streams: 0 # Maximum multiplexed streams in a connection before opening a new connection. Conflict with max-connections and min-streams.
|
# max-streams: 0 # Maximum multiplexed streams in a connection before opening a new connection. Conflict with max-connections and min-streams.
|
||||||
# padding: false # Enable padding. Requires sing-box server version 1.3-beta9 or later.
|
# padding: false # Enable padding. Requires sing-box server version 1.3-beta9 or later.
|
||||||
# statistic: false # 控制是否将底层连接显示在面板中,方便打断底层连接
|
# statistic: false # 控制是否将底层连接显示在面板中,方便打断底层连接
|
||||||
# only-tcp: false # 如果设置为true, smux的设置将不会对udp生效,udp连接会直接走底层协议
|
# only-tcp: false # 如果设置为 true, smux 的设置将不会对 udp 生效,udp 连接会直接走底层协议
|
||||||
|
|
||||||
- name: "ss2"
|
- name: "ss2"
|
||||||
type: ss
|
type: ss
|
||||||
@@ -383,6 +387,7 @@ proxies: # socks5
|
|||||||
# headers:
|
# headers:
|
||||||
# custom: value
|
# custom: value
|
||||||
# v2ray-http-upgrade: false
|
# v2ray-http-upgrade: false
|
||||||
|
# v2ray-http-upgrade-fast-open: false
|
||||||
|
|
||||||
- name: "ss4-shadow-tls"
|
- name: "ss4-shadow-tls"
|
||||||
type: ss
|
type: ss
|
||||||
@@ -405,18 +410,18 @@ proxies: # socks5
|
|||||||
password: [YOUR_SS_PASSWORD]
|
password: [YOUR_SS_PASSWORD]
|
||||||
client-fingerprint:
|
client-fingerprint:
|
||||||
chrome # One of: chrome, ios, firefox or safari
|
chrome # One of: chrome, ios, firefox or safari
|
||||||
# 可以是chrome, ios, firefox, safari中的一个
|
# 可以是 chrome, ios, firefox, safari 中的一个
|
||||||
plugin: restls
|
plugin: restls
|
||||||
plugin-opts:
|
plugin-opts:
|
||||||
host:
|
host:
|
||||||
"www.microsoft.com" # Must be a TLS 1.3 server
|
"www.microsoft.com" # Must be a TLS 1.3 server
|
||||||
# 应当是一个TLS 1.3 服务器
|
# 应当是一个 TLS 1.3 服务器
|
||||||
password: [YOUR_RESTLS_PASSWORD]
|
password: [YOUR_RESTLS_PASSWORD]
|
||||||
version-hint: "tls13"
|
version-hint: "tls13"
|
||||||
# Control your post-handshake traffic through restls-script
|
# Control your post-handshake traffic through restls-script
|
||||||
# Hide proxy behaviors like "tls in tls".
|
# Hide proxy behaviors like "tls in tls".
|
||||||
# see https://github.com/3andne/restls/blob/main/Restls-Script:%20Hide%20Your%20Proxy%20Traffic%20Behavior.md
|
# see https://github.com/3andne/restls/blob/main/Restls-Script:%20Hide%20Your%20Proxy%20Traffic%20Behavior.md
|
||||||
# 用restls剧本来控制握手后的行为,隐藏"tls in tls"等特征
|
# 用 restls 剧本来控制握手后的行为,隐藏"tls in tls"等特征
|
||||||
# 详情:https://github.com/3andne/restls/blob/main/Restls-Script:%20%E9%9A%90%E8%97%8F%E4%BD%A0%E7%9A%84%E4%BB%A3%E7%90%86%E8%A1%8C%E4%B8%BA.md
|
# 详情:https://github.com/3andne/restls/blob/main/Restls-Script:%20%E9%9A%90%E8%97%8F%E4%BD%A0%E7%9A%84%E4%BB%A3%E7%90%86%E8%A1%8C%E4%B8%BA.md
|
||||||
restls-script: "300?100<1,400~100,350~100,600~100,300~200,300~100"
|
restls-script: "300?100<1,400~100,350~100,600~100,300~200,300~100"
|
||||||
|
|
||||||
@@ -428,18 +433,18 @@ proxies: # socks5
|
|||||||
password: [YOUR_SS_PASSWORD]
|
password: [YOUR_SS_PASSWORD]
|
||||||
client-fingerprint:
|
client-fingerprint:
|
||||||
chrome # One of: chrome, ios, firefox or safari
|
chrome # One of: chrome, ios, firefox or safari
|
||||||
# 可以是chrome, ios, firefox, safari中的一个
|
# 可以是 chrome, ios, firefox, safari 中的一个
|
||||||
plugin: restls
|
plugin: restls
|
||||||
plugin-opts:
|
plugin-opts:
|
||||||
host:
|
host:
|
||||||
"vscode.dev" # Must be a TLS 1.2 server
|
"vscode.dev" # Must be a TLS 1.2 server
|
||||||
# 应当是一个TLS 1.2 服务器
|
# 应当是一个 TLS 1.2 服务器
|
||||||
password: [YOUR_RESTLS_PASSWORD]
|
password: [YOUR_RESTLS_PASSWORD]
|
||||||
version-hint: "tls12"
|
version-hint: "tls12"
|
||||||
restls-script: "1000?100<1,500~100,350~100,600~100,400~200"
|
restls-script: "1000?100<1,500~100,350~100,600~100,400~200"
|
||||||
|
|
||||||
# vmess
|
# vmess
|
||||||
# cipher支持 auto/aes-128-gcm/chacha20-poly1305/none
|
# cipher 支持 auto/aes-128-gcm/chacha20-poly1305/none
|
||||||
- name: "vmess"
|
- name: "vmess"
|
||||||
type: vmess
|
type: vmess
|
||||||
server: server
|
server: server
|
||||||
@@ -461,6 +466,7 @@ proxies: # socks5
|
|||||||
# max-early-data: 2048
|
# max-early-data: 2048
|
||||||
# early-data-header-name: Sec-WebSocket-Protocol
|
# early-data-header-name: Sec-WebSocket-Protocol
|
||||||
# v2ray-http-upgrade: false
|
# v2ray-http-upgrade: false
|
||||||
|
# v2ray-http-upgrade-fast-open: false
|
||||||
|
|
||||||
- name: "vmess-h2"
|
- name: "vmess-h2"
|
||||||
type: vmess
|
type: vmess
|
||||||
@@ -589,6 +595,7 @@ proxies: # socks5
|
|||||||
headers:
|
headers:
|
||||||
Host: example.com
|
Host: example.com
|
||||||
# v2ray-http-upgrade: false
|
# v2ray-http-upgrade: false
|
||||||
|
# v2ray-http-upgrade-fast-open: false
|
||||||
|
|
||||||
# Trojan
|
# Trojan
|
||||||
- name: "trojan"
|
- name: "trojan"
|
||||||
@@ -633,6 +640,7 @@ proxies: # socks5
|
|||||||
# headers:
|
# headers:
|
||||||
# Host: example.com
|
# Host: example.com
|
||||||
# v2ray-http-upgrade: false
|
# v2ray-http-upgrade: false
|
||||||
|
# v2ray-http-upgrade-fast-open: false
|
||||||
|
|
||||||
- name: "trojan-xtls"
|
- name: "trojan-xtls"
|
||||||
type: trojan
|
type: trojan
|
||||||
@@ -674,11 +682,13 @@ proxies: # socks5
|
|||||||
type: hysteria2
|
type: hysteria2
|
||||||
server: server.com
|
server: server.com
|
||||||
port: 443
|
port: 443
|
||||||
# up和down均不写或为0则使用BBR流控
|
# ports: 1000,2000-3000,5000 # port 不可省略
|
||||||
|
# hop-interval: 15
|
||||||
|
# up 和 down 均不写或为 0 则使用 BBR 流控
|
||||||
# up: "30 Mbps" # 若不写单位,默认为 Mbps
|
# up: "30 Mbps" # 若不写单位,默认为 Mbps
|
||||||
# down: "200 Mbps" # 若不写单位,默认为 Mbps
|
# down: "200 Mbps" # 若不写单位,默认为 Mbps
|
||||||
password: yourpassword
|
password: yourpassword
|
||||||
# obfs: salamander # 默认为空,如果填写则开启obfs,目前仅支持salamander
|
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前仅支持 salamander
|
||||||
# obfs-password: yourpassword
|
# obfs-password: yourpassword
|
||||||
# sni: server.com
|
# sni: server.com
|
||||||
# skip-cert-verify: false
|
# skip-cert-verify: false
|
||||||
@@ -704,14 +714,12 @@ proxies: # socks5
|
|||||||
# reserved: [209,98,59]
|
# reserved: [209,98,59]
|
||||||
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
|
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
|
||||||
# dialer-proxy: "ss1"
|
# dialer-proxy: "ss1"
|
||||||
# remote-dns-resolve: true # 强制dns远程解析,默认值为false
|
# remote-dns-resolve: true # 强制 dns 远程解析,默认值为 false
|
||||||
# dns: [ 1.1.1.1, 8.8.8.8 ] # 仅在remote-dns-resolve为true时生效
|
# dns: [ 1.1.1.1, 8.8.8.8 ] # 仅在 remote-dns-resolve 为 true 时生效
|
||||||
# 如果peers不为空,该段落中的allowed-ips不可为空;前面段落的server,port,ip,ipv6,public-key,pre-shared-key均会被忽略,但private-key会被保留且只能在顶层指定
|
# 如果 peers 不为空,该段落中的 allowed-ips 不可为空;前面段落的 server,port,public-key,pre-shared-key 均会被忽略,但 private-key 会被保留且只能在顶层指定
|
||||||
# peers:
|
# peers:
|
||||||
# - server: 162.159.192.1
|
# - server: 162.159.192.1
|
||||||
# port: 2480
|
# port: 2480
|
||||||
# ip: 172.16.0.2
|
|
||||||
# ipv6: fd01:5ca1:ab1e:80fa:ab85:6eea:213f:f4a5
|
|
||||||
# public-key: Cr8hWlKvtDt7nrvf+f0brNQQzabAqrjfBvas9pmowjo=
|
# public-key: Cr8hWlKvtDt7nrvf+f0brNQQzabAqrjfBvas9pmowjo=
|
||||||
# # pre-shared-key: 31aIhAPwktDGpH4JDhA8GNvjFXEf/a6+UaQRyOAiyfM=
|
# # pre-shared-key: 31aIhAPwktDGpH4JDhA8GNvjFXEf/a6+UaQRyOAiyfM=
|
||||||
# allowed-ips: ['0.0.0.0/0']
|
# allowed-ips: ['0.0.0.0/0']
|
||||||
@@ -722,9 +730,9 @@ proxies: # socks5
|
|||||||
server: www.example.com
|
server: www.example.com
|
||||||
port: 10443
|
port: 10443
|
||||||
type: tuic
|
type: tuic
|
||||||
# tuicV4必须填写token (不可同时填写uuid和password)
|
# tuicV4 必须填写 token(不可同时填写 uuid 和 password)
|
||||||
token: TOKEN
|
token: TOKEN
|
||||||
# tuicV5必须填写uuid和password(不可同时填写token)
|
# tuicV5 必须填写 uuid 和 password(不可同时填写 token)
|
||||||
uuid: 00000000-0000-0000-0000-000000000001
|
uuid: 00000000-0000-0000-0000-000000000001
|
||||||
password: PASSWORD_1
|
password: PASSWORD_1
|
||||||
# ip: 127.0.0.1 # for overwriting the DNS lookup result of the server address set in option 'server'
|
# ip: 127.0.0.1 # for overwriting the DNS lookup result of the server address set in option 'server'
|
||||||
@@ -742,8 +750,8 @@ proxies: # socks5
|
|||||||
# max-open-streams: 20 # default 100, too many open streams may hurt performance
|
# max-open-streams: 20 # default 100, too many open streams may hurt performance
|
||||||
# sni: example.com
|
# sni: example.com
|
||||||
#
|
#
|
||||||
# meta和sing-box私有扩展,将ss-uot用于udp中继,开启此选项后udp-relay-mode将失效
|
# meta 和 sing-box 私有扩展,将 ss-uot 用于 udp 中继,开启此选项后 udp-relay-mode 将失效
|
||||||
# 警告,与原版tuic不兼容!!!
|
# 警告,与原版 tuic 不兼容!!!
|
||||||
# udp-over-stream: false
|
# udp-over-stream: false
|
||||||
# udp-over-stream-version: 1
|
# udp-over-stream-version: 1
|
||||||
|
|
||||||
@@ -767,9 +775,21 @@ proxies: # socks5
|
|||||||
# protocol-param: "#"
|
# protocol-param: "#"
|
||||||
# udp: true
|
# udp: true
|
||||||
|
|
||||||
|
- name: "ssh-out"
|
||||||
|
type: ssh
|
||||||
|
|
||||||
|
server: 127.0.0.1
|
||||||
|
port: 22
|
||||||
|
username: root
|
||||||
|
password: password
|
||||||
|
privateKey: path
|
||||||
|
|
||||||
|
# dns 出站会将请求劫持到内部 dns 模块,所有请求均在内部处理
|
||||||
|
- name: "dns-out"
|
||||||
|
type: dns
|
||||||
proxy-groups:
|
proxy-groups:
|
||||||
# 代理链,目前relay可以支持udp的只有vmess/vless/trojan/ss/ssr/tuic
|
# 代理链,目前 relay 可以支持 udp 的只有 vmess/vless/trojan/ss/ssr/tuic
|
||||||
# wireguard目前不支持在relay中使用,请使用proxy中的dialer-proxy配置项
|
# wireguard 目前不支持在 relay 中使用,请使用 proxy 中的 dialer-proxy 配置项
|
||||||
# Traffic: mihomo <-> http <-> vmess <-> ss1 <-> ss2 <-> Internet
|
# Traffic: mihomo <-> http <-> vmess <-> ss1 <-> ss2 <-> Internet
|
||||||
- name: "relay"
|
- name: "relay"
|
||||||
type: relay
|
type: relay
|
||||||
@@ -843,10 +863,19 @@ proxy-groups:
|
|||||||
# Mihomo 格式的节点或支持 *ray 的分享格式
|
# Mihomo 格式的节点或支持 *ray 的分享格式
|
||||||
proxy-providers:
|
proxy-providers:
|
||||||
provider1:
|
provider1:
|
||||||
type: http # http 的 path 可空置,默认储存路径为 homedir的proxies文件夹,文件名为url的md5
|
type: http # http 的 path 可空置,默认储存路径为 homedir 的 proxies 文件夹,文件名为 url 的 md5
|
||||||
url: "url"
|
url: "url"
|
||||||
interval: 3600
|
interval: 3600
|
||||||
path: ./provider1.yaml # 默认只允许存储在 mihomo 的 Home Dir,如果想存储到任意位置,添加环境变量 SKIP_SAFE_PATH_CHECK=1
|
path: ./provider1.yaml # 默认只允许存储在 mihomo 的 Home Dir,如果想存储到任意位置,添加环境变量 SKIP_SAFE_PATH_CHECK=1
|
||||||
|
proxy: DIRECT
|
||||||
|
header:
|
||||||
|
User-Agent:
|
||||||
|
- "Clash/v1.18.0"
|
||||||
|
- "mihomo/1.18.3"
|
||||||
|
# Accept:
|
||||||
|
# - 'application/vnd.github.v3.raw'
|
||||||
|
# Authorization:
|
||||||
|
# - 'token 1231231'
|
||||||
health-check:
|
health-check:
|
||||||
enable: true
|
enable: true
|
||||||
interval: 600
|
interval: 600
|
||||||
@@ -862,6 +891,8 @@ proxy-providers:
|
|||||||
# interface-name: tailscale0
|
# interface-name: tailscale0
|
||||||
# routing-mark: 233
|
# routing-mark: 233
|
||||||
# ip-version: ipv4-prefer
|
# ip-version: ipv4-prefer
|
||||||
|
# additional-prefix: "[provider1]"
|
||||||
|
# additional-suffix: "test"
|
||||||
test:
|
test:
|
||||||
type: file
|
type: file
|
||||||
path: /test.yaml
|
path: /test.yaml
|
||||||
@@ -874,8 +905,9 @@ rule-providers:
|
|||||||
behavior: classical # domain ipcidr
|
behavior: classical # domain ipcidr
|
||||||
interval: 259200
|
interval: 259200
|
||||||
path: /path/to/save/file.yaml # 默认只允许存储在 mihomo 的 Home Dir,如果想存储到任意位置,添加环境变量 SKIP_SAFE_PATH_CHECK=1
|
path: /path/to/save/file.yaml # 默认只允许存储在 mihomo 的 Home Dir,如果想存储到任意位置,添加环境变量 SKIP_SAFE_PATH_CHECK=1
|
||||||
type: http # http 的 path 可空置,默认储存路径为 homedir的rules文件夹,文件名为url的md5
|
type: http # http 的 path 可空置,默认储存路径为 homedir 的 rules 文件夹,文件名为 url 的 md5
|
||||||
url: "url"
|
url: "url"
|
||||||
|
proxy: DIRECT
|
||||||
rule2:
|
rule2:
|
||||||
behavior: classical
|
behavior: classical
|
||||||
interval: 259200
|
interval: 259200
|
||||||
@@ -883,6 +915,8 @@ rule-providers:
|
|||||||
type: file
|
type: file
|
||||||
rules:
|
rules:
|
||||||
- RULE-SET,rule1,REJECT
|
- RULE-SET,rule1,REJECT
|
||||||
|
- IP-ASN,1,PROXY
|
||||||
|
- DOMAIN-REGEX,^abc,DIRECT
|
||||||
- DOMAIN-SUFFIX,baidu.com,DIRECT
|
- DOMAIN-SUFFIX,baidu.com,DIRECT
|
||||||
- DOMAIN-KEYWORD,google,ss1
|
- DOMAIN-KEYWORD,google,ss1
|
||||||
- IP-CIDR,1.1.1.1/32,ss1
|
- IP-CIDR,1.1.1.1/32,ss1
|
||||||
@@ -922,7 +956,7 @@ listeners:
|
|||||||
port: 10808
|
port: 10808
|
||||||
#listen: 0.0.0.0 # 默认监听 0.0.0.0
|
#listen: 0.0.0.0 # 默认监听 0.0.0.0
|
||||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定proxy处理
|
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理
|
||||||
# udp: false # 默认 true
|
# udp: false # 默认 true
|
||||||
|
|
||||||
- name: http-in-1
|
- name: http-in-1
|
||||||
@@ -930,14 +964,14 @@ listeners:
|
|||||||
port: 10809
|
port: 10809
|
||||||
listen: 0.0.0.0
|
listen: 0.0.0.0
|
||||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定proxy处理(当proxy不为空时,这里的proxy名称必须合法,否则会出错)
|
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||||
|
|
||||||
- name: mixed-in-1
|
- name: mixed-in-1
|
||||||
type: mixed # HTTP(S) 和 SOCKS 代理混合
|
type: mixed # HTTP(S) 和 SOCKS 代理混合
|
||||||
port: 10810
|
port: 10810
|
||||||
listen: 0.0.0.0
|
listen: 0.0.0.0
|
||||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定proxy处理(当proxy不为空时,这里的proxy名称必须合法,否则会出错)
|
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||||
# udp: false # 默认 true
|
# udp: false # 默认 true
|
||||||
|
|
||||||
- name: reidr-in-1
|
- name: reidr-in-1
|
||||||
@@ -945,14 +979,14 @@ listeners:
|
|||||||
port: 10811
|
port: 10811
|
||||||
listen: 0.0.0.0
|
listen: 0.0.0.0
|
||||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定proxy处理(当proxy不为空时,这里的proxy名称必须合法,否则会出错)
|
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||||
|
|
||||||
- name: tproxy-in-1
|
- name: tproxy-in-1
|
||||||
type: tproxy
|
type: tproxy
|
||||||
port: 10812
|
port: 10812
|
||||||
listen: 0.0.0.0
|
listen: 0.0.0.0
|
||||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定proxy处理(当proxy不为空时,这里的proxy名称必须合法,否则会出错)
|
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||||
# udp: false # 默认 true
|
# udp: false # 默认 true
|
||||||
|
|
||||||
- name: shadowsocks-in-1
|
- name: shadowsocks-in-1
|
||||||
@@ -960,7 +994,7 @@ listeners:
|
|||||||
port: 10813
|
port: 10813
|
||||||
listen: 0.0.0.0
|
listen: 0.0.0.0
|
||||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定proxy处理(当proxy不为空时,这里的proxy名称必须合法,否则会出错)
|
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||||
password: vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg=
|
password: vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg=
|
||||||
cipher: 2022-blake3-aes-256-gcm
|
cipher: 2022-blake3-aes-256-gcm
|
||||||
|
|
||||||
@@ -969,13 +1003,13 @@ listeners:
|
|||||||
port: 10814
|
port: 10814
|
||||||
listen: 0.0.0.0
|
listen: 0.0.0.0
|
||||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定proxy处理(当proxy不为空时,这里的proxy名称必须合法,否则会出错)
|
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||||
users:
|
users:
|
||||||
- username: 1
|
- username: 1
|
||||||
uuid: 9d0cb9d0-964f-4ef6-897d-6c6b3ccf9e68
|
uuid: 9d0cb9d0-964f-4ef6-897d-6c6b3ccf9e68
|
||||||
alterId: 1
|
alterId: 1
|
||||||
# ws-path: "/" # 如果不为空则开启websocket传输层
|
# ws-path: "/" # 如果不为空则开启 websocket 传输层
|
||||||
# 下面两项如果填写则开启tls(需要同时填写)
|
# 下面两项如果填写则开启 tls(需要同时填写)
|
||||||
# certificate: ./server.crt
|
# certificate: ./server.crt
|
||||||
# private-key: ./server.key
|
# private-key: ./server.key
|
||||||
|
|
||||||
@@ -984,10 +1018,10 @@ listeners:
|
|||||||
port: 10815
|
port: 10815
|
||||||
listen: 0.0.0.0
|
listen: 0.0.0.0
|
||||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定proxy处理(当proxy不为空时,这里的proxy名称必须合法,否则会出错)
|
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||||
# token: # tuicV4填写(可以同时填写users)
|
# token: # tuicV4 填写(可以同时填写 users)
|
||||||
# - TOKEN
|
# - TOKEN
|
||||||
# users: # tuicV5填写(可以同时填写token)
|
# users: # tuicV5 填写(可以同时填写 token)
|
||||||
# 00000000-0000-0000-0000-000000000000: PASSWORD_0
|
# 00000000-0000-0000-0000-000000000000: PASSWORD_0
|
||||||
# 00000000-0000-0000-0000-000000000001: PASSWORD_1
|
# 00000000-0000-0000-0000-000000000001: PASSWORD_1
|
||||||
# certificate: ./server.crt
|
# certificate: ./server.crt
|
||||||
@@ -1004,25 +1038,25 @@ listeners:
|
|||||||
port: 10816
|
port: 10816
|
||||||
listen: 0.0.0.0
|
listen: 0.0.0.0
|
||||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定proxy处理(当proxy不为空时,这里的proxy名称必须合法,否则会出错)
|
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||||
network: [tcp, udp]
|
network: [tcp, udp]
|
||||||
target: target.com
|
target: target.com
|
||||||
|
|
||||||
- name: tun-in-1
|
- name: tun-in-1
|
||||||
type: tun
|
type: tun
|
||||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定proxy处理(当proxy不为空时,这里的proxy名称必须合法,否则会出错)
|
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||||
stack: system # gvisor / mixed
|
stack: system # gvisor / mixed
|
||||||
dns-hijack:
|
dns-hijack:
|
||||||
- 0.0.0.0:53 # 需要劫持的 DNS
|
- 0.0.0.0:53 # 需要劫持的 DNS
|
||||||
# auto-detect-interface: false # 自动识别出口网卡
|
# auto-detect-interface: false # 自动识别出口网卡
|
||||||
# auto-route: false # 配置路由表
|
# auto-route: false # 配置路由表
|
||||||
# mtu: 9000 # 最大传输单元
|
# mtu: 9000 # 最大传输单元
|
||||||
inet4-address: # 必须手动设置ipv4地址段
|
inet4-address: # 必须手动设置 ipv4 地址段
|
||||||
- 198.19.0.1/30
|
- 198.19.0.1/30
|
||||||
inet6-address: # 必须手动设置ipv6地址段
|
inet6-address: # 必须手动设置 ipv6 地址段
|
||||||
- "fdfe:dcba:9877::1/126"
|
- "fdfe:dcba:9877::1/126"
|
||||||
# strict-route: true # 将所有连接路由到tun来防止泄漏,但你的设备将无法其他设备被访问
|
# strict-route: true # 将所有连接路由到 tun 来防止泄漏,但你的设备将无法其他设备被访问
|
||||||
# inet4-route-address: # 启用 auto-route 时使用自定义路由而不是默认路由
|
# inet4-route-address: # 启用 auto-route 时使用自定义路由而不是默认路由
|
||||||
# - 0.0.0.0/1
|
# - 0.0.0.0/1
|
||||||
# - 128.0.0.0/1
|
# - 128.0.0.0/1
|
||||||
@@ -1050,17 +1084,17 @@ listeners:
|
|||||||
# exclude-package: # 排除被路由的 Android 应用包名
|
# exclude-package: # 排除被路由的 Android 应用包名
|
||||||
# - com.android.captiveportallogin
|
# - com.android.captiveportallogin
|
||||||
# 入口配置与 Listener 等价,传入流量将和 socks,mixed 等入口一样按照 mode 所指定的方式进行匹配处理
|
# 入口配置与 Listener 等价,传入流量将和 socks,mixed 等入口一样按照 mode 所指定的方式进行匹配处理
|
||||||
# shadowsocks,vmess 入口配置(传入流量将和socks,mixed等入口一样按照mode所指定的方式进行匹配处理)
|
# shadowsocks,vmess 入口配置(传入流量将和 socks,mixed 等入口一样按照 mode 所指定的方式进行匹配处理)
|
||||||
# ss-config: ss://2022-blake3-aes-256-gcm:vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg=@:23456
|
# ss-config: ss://2022-blake3-aes-256-gcm:vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg=@:23456
|
||||||
# vmess-config: vmess://1:9d0cb9d0-964f-4ef6-897d-6c6b3ccf9e68@:12345
|
# vmess-config: vmess://1:9d0cb9d0-964f-4ef6-897d-6c6b3ccf9e68@:12345
|
||||||
|
|
||||||
# tuic服务器入口(传入流量将和socks,mixed等入口一样按照mode所指定的方式进行匹配处理)
|
# tuic 服务器入口(传入流量将和 socks,mixed 等入口一样按照 mode 所指定的方式进行匹配处理)
|
||||||
# tuic-server:
|
# tuic-server:
|
||||||
# enable: true
|
# enable: true
|
||||||
# listen: 127.0.0.1:10443
|
# listen: 127.0.0.1:10443
|
||||||
# token: # tuicV4填写(可以同时填写users)
|
# token: # tuicV4 填写(可以同时填写 users)
|
||||||
# - TOKEN
|
# - TOKEN
|
||||||
# users: # tuicV5填写(可以同时填写token)
|
# users: # tuicV5 填写(可以同时填写 token)
|
||||||
# 00000000-0000-0000-0000-000000000000: PASSWORD_0
|
# 00000000-0000-0000-0000-000000000000: PASSWORD_0
|
||||||
# 00000000-0000-0000-0000-000000000001: PASSWORD_1
|
# 00000000-0000-0000-0000-000000000001: PASSWORD_1
|
||||||
# certificate: ./server.crt
|
# certificate: ./server.crt
|
||||||
|
|||||||
67
go.mod
67
go.mod
@@ -8,53 +8,53 @@ require (
|
|||||||
github.com/bahlo/generic-list-go v0.2.0
|
github.com/bahlo/generic-list-go v0.2.0
|
||||||
github.com/cilium/ebpf v0.12.3
|
github.com/cilium/ebpf v0.12.3
|
||||||
github.com/coreos/go-iptables v0.7.0
|
github.com/coreos/go-iptables v0.7.0
|
||||||
github.com/dlclark/regexp2 v1.10.0
|
github.com/dlclark/regexp2 v1.11.0
|
||||||
github.com/go-chi/chi/v5 v5.0.11
|
github.com/go-chi/chi/v5 v5.0.12
|
||||||
github.com/go-chi/cors v1.2.1
|
github.com/go-chi/cors v1.2.1
|
||||||
github.com/go-chi/render v1.0.3
|
github.com/go-chi/render v1.0.3
|
||||||
github.com/gobwas/ws v1.3.2
|
github.com/gobwas/ws v1.4.0
|
||||||
github.com/gofrs/uuid/v5 v5.0.0
|
github.com/gofrs/uuid/v5 v5.2.0
|
||||||
github.com/insomniacslk/dhcp v0.0.0-20231206064809-8c70d406f6d2
|
github.com/insomniacslk/dhcp v0.0.0-20240419123447-f1cffa2c0c49
|
||||||
github.com/klauspost/cpuid/v2 v2.2.6
|
github.com/klauspost/cpuid/v2 v2.2.7
|
||||||
github.com/lunixbochs/struc v0.0.0-20200707160740-784aaebc1d40
|
github.com/lunixbochs/struc v0.0.0-20200707160740-784aaebc1d40
|
||||||
github.com/mdlayher/netlink v1.7.2
|
github.com/mdlayher/netlink v1.7.2
|
||||||
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759
|
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759
|
||||||
github.com/metacubex/quic-go v0.41.1-0.20240120014142-a02f4a533d4a
|
github.com/metacubex/quic-go v0.43.2-0.20240518033621-2c3d14c6b38e
|
||||||
github.com/metacubex/sing-quic v0.0.0-20240130040922-cbe613c88f20
|
github.com/metacubex/sing-quic v0.0.0-20240518034124-7696d3f7da72
|
||||||
github.com/metacubex/sing-shadowsocks v0.2.6
|
github.com/metacubex/sing-shadowsocks v0.2.6
|
||||||
github.com/metacubex/sing-shadowsocks2 v0.2.0
|
github.com/metacubex/sing-shadowsocks2 v0.2.0
|
||||||
github.com/metacubex/sing-tun v0.2.1-0.20240130042529-1f983547e9d4
|
github.com/metacubex/sing-tun v0.2.7-0.20240512075008-89e7c6208eec
|
||||||
github.com/metacubex/sing-vmess v0.1.9-0.20231207122118-72303677451f
|
github.com/metacubex/sing-vmess v0.1.9-0.20231207122118-72303677451f
|
||||||
github.com/metacubex/sing-wireguard v0.0.0-20231209125515-0594297f7232
|
github.com/metacubex/sing-wireguard v0.0.0-20240321042214-224f96122a63
|
||||||
github.com/miekg/dns v1.1.57
|
github.com/metacubex/tfo-go v0.0.0-20240228025757-be1269474a66
|
||||||
|
github.com/metacubex/utls v1.6.6
|
||||||
|
github.com/miekg/dns v1.1.59
|
||||||
github.com/mroth/weightedrand/v2 v2.1.0
|
github.com/mroth/weightedrand/v2 v2.1.0
|
||||||
github.com/openacid/low v0.1.21
|
github.com/openacid/low v0.1.21
|
||||||
github.com/oschwald/maxminddb-golang v1.12.0
|
github.com/oschwald/maxminddb-golang v1.12.0
|
||||||
github.com/puzpuzpuz/xsync/v3 v3.0.2
|
github.com/puzpuzpuz/xsync/v3 v3.1.0
|
||||||
github.com/sagernet/bbolt v0.0.0-20231014093535-ea5cb2fe9f0a
|
github.com/sagernet/bbolt v0.0.0-20231014093535-ea5cb2fe9f0a
|
||||||
github.com/sagernet/netlink v0.0.0-20220905062125-8043b4a9aa97
|
github.com/sagernet/netlink v0.0.0-20220905062125-8043b4a9aa97
|
||||||
github.com/sagernet/sing v0.3.0
|
github.com/sagernet/sing v0.3.8
|
||||||
github.com/sagernet/sing-mux v0.2.1-0.20240124034317-9bfb33698bb6
|
github.com/sagernet/sing-mux v0.2.1-0.20240124034317-9bfb33698bb6
|
||||||
github.com/sagernet/sing-shadowtls v0.1.4
|
github.com/sagernet/sing-shadowtls v0.1.4
|
||||||
github.com/sagernet/tfo-go v0.0.0-20231209031829-7b5343ac1dc6
|
|
||||||
github.com/sagernet/utls v1.5.4
|
|
||||||
github.com/sagernet/wireguard-go v0.0.0-20231209092712-9a439356a62e
|
github.com/sagernet/wireguard-go v0.0.0-20231209092712-9a439356a62e
|
||||||
github.com/samber/lo v1.39.0
|
github.com/samber/lo v1.39.0
|
||||||
github.com/shirou/gopsutil/v3 v3.23.12
|
github.com/shirou/gopsutil/v3 v3.24.4
|
||||||
github.com/sirupsen/logrus v1.9.3
|
github.com/sirupsen/logrus v1.9.3
|
||||||
github.com/stretchr/testify v1.8.4
|
github.com/stretchr/testify v1.9.0
|
||||||
github.com/wk8/go-ordered-map/v2 v2.1.8
|
github.com/wk8/go-ordered-map/v2 v2.1.8
|
||||||
github.com/zhangyunhao116/fastrand v0.3.0
|
github.com/zhangyunhao116/fastrand v0.4.0
|
||||||
go.uber.org/automaxprocs v1.5.3
|
go.uber.org/automaxprocs v1.5.3
|
||||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
|
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
|
||||||
golang.org/x/crypto v0.18.0
|
golang.org/x/crypto v0.23.0
|
||||||
golang.org/x/exp v0.0.0-20240110193028-0dcbfd608b1e
|
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842
|
||||||
golang.org/x/net v0.20.0
|
golang.org/x/net v0.25.0
|
||||||
golang.org/x/sync v0.6.0
|
golang.org/x/sync v0.7.0
|
||||||
golang.org/x/sys v0.16.0
|
golang.org/x/sys v0.20.0
|
||||||
google.golang.org/protobuf v1.32.0
|
google.golang.org/protobuf v1.34.1
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
lukechampine.com/blake3 v1.2.1
|
lukechampine.com/blake3 v1.3.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -63,7 +63,7 @@ require (
|
|||||||
github.com/ajg/form v1.5.1 // indirect
|
github.com/ajg/form v1.5.1 // indirect
|
||||||
github.com/andybalholm/brotli v1.0.6 // indirect
|
github.com/andybalholm/brotli v1.0.6 // indirect
|
||||||
github.com/buger/jsonparser v1.1.1 // indirect
|
github.com/buger/jsonparser v1.1.1 // indirect
|
||||||
github.com/cloudflare/circl v1.3.6 // indirect
|
github.com/cloudflare/circl v1.3.7 // indirect
|
||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
github.com/ericlagergren/aegis v0.0.0-20230312195928-b4ce538b56f9 // indirect
|
github.com/ericlagergren/aegis v0.0.0-20230312195928-b4ce538b56f9 // indirect
|
||||||
github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 // indirect
|
github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 // indirect
|
||||||
@@ -84,7 +84,7 @@ require (
|
|||||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||||
github.com/mailru/easyjson v0.7.7 // indirect
|
github.com/mailru/easyjson v0.7.7 // indirect
|
||||||
github.com/mdlayher/socket v0.4.1 // indirect
|
github.com/mdlayher/socket v0.4.1 // indirect
|
||||||
github.com/metacubex/gvisor v0.0.0-20231209122014-3e43224c7bbc // indirect
|
github.com/metacubex/gvisor v0.0.0-20240320004321-933faba989ec // indirect
|
||||||
github.com/oasisprotocol/deoxysii v0.0.0-20220228165953-2091330c22b7 // indirect
|
github.com/oasisprotocol/deoxysii v0.0.0-20220228165953-2091330c22b7 // indirect
|
||||||
github.com/onsi/ginkgo/v2 v2.9.5 // indirect
|
github.com/onsi/ginkgo/v2 v2.9.5 // indirect
|
||||||
github.com/pierrec/lz4/v4 v4.1.14 // indirect
|
github.com/pierrec/lz4/v4 v4.1.14 // indirect
|
||||||
@@ -93,7 +93,6 @@ require (
|
|||||||
github.com/quic-go/qpack v0.4.0 // indirect
|
github.com/quic-go/qpack v0.4.0 // indirect
|
||||||
github.com/quic-go/qtls-go1-20 v0.4.1 // indirect
|
github.com/quic-go/qtls-go1-20 v0.4.1 // indirect
|
||||||
github.com/sagernet/smux v0.0.0-20231208180855-7041f6ea79e7 // indirect
|
github.com/sagernet/smux v0.0.0-20231208180855-7041f6ea79e7 // indirect
|
||||||
github.com/scjalliance/comshim v0.0.0-20230315213746-5e51f40bd3b9 // indirect
|
|
||||||
github.com/shoenig/go-m1cpu v0.1.6 // indirect
|
github.com/shoenig/go-m1cpu v0.1.6 // indirect
|
||||||
github.com/sina-ghaderi/poly1305 v0.0.0-20220724002748-c5926b03988b // indirect
|
github.com/sina-ghaderi/poly1305 v0.0.0-20220724002748-c5926b03988b // indirect
|
||||||
github.com/sina-ghaderi/rabaead v0.0.0-20220730151906-ab6e06b96e8c // indirect
|
github.com/sina-ghaderi/rabaead v0.0.0-20220730151906-ab6e06b96e8c // indirect
|
||||||
@@ -102,13 +101,13 @@ require (
|
|||||||
github.com/tklauser/numcpus v0.6.1 // indirect
|
github.com/tklauser/numcpus v0.6.1 // indirect
|
||||||
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 // indirect
|
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 // indirect
|
||||||
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 // indirect
|
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 // indirect
|
||||||
github.com/yusufpapurcu/wmi v1.2.3 // indirect
|
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||||
gitlab.com/yawning/bsaes.git v0.0.0-20190805113838-0a714cd429ec // indirect
|
gitlab.com/yawning/bsaes.git v0.0.0-20190805113838-0a714cd429ec // indirect
|
||||||
go.uber.org/mock v0.3.0 // indirect
|
go.uber.org/mock v0.4.0 // indirect
|
||||||
golang.org/x/mod v0.14.0 // indirect
|
golang.org/x/mod v0.17.0 // indirect
|
||||||
golang.org/x/text v0.14.0 // indirect
|
golang.org/x/text v0.15.0 // indirect
|
||||||
golang.org/x/time v0.5.0 // indirect
|
golang.org/x/time v0.5.0 // indirect
|
||||||
golang.org/x/tools v0.16.0 // indirect
|
golang.org/x/tools v0.21.0 // indirect
|
||||||
)
|
)
|
||||||
|
|
||||||
replace github.com/sagernet/sing => github.com/metacubex/sing v0.0.0-20240111014253-f1818b6a82b2
|
replace github.com/sagernet/sing => github.com/metacubex/sing v0.0.0-20240518125217-e63d65a914d1
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user