mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-03-03 12:17:31 +00:00
Compare commits
192 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
644c04fdc9 | ||
|
|
926aaec717 | ||
|
|
a4b76809ac | ||
|
|
ff76576cbe | ||
|
|
1d5890abc1 | ||
|
|
a3c023ae3e | ||
|
|
8b32c4371e | ||
|
|
5a285acd32 | ||
|
|
c2209d68f7 | ||
|
|
fd39c2a7fc | ||
|
|
421dc79aea | ||
|
|
27b47f976c | ||
|
|
c25a38898f | ||
|
|
f3edbc2b45 | ||
|
|
6fb1f796a5 | ||
|
|
99e68e9983 | ||
|
|
6bffbdd9d3 | ||
|
|
cfdaebe952 | ||
|
|
c8af92a01f | ||
|
|
ff62386f6b | ||
|
|
85c56e7446 | ||
|
|
9ed9c3d1c3 | ||
|
|
dcfe664a7d | ||
|
|
fb1ae21fb7 | ||
|
|
90f47a6d0c | ||
|
|
f2bf4a077e | ||
|
|
8701639347 | ||
|
|
5bc0ac7281 | ||
|
|
c5fe3670ef | ||
|
|
de2ff37f4f | ||
|
|
da69b192f2 | ||
|
|
c13549f564 | ||
|
|
ce168c0e67 | ||
|
|
d225625378 | ||
|
|
40e0813869 | ||
|
|
94b591ed44 | ||
|
|
f7bd8b83e5 | ||
|
|
f45c6f5e91 | ||
|
|
3b15cbd9eb | ||
|
|
6f4da5f1fb | ||
|
|
fdc46f0471 | ||
|
|
57b527d54a | ||
|
|
29eaa4d699 | ||
|
|
92ecdfcc00 | ||
|
|
0992ee8adf | ||
|
|
0c25831726 | ||
|
|
9cc208bd47 | ||
|
|
b57f3052a8 | ||
|
|
3a1caf1316 | ||
|
|
1b1f95aa9c | ||
|
|
8a9300d44e | ||
|
|
abe6c3bb35 | ||
|
|
e28c8e6a51 | ||
|
|
74a86f147b | ||
|
|
7917f24f42 | ||
|
|
0dc5e3051d | ||
|
|
40b2cde2b2 | ||
|
|
6786705212 | ||
|
|
00638f30a7 | ||
|
|
2222d0e3fa | ||
|
|
f3ebd5c489 | ||
|
|
74e64d31e3 | ||
|
|
0c556bcaf3 | ||
|
|
7e71d21ab4 | ||
|
|
30bead4e2e | ||
|
|
16836ea465 | ||
|
|
d6f1af5372 | ||
|
|
26335f8ecc | ||
|
|
c4449a9f62 | ||
|
|
5e17d6fe01 | ||
|
|
8cdfd87d1e | ||
|
|
f02766a765 | ||
|
|
cea29e2615 | ||
|
|
a0f1ac4ef5 | ||
|
|
57e14e5b62 | ||
|
|
08fc100c85 | ||
|
|
571be856ea | ||
|
|
ad69ee84a9 | ||
|
|
dd7b3c28ad | ||
|
|
1b99759eaf | ||
|
|
a8f7e25851 | ||
|
|
909729ca8f | ||
|
|
6c527f8d20 | ||
|
|
7061c5a8ea | ||
|
|
23448ec119 | ||
|
|
318b3524c3 | ||
|
|
1d09ed82f1 | ||
|
|
b27325eed0 | ||
|
|
0d3d31dc5f | ||
|
|
108bf645fa | ||
|
|
50e1afd963 | ||
|
|
0336d64e52 | ||
|
|
02d954bfa8 | ||
|
|
9a124a390f | ||
|
|
fed4b369a3 | ||
|
|
f8ee5c1e15 | ||
|
|
8eba1c8afd | ||
|
|
65d3920f02 | ||
|
|
7e9e12cc4c | ||
|
|
80a90f05f3 | ||
|
|
3b63fef2eb | ||
|
|
29872007b3 | ||
|
|
33cde6592e | ||
|
|
c98f5f44b7 | ||
|
|
d094075c88 | ||
|
|
4188277b61 | ||
|
|
545d9b844d | ||
|
|
472cefb6d7 | ||
|
|
ccff0035cb | ||
|
|
455f2136f1 | ||
|
|
63781b3a6a | ||
|
|
c6e596f33f | ||
|
|
45cb45accb | ||
|
|
5c73025b53 | ||
|
|
cdd02a90c3 | ||
|
|
0ced98da4d | ||
|
|
84086a6e6c | ||
|
|
443200a51e | ||
|
|
aca0d97beb | ||
|
|
2605bf78f9 | ||
|
|
d2395fb43a | ||
|
|
e3d9a8e2fd | ||
|
|
1ae050ca3b | ||
|
|
7f38763e22 | ||
|
|
2a8831b0d0 | ||
|
|
cdf5e0c73e | ||
|
|
48f3ea8bc9 | ||
|
|
375e160368 | ||
|
|
b31664beeb | ||
|
|
7960bcae15 | ||
|
|
664ddb8d55 | ||
|
|
e4dfe09744 | ||
|
|
b56068ee1c | ||
|
|
99e888c829 | ||
|
|
873d0deeaa | ||
|
|
7e0a77c99c | ||
|
|
5f09db2655 | ||
|
|
10174d281c | ||
|
|
12c30acdda | ||
|
|
2790481709 | ||
|
|
182f60d424 | ||
|
|
930c70f065 | ||
|
|
fc61715e4e | ||
|
|
438be2d379 | ||
|
|
4e20ed65f2 | ||
|
|
ce760fcf19 | ||
|
|
0f76fdf4c5 | ||
|
|
03f4513f61 | ||
|
|
26f603057f | ||
|
|
b481eca4a4 | ||
|
|
eb028b65fc | ||
|
|
48c1b1cdb2 | ||
|
|
76e40baebc | ||
|
|
946b4025df | ||
|
|
089766b285 | ||
|
|
b643388539 | ||
|
|
0836ec6ee3 | ||
|
|
eeb2ad8dae | ||
|
|
71290b057f | ||
|
|
41b321dfe1 | ||
|
|
a18e99f966 | ||
|
|
f90d0b954c | ||
|
|
0408da2aee | ||
|
|
335d54e488 | ||
|
|
d11f9c895c | ||
|
|
e54ca7ceca | ||
|
|
ce82d49c25 | ||
|
|
8e6be1992b | ||
|
|
0e9102daae | ||
|
|
46dccf26d1 | ||
|
|
854c6a13c3 | ||
|
|
b4c3bbf660 | ||
|
|
6c726d6436 | ||
|
|
a0bdb861a9 | ||
|
|
eca5a27774 | ||
|
|
16d95df100 | ||
|
|
9b90719ddd | ||
|
|
7392529677 | ||
|
|
dc52c38179 | ||
|
|
d7999a32d3 | ||
|
|
b41ea05481 | ||
|
|
e6fe895190 | ||
|
|
adf553a958 | ||
|
|
2a915a5c94 | ||
|
|
1b0c72bfab | ||
|
|
e89af723cd | ||
|
|
e8fddd85af | ||
|
|
f04af734e3 | ||
|
|
00035302a1 | ||
|
|
578e659bb9 | ||
|
|
0f1baeb935 | ||
|
|
16ff9e815b |
182
.github/patch/go1.21.patch
vendored
Normal file
182
.github/patch/go1.21.patch
vendored
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
Subject: [PATCH] Revert "[release-branch.go1.21] crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
---
|
||||||
|
Index: src/crypto/rand/rand.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
--- a/src/crypto/rand/rand.go (revision 8bba868de983dd7bf55fcd121495ba8d6e2734e7)
|
||||||
|
+++ b/src/crypto/rand/rand.go (revision 7e6c963d81e14ee394402671d4044b2940c8d2c1)
|
||||||
|
@@ -15,7 +15,7 @@
|
||||||
|
// 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 ProcessPrng API.
|
||||||
|
+// On Windows systems, Reader uses the RtlGenRandom 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
|
||||||
|
Index: src/crypto/rand/rand_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand_windows.go b/src/crypto/rand/rand_windows.go
|
||||||
|
--- a/src/crypto/rand/rand_windows.go (revision 8bba868de983dd7bf55fcd121495ba8d6e2734e7)
|
||||||
|
+++ b/src/crypto/rand/rand_windows.go (revision 7e6c963d81e14ee394402671d4044b2940c8d2c1)
|
||||||
|
@@ -15,8 +15,11 @@
|
||||||
|
|
||||||
|
type rngReader struct{}
|
||||||
|
|
||||||
|
-func (r *rngReader) Read(b []byte) (int, error) {
|
||||||
|
- if err := windows.ProcessPrng(b); err != nil {
|
||||||
|
+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 {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(b), nil
|
||||||
|
Index: src/internal/syscall/windows/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go (revision 8bba868de983dd7bf55fcd121495ba8d6e2734e7)
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go (revision 7e6c963d81e14ee394402671d4044b2940c8d2c1)
|
||||||
|
@@ -384,7 +384,7 @@
|
||||||
|
//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 ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
+//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
|
||||||
|
//sys RtlLookupFunctionEntry(pc uintptr, baseAddress *uintptr, table *byte) (ret uintptr) = kernel32.RtlLookupFunctionEntry
|
||||||
|
//sys RtlVirtualUnwind(handlerType uint32, baseAddress uintptr, pc uintptr, entry uintptr, ctxt uintptr, data *uintptr, frame *uintptr, ctxptrs *byte) (ret uintptr) = kernel32.RtlVirtualUnwind
|
||||||
|
Index: src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go (revision 8bba868de983dd7bf55fcd121495ba8d6e2734e7)
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go (revision 7e6c963d81e14ee394402671d4044b2940c8d2c1)
|
||||||
|
@@ -37,14 +37,13 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
- 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"))
|
||||||
|
+ 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"))
|
||||||
|
|
||||||
|
procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
|
||||||
|
procDuplicateTokenEx = modadvapi32.NewProc("DuplicateTokenEx")
|
||||||
|
@@ -53,7 +52,7 @@
|
||||||
|
procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
+ procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procGetACP = modkernel32.NewProc("GetACP")
|
||||||
|
@@ -149,12 +148,12 @@
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func ProcessPrng(buf []byte) (err error) {
|
||||||
|
+func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
+ r1, _, e1 := syscall.Syscall(procSystemFunction036.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
Index: src/runtime/os_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
--- a/src/runtime/os_windows.go (revision 8bba868de983dd7bf55fcd121495ba8d6e2734e7)
|
||||||
|
+++ b/src/runtime/os_windows.go (revision 7e6c963d81e14ee394402671d4044b2940c8d2c1)
|
||||||
|
@@ -127,8 +127,15 @@
|
||||||
|
_AddVectoredContinueHandler,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
- _ProcessPrng 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
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -145,12 +152,12 @@
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
- bcryptprimitivesdll = [...]uint16{'b', 'c', 'r', 'y', 'p', 't', 'p', 'r', 'i', 'm', 'i', 't', 'i', 'v', 'e', 's', '.', 'd', 'l', 'l', 0}
|
||||||
|
- kernel32dll = [...]uint16{'k', 'e', 'r', 'n', 'e', 'l', '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}
|
||||||
|
+ advapi32dll = [...]uint16{'a', 'd', 'v', 'a', 'p', 'i', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ kernel32dll = [...]uint16{'k', 'e', 'r', 'n', 'e', 'l', '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}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Function to be called by windows CreateThread
|
||||||
|
@@ -249,11 +256,11 @@
|
||||||
|
}
|
||||||
|
_AddVectoredContinueHandler = windowsFindfunc(k32, []byte("AddVectoredContinueHandler\000"))
|
||||||
|
|
||||||
|
- bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
- if bcryptPrimitives == 0 {
|
||||||
|
- throw("bcryptprimitives.dll not found")
|
||||||
|
+ a32 := windowsLoadSystemLib(advapi32dll[:])
|
||||||
|
+ if a32 == 0 {
|
||||||
|
+ throw("advapi32.dll not found")
|
||||||
|
}
|
||||||
|
- _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
+ _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
|
||||||
|
n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
if n32 == 0 {
|
||||||
|
@@ -610,7 +617,7 @@
|
||||||
|
//go:nosplit
|
||||||
|
func getRandomData(r []byte) {
|
||||||
|
n := 0
|
||||||
|
- if stdcall2(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
extendRandom(r, n)
|
||||||
645
.github/patch/go1.22.patch
vendored
Normal file
645
.github/patch/go1.22.patch
vendored
Normal file
@@ -0,0 +1,645 @@
|
|||||||
|
Subject: [PATCH] Revert "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
Revert "syscall: remove Windows 7 console handle workaround"
|
||||||
|
Revert "net: remove sysSocket fallback for Windows 7"
|
||||||
|
Revert "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
---
|
||||||
|
Index: src/crypto/rand/rand.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
--- a/src/crypto/rand/rand.go (revision cb4eee693c382bea4222f20837e26501d40ed892)
|
||||||
|
+++ b/src/crypto/rand/rand.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
@@ -15,7 +15,7 @@
|
||||||
|
// 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 ProcessPrng API.
|
||||||
|
+// On Windows systems, Reader uses the RtlGenRandom 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
|
||||||
|
Index: src/crypto/rand/rand_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand_windows.go b/src/crypto/rand/rand_windows.go
|
||||||
|
--- a/src/crypto/rand/rand_windows.go (revision cb4eee693c382bea4222f20837e26501d40ed892)
|
||||||
|
+++ b/src/crypto/rand/rand_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
@@ -15,8 +15,11 @@
|
||||||
|
|
||||||
|
type rngReader struct{}
|
||||||
|
|
||||||
|
-func (r *rngReader) Read(b []byte) (int, error) {
|
||||||
|
- if err := windows.ProcessPrng(b); err != nil {
|
||||||
|
+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 {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(b), nil
|
||||||
|
Index: src/internal/syscall/windows/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go (revision cb4eee693c382bea4222f20837e26501d40ed892)
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
@@ -384,7 +384,7 @@
|
||||||
|
//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 ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
+//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
|
||||||
|
type FILE_ID_BOTH_DIR_INFO struct {
|
||||||
|
NextEntryOffset uint32
|
||||||
|
Index: src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go (revision cb4eee693c382bea4222f20837e26501d40ed892)
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
@@ -37,14 +37,13 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
- 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"))
|
||||||
|
+ 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"))
|
||||||
|
|
||||||
|
procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
|
||||||
|
procDuplicateTokenEx = modadvapi32.NewProc("DuplicateTokenEx")
|
||||||
|
@@ -56,7 +55,7 @@
|
||||||
|
procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
+ procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procGetACP = modkernel32.NewProc("GetACP")
|
||||||
|
@@ -180,12 +179,12 @@
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func ProcessPrng(buf []byte) (err error) {
|
||||||
|
+func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
+ r1, _, e1 := syscall.Syscall(procSystemFunction036.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
Index: src/runtime/os_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
--- a/src/runtime/os_windows.go (revision cb4eee693c382bea4222f20837e26501d40ed892)
|
||||||
|
+++ b/src/runtime/os_windows.go (revision 83ff9782e024cb328b690cbf0da4e7848a327f4f)
|
||||||
|
@@ -40,8 +40,8 @@
|
||||||
|
//go:cgo_import_dynamic runtime._GetSystemInfo GetSystemInfo%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._GetThreadContext GetThreadContext%2 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._SetThreadContext SetThreadContext%2 "kernel32.dll"
|
||||||
|
-//go:cgo_import_dynamic runtime._LoadLibraryExW LoadLibraryExW%3 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._LoadLibraryW LoadLibraryW%1 "kernel32.dll"
|
||||||
|
+//go:cgo_import_dynamic runtime._LoadLibraryA LoadLibraryA%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._PostQueuedCompletionStatus PostQueuedCompletionStatus%4 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceCounter QueryPerformanceCounter%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._RaiseFailFastException RaiseFailFastException%3 "kernel32.dll"
|
||||||
|
@@ -74,7 +74,6 @@
|
||||||
|
// Following syscalls are available on every Windows PC.
|
||||||
|
// All these variables are set by the Windows executable
|
||||||
|
// loader before the Go program starts.
|
||||||
|
- _AddVectoredContinueHandler,
|
||||||
|
_AddVectoredExceptionHandler,
|
||||||
|
_CloseHandle,
|
||||||
|
_CreateEventA,
|
||||||
|
@@ -98,8 +97,8 @@
|
||||||
|
_GetSystemInfo,
|
||||||
|
_GetThreadContext,
|
||||||
|
_SetThreadContext,
|
||||||
|
- _LoadLibraryExW,
|
||||||
|
_LoadLibraryW,
|
||||||
|
+ _LoadLibraryA,
|
||||||
|
_PostQueuedCompletionStatus,
|
||||||
|
_QueryPerformanceCounter,
|
||||||
|
_RaiseFailFastException,
|
||||||
|
@@ -127,8 +126,23 @@
|
||||||
|
_WriteFile,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
- _ProcessPrng stdFunction
|
||||||
|
+ // Following syscalls are only available on some Windows PCs.
|
||||||
|
+ // We will load syscalls, if available, before using them.
|
||||||
|
+ _AddDllDirectory,
|
||||||
|
+ _AddVectoredContinueHandler,
|
||||||
|
+ _LoadLibraryExA,
|
||||||
|
+ _LoadLibraryExW,
|
||||||
|
+ _ 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
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -143,14 +157,6 @@
|
||||||
|
_ stdFunction
|
||||||
|
)
|
||||||
|
|
||||||
|
-var (
|
||||||
|
- 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
|
||||||
|
// to start new os thread.
|
||||||
|
func tstart_stdcall(newm *m)
|
||||||
|
@@ -239,25 +245,51 @@
|
||||||
|
return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
-func windowsLoadSystemLib(name []uint16) uintptr {
|
||||||
|
- return stdcall3(_LoadLibraryExW, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+//go:linkname syscall_getSystemDirectory syscall.getSystemDirectory
|
||||||
|
+func syscall_getSystemDirectory() string {
|
||||||
|
+ return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func windowsLoadSystemLib(name []byte) uintptr {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ return stdcall3(_LoadLibraryExA, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ absName := append(sysDirectory[:sysDirectoryLen], name...)
|
||||||
|
+ return stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&absName[0])))
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOptionalSyscalls() {
|
||||||
|
- bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
- if bcryptPrimitives == 0 {
|
||||||
|
- throw("bcryptprimitives.dll not found")
|
||||||
|
+ var kernel32dll = []byte("kernel32.dll\000")
|
||||||
|
+ k32 := stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&kernel32dll[0])))
|
||||||
|
+ if k32 == 0 {
|
||||||
|
+ throw("kernel32.dll not found")
|
||||||
|
}
|
||||||
|
- _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
+ _AddDllDirectory = windowsFindfunc(k32, []byte("AddDllDirectory\000"))
|
||||||
|
+ _AddVectoredContinueHandler = windowsFindfunc(k32, []byte("AddVectoredContinueHandler\000"))
|
||||||
|
+ _LoadLibraryExA = windowsFindfunc(k32, []byte("LoadLibraryExA\000"))
|
||||||
|
+ _LoadLibraryExW = windowsFindfunc(k32, []byte("LoadLibraryExW\000"))
|
||||||
|
+ useLoadLibraryEx = (_LoadLibraryExW != nil && _LoadLibraryExA != nil && _AddDllDirectory != nil)
|
||||||
|
+
|
||||||
|
+ initSysDirectory()
|
||||||
|
|
||||||
|
- n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
+ var advapi32dll = []byte("advapi32.dll\000")
|
||||||
|
+ a32 := windowsLoadSystemLib(advapi32dll)
|
||||||
|
+ if a32 == 0 {
|
||||||
|
+ throw("advapi32.dll not found")
|
||||||
|
+ }
|
||||||
|
+ _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
+
|
||||||
|
+ var ntdll = []byte("ntdll.dll\000")
|
||||||
|
+ n32 := windowsLoadSystemLib(ntdll)
|
||||||
|
if n32 == 0 {
|
||||||
|
throw("ntdll.dll not found")
|
||||||
|
}
|
||||||
|
_RtlGetCurrentPeb = windowsFindfunc(n32, []byte("RtlGetCurrentPeb\000"))
|
||||||
|
_RtlGetNtVersionNumbers = windowsFindfunc(n32, []byte("RtlGetNtVersionNumbers\000"))
|
||||||
|
|
||||||
|
- m32 := windowsLoadSystemLib(winmmdll[:])
|
||||||
|
+ var winmmdll = []byte("winmm.dll\000")
|
||||||
|
+ m32 := windowsLoadSystemLib(winmmdll)
|
||||||
|
if m32 == 0 {
|
||||||
|
throw("winmm.dll not found")
|
||||||
|
}
|
||||||
|
@@ -267,7 +299,8 @@
|
||||||
|
throw("timeBegin/EndPeriod not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
- ws232 := windowsLoadSystemLib(ws2_32dll[:])
|
||||||
|
+ var ws232dll = []byte("ws2_32.dll\000")
|
||||||
|
+ ws232 := windowsLoadSystemLib(ws232dll)
|
||||||
|
if ws232 == 0 {
|
||||||
|
throw("ws2_32.dll not found")
|
||||||
|
}
|
||||||
|
@@ -286,7 +319,7 @@
|
||||||
|
context uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
- powrprof := windowsLoadSystemLib(powrprofdll[:])
|
||||||
|
+ powrprof := windowsLoadSystemLib([]byte("powrprof.dll\000"))
|
||||||
|
if powrprof == 0 {
|
||||||
|
return // Running on Windows 7, where we don't need it anyway.
|
||||||
|
}
|
||||||
|
@@ -360,6 +393,22 @@
|
||||||
|
// in sys_windows_386.s and sys_windows_amd64.s:
|
||||||
|
func getlasterror() uint32
|
||||||
|
|
||||||
|
+// When loading DLLs, we prefer to use LoadLibraryEx with
|
||||||
|
+// LOAD_LIBRARY_SEARCH_* flags, if available. LoadLibraryEx is not
|
||||||
|
+// available on old Windows, though, and the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags are not available on some versions of Windows without a
|
||||||
|
+// security patch.
|
||||||
|
+//
|
||||||
|
+// https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
|
||||||
|
+// "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
|
||||||
|
+// Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
|
||||||
|
+// systems that have KB2533623 installed. To determine whether the
|
||||||
|
+// flags are available, use GetProcAddress to get the address of the
|
||||||
|
+// AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
|
||||||
|
+// function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags can be used with LoadLibraryEx."
|
||||||
|
+var useLoadLibraryEx bool
|
||||||
|
+
|
||||||
|
var timeBeginPeriodRetValue uint32
|
||||||
|
|
||||||
|
// osRelaxMinNS indicates that sysmon shouldn't osRelax if the next
|
||||||
|
@@ -507,7 +556,6 @@
|
||||||
|
initHighResTimer()
|
||||||
|
timeBeginPeriodRetValue = osRelax(false)
|
||||||
|
|
||||||
|
- initSysDirectory()
|
||||||
|
initLongPathSupport()
|
||||||
|
|
||||||
|
ncpu = getproccount()
|
||||||
|
@@ -524,7 +572,7 @@
|
||||||
|
//go:nosplit
|
||||||
|
func readRandom(r []byte) int {
|
||||||
|
n := 0
|
||||||
|
- if stdcall2(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
Index: src/net/hook_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/hook_windows.go b/src/net/hook_windows.go
|
||||||
|
--- a/src/net/hook_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
+++ b/src/net/hook_windows.go (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
@@ -13,6 +13,7 @@
|
||||||
|
hostsFilePath = windows.GetSystemDirectory() + "/Drivers/etc/hosts"
|
||||||
|
|
||||||
|
// 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
|
||||||
|
Index: src/net/internal/socktest/main_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_test.go b/src/net/internal/socktest/main_test.go
|
||||||
|
--- a/src/net/internal/socktest/main_test.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
+++ b/src/net/internal/socktest/main_test.go (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
@@ -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 && !windows
|
||||||
|
+//go:build !js && !plan9 && !wasip1
|
||||||
|
|
||||||
|
package socktest_test
|
||||||
|
|
||||||
|
Index: src/net/internal/socktest/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_windows_test.go b/src/net/internal/socktest/main_windows_test.go
|
||||||
|
new file mode 100644
|
||||||
|
--- /dev/null (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
+++ b/src/net/internal/socktest/main_windows_test.go (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
@@ -0,0 +1,22 @@
|
||||||
|
+// 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
|
||||||
|
+}
|
||||||
|
Index: src/net/internal/socktest/sys_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/sys_windows.go b/src/net/internal/socktest/sys_windows.go
|
||||||
|
--- a/src/net/internal/socktest/sys_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
+++ b/src/net/internal/socktest/sys_windows.go (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
@@ -9,6 +9,38 @@
|
||||||
|
"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)
|
||||||
|
Index: src/net/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/main_windows_test.go b/src/net/main_windows_test.go
|
||||||
|
--- a/src/net/main_windows_test.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
+++ b/src/net/main_windows_test.go (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
@@ -8,6 +8,7 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Placeholders for saving original socket system calls.
|
||||||
|
+ origSocket = socketFunc
|
||||||
|
origWSASocket = wsaSocketFunc
|
||||||
|
origClosesocket = poll.CloseFunc
|
||||||
|
origConnect = connectFunc
|
||||||
|
@@ -17,6 +18,7 @@
|
||||||
|
)
|
||||||
|
|
||||||
|
func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
wsaSocketFunc = sw.WSASocket
|
||||||
|
poll.CloseFunc = sw.Closesocket
|
||||||
|
connectFunc = sw.Connect
|
||||||
|
@@ -26,6 +28,7 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func uninstallTestHooks() {
|
||||||
|
+ socketFunc = origSocket
|
||||||
|
wsaSocketFunc = origWSASocket
|
||||||
|
poll.CloseFunc = origClosesocket
|
||||||
|
connectFunc = origConnect
|
||||||
|
Index: src/net/sock_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/sock_windows.go b/src/net/sock_windows.go
|
||||||
|
--- a/src/net/sock_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
+++ b/src/net/sock_windows.go (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
@@ -20,6 +20,21 @@
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
Index: src/syscall/exec_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
--- a/src/syscall/exec_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
+++ b/src/syscall/exec_windows.go (revision 7f83badcb925a7e743188041cb6e561fc9b5b642)
|
||||||
|
@@ -14,7 +14,6 @@
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
-// ForkLock is not used on Windows.
|
||||||
|
var ForkLock sync.RWMutex
|
||||||
|
|
||||||
|
// EscapeArg rewrites command line argument s as prescribed
|
||||||
|
@@ -317,6 +316,17 @@
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
+ 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 {
|
||||||
|
@@ -325,7 +335,15 @@
|
||||||
|
fd := make([]Handle, len(attr.Files))
|
||||||
|
for i := range attr.Files {
|
||||||
|
if attr.Files[i] > 0 {
|
||||||
|
- err := DuplicateHandle(p, Handle(attr.Files[i]), parentProcess, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
+ 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)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
@@ -356,6 +374,14 @@
|
||||||
|
|
||||||
|
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
|
||||||
|
Index: src/runtime/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/syscall_windows.go b/src/runtime/syscall_windows.go
|
||||||
|
--- a/src/runtime/syscall_windows.go (revision 7f83badcb925a7e743188041cb6e561fc9b5b642)
|
||||||
|
+++ b/src/runtime/syscall_windows.go (revision 83ff9782e024cb328b690cbf0da4e7848a327f4f)
|
||||||
|
@@ -413,23 +413,36 @@
|
||||||
|
|
||||||
|
const _LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
|
||||||
|
|
||||||
|
+// When available, this function will use LoadLibraryEx with the filename
|
||||||
|
+// parameter and the important SEARCH_SYSTEM32 argument. But on systems that
|
||||||
|
+// do not have that option, absoluteFilepath should contain a fallback
|
||||||
|
+// to the full path inside of system32 for use with vanilla LoadLibrary.
|
||||||
|
+//
|
||||||
|
//go:linkname syscall_loadsystemlibrary syscall.loadsystemlibrary
|
||||||
|
//go:nosplit
|
||||||
|
//go:cgo_unsafe_args
|
||||||
|
-func syscall_loadsystemlibrary(filename *uint16) (handle, err uintptr) {
|
||||||
|
+func syscall_loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle, err uintptr) {
|
||||||
|
lockOSThread()
|
||||||
|
c := &getg().m.syscall
|
||||||
|
- c.fn = getLoadLibraryEx()
|
||||||
|
- c.n = 3
|
||||||
|
- args := struct {
|
||||||
|
- lpFileName *uint16
|
||||||
|
- hFile uintptr // always 0
|
||||||
|
- flags uint32
|
||||||
|
- }{filename, 0, _LOAD_LIBRARY_SEARCH_SYSTEM32}
|
||||||
|
- c.args = uintptr(noescape(unsafe.Pointer(&args)))
|
||||||
|
+
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ c.fn = getLoadLibraryEx()
|
||||||
|
+ c.n = 3
|
||||||
|
+ args := struct {
|
||||||
|
+ lpFileName *uint16
|
||||||
|
+ hFile uintptr // always 0
|
||||||
|
+ flags uint32
|
||||||
|
+ }{filename, 0, _LOAD_LIBRARY_SEARCH_SYSTEM32}
|
||||||
|
+ c.args = uintptr(noescape(unsafe.Pointer(&args)))
|
||||||
|
+ } else {
|
||||||
|
+ c.fn = getLoadLibrary()
|
||||||
|
+ c.n = 1
|
||||||
|
+ c.args = uintptr(noescape(unsafe.Pointer(&absoluteFilepath)))
|
||||||
|
+ }
|
||||||
|
|
||||||
|
cgocall(asmstdcallAddr, unsafe.Pointer(c))
|
||||||
|
KeepAlive(filename)
|
||||||
|
+ KeepAlive(absoluteFilepath)
|
||||||
|
handle = c.r1
|
||||||
|
if handle == 0 {
|
||||||
|
err = c.err
|
||||||
|
Index: src/syscall/dll_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/dll_windows.go b/src/syscall/dll_windows.go
|
||||||
|
--- a/src/syscall/dll_windows.go (revision 7f83badcb925a7e743188041cb6e561fc9b5b642)
|
||||||
|
+++ b/src/syscall/dll_windows.go (revision 83ff9782e024cb328b690cbf0da4e7848a327f4f)
|
||||||
|
@@ -44,7 +44,7 @@
|
||||||
|
|
||||||
|
func SyscallN(trap uintptr, args ...uintptr) (r1, r2 uintptr, err Errno)
|
||||||
|
func loadlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
-func loadsystemlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
+func loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle uintptr, err Errno)
|
||||||
|
func getprocaddress(handle uintptr, procname *uint8) (proc uintptr, err Errno)
|
||||||
|
|
||||||
|
// A DLL implements access to a single DLL.
|
||||||
|
@@ -53,6 +53,9 @@
|
||||||
|
Handle Handle
|
||||||
|
}
|
||||||
|
|
||||||
|
+//go:linkname getSystemDirectory
|
||||||
|
+func getSystemDirectory() string // Implemented in runtime package.
|
||||||
|
+
|
||||||
|
// LoadDLL loads the named DLL file into memory.
|
||||||
|
//
|
||||||
|
// If name is not an absolute path and is not a known system DLL used by
|
||||||
|
@@ -69,7 +72,11 @@
|
||||||
|
var h uintptr
|
||||||
|
var e Errno
|
||||||
|
if sysdll.IsSystemDLL[name] {
|
||||||
|
- h, e = loadsystemlibrary(namep)
|
||||||
|
+ absoluteFilepathp, err := UTF16PtrFromString(getSystemDirectory() + name)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return nil, err
|
||||||
|
+ }
|
||||||
|
+ h, e = loadsystemlibrary(namep, absoluteFilepathp)
|
||||||
|
} else {
|
||||||
|
h, e = loadlibrary(namep)
|
||||||
|
}
|
||||||
643
.github/patch/go1.23.patch
vendored
Normal file
643
.github/patch/go1.23.patch
vendored
Normal file
@@ -0,0 +1,643 @@
|
|||||||
|
Subject: [PATCH] Revert "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
Revert "syscall: remove Windows 7 console handle workaround"
|
||||||
|
Revert "net: remove sysSocket fallback for Windows 7"
|
||||||
|
Revert "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
---
|
||||||
|
Index: src/crypto/rand/rand.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
--- a/src/crypto/rand/rand.go (revision 6885bad7dd86880be6929c02085e5c7a67ff2887)
|
||||||
|
+++ b/src/crypto/rand/rand.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
@@ -16,7 +16,7 @@
|
||||||
|
// - On macOS and iOS, Reader uses arc4random_buf(3).
|
||||||
|
// - On OpenBSD and NetBSD, Reader uses getentropy(2).
|
||||||
|
// - On other Unix-like systems, Reader reads from /dev/urandom.
|
||||||
|
-// - On Windows, Reader uses the ProcessPrng API.
|
||||||
|
+// - On Windows systems, Reader uses the RtlGenRandom 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
|
||||||
|
Index: src/crypto/rand/rand_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand_windows.go b/src/crypto/rand/rand_windows.go
|
||||||
|
--- a/src/crypto/rand/rand_windows.go (revision 6885bad7dd86880be6929c02085e5c7a67ff2887)
|
||||||
|
+++ b/src/crypto/rand/rand_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
@@ -15,8 +15,11 @@
|
||||||
|
|
||||||
|
type rngReader struct{}
|
||||||
|
|
||||||
|
-func (r *rngReader) Read(b []byte) (int, error) {
|
||||||
|
- if err := windows.ProcessPrng(b); err != nil {
|
||||||
|
+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 {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(b), nil
|
||||||
|
Index: src/internal/syscall/windows/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go (revision 6885bad7dd86880be6929c02085e5c7a67ff2887)
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
@@ -414,7 +414,7 @@
|
||||||
|
//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 ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
+//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
|
||||||
|
type FILE_ID_BOTH_DIR_INFO struct {
|
||||||
|
NextEntryOffset uint32
|
||||||
|
Index: src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go (revision 6885bad7dd86880be6929c02085e5c7a67ff2887)
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
@@ -38,7 +38,6 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
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"))
|
||||||
|
@@ -57,7 +56,7 @@
|
||||||
|
procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
+ procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procGetACP = modkernel32.NewProc("GetACP")
|
||||||
|
@@ -183,12 +182,12 @@
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func ProcessPrng(buf []byte) (err error) {
|
||||||
|
+func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
+ r1, _, e1 := syscall.Syscall(procSystemFunction036.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
Index: src/runtime/os_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
--- a/src/runtime/os_windows.go (revision 6885bad7dd86880be6929c02085e5c7a67ff2887)
|
||||||
|
+++ b/src/runtime/os_windows.go (revision 69e2eed6dd0f6d815ebf15797761c13f31213dd6)
|
||||||
|
@@ -39,8 +39,8 @@
|
||||||
|
//go:cgo_import_dynamic runtime._GetSystemInfo GetSystemInfo%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._GetThreadContext GetThreadContext%2 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._SetThreadContext SetThreadContext%2 "kernel32.dll"
|
||||||
|
-//go:cgo_import_dynamic runtime._LoadLibraryExW LoadLibraryExW%3 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._LoadLibraryW LoadLibraryW%1 "kernel32.dll"
|
||||||
|
+//go:cgo_import_dynamic runtime._LoadLibraryA LoadLibraryA%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._PostQueuedCompletionStatus PostQueuedCompletionStatus%4 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceCounter QueryPerformanceCounter%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceFrequency QueryPerformanceFrequency%1 "kernel32.dll"
|
||||||
|
@@ -74,7 +74,6 @@
|
||||||
|
// Following syscalls are available on every Windows PC.
|
||||||
|
// All these variables are set by the Windows executable
|
||||||
|
// loader before the Go program starts.
|
||||||
|
- _AddVectoredContinueHandler,
|
||||||
|
_AddVectoredExceptionHandler,
|
||||||
|
_CloseHandle,
|
||||||
|
_CreateEventA,
|
||||||
|
@@ -97,8 +96,8 @@
|
||||||
|
_GetSystemInfo,
|
||||||
|
_GetThreadContext,
|
||||||
|
_SetThreadContext,
|
||||||
|
- _LoadLibraryExW,
|
||||||
|
_LoadLibraryW,
|
||||||
|
+ _LoadLibraryA,
|
||||||
|
_PostQueuedCompletionStatus,
|
||||||
|
_QueryPerformanceCounter,
|
||||||
|
_QueryPerformanceFrequency,
|
||||||
|
@@ -127,8 +126,23 @@
|
||||||
|
_WriteFile,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
- _ProcessPrng stdFunction
|
||||||
|
+ // Following syscalls are only available on some Windows PCs.
|
||||||
|
+ // We will load syscalls, if available, before using them.
|
||||||
|
+ _AddDllDirectory,
|
||||||
|
+ _AddVectoredContinueHandler,
|
||||||
|
+ _LoadLibraryExA,
|
||||||
|
+ _LoadLibraryExW,
|
||||||
|
+ _ 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
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -145,13 +159,6 @@
|
||||||
|
_ stdFunction
|
||||||
|
)
|
||||||
|
|
||||||
|
-var (
|
||||||
|
- 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}
|
||||||
|
-)
|
||||||
|
-
|
||||||
|
// Function to be called by windows CreateThread
|
||||||
|
// to start new os thread.
|
||||||
|
func tstart_stdcall(newm *m)
|
||||||
|
@@ -244,8 +251,18 @@
|
||||||
|
return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
-func windowsLoadSystemLib(name []uint16) uintptr {
|
||||||
|
- return stdcall3(_LoadLibraryExW, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+//go:linkname syscall_getSystemDirectory syscall.getSystemDirectory
|
||||||
|
+func syscall_getSystemDirectory() string {
|
||||||
|
+ return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func windowsLoadSystemLib(name []byte) uintptr {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ return stdcall3(_LoadLibraryExA, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ absName := append(sysDirectory[:sysDirectoryLen], name...)
|
||||||
|
+ return stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&absName[0])))
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
|
||||||
|
//go:linkname windows_QueryPerformanceCounter internal/syscall/windows.QueryPerformanceCounter
|
||||||
|
@@ -263,13 +280,28 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOptionalSyscalls() {
|
||||||
|
- bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
- if bcryptPrimitives == 0 {
|
||||||
|
- throw("bcryptprimitives.dll not found")
|
||||||
|
+ var kernel32dll = []byte("kernel32.dll\000")
|
||||||
|
+ k32 := stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&kernel32dll[0])))
|
||||||
|
+ if k32 == 0 {
|
||||||
|
+ throw("kernel32.dll not found")
|
||||||
|
}
|
||||||
|
- _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
+ _AddDllDirectory = windowsFindfunc(k32, []byte("AddDllDirectory\000"))
|
||||||
|
+ _AddVectoredContinueHandler = windowsFindfunc(k32, []byte("AddVectoredContinueHandler\000"))
|
||||||
|
+ _LoadLibraryExA = windowsFindfunc(k32, []byte("LoadLibraryExA\000"))
|
||||||
|
+ _LoadLibraryExW = windowsFindfunc(k32, []byte("LoadLibraryExW\000"))
|
||||||
|
+ useLoadLibraryEx = (_LoadLibraryExW != nil && _LoadLibraryExA != nil && _AddDllDirectory != nil)
|
||||||
|
+
|
||||||
|
+ initSysDirectory()
|
||||||
|
|
||||||
|
- n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
+ var advapi32dll = []byte("advapi32.dll\000")
|
||||||
|
+ a32 := windowsLoadSystemLib(advapi32dll)
|
||||||
|
+ if a32 == 0 {
|
||||||
|
+ throw("advapi32.dll not found")
|
||||||
|
+ }
|
||||||
|
+ _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
+
|
||||||
|
+ var ntdll = []byte("ntdll.dll\000")
|
||||||
|
+ n32 := windowsLoadSystemLib(ntdll)
|
||||||
|
if n32 == 0 {
|
||||||
|
throw("ntdll.dll not found")
|
||||||
|
}
|
||||||
|
@@ -298,7 +330,7 @@
|
||||||
|
context uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
- powrprof := windowsLoadSystemLib(powrprofdll[:])
|
||||||
|
+ powrprof := windowsLoadSystemLib([]byte("powrprof.dll\000"))
|
||||||
|
if powrprof == 0 {
|
||||||
|
return // Running on Windows 7, where we don't need it anyway.
|
||||||
|
}
|
||||||
|
@@ -357,6 +389,22 @@
|
||||||
|
// in sys_windows_386.s and sys_windows_amd64.s:
|
||||||
|
func getlasterror() uint32
|
||||||
|
|
||||||
|
+// When loading DLLs, we prefer to use LoadLibraryEx with
|
||||||
|
+// LOAD_LIBRARY_SEARCH_* flags, if available. LoadLibraryEx is not
|
||||||
|
+// available on old Windows, though, and the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags are not available on some versions of Windows without a
|
||||||
|
+// security patch.
|
||||||
|
+//
|
||||||
|
+// https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
|
||||||
|
+// "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
|
||||||
|
+// Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
|
||||||
|
+// systems that have KB2533623 installed. To determine whether the
|
||||||
|
+// flags are available, use GetProcAddress to get the address of the
|
||||||
|
+// AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
|
||||||
|
+// function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags can be used with LoadLibraryEx."
|
||||||
|
+var useLoadLibraryEx bool
|
||||||
|
+
|
||||||
|
var timeBeginPeriodRetValue uint32
|
||||||
|
|
||||||
|
// osRelaxMinNS indicates that sysmon shouldn't osRelax if the next
|
||||||
|
@@ -430,7 +478,8 @@
|
||||||
|
// Only load winmm.dll if we need it.
|
||||||
|
// This avoids a dependency on winmm.dll for Go programs
|
||||||
|
// that run on new Windows versions.
|
||||||
|
- m32 := windowsLoadSystemLib(winmmdll[:])
|
||||||
|
+ var winmmdll = []byte("winmm.dll\000")
|
||||||
|
+ m32 := windowsLoadSystemLib(winmmdll)
|
||||||
|
if m32 == 0 {
|
||||||
|
print("runtime: LoadLibraryExW failed; errno=", getlasterror(), "\n")
|
||||||
|
throw("winmm.dll not found")
|
||||||
|
@@ -471,6 +520,28 @@
|
||||||
|
canUseLongPaths = true
|
||||||
|
}
|
||||||
|
|
||||||
|
+var osVersionInfo struct {
|
||||||
|
+ majorVersion uint32
|
||||||
|
+ minorVersion uint32
|
||||||
|
+ buildNumber uint32
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func initOsVersionInfo() {
|
||||||
|
+ info := _OSVERSIONINFOW{}
|
||||||
|
+ info.osVersionInfoSize = uint32(unsafe.Sizeof(info))
|
||||||
|
+ stdcall1(_RtlGetVersion, uintptr(unsafe.Pointer(&info)))
|
||||||
|
+ osVersionInfo.majorVersion = info.majorVersion
|
||||||
|
+ osVersionInfo.minorVersion = info.minorVersion
|
||||||
|
+ osVersionInfo.buildNumber = info.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers syscall.rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) {
|
||||||
|
+ *majorVersion = osVersionInfo.majorVersion
|
||||||
|
+ *minorVersion = osVersionInfo.minorVersion
|
||||||
|
+ *buildNumber = osVersionInfo.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
func osinit() {
|
||||||
|
asmstdcallAddr = unsafe.Pointer(abi.FuncPCABI0(asmstdcall))
|
||||||
|
|
||||||
|
@@ -483,8 +554,8 @@
|
||||||
|
initHighResTimer()
|
||||||
|
timeBeginPeriodRetValue = osRelax(false)
|
||||||
|
|
||||||
|
- initSysDirectory()
|
||||||
|
initLongPathSupport()
|
||||||
|
+ initOsVersionInfo()
|
||||||
|
|
||||||
|
ncpu = getproccount()
|
||||||
|
|
||||||
|
@@ -500,7 +571,7 @@
|
||||||
|
//go:nosplit
|
||||||
|
func readRandom(r []byte) int {
|
||||||
|
n := 0
|
||||||
|
- if stdcall2(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
Index: src/net/hook_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/hook_windows.go b/src/net/hook_windows.go
|
||||||
|
--- a/src/net/hook_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
+++ b/src/net/hook_windows.go (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
@@ -13,6 +13,7 @@
|
||||||
|
hostsFilePath = windows.GetSystemDirectory() + "/Drivers/etc/hosts"
|
||||||
|
|
||||||
|
// 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
|
||||||
|
Index: src/net/internal/socktest/main_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_test.go b/src/net/internal/socktest/main_test.go
|
||||||
|
--- a/src/net/internal/socktest/main_test.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
+++ b/src/net/internal/socktest/main_test.go (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
@@ -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 && !windows
|
||||||
|
+//go:build !js && !plan9 && !wasip1
|
||||||
|
|
||||||
|
package socktest_test
|
||||||
|
|
||||||
|
Index: src/net/internal/socktest/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_windows_test.go b/src/net/internal/socktest/main_windows_test.go
|
||||||
|
new file mode 100644
|
||||||
|
--- /dev/null (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
+++ b/src/net/internal/socktest/main_windows_test.go (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
@@ -0,0 +1,22 @@
|
||||||
|
+// 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
|
||||||
|
+}
|
||||||
|
Index: src/net/internal/socktest/sys_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/sys_windows.go b/src/net/internal/socktest/sys_windows.go
|
||||||
|
--- a/src/net/internal/socktest/sys_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
+++ b/src/net/internal/socktest/sys_windows.go (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
@@ -9,6 +9,38 @@
|
||||||
|
"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)
|
||||||
|
Index: src/net/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/main_windows_test.go b/src/net/main_windows_test.go
|
||||||
|
--- a/src/net/main_windows_test.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
+++ b/src/net/main_windows_test.go (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
@@ -8,6 +8,7 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Placeholders for saving original socket system calls.
|
||||||
|
+ origSocket = socketFunc
|
||||||
|
origWSASocket = wsaSocketFunc
|
||||||
|
origClosesocket = poll.CloseFunc
|
||||||
|
origConnect = connectFunc
|
||||||
|
@@ -17,6 +18,7 @@
|
||||||
|
)
|
||||||
|
|
||||||
|
func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
wsaSocketFunc = sw.WSASocket
|
||||||
|
poll.CloseFunc = sw.Closesocket
|
||||||
|
connectFunc = sw.Connect
|
||||||
|
@@ -26,6 +28,7 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func uninstallTestHooks() {
|
||||||
|
+ socketFunc = origSocket
|
||||||
|
wsaSocketFunc = origWSASocket
|
||||||
|
poll.CloseFunc = origClosesocket
|
||||||
|
connectFunc = origConnect
|
||||||
|
Index: src/net/sock_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/sock_windows.go b/src/net/sock_windows.go
|
||||||
|
--- a/src/net/sock_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
+++ b/src/net/sock_windows.go (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
@@ -20,6 +20,21 @@
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
Index: src/syscall/exec_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
--- a/src/syscall/exec_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
+++ b/src/syscall/exec_windows.go (revision 6a31d3fa8e47ddabc10bd97bff10d9a85f4cfb76)
|
||||||
|
@@ -14,7 +14,6 @@
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
-// ForkLock is not used on Windows.
|
||||||
|
var ForkLock sync.RWMutex
|
||||||
|
|
||||||
|
// EscapeArg rewrites command line argument s as prescribed
|
||||||
|
@@ -254,6 +253,9 @@
|
||||||
|
var zeroProcAttr ProcAttr
|
||||||
|
var zeroSysProcAttr SysProcAttr
|
||||||
|
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32)
|
||||||
|
+
|
||||||
|
func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error) {
|
||||||
|
if len(argv0) == 0 {
|
||||||
|
return 0, 0, EWINDOWS
|
||||||
|
@@ -317,6 +319,17 @@
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
+ 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 {
|
||||||
|
@@ -325,7 +338,15 @@
|
||||||
|
fd := make([]Handle, len(attr.Files))
|
||||||
|
for i := range attr.Files {
|
||||||
|
if attr.Files[i] > 0 {
|
||||||
|
- err := DuplicateHandle(p, Handle(attr.Files[i]), parentProcess, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
+ 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)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
@@ -356,6 +377,14 @@
|
||||||
|
|
||||||
|
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
|
||||||
|
Index: src/runtime/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/syscall_windows.go b/src/runtime/syscall_windows.go
|
||||||
|
--- a/src/runtime/syscall_windows.go (revision 6a31d3fa8e47ddabc10bd97bff10d9a85f4cfb76)
|
||||||
|
+++ b/src/runtime/syscall_windows.go (revision 69e2eed6dd0f6d815ebf15797761c13f31213dd6)
|
||||||
|
@@ -413,10 +413,20 @@
|
||||||
|
|
||||||
|
const _LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
|
||||||
|
|
||||||
|
+// When available, this function will use LoadLibraryEx with the filename
|
||||||
|
+// parameter and the important SEARCH_SYSTEM32 argument. But on systems that
|
||||||
|
+// do not have that option, absoluteFilepath should contain a fallback
|
||||||
|
+// to the full path inside of system32 for use with vanilla LoadLibrary.
|
||||||
|
+//
|
||||||
|
//go:linkname syscall_loadsystemlibrary syscall.loadsystemlibrary
|
||||||
|
-func syscall_loadsystemlibrary(filename *uint16) (handle, err uintptr) {
|
||||||
|
- handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryExW)), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+func syscall_loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle, err uintptr) {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryExW)), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryW)), uintptr(unsafe.Pointer(absoluteFilepath)))
|
||||||
|
+ }
|
||||||
|
KeepAlive(filename)
|
||||||
|
+ KeepAlive(absoluteFilepath)
|
||||||
|
if handle != 0 {
|
||||||
|
err = 0
|
||||||
|
}
|
||||||
|
Index: src/syscall/dll_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/dll_windows.go b/src/syscall/dll_windows.go
|
||||||
|
--- a/src/syscall/dll_windows.go (revision 6a31d3fa8e47ddabc10bd97bff10d9a85f4cfb76)
|
||||||
|
+++ b/src/syscall/dll_windows.go (revision 69e2eed6dd0f6d815ebf15797761c13f31213dd6)
|
||||||
|
@@ -44,7 +44,7 @@
|
||||||
|
|
||||||
|
func SyscallN(trap uintptr, args ...uintptr) (r1, r2 uintptr, err Errno)
|
||||||
|
func loadlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
-func loadsystemlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
+func loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle uintptr, err Errno)
|
||||||
|
func getprocaddress(handle uintptr, procname *uint8) (proc uintptr, err Errno)
|
||||||
|
|
||||||
|
// A DLL implements access to a single DLL.
|
||||||
|
@@ -53,6 +53,9 @@
|
||||||
|
Handle Handle
|
||||||
|
}
|
||||||
|
|
||||||
|
+//go:linkname getSystemDirectory
|
||||||
|
+func getSystemDirectory() string // Implemented in runtime package.
|
||||||
|
+
|
||||||
|
// LoadDLL loads the named DLL file into memory.
|
||||||
|
//
|
||||||
|
// If name is not an absolute path and is not a known system DLL used by
|
||||||
|
@@ -69,7 +72,11 @@
|
||||||
|
var h uintptr
|
||||||
|
var e Errno
|
||||||
|
if sysdll.IsSystemDLL[name] {
|
||||||
|
- h, e = loadsystemlibrary(namep)
|
||||||
|
+ absoluteFilepathp, err := UTF16PtrFromString(getSystemDirectory() + name)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return nil, err
|
||||||
|
+ }
|
||||||
|
+ h, e = loadsystemlibrary(namep, absoluteFilepathp)
|
||||||
|
} else {
|
||||||
|
h, e = loadlibrary(namep)
|
||||||
|
}
|
||||||
657
.github/patch/go1.24.patch
vendored
Normal file
657
.github/patch/go1.24.patch
vendored
Normal file
@@ -0,0 +1,657 @@
|
|||||||
|
Subject: [PATCH] Revert "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
Revert "syscall: remove Windows 7 console handle workaround"
|
||||||
|
Revert "net: remove sysSocket fallback for Windows 7"
|
||||||
|
Revert "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
---
|
||||||
|
Index: src/crypto/internal/sysrand/rand_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/internal/sysrand/rand_windows.go b/src/crypto/internal/sysrand/rand_windows.go
|
||||||
|
--- a/src/crypto/internal/sysrand/rand_windows.go (revision 3901409b5d0fb7c85a3e6730a59943cc93b2835c)
|
||||||
|
+++ b/src/crypto/internal/sysrand/rand_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
@@ -7,5 +7,26 @@
|
||||||
|
import "internal/syscall/windows"
|
||||||
|
|
||||||
|
func read(b []byte) error {
|
||||||
|
- return windows.ProcessPrng(b)
|
||||||
|
+ // 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.
|
||||||
|
+ return batched(windows.RtlGenRandom, 1<<31-1)(b)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// batched returns a function that calls f to populate a []byte by chunking it
|
||||||
|
+// into subslices of, at most, readMax bytes.
|
||||||
|
+func batched(f func([]byte) error, readMax int) func([]byte) error {
|
||||||
|
+ return func(out []byte) error {
|
||||||
|
+ for len(out) > 0 {
|
||||||
|
+ read := len(out)
|
||||||
|
+ if read > readMax {
|
||||||
|
+ read = readMax
|
||||||
|
+ }
|
||||||
|
+ if err := f(out[:read]); err != nil {
|
||||||
|
+ return err
|
||||||
|
+ }
|
||||||
|
+ out = out[read:]
|
||||||
|
+ }
|
||||||
|
+ return nil
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
Index: src/crypto/rand/rand.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
--- a/src/crypto/rand/rand.go (revision 3901409b5d0fb7c85a3e6730a59943cc93b2835c)
|
||||||
|
+++ b/src/crypto/rand/rand.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
@@ -22,7 +22,7 @@
|
||||||
|
// - On legacy Linux (< 3.17), Reader opens /dev/urandom on first use.
|
||||||
|
// - On macOS, iOS, and OpenBSD Reader, uses arc4random_buf(3).
|
||||||
|
// - On NetBSD, Reader uses the kern.arandom sysctl.
|
||||||
|
-// - On Windows, Reader uses the ProcessPrng API.
|
||||||
|
+// - On Windows systems, Reader uses the RtlGenRandom API.
|
||||||
|
// - On js/wasm, Reader uses the Web Crypto API.
|
||||||
|
// - On wasip1/wasm, Reader uses random_get.
|
||||||
|
//
|
||||||
|
Index: src/internal/syscall/windows/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go (revision 3901409b5d0fb7c85a3e6730a59943cc93b2835c)
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
@@ -416,7 +416,7 @@
|
||||||
|
//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 ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
+//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
|
||||||
|
type FILE_ID_BOTH_DIR_INFO struct {
|
||||||
|
NextEntryOffset uint32
|
||||||
|
Index: src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go (revision 3901409b5d0fb7c85a3e6730a59943cc93b2835c)
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
@@ -38,7 +38,6 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
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"))
|
||||||
|
@@ -63,7 +62,7 @@
|
||||||
|
procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
+ procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procGetACP = modkernel32.NewProc("GetACP")
|
||||||
|
@@ -236,12 +235,12 @@
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func ProcessPrng(buf []byte) (err error) {
|
||||||
|
+func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
+ r1, _, e1 := syscall.Syscall(procSystemFunction036.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
Index: src/runtime/os_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
--- a/src/runtime/os_windows.go (revision 3901409b5d0fb7c85a3e6730a59943cc93b2835c)
|
||||||
|
+++ b/src/runtime/os_windows.go (revision ac3e93c061779dfefc0dd13a5b6e6f764a25621e)
|
||||||
|
@@ -40,8 +40,8 @@
|
||||||
|
//go:cgo_import_dynamic runtime._GetSystemInfo GetSystemInfo%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._GetThreadContext GetThreadContext%2 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._SetThreadContext SetThreadContext%2 "kernel32.dll"
|
||||||
|
-//go:cgo_import_dynamic runtime._LoadLibraryExW LoadLibraryExW%3 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._LoadLibraryW LoadLibraryW%1 "kernel32.dll"
|
||||||
|
+//go:cgo_import_dynamic runtime._LoadLibraryA LoadLibraryA%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._PostQueuedCompletionStatus PostQueuedCompletionStatus%4 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceCounter QueryPerformanceCounter%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceFrequency QueryPerformanceFrequency%1 "kernel32.dll"
|
||||||
|
@@ -75,7 +75,6 @@
|
||||||
|
// Following syscalls are available on every Windows PC.
|
||||||
|
// All these variables are set by the Windows executable
|
||||||
|
// loader before the Go program starts.
|
||||||
|
- _AddVectoredContinueHandler,
|
||||||
|
_AddVectoredExceptionHandler,
|
||||||
|
_CloseHandle,
|
||||||
|
_CreateEventA,
|
||||||
|
@@ -98,8 +97,8 @@
|
||||||
|
_GetSystemInfo,
|
||||||
|
_GetThreadContext,
|
||||||
|
_SetThreadContext,
|
||||||
|
- _LoadLibraryExW,
|
||||||
|
_LoadLibraryW,
|
||||||
|
+ _LoadLibraryA,
|
||||||
|
_PostQueuedCompletionStatus,
|
||||||
|
_QueryPerformanceCounter,
|
||||||
|
_QueryPerformanceFrequency,
|
||||||
|
@@ -128,8 +127,23 @@
|
||||||
|
_WriteFile,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
- _ProcessPrng stdFunction
|
||||||
|
+ // Following syscalls are only available on some Windows PCs.
|
||||||
|
+ // We will load syscalls, if available, before using them.
|
||||||
|
+ _AddDllDirectory,
|
||||||
|
+ _AddVectoredContinueHandler,
|
||||||
|
+ _LoadLibraryExA,
|
||||||
|
+ _LoadLibraryExW,
|
||||||
|
+ _ 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
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -146,13 +160,6 @@
|
||||||
|
_ stdFunction
|
||||||
|
)
|
||||||
|
|
||||||
|
-var (
|
||||||
|
- 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}
|
||||||
|
-)
|
||||||
|
-
|
||||||
|
// Function to be called by windows CreateThread
|
||||||
|
// to start new os thread.
|
||||||
|
func tstart_stdcall(newm *m)
|
||||||
|
@@ -245,8 +252,18 @@
|
||||||
|
return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
-func windowsLoadSystemLib(name []uint16) uintptr {
|
||||||
|
- return stdcall3(_LoadLibraryExW, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+//go:linkname syscall_getSystemDirectory syscall.getSystemDirectory
|
||||||
|
+func syscall_getSystemDirectory() string {
|
||||||
|
+ return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func windowsLoadSystemLib(name []byte) uintptr {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ return stdcall3(_LoadLibraryExA, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ absName := append(sysDirectory[:sysDirectoryLen], name...)
|
||||||
|
+ return stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&absName[0])))
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
|
||||||
|
//go:linkname windows_QueryPerformanceCounter internal/syscall/windows.QueryPerformanceCounter
|
||||||
|
@@ -264,13 +281,28 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOptionalSyscalls() {
|
||||||
|
- bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
- if bcryptPrimitives == 0 {
|
||||||
|
- throw("bcryptprimitives.dll not found")
|
||||||
|
+ var kernel32dll = []byte("kernel32.dll\000")
|
||||||
|
+ k32 := stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&kernel32dll[0])))
|
||||||
|
+ if k32 == 0 {
|
||||||
|
+ throw("kernel32.dll not found")
|
||||||
|
}
|
||||||
|
- _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
+ _AddDllDirectory = windowsFindfunc(k32, []byte("AddDllDirectory\000"))
|
||||||
|
+ _AddVectoredContinueHandler = windowsFindfunc(k32, []byte("AddVectoredContinueHandler\000"))
|
||||||
|
+ _LoadLibraryExA = windowsFindfunc(k32, []byte("LoadLibraryExA\000"))
|
||||||
|
+ _LoadLibraryExW = windowsFindfunc(k32, []byte("LoadLibraryExW\000"))
|
||||||
|
+ useLoadLibraryEx = (_LoadLibraryExW != nil && _LoadLibraryExA != nil && _AddDllDirectory != nil)
|
||||||
|
+
|
||||||
|
+ initSysDirectory()
|
||||||
|
|
||||||
|
- n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
+ var advapi32dll = []byte("advapi32.dll\000")
|
||||||
|
+ a32 := windowsLoadSystemLib(advapi32dll)
|
||||||
|
+ if a32 == 0 {
|
||||||
|
+ throw("advapi32.dll not found")
|
||||||
|
+ }
|
||||||
|
+ _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
+
|
||||||
|
+ var ntdll = []byte("ntdll.dll\000")
|
||||||
|
+ n32 := windowsLoadSystemLib(ntdll)
|
||||||
|
if n32 == 0 {
|
||||||
|
throw("ntdll.dll not found")
|
||||||
|
}
|
||||||
|
@@ -299,7 +331,7 @@
|
||||||
|
context uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
- powrprof := windowsLoadSystemLib(powrprofdll[:])
|
||||||
|
+ powrprof := windowsLoadSystemLib([]byte("powrprof.dll\000"))
|
||||||
|
if powrprof == 0 {
|
||||||
|
return // Running on Windows 7, where we don't need it anyway.
|
||||||
|
}
|
||||||
|
@@ -358,6 +390,22 @@
|
||||||
|
// in sys_windows_386.s and sys_windows_amd64.s:
|
||||||
|
func getlasterror() uint32
|
||||||
|
|
||||||
|
+// When loading DLLs, we prefer to use LoadLibraryEx with
|
||||||
|
+// LOAD_LIBRARY_SEARCH_* flags, if available. LoadLibraryEx is not
|
||||||
|
+// available on old Windows, though, and the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags are not available on some versions of Windows without a
|
||||||
|
+// security patch.
|
||||||
|
+//
|
||||||
|
+// https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
|
||||||
|
+// "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
|
||||||
|
+// Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
|
||||||
|
+// systems that have KB2533623 installed. To determine whether the
|
||||||
|
+// flags are available, use GetProcAddress to get the address of the
|
||||||
|
+// AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
|
||||||
|
+// function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags can be used with LoadLibraryEx."
|
||||||
|
+var useLoadLibraryEx bool
|
||||||
|
+
|
||||||
|
var timeBeginPeriodRetValue uint32
|
||||||
|
|
||||||
|
// osRelaxMinNS indicates that sysmon shouldn't osRelax if the next
|
||||||
|
@@ -431,7 +479,8 @@
|
||||||
|
// Only load winmm.dll if we need it.
|
||||||
|
// This avoids a dependency on winmm.dll for Go programs
|
||||||
|
// that run on new Windows versions.
|
||||||
|
- m32 := windowsLoadSystemLib(winmmdll[:])
|
||||||
|
+ var winmmdll = []byte("winmm.dll\000")
|
||||||
|
+ m32 := windowsLoadSystemLib(winmmdll)
|
||||||
|
if m32 == 0 {
|
||||||
|
print("runtime: LoadLibraryExW failed; errno=", getlasterror(), "\n")
|
||||||
|
throw("winmm.dll not found")
|
||||||
|
@@ -472,6 +521,28 @@
|
||||||
|
canUseLongPaths = true
|
||||||
|
}
|
||||||
|
|
||||||
|
+var osVersionInfo struct {
|
||||||
|
+ majorVersion uint32
|
||||||
|
+ minorVersion uint32
|
||||||
|
+ buildNumber uint32
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func initOsVersionInfo() {
|
||||||
|
+ info := _OSVERSIONINFOW{}
|
||||||
|
+ info.osVersionInfoSize = uint32(unsafe.Sizeof(info))
|
||||||
|
+ stdcall1(_RtlGetVersion, uintptr(unsafe.Pointer(&info)))
|
||||||
|
+ osVersionInfo.majorVersion = info.majorVersion
|
||||||
|
+ osVersionInfo.minorVersion = info.minorVersion
|
||||||
|
+ osVersionInfo.buildNumber = info.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers syscall.rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) {
|
||||||
|
+ *majorVersion = osVersionInfo.majorVersion
|
||||||
|
+ *minorVersion = osVersionInfo.minorVersion
|
||||||
|
+ *buildNumber = osVersionInfo.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
func osinit() {
|
||||||
|
asmstdcallAddr = unsafe.Pointer(abi.FuncPCABI0(asmstdcall))
|
||||||
|
|
||||||
|
@@ -484,8 +555,8 @@
|
||||||
|
initHighResTimer()
|
||||||
|
timeBeginPeriodRetValue = osRelax(false)
|
||||||
|
|
||||||
|
- initSysDirectory()
|
||||||
|
initLongPathSupport()
|
||||||
|
+ initOsVersionInfo()
|
||||||
|
|
||||||
|
ncpu = getproccount()
|
||||||
|
|
||||||
|
@@ -501,7 +572,7 @@
|
||||||
|
//go:nosplit
|
||||||
|
func readRandom(r []byte) int {
|
||||||
|
n := 0
|
||||||
|
- if stdcall2(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
Index: src/net/hook_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/hook_windows.go b/src/net/hook_windows.go
|
||||||
|
--- a/src/net/hook_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
+++ b/src/net/hook_windows.go (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
@@ -13,6 +13,7 @@
|
||||||
|
hostsFilePath = windows.GetSystemDirectory() + "/Drivers/etc/hosts"
|
||||||
|
|
||||||
|
// 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
|
||||||
|
Index: src/net/internal/socktest/main_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_test.go b/src/net/internal/socktest/main_test.go
|
||||||
|
--- a/src/net/internal/socktest/main_test.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
+++ b/src/net/internal/socktest/main_test.go (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
@@ -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 && !windows
|
||||||
|
+//go:build !js && !plan9 && !wasip1
|
||||||
|
|
||||||
|
package socktest_test
|
||||||
|
|
||||||
|
Index: src/net/internal/socktest/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_windows_test.go b/src/net/internal/socktest/main_windows_test.go
|
||||||
|
new file mode 100644
|
||||||
|
--- /dev/null (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
+++ b/src/net/internal/socktest/main_windows_test.go (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
@@ -0,0 +1,22 @@
|
||||||
|
+// 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
|
||||||
|
+}
|
||||||
|
Index: src/net/internal/socktest/sys_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/sys_windows.go b/src/net/internal/socktest/sys_windows.go
|
||||||
|
--- a/src/net/internal/socktest/sys_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
+++ b/src/net/internal/socktest/sys_windows.go (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
@@ -9,6 +9,38 @@
|
||||||
|
"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)
|
||||||
|
Index: src/net/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/main_windows_test.go b/src/net/main_windows_test.go
|
||||||
|
--- a/src/net/main_windows_test.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
+++ b/src/net/main_windows_test.go (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
@@ -8,6 +8,7 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Placeholders for saving original socket system calls.
|
||||||
|
+ origSocket = socketFunc
|
||||||
|
origWSASocket = wsaSocketFunc
|
||||||
|
origClosesocket = poll.CloseFunc
|
||||||
|
origConnect = connectFunc
|
||||||
|
@@ -17,6 +18,7 @@
|
||||||
|
)
|
||||||
|
|
||||||
|
func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
wsaSocketFunc = sw.WSASocket
|
||||||
|
poll.CloseFunc = sw.Closesocket
|
||||||
|
connectFunc = sw.Connect
|
||||||
|
@@ -26,6 +28,7 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func uninstallTestHooks() {
|
||||||
|
+ socketFunc = origSocket
|
||||||
|
wsaSocketFunc = origWSASocket
|
||||||
|
poll.CloseFunc = origClosesocket
|
||||||
|
connectFunc = origConnect
|
||||||
|
Index: src/net/sock_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/sock_windows.go b/src/net/sock_windows.go
|
||||||
|
--- a/src/net/sock_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
+++ b/src/net/sock_windows.go (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
@@ -20,6 +20,21 @@
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
Index: src/syscall/exec_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
--- a/src/syscall/exec_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
+++ b/src/syscall/exec_windows.go (revision 979d6d8bab3823ff572ace26767fd2ce3cf351ae)
|
||||||
|
@@ -14,7 +14,6 @@
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
-// ForkLock is not used on Windows.
|
||||||
|
var ForkLock sync.RWMutex
|
||||||
|
|
||||||
|
// EscapeArg rewrites command line argument s as prescribed
|
||||||
|
@@ -254,6 +253,9 @@
|
||||||
|
var zeroProcAttr ProcAttr
|
||||||
|
var zeroSysProcAttr SysProcAttr
|
||||||
|
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32)
|
||||||
|
+
|
||||||
|
func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error) {
|
||||||
|
if len(argv0) == 0 {
|
||||||
|
return 0, 0, EWINDOWS
|
||||||
|
@@ -317,6 +319,17 @@
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
+ 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 {
|
||||||
|
@@ -325,7 +338,15 @@
|
||||||
|
fd := make([]Handle, len(attr.Files))
|
||||||
|
for i := range attr.Files {
|
||||||
|
if attr.Files[i] > 0 {
|
||||||
|
- err := DuplicateHandle(p, Handle(attr.Files[i]), parentProcess, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
+ 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)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
@@ -356,6 +377,14 @@
|
||||||
|
|
||||||
|
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
|
||||||
|
Index: src/runtime/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/syscall_windows.go b/src/runtime/syscall_windows.go
|
||||||
|
--- a/src/runtime/syscall_windows.go (revision 979d6d8bab3823ff572ace26767fd2ce3cf351ae)
|
||||||
|
+++ b/src/runtime/syscall_windows.go (revision ac3e93c061779dfefc0dd13a5b6e6f764a25621e)
|
||||||
|
@@ -413,10 +413,20 @@
|
||||||
|
|
||||||
|
const _LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
|
||||||
|
|
||||||
|
+// When available, this function will use LoadLibraryEx with the filename
|
||||||
|
+// parameter and the important SEARCH_SYSTEM32 argument. But on systems that
|
||||||
|
+// do not have that option, absoluteFilepath should contain a fallback
|
||||||
|
+// to the full path inside of system32 for use with vanilla LoadLibrary.
|
||||||
|
+//
|
||||||
|
//go:linkname syscall_loadsystemlibrary syscall.loadsystemlibrary
|
||||||
|
-func syscall_loadsystemlibrary(filename *uint16) (handle, err uintptr) {
|
||||||
|
- handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryExW)), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+func syscall_loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle, err uintptr) {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryExW)), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryW)), uintptr(unsafe.Pointer(absoluteFilepath)))
|
||||||
|
+ }
|
||||||
|
KeepAlive(filename)
|
||||||
|
+ KeepAlive(absoluteFilepath)
|
||||||
|
if handle != 0 {
|
||||||
|
err = 0
|
||||||
|
}
|
||||||
|
Index: src/syscall/dll_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/dll_windows.go b/src/syscall/dll_windows.go
|
||||||
|
--- a/src/syscall/dll_windows.go (revision 979d6d8bab3823ff572ace26767fd2ce3cf351ae)
|
||||||
|
+++ b/src/syscall/dll_windows.go (revision ac3e93c061779dfefc0dd13a5b6e6f764a25621e)
|
||||||
|
@@ -45,7 +45,7 @@
|
||||||
|
//go:noescape
|
||||||
|
func SyscallN(trap uintptr, args ...uintptr) (r1, r2 uintptr, err Errno)
|
||||||
|
func loadlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
-func loadsystemlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
+func loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle uintptr, err Errno)
|
||||||
|
func getprocaddress(handle uintptr, procname *uint8) (proc uintptr, err Errno)
|
||||||
|
|
||||||
|
// A DLL implements access to a single DLL.
|
||||||
|
@@ -54,6 +54,9 @@
|
||||||
|
Handle Handle
|
||||||
|
}
|
||||||
|
|
||||||
|
+//go:linkname getSystemDirectory
|
||||||
|
+func getSystemDirectory() string // Implemented in runtime package.
|
||||||
|
+
|
||||||
|
// LoadDLL loads the named DLL file into memory.
|
||||||
|
//
|
||||||
|
// If name is not an absolute path and is not a known system DLL used by
|
||||||
|
@@ -70,7 +73,11 @@
|
||||||
|
var h uintptr
|
||||||
|
var e Errno
|
||||||
|
if sysdll.IsSystemDLL[name] {
|
||||||
|
- h, e = loadsystemlibrary(namep)
|
||||||
|
+ absoluteFilepathp, err := UTF16PtrFromString(getSystemDirectory() + name)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return nil, err
|
||||||
|
+ }
|
||||||
|
+ h, e = loadsystemlibrary(namep, absoluteFilepathp)
|
||||||
|
} else {
|
||||||
|
h, e = loadlibrary(namep)
|
||||||
|
}
|
||||||
657
.github/patch/go1.25.patch
vendored
Normal file
657
.github/patch/go1.25.patch
vendored
Normal file
@@ -0,0 +1,657 @@
|
|||||||
|
Subject: [PATCH] Revert "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
Revert "syscall: remove Windows 7 console handle workaround"
|
||||||
|
Revert "net: remove sysSocket fallback for Windows 7"
|
||||||
|
Revert "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
---
|
||||||
|
Index: src/crypto/internal/sysrand/rand_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/internal/sysrand/rand_windows.go b/src/crypto/internal/sysrand/rand_windows.go
|
||||||
|
--- a/src/crypto/internal/sysrand/rand_windows.go (revision 6e676ab2b809d46623acb5988248d95d1eb7939c)
|
||||||
|
+++ b/src/crypto/internal/sysrand/rand_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
@@ -7,5 +7,26 @@
|
||||||
|
import "internal/syscall/windows"
|
||||||
|
|
||||||
|
func read(b []byte) error {
|
||||||
|
- return windows.ProcessPrng(b)
|
||||||
|
+ // 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.
|
||||||
|
+ return batched(windows.RtlGenRandom, 1<<31-1)(b)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// batched returns a function that calls f to populate a []byte by chunking it
|
||||||
|
+// into subslices of, at most, readMax bytes.
|
||||||
|
+func batched(f func([]byte) error, readMax int) func([]byte) error {
|
||||||
|
+ return func(out []byte) error {
|
||||||
|
+ for len(out) > 0 {
|
||||||
|
+ read := len(out)
|
||||||
|
+ if read > readMax {
|
||||||
|
+ read = readMax
|
||||||
|
+ }
|
||||||
|
+ if err := f(out[:read]); err != nil {
|
||||||
|
+ return err
|
||||||
|
+ }
|
||||||
|
+ out = out[read:]
|
||||||
|
+ }
|
||||||
|
+ return nil
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
Index: src/crypto/rand/rand.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
--- a/src/crypto/rand/rand.go (revision 6e676ab2b809d46623acb5988248d95d1eb7939c)
|
||||||
|
+++ b/src/crypto/rand/rand.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
@@ -22,7 +22,7 @@
|
||||||
|
// - On legacy Linux (< 3.17), Reader opens /dev/urandom on first use.
|
||||||
|
// - On macOS, iOS, and OpenBSD Reader, uses arc4random_buf(3).
|
||||||
|
// - On NetBSD, Reader uses the kern.arandom sysctl.
|
||||||
|
-// - On Windows, Reader uses the ProcessPrng API.
|
||||||
|
+// - On Windows systems, Reader uses the RtlGenRandom API.
|
||||||
|
// - On js/wasm, Reader uses the Web Crypto API.
|
||||||
|
// - On wasip1/wasm, Reader uses random_get.
|
||||||
|
//
|
||||||
|
Index: src/internal/syscall/windows/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go (revision 6e676ab2b809d46623acb5988248d95d1eb7939c)
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
@@ -419,7 +419,7 @@
|
||||||
|
//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 ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
+//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
|
||||||
|
type FILE_ID_BOTH_DIR_INFO struct {
|
||||||
|
NextEntryOffset uint32
|
||||||
|
Index: src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go (revision 6e676ab2b809d46623acb5988248d95d1eb7939c)
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
@@ -38,7 +38,6 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
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"))
|
||||||
|
@@ -63,7 +62,7 @@
|
||||||
|
procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
+ procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort")
|
||||||
|
@@ -242,12 +241,12 @@
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func ProcessPrng(buf []byte) (err error) {
|
||||||
|
+func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
+ r1, _, e1 := syscall.Syscall(procSystemFunction036.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
Index: src/runtime/os_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
--- a/src/runtime/os_windows.go (revision 6e676ab2b809d46623acb5988248d95d1eb7939c)
|
||||||
|
+++ b/src/runtime/os_windows.go (revision f56f1e23507e646c85243a71bde7b9629b2f970c)
|
||||||
|
@@ -39,8 +39,8 @@
|
||||||
|
//go:cgo_import_dynamic runtime._GetSystemInfo GetSystemInfo%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._GetThreadContext GetThreadContext%2 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._SetThreadContext SetThreadContext%2 "kernel32.dll"
|
||||||
|
-//go:cgo_import_dynamic runtime._LoadLibraryExW LoadLibraryExW%3 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._LoadLibraryW LoadLibraryW%1 "kernel32.dll"
|
||||||
|
+//go:cgo_import_dynamic runtime._LoadLibraryA LoadLibraryA%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._PostQueuedCompletionStatus PostQueuedCompletionStatus%4 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceCounter QueryPerformanceCounter%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceFrequency QueryPerformanceFrequency%1 "kernel32.dll"
|
||||||
|
@@ -74,7 +74,6 @@
|
||||||
|
// Following syscalls are available on every Windows PC.
|
||||||
|
// All these variables are set by the Windows executable
|
||||||
|
// loader before the Go program starts.
|
||||||
|
- _AddVectoredContinueHandler,
|
||||||
|
_AddVectoredExceptionHandler,
|
||||||
|
_CloseHandle,
|
||||||
|
_CreateEventA,
|
||||||
|
@@ -97,8 +96,8 @@
|
||||||
|
_GetSystemInfo,
|
||||||
|
_GetThreadContext,
|
||||||
|
_SetThreadContext,
|
||||||
|
- _LoadLibraryExW,
|
||||||
|
_LoadLibraryW,
|
||||||
|
+ _LoadLibraryA,
|
||||||
|
_PostQueuedCompletionStatus,
|
||||||
|
_QueryPerformanceCounter,
|
||||||
|
_QueryPerformanceFrequency,
|
||||||
|
@@ -127,8 +126,23 @@
|
||||||
|
_WriteFile,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
- _ProcessPrng stdFunction
|
||||||
|
+ // Following syscalls are only available on some Windows PCs.
|
||||||
|
+ // We will load syscalls, if available, before using them.
|
||||||
|
+ _AddDllDirectory,
|
||||||
|
+ _AddVectoredContinueHandler,
|
||||||
|
+ _LoadLibraryExA,
|
||||||
|
+ _LoadLibraryExW,
|
||||||
|
+ _ 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
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -145,13 +159,6 @@
|
||||||
|
_ stdFunction
|
||||||
|
)
|
||||||
|
|
||||||
|
-var (
|
||||||
|
- 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}
|
||||||
|
-)
|
||||||
|
-
|
||||||
|
// Function to be called by windows CreateThread
|
||||||
|
// to start new os thread.
|
||||||
|
func tstart_stdcall(newm *m)
|
||||||
|
@@ -244,8 +251,18 @@
|
||||||
|
return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
-func windowsLoadSystemLib(name []uint16) uintptr {
|
||||||
|
- return stdcall3(_LoadLibraryExW, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+//go:linkname syscall_getSystemDirectory syscall.getSystemDirectory
|
||||||
|
+func syscall_getSystemDirectory() string {
|
||||||
|
+ return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func windowsLoadSystemLib(name []byte) uintptr {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ return stdcall3(_LoadLibraryExA, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ absName := append(sysDirectory[:sysDirectoryLen], name...)
|
||||||
|
+ return stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&absName[0])))
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
|
||||||
|
//go:linkname windows_QueryPerformanceCounter internal/syscall/windows.QueryPerformanceCounter
|
||||||
|
@@ -263,13 +280,28 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOptionalSyscalls() {
|
||||||
|
- bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
- if bcryptPrimitives == 0 {
|
||||||
|
- throw("bcryptprimitives.dll not found")
|
||||||
|
+ var kernel32dll = []byte("kernel32.dll\000")
|
||||||
|
+ k32 := stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&kernel32dll[0])))
|
||||||
|
+ if k32 == 0 {
|
||||||
|
+ throw("kernel32.dll not found")
|
||||||
|
}
|
||||||
|
- _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
+ _AddDllDirectory = windowsFindfunc(k32, []byte("AddDllDirectory\000"))
|
||||||
|
+ _AddVectoredContinueHandler = windowsFindfunc(k32, []byte("AddVectoredContinueHandler\000"))
|
||||||
|
+ _LoadLibraryExA = windowsFindfunc(k32, []byte("LoadLibraryExA\000"))
|
||||||
|
+ _LoadLibraryExW = windowsFindfunc(k32, []byte("LoadLibraryExW\000"))
|
||||||
|
+ useLoadLibraryEx = (_LoadLibraryExW != nil && _LoadLibraryExA != nil && _AddDllDirectory != nil)
|
||||||
|
+
|
||||||
|
+ initSysDirectory()
|
||||||
|
|
||||||
|
- n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
+ var advapi32dll = []byte("advapi32.dll\000")
|
||||||
|
+ a32 := windowsLoadSystemLib(advapi32dll)
|
||||||
|
+ if a32 == 0 {
|
||||||
|
+ throw("advapi32.dll not found")
|
||||||
|
+ }
|
||||||
|
+ _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
+
|
||||||
|
+ var ntdll = []byte("ntdll.dll\000")
|
||||||
|
+ n32 := windowsLoadSystemLib(ntdll)
|
||||||
|
if n32 == 0 {
|
||||||
|
throw("ntdll.dll not found")
|
||||||
|
}
|
||||||
|
@@ -298,7 +330,7 @@
|
||||||
|
context uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
- powrprof := windowsLoadSystemLib(powrprofdll[:])
|
||||||
|
+ powrprof := windowsLoadSystemLib([]byte("powrprof.dll\000"))
|
||||||
|
if powrprof == 0 {
|
||||||
|
return // Running on Windows 7, where we don't need it anyway.
|
||||||
|
}
|
||||||
|
@@ -357,6 +389,22 @@
|
||||||
|
// in sys_windows_386.s and sys_windows_amd64.s:
|
||||||
|
func getlasterror() uint32
|
||||||
|
|
||||||
|
+// When loading DLLs, we prefer to use LoadLibraryEx with
|
||||||
|
+// LOAD_LIBRARY_SEARCH_* flags, if available. LoadLibraryEx is not
|
||||||
|
+// available on old Windows, though, and the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags are not available on some versions of Windows without a
|
||||||
|
+// security patch.
|
||||||
|
+//
|
||||||
|
+// https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
|
||||||
|
+// "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
|
||||||
|
+// Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
|
||||||
|
+// systems that have KB2533623 installed. To determine whether the
|
||||||
|
+// flags are available, use GetProcAddress to get the address of the
|
||||||
|
+// AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
|
||||||
|
+// function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags can be used with LoadLibraryEx."
|
||||||
|
+var useLoadLibraryEx bool
|
||||||
|
+
|
||||||
|
var timeBeginPeriodRetValue uint32
|
||||||
|
|
||||||
|
// osRelaxMinNS indicates that sysmon shouldn't osRelax if the next
|
||||||
|
@@ -430,7 +478,8 @@
|
||||||
|
// Only load winmm.dll if we need it.
|
||||||
|
// This avoids a dependency on winmm.dll for Go programs
|
||||||
|
// that run on new Windows versions.
|
||||||
|
- m32 := windowsLoadSystemLib(winmmdll[:])
|
||||||
|
+ var winmmdll = []byte("winmm.dll\000")
|
||||||
|
+ m32 := windowsLoadSystemLib(winmmdll)
|
||||||
|
if m32 == 0 {
|
||||||
|
print("runtime: LoadLibraryExW failed; errno=", getlasterror(), "\n")
|
||||||
|
throw("winmm.dll not found")
|
||||||
|
@@ -471,6 +520,28 @@
|
||||||
|
canUseLongPaths = true
|
||||||
|
}
|
||||||
|
|
||||||
|
+var osVersionInfo struct {
|
||||||
|
+ majorVersion uint32
|
||||||
|
+ minorVersion uint32
|
||||||
|
+ buildNumber uint32
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func initOsVersionInfo() {
|
||||||
|
+ info := _OSVERSIONINFOW{}
|
||||||
|
+ info.osVersionInfoSize = uint32(unsafe.Sizeof(info))
|
||||||
|
+ stdcall1(_RtlGetVersion, uintptr(unsafe.Pointer(&info)))
|
||||||
|
+ osVersionInfo.majorVersion = info.majorVersion
|
||||||
|
+ osVersionInfo.minorVersion = info.minorVersion
|
||||||
|
+ osVersionInfo.buildNumber = info.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers syscall.rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) {
|
||||||
|
+ *majorVersion = osVersionInfo.majorVersion
|
||||||
|
+ *minorVersion = osVersionInfo.minorVersion
|
||||||
|
+ *buildNumber = osVersionInfo.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
func osinit() {
|
||||||
|
asmstdcallAddr = unsafe.Pointer(abi.FuncPCABI0(asmstdcall))
|
||||||
|
|
||||||
|
@@ -483,8 +554,8 @@
|
||||||
|
initHighResTimer()
|
||||||
|
timeBeginPeriodRetValue = osRelax(false)
|
||||||
|
|
||||||
|
- initSysDirectory()
|
||||||
|
initLongPathSupport()
|
||||||
|
+ initOsVersionInfo()
|
||||||
|
|
||||||
|
numCPUStartup = getCPUCount()
|
||||||
|
|
||||||
|
@@ -500,7 +571,7 @@
|
||||||
|
//go:nosplit
|
||||||
|
func readRandom(r []byte) int {
|
||||||
|
n := 0
|
||||||
|
- if stdcall2(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
Index: src/net/hook_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/hook_windows.go b/src/net/hook_windows.go
|
||||||
|
--- a/src/net/hook_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
+++ b/src/net/hook_windows.go (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
@@ -13,6 +13,7 @@
|
||||||
|
hostsFilePath = windows.GetSystemDirectory() + "/Drivers/etc/hosts"
|
||||||
|
|
||||||
|
// 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
|
||||||
|
Index: src/net/internal/socktest/main_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_test.go b/src/net/internal/socktest/main_test.go
|
||||||
|
--- a/src/net/internal/socktest/main_test.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
+++ b/src/net/internal/socktest/main_test.go (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
@@ -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 && !windows
|
||||||
|
+//go:build !js && !plan9 && !wasip1
|
||||||
|
|
||||||
|
package socktest_test
|
||||||
|
|
||||||
|
Index: src/net/internal/socktest/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_windows_test.go b/src/net/internal/socktest/main_windows_test.go
|
||||||
|
new file mode 100644
|
||||||
|
--- /dev/null (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
+++ b/src/net/internal/socktest/main_windows_test.go (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
@@ -0,0 +1,22 @@
|
||||||
|
+// 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
|
||||||
|
+}
|
||||||
|
Index: src/net/internal/socktest/sys_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/sys_windows.go b/src/net/internal/socktest/sys_windows.go
|
||||||
|
--- a/src/net/internal/socktest/sys_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
+++ b/src/net/internal/socktest/sys_windows.go (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
@@ -9,6 +9,38 @@
|
||||||
|
"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)
|
||||||
|
Index: src/net/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/main_windows_test.go b/src/net/main_windows_test.go
|
||||||
|
--- a/src/net/main_windows_test.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
+++ b/src/net/main_windows_test.go (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
@@ -12,6 +12,7 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Placeholders for saving original socket system calls.
|
||||||
|
+ origSocket = socketFunc
|
||||||
|
origWSASocket = wsaSocketFunc
|
||||||
|
origClosesocket = poll.CloseFunc
|
||||||
|
origConnect = connectFunc
|
||||||
|
@@ -21,6 +22,7 @@
|
||||||
|
)
|
||||||
|
|
||||||
|
func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
wsaSocketFunc = sw.WSASocket
|
||||||
|
poll.CloseFunc = sw.Closesocket
|
||||||
|
connectFunc = sw.Connect
|
||||||
|
@@ -30,6 +32,7 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func uninstallTestHooks() {
|
||||||
|
+ socketFunc = origSocket
|
||||||
|
wsaSocketFunc = origWSASocket
|
||||||
|
poll.CloseFunc = origClosesocket
|
||||||
|
connectFunc = origConnect
|
||||||
|
Index: src/net/sock_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/sock_windows.go b/src/net/sock_windows.go
|
||||||
|
--- a/src/net/sock_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
+++ b/src/net/sock_windows.go (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
@@ -20,6 +20,21 @@
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
Index: src/syscall/exec_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
--- a/src/syscall/exec_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
+++ b/src/syscall/exec_windows.go (revision a5b2168bb836ed9d6601c626f95e56c07923f906)
|
||||||
|
@@ -14,7 +14,6 @@
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
-// ForkLock is not used on Windows.
|
||||||
|
var ForkLock sync.RWMutex
|
||||||
|
|
||||||
|
// EscapeArg rewrites command line argument s as prescribed
|
||||||
|
@@ -254,6 +253,9 @@
|
||||||
|
var zeroProcAttr ProcAttr
|
||||||
|
var zeroSysProcAttr SysProcAttr
|
||||||
|
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32)
|
||||||
|
+
|
||||||
|
func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error) {
|
||||||
|
if len(argv0) == 0 {
|
||||||
|
return 0, 0, EWINDOWS
|
||||||
|
@@ -317,6 +319,17 @@
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
+ 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 {
|
||||||
|
@@ -325,7 +338,15 @@
|
||||||
|
fd := make([]Handle, len(attr.Files))
|
||||||
|
for i := range attr.Files {
|
||||||
|
if attr.Files[i] > 0 {
|
||||||
|
- err := DuplicateHandle(p, Handle(attr.Files[i]), parentProcess, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
+ 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)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
@@ -356,6 +377,14 @@
|
||||||
|
|
||||||
|
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
|
||||||
|
Index: src/runtime/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/syscall_windows.go b/src/runtime/syscall_windows.go
|
||||||
|
--- a/src/runtime/syscall_windows.go (revision a5b2168bb836ed9d6601c626f95e56c07923f906)
|
||||||
|
+++ b/src/runtime/syscall_windows.go (revision f56f1e23507e646c85243a71bde7b9629b2f970c)
|
||||||
|
@@ -413,10 +413,20 @@
|
||||||
|
|
||||||
|
const _LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
|
||||||
|
|
||||||
|
+// When available, this function will use LoadLibraryEx with the filename
|
||||||
|
+// parameter and the important SEARCH_SYSTEM32 argument. But on systems that
|
||||||
|
+// do not have that option, absoluteFilepath should contain a fallback
|
||||||
|
+// to the full path inside of system32 for use with vanilla LoadLibrary.
|
||||||
|
+//
|
||||||
|
//go:linkname syscall_loadsystemlibrary syscall.loadsystemlibrary
|
||||||
|
-func syscall_loadsystemlibrary(filename *uint16) (handle, err uintptr) {
|
||||||
|
- handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryExW)), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+func syscall_loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle, err uintptr) {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryExW)), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryW)), uintptr(unsafe.Pointer(absoluteFilepath)))
|
||||||
|
+ }
|
||||||
|
KeepAlive(filename)
|
||||||
|
+ KeepAlive(absoluteFilepath)
|
||||||
|
if handle != 0 {
|
||||||
|
err = 0
|
||||||
|
}
|
||||||
|
Index: src/syscall/dll_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/dll_windows.go b/src/syscall/dll_windows.go
|
||||||
|
--- a/src/syscall/dll_windows.go (revision a5b2168bb836ed9d6601c626f95e56c07923f906)
|
||||||
|
+++ b/src/syscall/dll_windows.go (revision f56f1e23507e646c85243a71bde7b9629b2f970c)
|
||||||
|
@@ -45,7 +45,7 @@
|
||||||
|
//go:noescape
|
||||||
|
func SyscallN(trap uintptr, args ...uintptr) (r1, r2 uintptr, err Errno)
|
||||||
|
func loadlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
-func loadsystemlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
+func loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle uintptr, err Errno)
|
||||||
|
func getprocaddress(handle uintptr, procname *uint8) (proc uintptr, err Errno)
|
||||||
|
|
||||||
|
// A DLL implements access to a single DLL.
|
||||||
|
@@ -54,6 +54,9 @@
|
||||||
|
Handle Handle
|
||||||
|
}
|
||||||
|
|
||||||
|
+//go:linkname getSystemDirectory
|
||||||
|
+func getSystemDirectory() string // Implemented in runtime package.
|
||||||
|
+
|
||||||
|
// LoadDLL loads the named DLL file into memory.
|
||||||
|
//
|
||||||
|
// If name is not an absolute path and is not a known system DLL used by
|
||||||
|
@@ -70,7 +73,11 @@
|
||||||
|
var h uintptr
|
||||||
|
var e Errno
|
||||||
|
if sysdll.IsSystemDLL[name] {
|
||||||
|
- h, e = loadsystemlibrary(namep)
|
||||||
|
+ absoluteFilepathp, err := UTF16PtrFromString(getSystemDirectory() + name)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return nil, err
|
||||||
|
+ }
|
||||||
|
+ h, e = loadsystemlibrary(namep, absoluteFilepathp)
|
||||||
|
} else {
|
||||||
|
h, e = loadlibrary(namep)
|
||||||
|
}
|
||||||
59
.github/workflows/build.yml
vendored
59
.github/workflows/build.yml
vendored
@@ -80,6 +80,13 @@ jobs:
|
|||||||
- { goos: android, goarch: arm, ndk: armv7a-linux-androideabi34, output: armv7 }
|
- { goos: android, goarch: arm, ndk: armv7a-linux-androideabi34, output: armv7 }
|
||||||
- { goos: android, goarch: arm64, ndk: aarch64-linux-android34, output: arm64-v8 }
|
- { goos: android, goarch: arm64, ndk: aarch64-linux-android34, output: arm64-v8 }
|
||||||
|
|
||||||
|
# Go 1.24 with special patch can work on Windows 7
|
||||||
|
# https://github.com/MetaCubeX/go/commits/release-branch.go1.24/
|
||||||
|
- { goos: windows, goarch: '386', output: '386-go124', goversion: '1.24' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-v1-go124, goversion: '1.24' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v2, output: amd64-v2-go124, goversion: '1.24' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-v3-go124, goversion: '1.24' }
|
||||||
|
|
||||||
# Go 1.23 with special patch can work on Windows 7
|
# Go 1.23 with special patch can work on Windows 7
|
||||||
# https://github.com/MetaCubeX/go/commits/release-branch.go1.23/
|
# https://github.com/MetaCubeX/go/commits/release-branch.go1.23/
|
||||||
- { goos: windows, goarch: '386', output: '386-go123', goversion: '1.23' }
|
- { goos: windows, goarch: '386', output: '386-go123', goversion: '1.23' }
|
||||||
@@ -108,6 +115,12 @@ jobs:
|
|||||||
- { goos: windows, goarch: amd64, goamd64: v2, output: amd64-v2-go120, goversion: '1.20' }
|
- { goos: windows, goarch: amd64, goamd64: v2, output: amd64-v2-go120, goversion: '1.20' }
|
||||||
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-v3-go120, goversion: '1.20' }
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-v3-go120, goversion: '1.20' }
|
||||||
|
|
||||||
|
# Go 1.24 is the last release that will run on macOS 11 Big Sur. Go 1.25 will require macOS 12 Monterey or later.
|
||||||
|
- { goos: darwin, goarch: arm64, output: arm64-go124, goversion: '1.24' }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-v1-go124, goversion: '1.24' }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v2, output: amd64-v2-go124, goversion: '1.24' }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64-v3-go124, goversion: '1.24' }
|
||||||
|
|
||||||
# Go 1.22 is the last release that will run on macOS 10.15 Catalina. Go 1.23 will require macOS 11 Big Sur or later.
|
# Go 1.22 is the last release that will run on macOS 10.15 Catalina. Go 1.23 will require macOS 11 Big Sur or later.
|
||||||
- { goos: darwin, goarch: arm64, output: arm64-go122, goversion: '1.22' }
|
- { goos: darwin, goarch: arm64, output: arm64-go122, goversion: '1.22' }
|
||||||
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-v1-go122, goversion: '1.22' }
|
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-v1-go122, goversion: '1.22' }
|
||||||
@@ -133,17 +146,17 @@ jobs:
|
|||||||
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64-v3-go120, goversion: '1.20' }
|
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64-v3-go120, goversion: '1.20' }
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v5
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
if: ${{ matrix.jobs.goversion == '' && matrix.jobs.abi != '1' }}
|
if: ${{ matrix.jobs.goversion == '' && matrix.jobs.abi != '1' }}
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v6
|
||||||
with:
|
with:
|
||||||
go-version: '1.24'
|
go-version: '1.25'
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
if: ${{ matrix.jobs.goversion != '' && matrix.jobs.abi != '1' }}
|
if: ${{ matrix.jobs.goversion != '' && matrix.jobs.abi != '1' }}
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v6
|
||||||
with:
|
with:
|
||||||
go-version: ${{ matrix.jobs.goversion }}
|
go-version: ${{ matrix.jobs.goversion }}
|
||||||
|
|
||||||
@@ -154,6 +167,21 @@ jobs:
|
|||||||
sudo tar zxf go1.24.0.linux-amd64-abi1.tar.gz -C /usr/local
|
sudo tar zxf go1.24.0.linux-amd64-abi1.tar.gz -C /usr/local
|
||||||
echo "/usr/local/go/bin" >> $GITHUB_PATH
|
echo "/usr/local/go/bin" >> $GITHUB_PATH
|
||||||
|
|
||||||
|
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||||
|
# this patch file only works on golang1.25.x
|
||||||
|
# that means after golang1.26 release it must be changed
|
||||||
|
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.25/
|
||||||
|
# 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"
|
||||||
|
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
- name: Revert Golang1.25 commit for Windows7/8
|
||||||
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '' }}
|
||||||
|
run: |
|
||||||
|
cd $(go env GOROOT)
|
||||||
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.25.patch
|
||||||
|
|
||||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||||
# this patch file only works on golang1.24.x
|
# this patch file only works on golang1.24.x
|
||||||
# that means after golang1.25 release it must be changed
|
# that means after golang1.25 release it must be changed
|
||||||
@@ -164,13 +192,10 @@ jobs:
|
|||||||
# 48042aa09c2f878c4faa576948b07fe625c4707a: "syscall: remove Windows 7 console handle workaround"
|
# 48042aa09c2f878c4faa576948b07fe625c4707a: "syscall: remove Windows 7 console handle workaround"
|
||||||
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
- name: Revert Golang1.24 commit for Windows7/8
|
- name: Revert Golang1.24 commit for Windows7/8
|
||||||
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '' }}
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.24' }}
|
||||||
run: |
|
run: |
|
||||||
cd $(go env GOROOT)
|
cd $(go env GOROOT)
|
||||||
curl https://github.com/MetaCubeX/go/commit/2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8.diff | patch --verbose -p 1
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.24.patch
|
||||||
curl https://github.com/MetaCubeX/go/commit/7b1fd7d39c6be0185fbe1d929578ab372ac5c632.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/979d6d8bab3823ff572ace26767fd2ce3cf351ae.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/ac3e93c061779dfefc0dd13a5b6e6f764a25621e.diff | patch --verbose -p 1
|
|
||||||
|
|
||||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||||
# this patch file only works on golang1.23.x
|
# this patch file only works on golang1.23.x
|
||||||
@@ -185,10 +210,7 @@ jobs:
|
|||||||
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.23' }}
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.23' }}
|
||||||
run: |
|
run: |
|
||||||
cd $(go env GOROOT)
|
cd $(go env GOROOT)
|
||||||
curl https://github.com/MetaCubeX/go/commit/9ac42137ef6730e8b7daca016ece831297a1d75b.diff | patch --verbose -p 1
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.23.patch
|
||||||
curl https://github.com/MetaCubeX/go/commit/21290de8a4c91408de7c2b5b68757b1e90af49dd.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/6a31d3fa8e47ddabc10bd97bff10d9a85f4cfb76.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/69e2eed6dd0f6d815ebf15797761c13f31213dd6.diff | patch --verbose -p 1
|
|
||||||
|
|
||||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||||
# this patch file only works on golang1.22.x
|
# this patch file only works on golang1.22.x
|
||||||
@@ -203,17 +225,14 @@ jobs:
|
|||||||
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.22' }}
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.22' }}
|
||||||
run: |
|
run: |
|
||||||
cd $(go env GOROOT)
|
cd $(go env GOROOT)
|
||||||
curl https://github.com/MetaCubeX/go/commit/9779155f18b6556a034f7bb79fb7fb2aad1e26a9.diff | patch --verbose -p 1
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.22.patch
|
||||||
curl https://github.com/MetaCubeX/go/commit/ef0606261340e608017860b423ffae5c1ce78239.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/7f83badcb925a7e743188041cb6e561fc9b5b642.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/83ff9782e024cb328b690cbf0da4e7848a327f4f.diff | patch --verbose -p 1
|
|
||||||
|
|
||||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||||
- name: Revert Golang1.21 commit for Windows7/8
|
- name: Revert Golang1.21 commit for Windows7/8
|
||||||
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.21' }}
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.21' }}
|
||||||
run: |
|
run: |
|
||||||
cd $(go env GOROOT)
|
cd $(go env GOROOT)
|
||||||
curl https://github.com/golang/go/commit/9e43850a3298a9b8b1162ba0033d4c53f8637571.diff | patch --verbose -R -p 1
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.21.patch
|
||||||
|
|
||||||
- name: Set variables
|
- name: Set variables
|
||||||
run: |
|
run: |
|
||||||
@@ -402,7 +421,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v5
|
||||||
with:
|
with:
|
||||||
ref: Meta
|
ref: Meta
|
||||||
fetch-depth: '0'
|
fetch-depth: '0'
|
||||||
@@ -461,7 +480,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v5
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
|
|||||||
68
.github/workflows/test.yml
vendored
68
.github/workflows/test.yml
vendored
@@ -22,8 +22,9 @@ jobs:
|
|||||||
- 'windows-latest' # amd64 windows
|
- 'windows-latest' # amd64 windows
|
||||||
- 'macos-latest' # arm64 macos
|
- 'macos-latest' # arm64 macos
|
||||||
- 'ubuntu-24.04-arm' # arm64 linux
|
- 'ubuntu-24.04-arm' # arm64 linux
|
||||||
- 'macos-13' # amd64 macos
|
- 'macos-15-intel' # amd64 macos
|
||||||
go-version:
|
go-version:
|
||||||
|
- '1.25'
|
||||||
- '1.24'
|
- '1.24'
|
||||||
- '1.23'
|
- '1.23'
|
||||||
- '1.22'
|
- '1.22'
|
||||||
@@ -40,73 +41,18 @@ jobs:
|
|||||||
# Fix mingw trying to be smart and converting paths https://github.com/moby/moby/issues/24029#issuecomment-250412919
|
# Fix mingw trying to be smart and converting paths https://github.com/moby/moby/issues/24029#issuecomment-250412919
|
||||||
MSYS_NO_PATHCONV: true
|
MSYS_NO_PATHCONV: true
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v5
|
||||||
|
|
||||||
- name: Setup Go
|
- name: Setup Go
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v6
|
||||||
with:
|
with:
|
||||||
go-version: ${{ matrix.go-version }}
|
go-version: ${{ matrix.go-version }}
|
||||||
|
|
||||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
- name: Revert Golang commit for Windows7/8
|
||||||
# this patch file only works on golang1.24.x
|
if: ${{ runner.os == 'Windows' && matrix.go-version != '1.20' }}
|
||||||
# that means after golang1.25 release it must be changed
|
|
||||||
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.24/
|
|
||||||
# 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"
|
|
||||||
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
|
||||||
- name: Revert Golang1.24 commit for Windows7/8
|
|
||||||
if: ${{ runner.os == 'Windows' && matrix.go-version == '1.24' }}
|
|
||||||
run: |
|
run: |
|
||||||
cd $(go env GOROOT)
|
cd $(go env GOROOT)
|
||||||
curl https://github.com/MetaCubeX/go/commit/2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8.diff | patch --verbose -p 1
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go${{matrix.go-version}}.patch
|
||||||
curl https://github.com/MetaCubeX/go/commit/7b1fd7d39c6be0185fbe1d929578ab372ac5c632.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/979d6d8bab3823ff572ace26767fd2ce3cf351ae.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/ac3e93c061779dfefc0dd13a5b6e6f764a25621e.diff | patch --verbose -p 1
|
|
||||||
|
|
||||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
|
||||||
# this patch file only works on golang1.23.x
|
|
||||||
# that means after golang1.24 release it must be changed
|
|
||||||
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.23/
|
|
||||||
# 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"
|
|
||||||
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
|
||||||
- name: Revert Golang1.23 commit for Windows7/8
|
|
||||||
if: ${{ runner.os == 'Windows' && matrix.go-version == '1.23' }}
|
|
||||||
run: |
|
|
||||||
cd $(go env GOROOT)
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/9ac42137ef6730e8b7daca016ece831297a1d75b.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/21290de8a4c91408de7c2b5b68757b1e90af49dd.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/6a31d3fa8e47ddabc10bd97bff10d9a85f4cfb76.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/69e2eed6dd0f6d815ebf15797761c13f31213dd6.diff | patch --verbose -p 1
|
|
||||||
|
|
||||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
|
||||||
# this patch file only works on golang1.22.x
|
|
||||||
# that means after golang1.23 release it must be changed
|
|
||||||
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.22/
|
|
||||||
# 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"
|
|
||||||
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
|
||||||
- name: Revert Golang1.22 commit for Windows7/8
|
|
||||||
if: ${{ runner.os == 'Windows' && matrix.go-version == '1.22' }}
|
|
||||||
run: |
|
|
||||||
cd $(go env GOROOT)
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/9779155f18b6556a034f7bb79fb7fb2aad1e26a9.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/ef0606261340e608017860b423ffae5c1ce78239.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/7f83badcb925a7e743188041cb6e561fc9b5b642.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/83ff9782e024cb328b690cbf0da4e7848a327f4f.diff | patch --verbose -p 1
|
|
||||||
|
|
||||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
|
||||||
- name: Revert Golang1.21 commit for Windows7/8
|
|
||||||
if: ${{ runner.os == 'Windows' && matrix.go-version == '1.21' }}
|
|
||||||
run: |
|
|
||||||
cd $(go env GOROOT)
|
|
||||||
curl https://github.com/golang/go/commit/9e43850a3298a9b8b1162ba0033d4c53f8637571.diff | patch --verbose -R -p 1
|
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: go test ./... -v -count=1
|
run: go test ./... -v -count=1
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ RUN echo "I'm building for $TARGETPLATFORM"
|
|||||||
|
|
||||||
RUN apk add --no-cache gzip && \
|
RUN apk add --no-cache gzip && \
|
||||||
mkdir /mihomo-config && \
|
mkdir /mihomo-config && \
|
||||||
wget -O /mihomo-config/geoip.metadb https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.metadb && \
|
wget -O /mihomo-config/geoip.metadb https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.metadb && \
|
||||||
wget -O /mihomo-config/geosite.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geosite.dat && \
|
wget -O /mihomo-config/geosite.dat https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geosite.dat && \
|
||||||
wget -O /mihomo-config/geoip.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.dat
|
wget -O /mihomo-config/geoip.dat https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.dat
|
||||||
|
|
||||||
COPY docker/file-name.sh /mihomo/file-name.sh
|
COPY docker/file-name.sh /mihomo/file-name.sh
|
||||||
WORKDIR /mihomo
|
WORKDIR /mihomo
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package adapter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
@@ -52,26 +51,12 @@ func (p *Proxy) AliveForTestUrl(url string) bool {
|
|||||||
return p.alive.Load()
|
return p.alive.Load()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dial implements C.Proxy
|
|
||||||
func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
|
|
||||||
defer cancel()
|
|
||||||
return p.DialContext(ctx, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
conn, err := p.ProxyAdapter.DialContext(ctx, metadata)
|
conn, err := p.ProxyAdapter.DialContext(ctx, metadata)
|
||||||
return conn, err
|
return conn, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialUDP implements C.ProxyAdapter
|
|
||||||
func (p *Proxy) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultUDPTimeout)
|
|
||||||
defer cancel()
|
|
||||||
return p.ListenPacketContext(ctx, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (p *Proxy) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
func (p *Proxy) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata)
|
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata)
|
||||||
@@ -236,6 +221,11 @@ func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.In
|
|||||||
}
|
}
|
||||||
req = req.WithContext(ctx)
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
|
tlsConfig, err := ca.GetTLSConfig(ca.Option{})
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
transport := &http.Transport{
|
transport := &http.Transport{
|
||||||
DialContext: func(context.Context, string, string) (net.Conn, error) {
|
DialContext: func(context.Context, string, string) (net.Conn, error) {
|
||||||
return instance, nil
|
return instance, nil
|
||||||
@@ -245,7 +235,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{}),
|
TLSClientConfig: tlsConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{
|
client := http.Client{
|
||||||
|
|||||||
@@ -36,6 +36,8 @@ type AnyTLSOption struct {
|
|||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
IdleSessionCheckInterval int `proxy:"idle-session-check-interval,omitempty"`
|
IdleSessionCheckInterval int `proxy:"idle-session-check-interval,omitempty"`
|
||||||
IdleSessionTimeout int `proxy:"idle-session-timeout,omitempty"`
|
IdleSessionTimeout int `proxy:"idle-session-timeout,omitempty"`
|
||||||
@@ -120,6 +122,8 @@ func NewAnyTLS(option AnyTLSOption) (*AnyTLS, error) {
|
|||||||
SkipCertVerify: option.SkipCertVerify,
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
NextProtos: option.ALPN,
|
NextProtos: option.ALPN,
|
||||||
FingerPrint: option.Fingerprint,
|
FingerPrint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
ClientFingerprint: option.ClientFingerprint,
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
ECH: echConfig,
|
ECH: echConfig,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -263,7 +263,9 @@ func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
|||||||
if _, ok := c.(syscall.Conn); !ok { // exclusion system conn like *net.TCPConn
|
if _, ok := c.(syscall.Conn); !ok { // exclusion system conn like *net.TCPConn
|
||||||
c = N.NewDeadlineConn(c) // most conn from outbound can't handle readDeadline correctly
|
c = N.NewDeadlineConn(c) // most conn from outbound can't handle readDeadline correctly
|
||||||
}
|
}
|
||||||
return &conn{N.NewExtendedConn(c), []string{a.Name()}, a.Addr()}
|
cc := &conn{N.NewExtendedConn(c), nil, a.Addr()}
|
||||||
|
cc.AppendToChains(a)
|
||||||
|
return cc
|
||||||
}
|
}
|
||||||
|
|
||||||
type packetConn struct {
|
type packetConn struct {
|
||||||
@@ -320,7 +322,9 @@ func newPacketConn(pc net.PacketConn, a ProxyAdapter) C.PacketConn {
|
|||||||
if _, ok := pc.(syscall.Conn); !ok { // exclusion system conn like *net.UDPConn
|
if _, ok := pc.(syscall.Conn); !ok { // exclusion system conn like *net.UDPConn
|
||||||
epc = N.NewDeadlineEnhancePacketConn(epc) // most conn from outbound can't handle readDeadline correctly
|
epc = N.NewDeadlineEnhancePacketConn(epc) // most conn from outbound can't handle readDeadline correctly
|
||||||
}
|
}
|
||||||
return &packetConn{epc, []string{a.Name()}, a.Name(), utils.NewUUIDV4().String(), a.Addr(), a.ResolveUDP}
|
cpc := &packetConn{epc, nil, a.Name(), utils.NewUUIDV4().String(), a.Addr(), a.ResolveUDP}
|
||||||
|
cpc.AppendToChains(a)
|
||||||
|
return cpc
|
||||||
}
|
}
|
||||||
|
|
||||||
type AddRef interface {
|
type AddRef interface {
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ type HttpOption struct {
|
|||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
Headers map[string]string `proxy:"headers,omitempty"`
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,10 +169,15 @@ func NewHttp(option HttpOption) (*Http, error) {
|
|||||||
sni = option.SNI
|
sni = option.SNI
|
||||||
}
|
}
|
||||||
var err error
|
var err error
|
||||||
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(&tls.Config{
|
tlsConfig, err = ca.GetTLSConfig(ca.Option{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
TLSConfig: &tls.Config{
|
||||||
ServerName: sni,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
}, option.Fingerprint)
|
ServerName: sni,
|
||||||
|
},
|
||||||
|
Fingerprint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -125,9 +125,9 @@ type HysteriaOption struct {
|
|||||||
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
CustomCA string `proxy:"ca,omitempty"`
|
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
|
||||||
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
||||||
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
||||||
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
||||||
@@ -160,19 +160,21 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
serverName = option.SNI
|
serverName = option.SNI
|
||||||
}
|
}
|
||||||
|
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig, err := ca.GetTLSConfig(ca.Option{
|
||||||
ServerName: serverName,
|
TLSConfig: &tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
ServerName: serverName,
|
||||||
MinVersion: tls.VersionTLS13,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
}
|
MinVersion: tls.VersionTLS13,
|
||||||
|
},
|
||||||
var err error
|
Fingerprint: option.Fingerprint,
|
||||||
tlsConfig, err = ca.GetTLSConfig(tlsConfig, option.Fingerprint, option.CustomCA, option.CustomCAString)
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
if option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||||
tlsConfig.NextProtos = option.ALPN
|
tlsConfig.NextProtos = option.ALPN
|
||||||
} else {
|
} else {
|
||||||
tlsConfig.NextProtos = []string{DefaultALPN}
|
tlsConfig.NextProtos = []string{DefaultALPN}
|
||||||
|
|||||||
@@ -55,9 +55,9 @@ type Hysteria2Option struct {
|
|||||||
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
CustomCA string `proxy:"ca,omitempty"`
|
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
|
||||||
CWND int `proxy:"cwnd,omitempty"`
|
CWND int `proxy:"cwnd,omitempty"`
|
||||||
UdpMTU int `proxy:"udp-mtu,omitempty"`
|
UdpMTU int `proxy:"udp-mtu,omitempty"`
|
||||||
|
|
||||||
@@ -141,19 +141,21 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
|||||||
serverName = option.SNI
|
serverName = option.SNI
|
||||||
}
|
}
|
||||||
|
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig, err := ca.GetTLSConfig(ca.Option{
|
||||||
ServerName: serverName,
|
TLSConfig: &tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
ServerName: serverName,
|
||||||
MinVersion: tls.VersionTLS13,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
}
|
MinVersion: tls.VersionTLS13,
|
||||||
|
},
|
||||||
var err error
|
Fingerprint: option.Fingerprint,
|
||||||
tlsConfig, err = ca.GetTLSConfig(tlsConfig, option.Fingerprint, option.CustomCA, option.CustomCAString)
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
if option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||||
tlsConfig.NextProtos = option.ALPN
|
tlsConfig.NextProtos = option.ALPN
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,15 +28,16 @@ type Mieru struct {
|
|||||||
|
|
||||||
type MieruOption struct {
|
type MieruOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port,omitempty"`
|
Port int `proxy:"port,omitempty"`
|
||||||
PortRange string `proxy:"port-range,omitempty"`
|
PortRange string `proxy:"port-range,omitempty"`
|
||||||
Transport string `proxy:"transport"`
|
Transport string `proxy:"transport"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
UserName string `proxy:"username"`
|
UserName string `proxy:"username"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
Multiplexing string `proxy:"multiplexing,omitempty"`
|
Multiplexing string `proxy:"multiplexing,omitempty"`
|
||||||
|
HandshakeMode string `proxy:"handshake-mode,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@@ -245,6 +246,9 @@ func buildMieruClientConfig(option MieruOption) (*mieruclient.ClientConfig, erro
|
|||||||
Level: mierupb.MultiplexingLevel(multiplexing).Enum(),
|
Level: mierupb.MultiplexingLevel(multiplexing).Enum(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if handshakeMode, ok := mierupb.HandshakeMode_value[option.HandshakeMode]; ok {
|
||||||
|
config.Profile.HandshakeMode = (*mierupb.HandshakeMode)(&handshakeMode)
|
||||||
|
}
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,6 +298,11 @@ func validateMieruOption(option MieruOption) error {
|
|||||||
return fmt.Errorf("invalid multiplexing level: %s", option.Multiplexing)
|
return fmt.Errorf("invalid multiplexing level: %s", option.Multiplexing)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if option.HandshakeMode != "" {
|
||||||
|
if _, ok := mierupb.HandshakeMode_value[option.HandshakeMode]; !ok {
|
||||||
|
return fmt.Errorf("invalid handshake mode: %s", option.HandshakeMode)
|
||||||
|
}
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,9 @@ import (
|
|||||||
"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/ntp"
|
||||||
gost "github.com/metacubex/mihomo/transport/gost-plugin"
|
gost "github.com/metacubex/mihomo/transport/gost-plugin"
|
||||||
|
"github.com/metacubex/mihomo/transport/kcptun"
|
||||||
"github.com/metacubex/mihomo/transport/restls"
|
"github.com/metacubex/mihomo/transport/restls"
|
||||||
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
|
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
|
||||||
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
|
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
|
||||||
@@ -35,6 +37,7 @@ type ShadowSocks struct {
|
|||||||
gostOption *gost.Option
|
gostOption *gost.Option
|
||||||
shadowTLSOption *shadowtls.ShadowTLSOption
|
shadowTLSOption *shadowtls.ShadowTLSOption
|
||||||
restlsConfig *restls.Config
|
restlsConfig *restls.Config
|
||||||
|
kcptunClient *kcptun.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShadowSocksOption struct {
|
type ShadowSocksOption struct {
|
||||||
@@ -64,6 +67,8 @@ type v2rayObfsOption struct {
|
|||||||
TLS bool `obfs:"tls,omitempty"`
|
TLS bool `obfs:"tls,omitempty"`
|
||||||
ECHOpts ECHOptions `obfs:"ech-opts,omitempty"`
|
ECHOpts ECHOptions `obfs:"ech-opts,omitempty"`
|
||||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
|
Certificate string `obfs:"certificate,omitempty"`
|
||||||
|
PrivateKey string `obfs:"private-key,omitempty"`
|
||||||
Headers map[string]string `obfs:"headers,omitempty"`
|
Headers map[string]string `obfs:"headers,omitempty"`
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
Mux bool `obfs:"mux,omitempty"`
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
@@ -78,6 +83,8 @@ type gostObfsOption struct {
|
|||||||
TLS bool `obfs:"tls,omitempty"`
|
TLS bool `obfs:"tls,omitempty"`
|
||||||
ECHOpts ECHOptions `obfs:"ech-opts,omitempty"`
|
ECHOpts ECHOptions `obfs:"ech-opts,omitempty"`
|
||||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
|
Certificate string `obfs:"certificate,omitempty"`
|
||||||
|
PrivateKey string `obfs:"private-key,omitempty"`
|
||||||
Headers map[string]string `obfs:"headers,omitempty"`
|
Headers map[string]string `obfs:"headers,omitempty"`
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
Mux bool `obfs:"mux,omitempty"`
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
@@ -87,6 +94,8 @@ type shadowTLSOption struct {
|
|||||||
Password string `obfs:"password,omitempty"`
|
Password string `obfs:"password,omitempty"`
|
||||||
Host string `obfs:"host"`
|
Host string `obfs:"host"`
|
||||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
|
Certificate string `obfs:"certificate,omitempty"`
|
||||||
|
PrivateKey string `obfs:"private-key,omitempty"`
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
Version int `obfs:"version,omitempty"`
|
Version int `obfs:"version,omitempty"`
|
||||||
ALPN []string `obfs:"alpn,omitempty"`
|
ALPN []string `obfs:"alpn,omitempty"`
|
||||||
@@ -99,6 +108,32 @@ type restlsOption struct {
|
|||||||
RestlsScript string `obfs:"restls-script,omitempty"`
|
RestlsScript string `obfs:"restls-script,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type kcpTunOption struct {
|
||||||
|
Key string `obfs:"key,omitempty"`
|
||||||
|
Crypt string `obfs:"crypt,omitempty"`
|
||||||
|
Mode string `obfs:"mode,omitempty"`
|
||||||
|
Conn int `obfs:"conn,omitempty"`
|
||||||
|
AutoExpire int `obfs:"autoexpire,omitempty"`
|
||||||
|
ScavengeTTL int `obfs:"scavengettl,omitempty"`
|
||||||
|
MTU int `obfs:"mtu,omitempty"`
|
||||||
|
SndWnd int `obfs:"sndwnd,omitempty"`
|
||||||
|
RcvWnd int `obfs:"rcvwnd,omitempty"`
|
||||||
|
DataShard int `obfs:"datashard,omitempty"`
|
||||||
|
ParityShard int `obfs:"parityshard,omitempty"`
|
||||||
|
DSCP int `obfs:"dscp,omitempty"`
|
||||||
|
NoComp bool `obfs:"nocomp,omitempty"`
|
||||||
|
AckNodelay bool `obfs:"acknodelay,omitempty"`
|
||||||
|
NoDelay int `obfs:"nodelay,omitempty"`
|
||||||
|
Interval int `obfs:"interval,omitempty"`
|
||||||
|
Resend int `obfs:"resend,omitempty"`
|
||||||
|
NoCongestion int `obfs:"nc,omitempty"`
|
||||||
|
SockBuf int `obfs:"sockbuf,omitempty"`
|
||||||
|
SmuxVer int `obfs:"smuxver,omitempty"`
|
||||||
|
SmuxBuf int `obfs:"smuxbuf,omitempty"`
|
||||||
|
StreamBuf int `obfs:"streambuf,omitempty"`
|
||||||
|
KeepAlive int `obfs:"keepalive,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// StreamConnContext implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) {
|
func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) {
|
||||||
useEarly := false
|
useEarly := false
|
||||||
@@ -167,7 +202,27 @@ func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Diale
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
var c net.Conn
|
||||||
|
if ss.kcptunClient != nil {
|
||||||
|
c, err = ss.kcptunClient.OpenStream(ctx, func(ctx context.Context) (net.PacketConn, net.Addr, error) {
|
||||||
|
if err = ss.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
addr, err := resolveUDPAddr(ctx, "udp", ss.addr, ss.prefer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc, err := dialer.ListenPacket(ctx, "udp", "", addr.AddrPort())
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return pc, addr, nil
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
@@ -249,10 +304,18 @@ func (ss *ShadowSocks) SupportUOT() bool {
|
|||||||
return ss.option.UDPOverTCP
|
return ss.option.UDPOverTCP
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ss *ShadowSocks) Close() error {
|
||||||
|
if ss.kcptunClient != nil {
|
||||||
|
return ss.kcptunClient.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
method, err := shadowsocks.CreateMethod(context.Background(), option.Cipher, shadowsocks.MethodOptions{
|
method, err := shadowsocks.CreateMethod(option.Cipher, shadowsocks.MethodOptions{
|
||||||
Password: option.Password,
|
Password: option.Password,
|
||||||
|
TimeFunc: ntp.Now,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ss %s cipher: %s initialize error: %w", addr, option.Cipher, err)
|
return nil, fmt.Errorf("ss %s cipher: %s initialize error: %w", addr, option.Cipher, err)
|
||||||
@@ -263,6 +326,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
var obfsOption *simpleObfsOption
|
var obfsOption *simpleObfsOption
|
||||||
var shadowTLSOpt *shadowtls.ShadowTLSOption
|
var shadowTLSOpt *shadowtls.ShadowTLSOption
|
||||||
var restlsConfig *restls.Config
|
var restlsConfig *restls.Config
|
||||||
|
var kcptunClient *kcptun.Client
|
||||||
obfsMode := ""
|
obfsMode := ""
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
@@ -300,6 +364,8 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
v2rayOption.TLS = true
|
v2rayOption.TLS = true
|
||||||
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
||||||
v2rayOption.Fingerprint = opts.Fingerprint
|
v2rayOption.Fingerprint = opts.Fingerprint
|
||||||
|
v2rayOption.Certificate = opts.Certificate
|
||||||
|
v2rayOption.PrivateKey = opts.PrivateKey
|
||||||
|
|
||||||
echConfig, err := opts.ECHOpts.Parse()
|
echConfig, err := opts.ECHOpts.Parse()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -328,6 +394,8 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
gostOption.TLS = true
|
gostOption.TLS = true
|
||||||
gostOption.SkipCertVerify = opts.SkipCertVerify
|
gostOption.SkipCertVerify = opts.SkipCertVerify
|
||||||
gostOption.Fingerprint = opts.Fingerprint
|
gostOption.Fingerprint = opts.Fingerprint
|
||||||
|
gostOption.Certificate = opts.Certificate
|
||||||
|
gostOption.PrivateKey = opts.PrivateKey
|
||||||
|
|
||||||
echConfig, err := opts.ECHOpts.Parse()
|
echConfig, err := opts.ECHOpts.Parse()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -348,6 +416,8 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
Password: opt.Password,
|
Password: opt.Password,
|
||||||
Host: opt.Host,
|
Host: opt.Host,
|
||||||
Fingerprint: opt.Fingerprint,
|
Fingerprint: opt.Fingerprint,
|
||||||
|
Certificate: opt.Certificate,
|
||||||
|
PrivateKey: opt.PrivateKey,
|
||||||
ClientFingerprint: option.ClientFingerprint,
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
SkipCertVerify: opt.SkipCertVerify,
|
SkipCertVerify: opt.SkipCertVerify,
|
||||||
Version: opt.Version,
|
Version: opt.Version,
|
||||||
@@ -370,6 +440,39 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} else if option.Plugin == kcptun.Mode {
|
||||||
|
obfsMode = kcptun.Mode
|
||||||
|
kcptunOpt := &kcpTunOption{}
|
||||||
|
if err := decoder.Decode(option.PluginOpts, kcptunOpt); err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize kcptun-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
kcptunClient = kcptun.NewClient(kcptun.Config{
|
||||||
|
Key: kcptunOpt.Key,
|
||||||
|
Crypt: kcptunOpt.Crypt,
|
||||||
|
Mode: kcptunOpt.Mode,
|
||||||
|
Conn: kcptunOpt.Conn,
|
||||||
|
AutoExpire: kcptunOpt.AutoExpire,
|
||||||
|
ScavengeTTL: kcptunOpt.ScavengeTTL,
|
||||||
|
MTU: kcptunOpt.MTU,
|
||||||
|
SndWnd: kcptunOpt.SndWnd,
|
||||||
|
RcvWnd: kcptunOpt.RcvWnd,
|
||||||
|
DataShard: kcptunOpt.DataShard,
|
||||||
|
ParityShard: kcptunOpt.ParityShard,
|
||||||
|
DSCP: kcptunOpt.DSCP,
|
||||||
|
NoComp: kcptunOpt.NoComp,
|
||||||
|
AckNodelay: kcptunOpt.AckNodelay,
|
||||||
|
NoDelay: kcptunOpt.NoDelay,
|
||||||
|
Interval: kcptunOpt.Interval,
|
||||||
|
Resend: kcptunOpt.Resend,
|
||||||
|
NoCongestion: kcptunOpt.NoCongestion,
|
||||||
|
SockBuf: kcptunOpt.SockBuf,
|
||||||
|
SmuxVer: kcptunOpt.SmuxVer,
|
||||||
|
SmuxBuf: kcptunOpt.SmuxBuf,
|
||||||
|
StreamBuf: kcptunOpt.StreamBuf,
|
||||||
|
KeepAlive: kcptunOpt.KeepAlive,
|
||||||
|
})
|
||||||
|
option.UDPOverTCP = true // must open uot
|
||||||
}
|
}
|
||||||
switch option.UDPOverTCPVersion {
|
switch option.UDPOverTCPVersion {
|
||||||
case uot.Version, uot.LegacyVersion:
|
case uot.Version, uot.LegacyVersion:
|
||||||
@@ -400,5 +503,6 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
shadowTLSOption: shadowTLSOpt,
|
shadowTLSOption: shadowTLSOpt,
|
||||||
restlsConfig: restlsConfig,
|
restlsConfig: restlsConfig,
|
||||||
|
kcptunClient: kcptunClient,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -252,13 +252,14 @@ func (spc *ssrPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr
|
|||||||
return nil, nil, nil, errors.New("parse addr error")
|
return nil, nil, nil, errors.New("parse addr error")
|
||||||
}
|
}
|
||||||
|
|
||||||
addr = _addr.UDPAddr()
|
udpAddr := _addr.UDPAddr()
|
||||||
if addr == nil {
|
if udpAddr == nil {
|
||||||
if put != nil {
|
if put != nil {
|
||||||
put()
|
put()
|
||||||
}
|
}
|
||||||
return nil, nil, nil, errors.New("parse addr error")
|
return nil, nil, nil, errors.New("parse addr error")
|
||||||
}
|
}
|
||||||
|
addr = udpAddr
|
||||||
|
|
||||||
data = data[len(_addr):]
|
data = data[len(_addr):]
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ type Socks5Option struct {
|
|||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConnContext implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
@@ -193,13 +195,16 @@ func (ss *Socks5) clientHandshakeContext(ctx context.Context, c net.Conn, addr s
|
|||||||
func NewSocks5(option Socks5Option) (*Socks5, error) {
|
func NewSocks5(option Socks5Option) (*Socks5, error) {
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
tlsConfig = &tls.Config{
|
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
|
||||||
ServerName: option.Server,
|
|
||||||
}
|
|
||||||
|
|
||||||
var err error
|
var err error
|
||||||
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
tlsConfig, err = ca.GetTLSConfig(ca.Option{
|
||||||
|
TLSConfig: &tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ServerName: option.Server,
|
||||||
|
},
|
||||||
|
Fingerprint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,6 +48,8 @@ type TrojanOption struct {
|
|||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
@@ -95,19 +97,22 @@ func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.
|
|||||||
}
|
}
|
||||||
|
|
||||||
alpn := trojan.DefaultWebsocketALPN
|
alpn := trojan.DefaultWebsocketALPN
|
||||||
if len(t.option.ALPN) != 0 {
|
if t.option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||||
alpn = t.option.ALPN
|
alpn = t.option.ALPN
|
||||||
}
|
}
|
||||||
|
|
||||||
wsOpts.TLS = true
|
wsOpts.TLS = true
|
||||||
tlsConfig := &tls.Config{
|
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
|
||||||
NextProtos: alpn,
|
TLSConfig: &tls.Config{
|
||||||
MinVersion: tls.VersionTLS12,
|
NextProtos: alpn,
|
||||||
InsecureSkipVerify: t.option.SkipCertVerify,
|
MinVersion: tls.VersionTLS12,
|
||||||
ServerName: t.option.SNI,
|
InsecureSkipVerify: t.option.SkipCertVerify,
|
||||||
}
|
ServerName: t.option.SNI,
|
||||||
|
},
|
||||||
wsOpts.TLSConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, t.option.Fingerprint)
|
Fingerprint: t.option.Fingerprint,
|
||||||
|
Certificate: t.option.Certificate,
|
||||||
|
PrivateKey: t.option.PrivateKey,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -119,13 +124,15 @@ func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.
|
|||||||
// default tcp network
|
// default tcp network
|
||||||
// handle TLS
|
// handle TLS
|
||||||
alpn := trojan.DefaultALPN
|
alpn := trojan.DefaultALPN
|
||||||
if len(t.option.ALPN) != 0 {
|
if t.option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||||
alpn = t.option.ALPN
|
alpn = t.option.ALPN
|
||||||
}
|
}
|
||||||
c, err = vmess.StreamTLSConn(ctx, c, &vmess.TLSConfig{
|
c, err = vmess.StreamTLSConn(ctx, c, &vmess.TLSConfig{
|
||||||
Host: t.option.SNI,
|
Host: t.option.SNI,
|
||||||
SkipCertVerify: t.option.SkipCertVerify,
|
SkipCertVerify: t.option.SkipCertVerify,
|
||||||
FingerPrint: t.option.Fingerprint,
|
FingerPrint: t.option.Fingerprint,
|
||||||
|
Certificate: t.option.Certificate,
|
||||||
|
PrivateKey: t.option.PrivateKey,
|
||||||
ClientFingerprint: t.option.ClientFingerprint,
|
ClientFingerprint: t.option.ClientFingerprint,
|
||||||
NextProtos: alpn,
|
NextProtos: alpn,
|
||||||
ECH: t.echConfig,
|
ECH: t.echConfig,
|
||||||
@@ -363,15 +370,17 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig, err := ca.GetTLSConfig(ca.Option{
|
||||||
NextProtos: option.ALPN,
|
TLSConfig: &tls.Config{
|
||||||
MinVersion: tls.VersionTLS12,
|
NextProtos: option.ALPN,
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
MinVersion: tls.VersionTLS12,
|
||||||
ServerName: option.SNI,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
}
|
ServerName: option.SNI,
|
||||||
|
},
|
||||||
var err error
|
Fingerprint: option.Fingerprint,
|
||||||
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,8 +55,8 @@ type TuicOption struct {
|
|||||||
CWND int `proxy:"cwnd,omitempty"`
|
CWND int `proxy:"cwnd,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
CustomCA string `proxy:"ca,omitempty"`
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
||||||
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
||||||
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
||||||
@@ -161,17 +161,20 @@ func (t *Tuic) ProxyInfo() C.ProxyInfo {
|
|||||||
func NewTuic(option TuicOption) (*Tuic, error) {
|
func NewTuic(option TuicOption) (*Tuic, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
serverName := option.Server
|
serverName := option.Server
|
||||||
tlsConfig := &tls.Config{
|
|
||||||
ServerName: serverName,
|
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
|
||||||
MinVersion: tls.VersionTLS13,
|
|
||||||
}
|
|
||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
tlsConfig.ServerName = option.SNI
|
serverName = option.SNI
|
||||||
}
|
}
|
||||||
|
|
||||||
var err error
|
tlsConfig, err := ca.GetTLSConfig(ca.Option{
|
||||||
tlsConfig, err = ca.GetTLSConfig(tlsConfig, option.Fingerprint, option.CustomCA, option.CustomCAString)
|
TLSConfig: &tls.Config{
|
||||||
|
ServerName: serverName,
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
MinVersion: tls.VersionTLS13,
|
||||||
|
},
|
||||||
|
Fingerprint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ func resolveUDPAddr(ctx context.Context, network, address string, prefer C.DNSPr
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var ip netip.Addr
|
var ip netip.Addr
|
||||||
switch prefer {
|
switch prefer {
|
||||||
case C.IPv4Only:
|
case C.IPv4Only:
|
||||||
@@ -56,7 +57,17 @@ func resolveUDPAddr(ctx context.Context, network, address string, prefer C.DNSPr
|
|||||||
}
|
}
|
||||||
|
|
||||||
ip, port = resolver.LookupIP4P(ip, port)
|
ip, port = resolver.LookupIP4P(ip, port)
|
||||||
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
|
||||||
|
var uint16Port uint16
|
||||||
|
if port, err := strconv.ParseUint(port, 10, 16); err == nil {
|
||||||
|
uint16Port = uint16(port)
|
||||||
|
} else {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// our resolver always unmap before return, so unneeded unmap at here
|
||||||
|
// which is different with net.ResolveUDPAddr maybe return 4in6 address
|
||||||
|
// 4in6 addresses can cause some strange effects on sing-based code
|
||||||
|
return net.UDPAddrFromAddrPort(netip.AddrPortFrom(ip, uint16Port)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func safeConnClose(c net.Conn, err error) {
|
func safeConnClose(c net.Conn, err error) {
|
||||||
|
|||||||
@@ -3,14 +3,10 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"encoding/binary"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/convert"
|
"github.com/metacubex/mihomo/common/convert"
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
@@ -23,6 +19,7 @@ import (
|
|||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/transport/gun"
|
"github.com/metacubex/mihomo/transport/gun"
|
||||||
"github.com/metacubex/mihomo/transport/vless"
|
"github.com/metacubex/mihomo/transport/vless"
|
||||||
|
"github.com/metacubex/mihomo/transport/vless/encryption"
|
||||||
"github.com/metacubex/mihomo/transport/vmess"
|
"github.com/metacubex/mihomo/transport/vmess"
|
||||||
|
|
||||||
vmessSing "github.com/metacubex/sing-vmess"
|
vmessSing "github.com/metacubex/sing-vmess"
|
||||||
@@ -30,16 +27,13 @@ import (
|
|||||||
M "github.com/metacubex/sing/common/metadata"
|
M "github.com/metacubex/sing/common/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
|
||||||
// max packet length
|
|
||||||
maxLength = 1024 << 3
|
|
||||||
)
|
|
||||||
|
|
||||||
type Vless struct {
|
type Vless struct {
|
||||||
*Base
|
*Base
|
||||||
client *vless.Client
|
client *vless.Client
|
||||||
option *VlessOption
|
option *VlessOption
|
||||||
|
|
||||||
|
encryption *encryption.ClientInstance
|
||||||
|
|
||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
@@ -62,6 +56,7 @@ type VlessOption struct {
|
|||||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
XUDP bool `proxy:"xudp,omitempty"`
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
|
Encryption string `proxy:"encryption,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
@@ -69,10 +64,11 @@ type VlessOption struct {
|
|||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
@@ -101,14 +97,17 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
}
|
}
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
wsOpts.TLS = true
|
wsOpts.TLS = true
|
||||||
tlsConfig := &tls.Config{
|
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
|
||||||
MinVersion: tls.VersionTLS12,
|
TLSConfig: &tls.Config{
|
||||||
ServerName: host,
|
MinVersion: tls.VersionTLS12,
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
ServerName: host,
|
||||||
NextProtos: []string{"http/1.1"},
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
}
|
NextProtos: []string{"http/1.1"},
|
||||||
|
},
|
||||||
wsOpts.TLSConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
Fingerprint: v.option.Fingerprint,
|
||||||
|
Certificate: v.option.Certificate,
|
||||||
|
PrivateKey: v.option.PrivateKey,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -173,6 +172,12 @@ func (v *Vless) streamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
done := N.SetupContextForConn(ctx, c)
|
done := N.SetupContextForConn(ctx, c)
|
||||||
defer done(&err)
|
defer done(&err)
|
||||||
}
|
}
|
||||||
|
if v.encryption != nil {
|
||||||
|
c, err = v.encryption.Handshake(c)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
if v.option.PacketAddr {
|
if v.option.PacketAddr {
|
||||||
metadata = &C.Metadata{
|
metadata = &C.Metadata{
|
||||||
@@ -188,9 +193,6 @@ func (v *Vless) streamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
conn, err = v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
conn, err = v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
||||||
if v.option.PacketAddr {
|
|
||||||
conn = packetaddr.NewBindConn(conn)
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
conn, err = v.client.StreamConn(c, parseVlessAddr(metadata, false))
|
conn, err = v.client.StreamConn(c, parseVlessAddr(metadata, false))
|
||||||
}
|
}
|
||||||
@@ -208,6 +210,8 @@ func (v *Vless) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (ne
|
|||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
FingerPrint: v.option.Fingerprint,
|
FingerPrint: v.option.Fingerprint,
|
||||||
|
Certificate: v.option.Certificate,
|
||||||
|
PrivateKey: v.option.PrivateKey,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
ECH: v.echConfig,
|
ECH: v.echConfig,
|
||||||
Reality: v.realityConfig,
|
Reality: v.realityConfig,
|
||||||
@@ -352,12 +356,11 @@ func (v *Vless) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metada
|
|||||||
), v), nil
|
), v), nil
|
||||||
} else if v.option.PacketAddr {
|
} else if v.option.PacketAddr {
|
||||||
return newPacketConn(N.NewThreadSafePacketConn(
|
return newPacketConn(N.NewThreadSafePacketConn(
|
||||||
packetaddr.NewConn(&vlessPacketConn{
|
packetaddr.NewConn(v.client.PacketConn(c, metadata.UDPAddr()),
|
||||||
Conn: c, rAddr: metadata.UDPAddr(),
|
M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||||
}, M.SocksaddrFromNet(metadata.UDPAddr())),
|
|
||||||
), v), nil
|
), v), nil
|
||||||
}
|
}
|
||||||
return newPacketConn(N.NewThreadSafePacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}), v), nil
|
return newPacketConn(N.NewThreadSafePacketConn(v.client.PacketConn(c, metadata.UDPAddr())), v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@@ -408,101 +411,9 @@ func parseVlessAddr(metadata *C.Metadata, xudp bool) *vless.DstAddr {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type vlessPacketConn struct {
|
|
||||||
net.Conn
|
|
||||||
rAddr net.Addr
|
|
||||||
remain int
|
|
||||||
mux sync.Mutex
|
|
||||||
cache [2]byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *vlessPacketConn) writePacket(payload []byte) (int, error) {
|
|
||||||
binary.BigEndian.PutUint16(c.cache[:], uint16(len(payload)))
|
|
||||||
|
|
||||||
if _, err := c.Conn.Write(c.cache[:]); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.Conn.Write(payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *vlessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
|
||||||
total := len(b)
|
|
||||||
if total == 0 {
|
|
||||||
return 0, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if total <= maxLength {
|
|
||||||
return c.writePacket(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
offset := 0
|
|
||||||
|
|
||||||
for offset < total {
|
|
||||||
cursor := offset + maxLength
|
|
||||||
if cursor > total {
|
|
||||||
cursor = total
|
|
||||||
}
|
|
||||||
|
|
||||||
n, err := c.writePacket(b[offset:cursor])
|
|
||||||
if err != nil {
|
|
||||||
return offset + n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
offset = cursor
|
|
||||||
if offset == total {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return total, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|
||||||
c.mux.Lock()
|
|
||||||
defer c.mux.Unlock()
|
|
||||||
|
|
||||||
if c.remain > 0 {
|
|
||||||
length := len(b)
|
|
||||||
if c.remain < length {
|
|
||||||
length = c.remain
|
|
||||||
}
|
|
||||||
|
|
||||||
n, err := c.Conn.Read(b[:length])
|
|
||||||
if err != nil {
|
|
||||||
return 0, c.rAddr, err
|
|
||||||
}
|
|
||||||
|
|
||||||
c.remain -= n
|
|
||||||
return n, c.rAddr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := c.Conn.Read(b[:2]); err != nil {
|
|
||||||
return 0, c.rAddr, err
|
|
||||||
}
|
|
||||||
|
|
||||||
total := int(binary.BigEndian.Uint16(b[:2]))
|
|
||||||
if total == 0 {
|
|
||||||
return 0, c.rAddr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
length := len(b)
|
|
||||||
if length > total {
|
|
||||||
length = total
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := io.ReadFull(c.Conn, b[:length]); err != nil {
|
|
||||||
return 0, c.rAddr, errors.New("read packet error")
|
|
||||||
}
|
|
||||||
|
|
||||||
c.remain = total - length
|
|
||||||
|
|
||||||
return length, c.rAddr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewVless(option VlessOption) (*Vless, error) {
|
func NewVless(option VlessOption) (*Vless, error) {
|
||||||
var addons *vless.Addons
|
var addons *vless.Addons
|
||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
if len(option.Flow) >= 16 {
|
||||||
option.Flow = option.Flow[:16]
|
option.Flow = option.Flow[:16]
|
||||||
if option.Flow != vless.XRV {
|
if option.Flow != vless.XRV {
|
||||||
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||||
@@ -547,6 +458,11 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
v.encryption, err = encryption.NewClient(option.Encryption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
v.realityConfig, err = v.option.RealityOpts.Parse()
|
v.realityConfig, err = v.option.RealityOpts.Parse()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -589,10 +505,15 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
}
|
}
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(&tls.Config{
|
tlsConfig, err = ca.GetTLSConfig(ca.Option{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
TLSConfig: &tls.Config{
|
||||||
ServerName: v.option.ServerName,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
}, v.option.Fingerprint)
|
ServerName: v.option.ServerName,
|
||||||
|
},
|
||||||
|
Fingerprint: v.option.Fingerprint,
|
||||||
|
Certificate: v.option.Certificate,
|
||||||
|
PrivateKey: v.option.PrivateKey,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,6 +58,8 @@ type VmessOption struct {
|
|||||||
ALPN []string `proxy:"alpn,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
@@ -123,13 +125,16 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
|
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
wsOpts.TLS = true
|
wsOpts.TLS = true
|
||||||
tlsConfig := &tls.Config{
|
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
|
||||||
ServerName: host,
|
TLSConfig: &tls.Config{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
ServerName: host,
|
||||||
NextProtos: []string{"http/1.1"},
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
}
|
NextProtos: []string{"http/1.1"},
|
||||||
|
},
|
||||||
wsOpts.TLSConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
Fingerprint: v.option.Fingerprint,
|
||||||
|
Certificate: v.option.Certificate,
|
||||||
|
PrivateKey: v.option.PrivateKey,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -178,6 +183,8 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
FingerPrint: v.option.Fingerprint,
|
FingerPrint: v.option.Fingerprint,
|
||||||
|
Certificate: v.option.Certificate,
|
||||||
|
PrivateKey: v.option.PrivateKey,
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Reality: v.realityConfig,
|
Reality: v.realityConfig,
|
||||||
@@ -208,6 +215,8 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
FingerPrint: v.option.Fingerprint,
|
FingerPrint: v.option.Fingerprint,
|
||||||
|
Certificate: v.option.Certificate,
|
||||||
|
PrivateKey: v.option.PrivateKey,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
ECH: v.echConfig,
|
ECH: v.echConfig,
|
||||||
Reality: v.realityConfig,
|
Reality: v.realityConfig,
|
||||||
@@ -501,10 +510,15 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
}
|
}
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(&tls.Config{
|
tlsConfig, err = ca.GetTLSConfig(ca.Option{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
TLSConfig: &tls.Config{
|
||||||
ServerName: v.option.ServerName,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
}, v.option.Fingerprint)
|
ServerName: v.option.ServerName,
|
||||||
|
},
|
||||||
|
Fingerprint: v.option.Fingerprint,
|
||||||
|
Certificate: v.option.Certificate,
|
||||||
|
PrivateKey: v.option.PrivateKey,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -87,15 +87,26 @@ type WireGuardPeerOption struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AmneziaWGOption struct {
|
type AmneziaWGOption struct {
|
||||||
JC int `proxy:"jc"`
|
JC int `proxy:"jc,omitempty"`
|
||||||
JMin int `proxy:"jmin"`
|
JMin int `proxy:"jmin,omitempty"`
|
||||||
JMax int `proxy:"jmax"`
|
JMax int `proxy:"jmax,omitempty"`
|
||||||
S1 int `proxy:"s1"`
|
S1 int `proxy:"s1,omitempty"`
|
||||||
S2 int `proxy:"s2"`
|
S2 int `proxy:"s2,omitempty"`
|
||||||
H1 uint32 `proxy:"h1"`
|
S3 int `proxy:"s3,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
H2 uint32 `proxy:"h2"`
|
S4 int `proxy:"s4,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
H3 uint32 `proxy:"h3"`
|
H1 string `proxy:"h1,omitempty"` // In AmneziaWG v1.x, it was uint32, but our WeaklyTypedInput can handle this situation
|
||||||
H4 uint32 `proxy:"h4"`
|
H2 string `proxy:"h2,omitempty"` // In AmneziaWG v1.x, it was uint32, but our WeaklyTypedInput can handle this situation
|
||||||
|
H3 string `proxy:"h3,omitempty"` // In AmneziaWG v1.x, it was uint32, but our WeaklyTypedInput can handle this situation
|
||||||
|
H4 string `proxy:"h4,omitempty"` // In AmneziaWG v1.x, it was uint32, but our WeaklyTypedInput can handle this situation
|
||||||
|
I1 string `proxy:"i1,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
|
I2 string `proxy:"i2,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
|
I3 string `proxy:"i3,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
|
I4 string `proxy:"i4,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
|
I5 string `proxy:"i5,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
|
J1 string `proxy:"j1,omitempty"` // AmneziaWG v1.5 only (removed in v2)
|
||||||
|
J2 string `proxy:"j2,omitempty"` // AmneziaWG v1.5 only (removed in v2)
|
||||||
|
J3 string `proxy:"j3,omitempty"` // AmneziaWG v1.5 only (removed in v2)
|
||||||
|
Itime int64 `proxy:"itime,omitempty"` // AmneziaWG v1.5 only (removed in v2)
|
||||||
}
|
}
|
||||||
|
|
||||||
type wgSingErrorHandler struct {
|
type wgSingErrorHandler struct {
|
||||||
@@ -386,15 +397,66 @@ func (w *WireGuard) genIpcConf(ctx context.Context, updateOnly bool) (string, er
|
|||||||
if !updateOnly {
|
if !updateOnly {
|
||||||
ipcConf += "private_key=" + w.option.PrivateKey + "\n"
|
ipcConf += "private_key=" + w.option.PrivateKey + "\n"
|
||||||
if w.option.AmneziaWGOption != nil {
|
if w.option.AmneziaWGOption != nil {
|
||||||
ipcConf += "jc=" + strconv.Itoa(w.option.AmneziaWGOption.JC) + "\n"
|
if w.option.AmneziaWGOption.JC != 0 {
|
||||||
ipcConf += "jmin=" + strconv.Itoa(w.option.AmneziaWGOption.JMin) + "\n"
|
ipcConf += "jc=" + strconv.Itoa(w.option.AmneziaWGOption.JC) + "\n"
|
||||||
ipcConf += "jmax=" + strconv.Itoa(w.option.AmneziaWGOption.JMax) + "\n"
|
}
|
||||||
ipcConf += "s1=" + strconv.Itoa(w.option.AmneziaWGOption.S1) + "\n"
|
if w.option.AmneziaWGOption.JMin != 0 {
|
||||||
ipcConf += "s2=" + strconv.Itoa(w.option.AmneziaWGOption.S2) + "\n"
|
ipcConf += "jmin=" + strconv.Itoa(w.option.AmneziaWGOption.JMin) + "\n"
|
||||||
ipcConf += "h1=" + strconv.FormatUint(uint64(w.option.AmneziaWGOption.H1), 10) + "\n"
|
}
|
||||||
ipcConf += "h2=" + strconv.FormatUint(uint64(w.option.AmneziaWGOption.H2), 10) + "\n"
|
if w.option.AmneziaWGOption.JMax != 0 {
|
||||||
ipcConf += "h3=" + strconv.FormatUint(uint64(w.option.AmneziaWGOption.H3), 10) + "\n"
|
ipcConf += "jmax=" + strconv.Itoa(w.option.AmneziaWGOption.JMax) + "\n"
|
||||||
ipcConf += "h4=" + strconv.FormatUint(uint64(w.option.AmneziaWGOption.H4), 10) + "\n"
|
}
|
||||||
|
if w.option.AmneziaWGOption.S1 != 0 {
|
||||||
|
ipcConf += "s1=" + strconv.Itoa(w.option.AmneziaWGOption.S1) + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.S2 != 0 {
|
||||||
|
ipcConf += "s2=" + strconv.Itoa(w.option.AmneziaWGOption.S2) + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.S3 != 0 {
|
||||||
|
ipcConf += "s3=" + strconv.Itoa(w.option.AmneziaWGOption.S3) + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.S4 != 0 {
|
||||||
|
ipcConf += "s4=" + strconv.Itoa(w.option.AmneziaWGOption.S4) + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.H1 != "" {
|
||||||
|
ipcConf += "h1=" + w.option.AmneziaWGOption.H1 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.H2 != "" {
|
||||||
|
ipcConf += "h2=" + w.option.AmneziaWGOption.H2 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.H3 != "" {
|
||||||
|
ipcConf += "h3=" + w.option.AmneziaWGOption.H3 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.H4 != "" {
|
||||||
|
ipcConf += "h4=" + w.option.AmneziaWGOption.H4 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.I1 != "" {
|
||||||
|
ipcConf += "i1=" + w.option.AmneziaWGOption.I1 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.I2 != "" {
|
||||||
|
ipcConf += "i2=" + w.option.AmneziaWGOption.I2 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.I3 != "" {
|
||||||
|
ipcConf += "i3=" + w.option.AmneziaWGOption.I3 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.I4 != "" {
|
||||||
|
ipcConf += "i4=" + w.option.AmneziaWGOption.I4 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.I5 != "" {
|
||||||
|
ipcConf += "i5=" + w.option.AmneziaWGOption.I5 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.J1 != "" {
|
||||||
|
ipcConf += "j1=" + w.option.AmneziaWGOption.J1 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.J2 != "" {
|
||||||
|
ipcConf += "j2=" + w.option.AmneziaWGOption.J2 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.J3 != "" {
|
||||||
|
ipcConf += "j3=" + w.option.AmneziaWGOption.J3 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.Itime != 0 {
|
||||||
|
ipcConf += "itime=" + strconv.FormatInt(int64(w.option.AmneziaWGOption.Itime), 10) + "\n"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(w.option.Peers) > 0 {
|
if len(w.option.Peers) > 0 {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Fallback struct {
|
type Fallback struct {
|
||||||
@@ -150,7 +150,7 @@ func (f *Fallback) ForceSet(name string) {
|
|||||||
f.selected = name
|
f.selected = name
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
func NewFallback(option *GroupCommonOption, providers []P.ProxyProvider) *Fallback {
|
||||||
return &Fallback{
|
return &Fallback{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
Name: option.Name,
|
||||||
|
|||||||
@@ -12,8 +12,7 @@ import (
|
|||||||
"github.com/metacubex/mihomo/common/atomic"
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
types "github.com/metacubex/mihomo/constant/provider"
|
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
"github.com/metacubex/mihomo/tunnel"
|
"github.com/metacubex/mihomo/tunnel"
|
||||||
|
|
||||||
@@ -26,7 +25,7 @@ type GroupBase struct {
|
|||||||
filterRegs []*regexp2.Regexp
|
filterRegs []*regexp2.Regexp
|
||||||
excludeFilterRegs []*regexp2.Regexp
|
excludeFilterRegs []*regexp2.Regexp
|
||||||
excludeTypeArray []string
|
excludeTypeArray []string
|
||||||
providers []provider.ProxyProvider
|
providers []P.ProxyProvider
|
||||||
failedTestMux sync.Mutex
|
failedTestMux sync.Mutex
|
||||||
failedTimes int
|
failedTimes int
|
||||||
failedTime time.Time
|
failedTime time.Time
|
||||||
@@ -48,7 +47,7 @@ type GroupBaseOption struct {
|
|||||||
ExcludeType string
|
ExcludeType string
|
||||||
TestTimeout int
|
TestTimeout int
|
||||||
MaxFailedTimes int
|
MaxFailedTimes int
|
||||||
Providers []provider.ProxyProvider
|
Providers []P.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||||
@@ -125,7 +124,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for _, pd := range gb.providers {
|
for _, pd := range gb.providers {
|
||||||
if pd.VehicleType() == types.Compatible { // compatible provider unneeded filter
|
if pd.VehicleType() == P.Compatible { // compatible provider unneeded filter
|
||||||
proxies = append(proxies, pd.Proxies()...)
|
proxies = append(proxies, pd.Proxies()...)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import (
|
|||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
|
|
||||||
"golang.org/x/net/publicsuffix"
|
"golang.org/x/net/publicsuffix"
|
||||||
)
|
)
|
||||||
@@ -194,7 +194,7 @@ func strategyStickySessions(url string) strategyFn {
|
|||||||
key := utils.MapHash(getKeyWithSrcAndDst(metadata))
|
key := utils.MapHash(getKeyWithSrcAndDst(metadata))
|
||||||
length := len(proxies)
|
length := len(proxies)
|
||||||
idx, has := lruCache.Get(key)
|
idx, has := lruCache.Get(key)
|
||||||
if !has {
|
if !has || idx >= length {
|
||||||
idx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
|
idx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -239,7 +239,7 @@ func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
|
func NewLoadBalance(option *GroupCommonOption, providers []P.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
|
||||||
var strategyFn strategyFn
|
var strategyFn strategyFn
|
||||||
switch strategy {
|
switch strategy {
|
||||||
case "consistent-hashing":
|
case "consistent-hashing":
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
"github.com/metacubex/mihomo/common/structure"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
types "github.com/metacubex/mihomo/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -48,7 +48,7 @@ type GroupCommonOption struct {
|
|||||||
RoutingMark int `group:"routing-mark,omitempty"`
|
RoutingMark int `group:"routing-mark,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider, AllProxies []string, AllProviders []string) (C.ProxyAdapter, error) {
|
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]P.ProxyProvider, AllProxies []string, AllProviders []string) (C.ProxyAdapter, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
||||||
|
|
||||||
groupOption := &GroupCommonOption{
|
groupOption := &GroupCommonOption{
|
||||||
@@ -71,7 +71,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
|
|
||||||
groupName := groupOption.Name
|
groupName := groupOption.Name
|
||||||
|
|
||||||
providers := []types.ProxyProvider{}
|
providers := []P.ProxyProvider{}
|
||||||
|
|
||||||
if groupOption.IncludeAll {
|
if groupOption.IncludeAll {
|
||||||
groupOption.IncludeAllProviders = true
|
groupOption.IncludeAllProviders = true
|
||||||
@@ -169,7 +169,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
providers = append([]types.ProxyProvider{pd}, providers...)
|
providers = append([]P.ProxyProvider{pd}, providers...)
|
||||||
providersMap[groupName] = pd
|
providersMap[groupName] = pd
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,15 +206,15 @@ func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
|||||||
return ps, nil
|
return ps, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]types.ProxyProvider, error) {
|
func getProviders(mapping map[string]P.ProxyProvider, list []string) ([]P.ProxyProvider, error) {
|
||||||
var ps []types.ProxyProvider
|
var ps []P.ProxyProvider
|
||||||
for _, name := range list {
|
for _, name := range list {
|
||||||
p, ok := mapping[name]
|
p, ok := mapping[name]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("'%s' not found", name)
|
return nil, fmt.Errorf("'%s' not found", name)
|
||||||
}
|
}
|
||||||
|
|
||||||
if p.VehicleType() == types.Compatible {
|
if p.VehicleType() == P.Compatible {
|
||||||
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
||||||
}
|
}
|
||||||
ps = append(ps, p)
|
ps = append(ps, p)
|
||||||
@@ -222,7 +222,7 @@ func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]type
|
|||||||
return ps, nil
|
return ps, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func addTestUrlToProviders(providers []types.ProxyProvider, url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
func addTestUrlToProviders(providers []P.ProxyProvider, url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||||
if len(providers) == 0 || len(url) == 0 {
|
if len(providers) == 0 || len(url) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,22 +4,22 @@ package outboundgroup
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ProxyGroup interface {
|
type ProxyGroup interface {
|
||||||
C.ProxyAdapter
|
C.ProxyAdapter
|
||||||
|
|
||||||
Providers() []provider.ProxyProvider
|
Providers() []P.ProxyProvider
|
||||||
Proxies() []C.Proxy
|
Proxies() []C.Proxy
|
||||||
Now() string
|
Now() string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Providers() []provider.ProxyProvider {
|
func (f *Fallback) Providers() []P.ProxyProvider {
|
||||||
return f.providers
|
return f.providers
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lb *LoadBalance) Providers() []provider.ProxyProvider {
|
func (lb *LoadBalance) Providers() []P.ProxyProvider {
|
||||||
return lb.providers
|
return lb.providers
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ func (lb *LoadBalance) Now() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Relay) Providers() []provider.ProxyProvider {
|
func (r *Relay) Providers() []P.ProxyProvider {
|
||||||
return r.providers
|
return r.providers
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,7 +47,7 @@ func (r *Relay) Now() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) Providers() []provider.ProxyProvider {
|
func (s *Selector) Providers() []P.ProxyProvider {
|
||||||
return s.providers
|
return s.providers
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ func (s *Selector) Proxies() []C.Proxy {
|
|||||||
return s.GetProxies(false)
|
return s.GetProxies(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) Providers() []provider.ProxyProvider {
|
func (u *URLTest) Providers() []P.ProxyProvider {
|
||||||
return u.providers
|
return u.providers
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"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/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -149,7 +149,7 @@ func (r *Relay) Addr() string {
|
|||||||
return proxies[len(proxies)-1].Addr()
|
return proxies[len(proxies)-1].Addr()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
func NewRelay(option *GroupCommonOption, providers []P.ProxyProvider) *Relay {
|
||||||
log.Warnln("The group [%s] with relay type is deprecated, please using dialer-proxy instead", option.Name)
|
log.Warnln("The group [%s] with relay type is deprecated, please using dialer-proxy instead", option.Name)
|
||||||
return &Relay{
|
return &Relay{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Selector struct {
|
type Selector struct {
|
||||||
@@ -108,7 +108,7 @@ func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
|||||||
return proxies[0]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider) *Selector {
|
func NewSelector(option *GroupCommonOption, providers []P.ProxyProvider) *Selector {
|
||||||
return &Selector{
|
return &Selector{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
Name: option.Name,
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
"github.com/metacubex/mihomo/common/singledo"
|
"github.com/metacubex/mihomo/common/singledo"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type urlTestOption func(*URLTest)
|
type urlTestOption func(*URLTest)
|
||||||
@@ -202,7 +202,7 @@ func parseURLTestOption(config map[string]any) []urlTestOption {
|
|||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
|
func NewURLTest(option *GroupCommonOption, providers []P.ProxyProvider, options ...urlTestOption) *URLTest {
|
||||||
urlTest := &URLTest{
|
urlTest := &URLTest{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
Name: option.Name,
|
||||||
|
|||||||
@@ -49,13 +49,7 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
}
|
}
|
||||||
proxy, err = outbound.NewHttp(*httpOption)
|
proxy, err = outbound.NewHttp(*httpOption)
|
||||||
case "vmess":
|
case "vmess":
|
||||||
vmessOption := &outbound.VmessOption{
|
vmessOption := &outbound.VmessOption{}
|
||||||
HTTPOpts: outbound.HTTPOptions{
|
|
||||||
Method: "GET",
|
|
||||||
Path: []string{"/"},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
err = decoder.Decode(mapping, vmessOption)
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/resource"
|
"github.com/metacubex/mihomo/component/resource"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
types "github.com/metacubex/mihomo/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
)
|
)
|
||||||
@@ -73,7 +73,7 @@ type proxyProviderSchema struct {
|
|||||||
Header map[string][]string `provider:"header,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) (P.ProxyProvider, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
||||||
|
|
||||||
schema := &proxyProviderSchema{
|
schema := &proxyProviderSchema{
|
||||||
@@ -104,7 +104,7 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var vehicle types.Vehicle
|
var vehicle P.Vehicle
|
||||||
switch schema.Type {
|
switch schema.Type {
|
||||||
case "file":
|
case "file":
|
||||||
path := C.Path.Resolve(schema.Path)
|
path := C.Path.Resolve(schema.Path)
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
"github.com/metacubex/mihomo/component/profile/cachefile"
|
"github.com/metacubex/mihomo/component/profile/cachefile"
|
||||||
"github.com/metacubex/mihomo/component/resource"
|
"github.com/metacubex/mihomo/component/resource"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
types "github.com/metacubex/mihomo/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
"github.com/metacubex/mihomo/tunnel/statistic"
|
"github.com/metacubex/mihomo/tunnel/statistic"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
@@ -68,8 +68,8 @@ func (bp *baseProvider) HealthCheck() {
|
|||||||
bp.healthCheck.check()
|
bp.healthCheck.check()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (bp *baseProvider) Type() types.ProviderType {
|
func (bp *baseProvider) Type() P.ProviderType {
|
||||||
return types.Proxy
|
return P.Proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
func (bp *baseProvider) Proxies() []C.Proxy {
|
func (bp *baseProvider) Proxies() []C.Proxy {
|
||||||
@@ -171,7 +171,7 @@ func (pp *proxySetProvider) Close() error {
|
|||||||
return pp.Fetcher.Close()
|
return pp.Fetcher.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, payload []map[string]any, parser resource.Parser[[]C.Proxy], vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, payload []map[string]any, parser resource.Parser[[]C.Proxy], vehicle P.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
pd := &proxySetProvider{
|
pd := &proxySetProvider{
|
||||||
baseProvider: baseProvider{
|
baseProvider: baseProvider{
|
||||||
name: name,
|
name: name,
|
||||||
@@ -238,8 +238,8 @@ func (ip *inlineProvider) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ip *inlineProvider) VehicleType() types.VehicleType {
|
func (ip *inlineProvider) VehicleType() P.VehicleType {
|
||||||
return types.Inline
|
return P.Inline
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ip *inlineProvider) Update() error {
|
func (ip *inlineProvider) Update() error {
|
||||||
@@ -303,8 +303,8 @@ func (cp *compatibleProvider) Update() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) VehicleType() types.VehicleType {
|
func (cp *compatibleProvider) VehicleType() P.VehicleType {
|
||||||
return types.Compatible
|
return P.Compatible
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {
|
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {
|
||||||
@@ -331,15 +331,22 @@ func (cp *CompatibleProvider) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewProxiesParser(filter string, excludeFilter string, excludeType string, dialerProxy string, override OverrideSchema) (resource.Parser[[]C.Proxy], error) {
|
func NewProxiesParser(filter string, excludeFilter string, excludeType string, dialerProxy string, override OverrideSchema) (resource.Parser[[]C.Proxy], error) {
|
||||||
excludeFilterReg, err := regexp2.Compile(excludeFilter, regexp2.None)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
|
||||||
}
|
|
||||||
var excludeTypeArray []string
|
var excludeTypeArray []string
|
||||||
if excludeType != "" {
|
if excludeType != "" {
|
||||||
excludeTypeArray = strings.Split(excludeType, "|")
|
excludeTypeArray = strings.Split(excludeType, "|")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var excludeFilterRegs []*regexp2.Regexp
|
||||||
|
if excludeFilter != "" {
|
||||||
|
for _, excludeFilter := range strings.Split(excludeFilter, "`") {
|
||||||
|
excludeFilterReg, err := regexp2.Compile(excludeFilter, regexp2.None)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
||||||
|
}
|
||||||
|
excludeFilterRegs = append(excludeFilterRegs, excludeFilterReg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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, regexp2.None)
|
filterReg, err := regexp2.Compile(filter, regexp2.None)
|
||||||
@@ -367,8 +374,9 @@ func NewProxiesParser(filter string, excludeFilter string, excludeType string, d
|
|||||||
proxies := []C.Proxy{}
|
proxies := []C.Proxy{}
|
||||||
proxiesSet := map[string]struct{}{}
|
proxiesSet := map[string]struct{}{}
|
||||||
for _, filterReg := range filterRegs {
|
for _, filterReg := range filterRegs {
|
||||||
|
LOOP1:
|
||||||
for idx, mapping := range schema.Proxies {
|
for idx, mapping := range schema.Proxies {
|
||||||
if nil != excludeTypeArray && len(excludeTypeArray) > 0 {
|
if len(excludeTypeArray) > 0 {
|
||||||
mType, ok := mapping["type"]
|
mType, ok := mapping["type"]
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
@@ -377,18 +385,11 @@ func NewProxiesParser(filter string, excludeFilter string, excludeType string, d
|
|||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
flag := false
|
for _, excludeType := range excludeTypeArray {
|
||||||
for i := range excludeTypeArray {
|
if strings.EqualFold(pType, excludeType) {
|
||||||
if strings.EqualFold(pType, excludeTypeArray[i]) {
|
continue LOOP1
|
||||||
flag = true
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
if flag {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
mName, ok := mapping["name"]
|
mName, ok := mapping["name"]
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -398,9 +399,11 @@ func NewProxiesParser(filter string, excludeFilter string, excludeType string, d
|
|||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if len(excludeFilter) > 0 {
|
if len(excludeFilterRegs) > 0 {
|
||||||
if mat, _ := excludeFilterReg.MatchString(name); mat {
|
for _, excludeFilterReg := range excludeFilterRegs {
|
||||||
continue
|
if mat, _ := excludeFilterReg.MatchString(name); mat {
|
||||||
|
continue LOOP1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(filter) > 0 {
|
if len(filter) > 0 {
|
||||||
|
|||||||
@@ -5,58 +5,50 @@ import (
|
|||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
func DefaultValue[T any]() T {
|
|
||||||
var defaultValue T
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
type TypedValue[T any] struct {
|
type TypedValue[T any] struct {
|
||||||
_ noCopy
|
value atomic.Pointer[T]
|
||||||
value atomic.Value
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// tValue is a struct with determined type to resolve atomic.Value usages with interface types
|
func (t *TypedValue[T]) Load() (v T) {
|
||||||
// https://github.com/golang/go/issues/22550
|
v, _ = t.LoadOk()
|
||||||
//
|
return
|
||||||
// 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]) LoadOk() (v T, ok bool) {
|
||||||
value, _ := t.LoadOk()
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TypedValue[T]) LoadOk() (_ T, ok bool) {
|
|
||||||
value := t.value.Load()
|
value := t.value.Load()
|
||||||
if value == nil {
|
if value == nil {
|
||||||
return DefaultValue[T](), false
|
return
|
||||||
}
|
}
|
||||||
return value.(tValue[T]).value, true
|
return *value, true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) Store(value T) {
|
func (t *TypedValue[T]) Store(value T) {
|
||||||
t.value.Store(tValue[T]{value})
|
t.value.Store(&value)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) Swap(new T) T {
|
func (t *TypedValue[T]) Swap(new T) (v T) {
|
||||||
old := t.value.Swap(tValue[T]{new})
|
old := t.value.Swap(&new)
|
||||||
if old == nil {
|
if old == nil {
|
||||||
return DefaultValue[T]()
|
return
|
||||||
}
|
}
|
||||||
return old.(tValue[T]).value
|
return *old
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) CompareAndSwap(old, new T) bool {
|
func (t *TypedValue[T]) CompareAndSwap(old, new T) bool {
|
||||||
return t.value.CompareAndSwap(tValue[T]{old}, tValue[T]{new}) ||
|
for {
|
||||||
// In the edge-case where [atomic.Value.Store] is uninitialized
|
currentP := t.value.Load()
|
||||||
// and trying to compare with the zero value of T,
|
var currentValue T
|
||||||
// then compare-and-swap with the nil any value.
|
if currentP != nil {
|
||||||
(any(old) == any(DefaultValue[T]()) && t.value.CompareAndSwap(any(nil), tValue[T]{new}))
|
currentValue = *currentP
|
||||||
|
}
|
||||||
|
// Compare old and current via runtime equality check.
|
||||||
|
if any(currentValue) != any(old) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if t.value.CompareAndSwap(currentP, &new) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) MarshalJSON() ([]byte, error) {
|
func (t *TypedValue[T]) MarshalJSON() ([]byte, error) {
|
||||||
@@ -89,9 +81,3 @@ func NewTypedValue[T any](t T) (v TypedValue[T]) {
|
|||||||
v.Store(t)
|
v.Store(t)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
type noCopy struct{}
|
|
||||||
|
|
||||||
// Lock is a no-op used by -copylocks checker from `go vet`.
|
|
||||||
func (*noCopy) Lock() {}
|
|
||||||
func (*noCopy) Unlock() {}
|
|
||||||
|
|||||||
@@ -7,20 +7,6 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestTypedValue(t *testing.T) {
|
func TestTypedValue(t *testing.T) {
|
||||||
{
|
|
||||||
// Always wrapping should not allocate for simple values
|
|
||||||
// because tValue[T] has the same memory layout as T.
|
|
||||||
var v TypedValue[bool]
|
|
||||||
bools := []bool{true, false}
|
|
||||||
if n := int(testing.AllocsPerRun(1000, func() {
|
|
||||||
for _, b := range bools {
|
|
||||||
v.Store(b)
|
|
||||||
}
|
|
||||||
})); n != 0 {
|
|
||||||
t.Errorf("AllocsPerRun = %d, want 0", n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
{
|
{
|
||||||
var v TypedValue[int]
|
var v TypedValue[int]
|
||||||
got, gotOk := v.LoadOk()
|
got, gotOk := v.LoadOk()
|
||||||
@@ -58,20 +44,126 @@ func TestTypedValue(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
e1, e2, e3 := io.EOF, &os.PathError{}, &os.PathError{}
|
||||||
|
var v TypedValue[error]
|
||||||
|
if v.CompareAndSwap(e1, e2) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != nil {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, nil)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(nil, e1) != true {
|
||||||
|
t.Fatalf("CompareAndSwap = false, want true")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != e1 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, e1)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(e2, e3) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != e1 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, e1)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(e1, e2) != true {
|
||||||
|
t.Fatalf("CompareAndSwap = false, want true")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != e2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, e2)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(e3, e2) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != e2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, e2)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(nil, e3) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != e2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, e2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
c1, c2, c3 := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
c1, c2, c3 := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||||
var v TypedValue[chan struct{}]
|
var v TypedValue[chan struct{}]
|
||||||
if v.CompareAndSwap(c1, c2) != false {
|
if v.CompareAndSwap(c1, c2) != false {
|
||||||
t.Fatalf("CompareAndSwap = true, want false")
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
}
|
}
|
||||||
|
if value := v.Load(); value != nil {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, nil)
|
||||||
|
}
|
||||||
if v.CompareAndSwap(nil, c1) != true {
|
if v.CompareAndSwap(nil, c1) != true {
|
||||||
t.Fatalf("CompareAndSwap = false, want true")
|
t.Fatalf("CompareAndSwap = false, want true")
|
||||||
}
|
}
|
||||||
|
if value := v.Load(); value != c1 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c1)
|
||||||
|
}
|
||||||
if v.CompareAndSwap(c2, c3) != false {
|
if v.CompareAndSwap(c2, c3) != false {
|
||||||
t.Fatalf("CompareAndSwap = true, want false")
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
}
|
}
|
||||||
|
if value := v.Load(); value != c1 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c1)
|
||||||
|
}
|
||||||
if v.CompareAndSwap(c1, c2) != true {
|
if v.CompareAndSwap(c1, c2) != true {
|
||||||
t.Fatalf("CompareAndSwap = false, want true")
|
t.Fatalf("CompareAndSwap = false, want true")
|
||||||
}
|
}
|
||||||
|
if value := v.Load(); value != c2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c2)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(c3, c2) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c2)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(nil, c3) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
c1, c2, c3 := &io.LimitedReader{}, &io.SectionReader{}, &io.SectionReader{}
|
||||||
|
var v TypedValue[io.Reader]
|
||||||
|
if v.CompareAndSwap(c1, c2) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != nil {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, nil)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(nil, c1) != true {
|
||||||
|
t.Fatalf("CompareAndSwap = false, want true")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c1 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c1)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(c2, c3) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c1 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c1)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(c1, c2) != true {
|
||||||
|
t.Fatalf("CompareAndSwap = false, want true")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c2)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(c3, c2) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c2)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(nil, c3) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c2)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ var NewPacket = buf.NewPacket
|
|||||||
var NewSize = buf.NewSize
|
var NewSize = buf.NewSize
|
||||||
var With = buf.With
|
var With = buf.With
|
||||||
var As = buf.As
|
var As = buf.As
|
||||||
|
var ReleaseMulti = buf.ReleaseMulti
|
||||||
|
|
||||||
var (
|
var (
|
||||||
Must = common.Must
|
Must = common.Must
|
||||||
|
|||||||
@@ -221,6 +221,9 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
if flow := query.Get("flow"); flow != "" {
|
if flow := query.Get("flow"); flow != "" {
|
||||||
vless["flow"] = strings.ToLower(flow)
|
vless["flow"] = strings.ToLower(flow)
|
||||||
}
|
}
|
||||||
|
if encryption := query.Get("encryption"); encryption != "" {
|
||||||
|
vless["encryption"] = encryption
|
||||||
|
}
|
||||||
proxies = append(proxies, vless)
|
proxies = append(proxies, vless)
|
||||||
|
|
||||||
case "vmess":
|
case "vmess":
|
||||||
|
|||||||
@@ -138,3 +138,5 @@ func escape[T any](x T) T {
|
|||||||
// ptrSize is the size of a pointer in bytes - unsafe.Sizeof(uintptr(0)) but as an ideal constant.
|
// ptrSize is the size of a pointer in bytes - unsafe.Sizeof(uintptr(0)) but as an ideal constant.
|
||||||
// It is also the size of the machine's native word size (that is, 4 on 32-bit systems, 8 on 64-bit).
|
// It is also the size of the machine's native word size (that is, 4 on 32-bit systems, 8 on 64-bit).
|
||||||
const ptrSize = 4 << (^uintptr(0) >> 63)
|
const ptrSize = 4 << (^uintptr(0) >> 63)
|
||||||
|
|
||||||
|
const testComparableAllocations = false
|
||||||
|
|||||||
@@ -11,3 +11,5 @@ func Comparable[T comparable](seed Seed, v T) uint64 {
|
|||||||
func WriteComparable[T comparable](h *Hash, x T) {
|
func WriteComparable[T comparable](h *Hash, x T) {
|
||||||
maphash.WriteComparable(h, x)
|
maphash.WriteComparable(h, x)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const testComparableAllocations = true
|
||||||
|
|||||||
@@ -423,7 +423,9 @@ func TestWriteComparableNoncommute(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestComparableAllocations(t *testing.T) {
|
func TestComparableAllocations(t *testing.T) {
|
||||||
t.Skip("test broken in old golang version")
|
if !testComparableAllocations {
|
||||||
|
t.Skip("test broken in old golang version")
|
||||||
|
}
|
||||||
seed := MakeSeed()
|
seed := MakeSeed()
|
||||||
x := heapStr(t)
|
x := heapStr(t)
|
||||||
allocs := testing.AllocsPerRun(10, func() {
|
allocs := testing.AllocsPerRun(10, func() {
|
||||||
|
|||||||
@@ -149,6 +149,10 @@ func (c *Conn) ReaderReplaceable() bool {
|
|||||||
return c.disablePipe.Load() || c.deadline.Load().IsZero()
|
return c.disablePipe.Load() || c.deadline.Load().IsZero()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Conn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Conn) Upstream() any {
|
func (c *Conn) Upstream() any {
|
||||||
return c.ExtendedConn
|
return c.ExtendedConn
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"runtime"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/net/deadline"
|
"github.com/metacubex/mihomo/common/net/deadline"
|
||||||
|
|
||||||
@@ -22,11 +21,26 @@ type ExtendedReader = network.ExtendedReader
|
|||||||
|
|
||||||
var WriteBuffer = bufio.WriteBuffer
|
var WriteBuffer = bufio.WriteBuffer
|
||||||
|
|
||||||
|
type ReadWaitOptions = network.ReadWaitOptions
|
||||||
|
|
||||||
|
var NewReadWaitOptions = network.NewReadWaitOptions
|
||||||
|
var CalculateFrontHeadroom = network.CalculateFrontHeadroom
|
||||||
|
var CalculateRearHeadroom = network.CalculateRearHeadroom
|
||||||
|
|
||||||
|
type ReaderWithUpstream = network.ReaderWithUpstream
|
||||||
|
type WithUpstreamReader = network.WithUpstreamReader
|
||||||
|
type WriterWithUpstream = network.WriterWithUpstream
|
||||||
|
type WithUpstreamWriter = network.WithUpstreamWriter
|
||||||
|
type WithUpstream = common.WithUpstream
|
||||||
|
|
||||||
|
var UnwrapReader = network.UnwrapReader
|
||||||
|
var UnwrapWriter = network.UnwrapWriter
|
||||||
|
|
||||||
func NewDeadlineConn(conn net.Conn) ExtendedConn {
|
func NewDeadlineConn(conn net.Conn) ExtendedConn {
|
||||||
if deadline.IsPipe(conn) || deadline.IsPipe(network.UnwrapReader(conn)) {
|
if deadline.IsPipe(conn) || deadline.IsPipe(UnwrapReader(conn)) {
|
||||||
return NewExtendedConn(conn) // pipe always have correctly deadline implement
|
return NewExtendedConn(conn) // pipe always have correctly deadline implement
|
||||||
}
|
}
|
||||||
if deadline.IsConn(conn) || deadline.IsConn(network.UnwrapReader(conn)) {
|
if deadline.IsConn(conn) || deadline.IsConn(UnwrapReader(conn)) {
|
||||||
return NewExtendedConn(conn) // was a *deadline.Conn
|
return NewExtendedConn(conn) // was a *deadline.Conn
|
||||||
}
|
}
|
||||||
return deadline.NewConn(conn)
|
return deadline.NewConn(conn)
|
||||||
@@ -43,9 +57,37 @@ type CountFunc = network.CountFunc
|
|||||||
|
|
||||||
var Pipe = deadline.Pipe
|
var Pipe = deadline.Pipe
|
||||||
|
|
||||||
// Relay copies between left and right bidirectionally.
|
func closeWrite(writer io.Closer) error {
|
||||||
func Relay(leftConn, rightConn net.Conn) {
|
if c, ok := common.Cast[network.WriteCloser](writer); ok {
|
||||||
defer runtime.KeepAlive(leftConn)
|
return c.CloseWrite()
|
||||||
defer runtime.KeepAlive(rightConn)
|
}
|
||||||
_ = bufio.CopyConn(context.TODO(), leftConn, rightConn)
|
return writer.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Relay copies between left and right bidirectionally.
|
||||||
|
// like [bufio.CopyConn] but remove unneeded [context.Context] handle and the cost of [task.Group]
|
||||||
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
|
defer func() {
|
||||||
|
_ = leftConn.Close()
|
||||||
|
_ = rightConn.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
ch := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
_, err := bufio.Copy(leftConn, rightConn)
|
||||||
|
if err == nil {
|
||||||
|
_ = closeWrite(leftConn)
|
||||||
|
} else {
|
||||||
|
_ = leftConn.Close()
|
||||||
|
}
|
||||||
|
close(ch)
|
||||||
|
}()
|
||||||
|
|
||||||
|
_, err := bufio.Copy(rightConn, leftConn)
|
||||||
|
if err == nil {
|
||||||
|
_ = closeWrite(rightConn)
|
||||||
|
} else {
|
||||||
|
_ = rightConn.Close()
|
||||||
|
}
|
||||||
|
<-ch
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ package queue
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/samber/lo"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Queue is a simple concurrent safe queue
|
// Queue is a simple concurrent safe queue
|
||||||
@@ -24,33 +22,32 @@ func (q *Queue[T]) Put(items ...T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Pop returns the head of items.
|
// Pop returns the head of items.
|
||||||
func (q *Queue[T]) Pop() T {
|
func (q *Queue[T]) Pop() (head T) {
|
||||||
if len(q.items) == 0 {
|
if len(q.items) == 0 {
|
||||||
return lo.Empty[T]()
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
q.lock.Lock()
|
q.lock.Lock()
|
||||||
head := q.items[0]
|
head = q.items[0]
|
||||||
q.items = q.items[1:]
|
q.items = q.items[1:]
|
||||||
q.lock.Unlock()
|
q.lock.Unlock()
|
||||||
return head
|
return head
|
||||||
}
|
}
|
||||||
|
|
||||||
// Last returns the last of item.
|
// Last returns the last of item.
|
||||||
func (q *Queue[T]) Last() T {
|
func (q *Queue[T]) Last() (last T) {
|
||||||
if len(q.items) == 0 {
|
if len(q.items) == 0 {
|
||||||
return lo.Empty[T]()
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
q.lock.RLock()
|
q.lock.RLock()
|
||||||
last := q.items[len(q.items)-1]
|
last = q.items[len(q.items)-1]
|
||||||
q.lock.RUnlock()
|
q.lock.RUnlock()
|
||||||
return last
|
return last
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy get the copy of queue.
|
// Copy get the copy of queue.
|
||||||
func (q *Queue[T]) Copy() []T {
|
func (q *Queue[T]) Copy() (items []T) {
|
||||||
items := []T{}
|
|
||||||
q.lock.RLock()
|
q.lock.RLock()
|
||||||
items = append(items, q.items...)
|
items = append(items, q.items...)
|
||||||
q.lock.RUnlock()
|
q.lock.RUnlock()
|
||||||
|
|||||||
215
common/queue/queue_test.go
Normal file
215
common/queue/queue_test.go
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
package queue
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestQueuePut tests the Put method of Queue
|
||||||
|
func TestQueuePut(t *testing.T) {
|
||||||
|
// Initialize a new queue
|
||||||
|
q := New[int](10)
|
||||||
|
|
||||||
|
// Test putting a single item
|
||||||
|
q.Put(1)
|
||||||
|
assert.Equal(t, int64(1), q.Len(), "Queue length should be 1 after putting one item")
|
||||||
|
|
||||||
|
// Test putting multiple items
|
||||||
|
q.Put(2, 3, 4)
|
||||||
|
assert.Equal(t, int64(4), q.Len(), "Queue length should be 4 after putting three more items")
|
||||||
|
|
||||||
|
// Test putting zero items (should not change queue)
|
||||||
|
q.Put()
|
||||||
|
assert.Equal(t, int64(4), q.Len(), "Queue length should remain unchanged when putting zero items")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestQueuePop tests the Pop method of Queue
|
||||||
|
func TestQueuePop(t *testing.T) {
|
||||||
|
// Initialize a new queue with items
|
||||||
|
q := New[int](10)
|
||||||
|
q.Put(1, 2, 3)
|
||||||
|
|
||||||
|
// Test popping items in FIFO order
|
||||||
|
item := q.Pop()
|
||||||
|
assert.Equal(t, 1, item, "First item popped should be 1")
|
||||||
|
assert.Equal(t, int64(2), q.Len(), "Queue length should be 2 after popping one item")
|
||||||
|
|
||||||
|
item = q.Pop()
|
||||||
|
assert.Equal(t, 2, item, "Second item popped should be 2")
|
||||||
|
assert.Equal(t, int64(1), q.Len(), "Queue length should be 1 after popping two items")
|
||||||
|
|
||||||
|
item = q.Pop()
|
||||||
|
assert.Equal(t, 3, item, "Third item popped should be 3")
|
||||||
|
assert.Equal(t, int64(0), q.Len(), "Queue length should be 0 after popping all items")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestQueuePopEmpty tests the Pop method on an empty queue
|
||||||
|
func TestQueuePopEmpty(t *testing.T) {
|
||||||
|
// Initialize a new empty queue
|
||||||
|
q := New[int](0)
|
||||||
|
|
||||||
|
// Test popping from an empty queue
|
||||||
|
item := q.Pop()
|
||||||
|
assert.Equal(t, 0, item, "Popping from an empty queue should return the zero value")
|
||||||
|
assert.Equal(t, int64(0), q.Len(), "Queue length should remain 0 after popping from an empty queue")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestQueueLast tests the Last method of Queue
|
||||||
|
func TestQueueLast(t *testing.T) {
|
||||||
|
// Initialize a new queue with items
|
||||||
|
q := New[int](10)
|
||||||
|
q.Put(1, 2, 3)
|
||||||
|
|
||||||
|
// Test getting the last item
|
||||||
|
item := q.Last()
|
||||||
|
assert.Equal(t, 3, item, "Last item should be 3")
|
||||||
|
assert.Equal(t, int64(3), q.Len(), "Queue length should remain unchanged after calling Last")
|
||||||
|
|
||||||
|
// Test Last on an empty queue
|
||||||
|
emptyQ := New[int](0)
|
||||||
|
emptyItem := emptyQ.Last()
|
||||||
|
assert.Equal(t, 0, emptyItem, "Last on an empty queue should return the zero value")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestQueueCopy tests the Copy method of Queue
|
||||||
|
func TestQueueCopy(t *testing.T) {
|
||||||
|
// Initialize a new queue with items
|
||||||
|
q := New[int](10)
|
||||||
|
q.Put(1, 2, 3)
|
||||||
|
|
||||||
|
// Test copying the queue
|
||||||
|
copy := q.Copy()
|
||||||
|
assert.Equal(t, 3, len(copy), "Copy should have the same number of items as the original queue")
|
||||||
|
assert.Equal(t, 1, copy[0], "First item in copy should be 1")
|
||||||
|
assert.Equal(t, 2, copy[1], "Second item in copy should be 2")
|
||||||
|
assert.Equal(t, 3, copy[2], "Third item in copy should be 3")
|
||||||
|
|
||||||
|
// Verify that modifying the copy doesn't affect the original queue
|
||||||
|
copy[0] = 99
|
||||||
|
assert.Equal(t, 1, q.Pop(), "Original queue should not be affected by modifying the copy")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestQueueLen tests the Len method of Queue
|
||||||
|
func TestQueueLen(t *testing.T) {
|
||||||
|
// Initialize a new empty queue
|
||||||
|
q := New[int](10)
|
||||||
|
assert.Equal(t, int64(0), q.Len(), "New queue should have length 0")
|
||||||
|
|
||||||
|
// Add items and check length
|
||||||
|
q.Put(1, 2)
|
||||||
|
assert.Equal(t, int64(2), q.Len(), "Queue length should be 2 after putting two items")
|
||||||
|
|
||||||
|
// Remove an item and check length
|
||||||
|
q.Pop()
|
||||||
|
assert.Equal(t, int64(1), q.Len(), "Queue length should be 1 after popping one item")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestQueueNew tests the New constructor
|
||||||
|
func TestQueueNew(t *testing.T) {
|
||||||
|
// Test creating a new queue with different hints
|
||||||
|
q1 := New[int](0)
|
||||||
|
assert.NotNil(t, q1, "New queue should not be nil")
|
||||||
|
assert.Equal(t, int64(0), q1.Len(), "New queue should have length 0")
|
||||||
|
|
||||||
|
q2 := New[int](10)
|
||||||
|
assert.NotNil(t, q2, "New queue should not be nil")
|
||||||
|
assert.Equal(t, int64(0), q2.Len(), "New queue should have length 0")
|
||||||
|
|
||||||
|
// Test with a different type
|
||||||
|
q3 := New[string](5)
|
||||||
|
assert.NotNil(t, q3, "New queue should not be nil")
|
||||||
|
assert.Equal(t, int64(0), q3.Len(), "New queue should have length 0")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestQueueConcurrency tests the concurrency safety of Queue
|
||||||
|
func TestQueueConcurrency(t *testing.T) {
|
||||||
|
// Initialize a new queue
|
||||||
|
q := New[int](100)
|
||||||
|
|
||||||
|
// Number of goroutines and operations
|
||||||
|
goroutines := 10
|
||||||
|
operations := 100
|
||||||
|
|
||||||
|
// Wait group to synchronize goroutines
|
||||||
|
wg := sync.WaitGroup{}
|
||||||
|
wg.Add(goroutines * 2) // For both producers and consumers
|
||||||
|
|
||||||
|
// Start producer goroutines
|
||||||
|
for i := 0; i < goroutines; i++ {
|
||||||
|
go func(id int) {
|
||||||
|
defer wg.Done()
|
||||||
|
for j := 0; j < operations; j++ {
|
||||||
|
q.Put(id*operations + j)
|
||||||
|
// Small sleep to increase chance of race conditions
|
||||||
|
time.Sleep(time.Microsecond)
|
||||||
|
}
|
||||||
|
}(i)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start consumer goroutines
|
||||||
|
consumed := make(chan int, goroutines*operations)
|
||||||
|
for i := 0; i < goroutines; i++ {
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for j := 0; j < operations; j++ {
|
||||||
|
// Try to pop an item, but don't block if queue is empty
|
||||||
|
// Use a mutex to avoid race condition between Len() check and Pop()
|
||||||
|
q.lock.Lock()
|
||||||
|
if len(q.items) > 0 {
|
||||||
|
item := q.items[0]
|
||||||
|
q.items = q.items[1:]
|
||||||
|
q.lock.Unlock()
|
||||||
|
consumed <- item
|
||||||
|
} else {
|
||||||
|
q.lock.Unlock()
|
||||||
|
}
|
||||||
|
// Small sleep to increase chance of race conditions
|
||||||
|
time.Sleep(time.Microsecond)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for all goroutines to finish
|
||||||
|
wg.Wait()
|
||||||
|
// Close the consumed channel
|
||||||
|
close(consumed)
|
||||||
|
|
||||||
|
// Count the number of consumed items
|
||||||
|
consumedCount := 0
|
||||||
|
for range consumed {
|
||||||
|
consumedCount++
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check that the queue is in a consistent state
|
||||||
|
totalItems := goroutines * operations
|
||||||
|
remaining := int(q.Len())
|
||||||
|
assert.Equal(t, totalItems, consumedCount+remaining, "Total items should equal consumed items plus remaining items")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestQueueWithDifferentTypes tests the Queue with different types
|
||||||
|
func TestQueueWithDifferentTypes(t *testing.T) {
|
||||||
|
// Test with string type
|
||||||
|
qString := New[string](5)
|
||||||
|
qString.Put("hello", "world")
|
||||||
|
assert.Equal(t, int64(2), qString.Len(), "Queue length should be 2")
|
||||||
|
assert.Equal(t, "hello", qString.Pop(), "First item should be 'hello'")
|
||||||
|
assert.Equal(t, "world", qString.Pop(), "Second item should be 'world'")
|
||||||
|
|
||||||
|
// Test with struct type
|
||||||
|
type Person struct {
|
||||||
|
Name string
|
||||||
|
Age int
|
||||||
|
}
|
||||||
|
|
||||||
|
qStruct := New[Person](5)
|
||||||
|
qStruct.Put(Person{Name: "Alice", Age: 30}, Person{Name: "Bob", Age: 25})
|
||||||
|
assert.Equal(t, int64(2), qStruct.Len(), "Queue length should be 2")
|
||||||
|
|
||||||
|
firstPerson := qStruct.Pop()
|
||||||
|
assert.Equal(t, "Alice", firstPerson.Name, "First person's name should be 'Alice'")
|
||||||
|
secondPerson := qStruct.Pop()
|
||||||
|
assert.Equal(t, "Bob", secondPerson.Name, "Second person's name should be 'Bob'")
|
||||||
|
}
|
||||||
@@ -53,6 +53,12 @@ func (d *Decoder) Decode(src map[string]any, dst any) error {
|
|||||||
key, omitKey, found := strings.Cut(tag, ",")
|
key, omitKey, found := strings.Cut(tag, ",")
|
||||||
omitempty := found && omitKey == "omitempty"
|
omitempty := found && omitKey == "omitempty"
|
||||||
|
|
||||||
|
// As a special case, if the field tag is "-", the field is always omitted.
|
||||||
|
// Note that a field with name "-" can still be generated using the tag "-,".
|
||||||
|
if key == "-" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
value, ok := src[key]
|
value, ok := src[key]
|
||||||
if !ok {
|
if !ok {
|
||||||
if d.option.KeyReplacer != nil {
|
if d.option.KeyReplacer != nil {
|
||||||
|
|||||||
@@ -288,3 +288,23 @@ func TestStructure_Null(t *testing.T) {
|
|||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
assert.Equal(t, s.Opt.Bar, "")
|
assert.Equal(t, s.Opt.Bar, "")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestStructure_Ignore(t *testing.T) {
|
||||||
|
rawMap := map[string]any{
|
||||||
|
"-": "newData",
|
||||||
|
}
|
||||||
|
|
||||||
|
s := struct {
|
||||||
|
MustIgnore string `test:"-"`
|
||||||
|
}{MustIgnore: "oldData"}
|
||||||
|
|
||||||
|
err := decoder.Decode(rawMap, &s)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, s.MustIgnore, "oldData")
|
||||||
|
|
||||||
|
// test omitempty
|
||||||
|
delete(rawMap, "-")
|
||||||
|
err = decoder.Decode(rawMap, &s)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, s.MustIgnore, "oldData")
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,7 +10,9 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/common/once"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/ntp"
|
||||||
)
|
)
|
||||||
|
|
||||||
var globalCertPool *x509.CertPool
|
var globalCertPool *x509.CertPool
|
||||||
@@ -65,70 +67,61 @@ func ResetCertificate() {
|
|||||||
initializeCertPool()
|
initializeCertPool()
|
||||||
}
|
}
|
||||||
|
|
||||||
func getCertPool() *x509.CertPool {
|
func GetCertPool() *x509.CertPool {
|
||||||
|
mutex.Lock()
|
||||||
|
defer mutex.Unlock()
|
||||||
if globalCertPool == nil {
|
if globalCertPool == nil {
|
||||||
mutex.Lock()
|
|
||||||
defer mutex.Unlock()
|
|
||||||
if globalCertPool != nil {
|
|
||||||
return globalCertPool
|
|
||||||
}
|
|
||||||
initializeCertPool()
|
initializeCertPool()
|
||||||
}
|
}
|
||||||
return globalCertPool
|
return globalCertPool
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetCertPool(customCA string, customCAString string) (*x509.CertPool, error) {
|
type Option struct {
|
||||||
var certificate []byte
|
TLSConfig *tls.Config
|
||||||
var err error
|
Fingerprint string
|
||||||
if len(customCA) > 0 {
|
ZeroTrust bool
|
||||||
path := C.Path.Resolve(customCA)
|
Certificate string
|
||||||
if !C.Path.IsSafePath(path) {
|
PrivateKey string
|
||||||
return nil, C.Path.ErrNotSafePath(path)
|
|
||||||
}
|
|
||||||
certificate, err = os.ReadFile(path)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("load ca error: %w", err)
|
|
||||||
}
|
|
||||||
} else if customCAString != "" {
|
|
||||||
certificate = []byte(customCAString)
|
|
||||||
}
|
|
||||||
if len(certificate) > 0 {
|
|
||||||
certPool := x509.NewCertPool()
|
|
||||||
if !certPool.AppendCertsFromPEM(certificate) {
|
|
||||||
return nil, fmt.Errorf("failed to parse certificate:\n\n %s", certificate)
|
|
||||||
}
|
|
||||||
return certPool, nil
|
|
||||||
} else {
|
|
||||||
return getCertPool(), nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetTLSConfig specified fingerprint, customCA and customCAString
|
func GetTLSConfig(opt Option) (tlsConfig *tls.Config, err error) {
|
||||||
func GetTLSConfig(tlsConfig *tls.Config, fingerprint string, customCA string, customCAString string) (_ *tls.Config, err error) {
|
tlsConfig = opt.TLSConfig
|
||||||
if tlsConfig == nil {
|
if tlsConfig == nil {
|
||||||
tlsConfig = &tls.Config{}
|
tlsConfig = &tls.Config{}
|
||||||
}
|
}
|
||||||
tlsConfig.RootCAs, err = GetCertPool(customCA, customCAString)
|
tlsConfig.Time = ntp.Now
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
if opt.ZeroTrust {
|
||||||
|
tlsConfig.RootCAs = zeroTrustCertPool()
|
||||||
|
} else {
|
||||||
|
tlsConfig.RootCAs = GetCertPool()
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(fingerprint) > 0 {
|
if len(opt.Fingerprint) > 0 {
|
||||||
tlsConfig.VerifyPeerCertificate, err = NewFingerprintVerifier(fingerprint)
|
tlsConfig.VerifyPeerCertificate, err = NewFingerprintVerifier(opt.Fingerprint, tlsConfig.Time)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
tlsConfig.InsecureSkipVerify = true
|
tlsConfig.InsecureSkipVerify = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(opt.Certificate) > 0 || len(opt.PrivateKey) > 0 {
|
||||||
|
var cert tls.Certificate
|
||||||
|
cert, err = LoadTLSKeyPair(opt.Certificate, opt.PrivateKey, C.Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tlsConfig.Certificates = []tls.Certificate{cert}
|
||||||
|
}
|
||||||
return tlsConfig, nil
|
return tlsConfig, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetSpecifiedFingerprintTLSConfig specified fingerprint
|
var zeroTrustCertPool = once.OnceValue(func() *x509.CertPool {
|
||||||
func GetSpecifiedFingerprintTLSConfig(tlsConfig *tls.Config, fingerprint string) (*tls.Config, error) {
|
if len(_CaCertificates) != 0 { // always using embed cert first
|
||||||
return GetTLSConfig(tlsConfig, fingerprint, "", "")
|
zeroTrustCertPool := x509.NewCertPool()
|
||||||
}
|
if zeroTrustCertPool.AppendCertsFromPEM(_CaCertificates) {
|
||||||
|
return zeroTrustCertPool
|
||||||
func GetGlobalTLSConfig(tlsConfig *tls.Config) *tls.Config {
|
}
|
||||||
tlsConfig, _ = GetTLSConfig(tlsConfig, "", "", "")
|
}
|
||||||
return tlsConfig
|
return nil // fallback to system pool
|
||||||
}
|
})
|
||||||
|
|||||||
@@ -7,10 +7,11 @@ import (
|
|||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewFingerprintVerifier returns a function that verifies whether a certificate's SHA-256 fingerprint matches the given one.
|
// NewFingerprintVerifier returns a function that verifies whether a certificate's SHA-256 fingerprint matches the given one.
|
||||||
func NewFingerprintVerifier(fingerprint string) (func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error, error) {
|
func NewFingerprintVerifier(fingerprint string, time func() time.Time) (func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error, error) {
|
||||||
switch fingerprint {
|
switch fingerprint {
|
||||||
case "chrome", "firefox", "safari", "ios", "android", "edge", "360", "qq", "random", "randomized": // WTF???
|
case "chrome", "firefox", "safari", "ios", "android", "edge", "360", "qq", "random", "randomized": // WTF???
|
||||||
return nil, fmt.Errorf("`fingerprint` is used for TLS certificate pinning. If you need to specify the browser fingerprint, use `client-fingerprint`")
|
return nil, fmt.Errorf("`fingerprint` is used for TLS certificate pinning. If you need to specify the browser fingerprint, use `client-fingerprint`")
|
||||||
@@ -27,9 +28,40 @@ func NewFingerprintVerifier(fingerprint string) (func(rawCerts [][]byte, verifie
|
|||||||
|
|
||||||
return func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
return func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||||
// ssl pining
|
// ssl pining
|
||||||
for _, rawCert := range rawCerts {
|
for i, rawCert := range rawCerts {
|
||||||
hash := sha256.Sum256(rawCert)
|
hash := sha256.Sum256(rawCert)
|
||||||
if bytes.Equal(fpByte, hash[:]) {
|
if bytes.Equal(fpByte, hash[:]) {
|
||||||
|
if i > 0 {
|
||||||
|
|
||||||
|
// When the fingerprint matches a non-leaf certificate,
|
||||||
|
// the certificate chain validity is verified using the certificate as the trusted root certificate.
|
||||||
|
//
|
||||||
|
// Currently, we do not verify that the SNI matches the certificate's DNS name,
|
||||||
|
// but we do verify the validity of the child certificate,
|
||||||
|
// including the issuance time and whether the child certificate was issued by the parent certificate.
|
||||||
|
|
||||||
|
certs := make([]*x509.Certificate, i+1) // stop at i
|
||||||
|
for j := range certs {
|
||||||
|
cert, err := x509.ParseCertificate(rawCerts[j])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
certs[j] = cert
|
||||||
|
}
|
||||||
|
opts := x509.VerifyOptions{
|
||||||
|
Roots: x509.NewCertPool(),
|
||||||
|
Intermediates: x509.NewCertPool(),
|
||||||
|
}
|
||||||
|
if time != nil {
|
||||||
|
opts.CurrentTime = time()
|
||||||
|
}
|
||||||
|
opts.Roots.AddCert(certs[i])
|
||||||
|
for _, cert := range certs[1:] {
|
||||||
|
opts.Intermediates.AddCert(cert)
|
||||||
|
}
|
||||||
|
_, err := certs[0].Verify(opts)
|
||||||
|
return err
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
351
component/ca/fingerprint_test.go
Normal file
351
component/ca/fingerprint_test.go
Normal file
@@ -0,0 +1,351 @@
|
|||||||
|
package ca
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/pem"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFingerprintVerifierLeaf(t *testing.T) {
|
||||||
|
leafFingerprint := CalculateFingerprint(leafPEM.Bytes)
|
||||||
|
verifier, err := NewFingerprintVerifier(leafFingerprint, func() time.Time {
|
||||||
|
return time.Unix(1677615892, 0)
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{leafPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{leafPEM.Bytes, smimeIntermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{leafPEM.Bytes, intermediatePEM.Bytes, smimeRootPEM.Bytes}, nil)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{leafWithInvalidHashPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||||
|
assert.Error(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{smimeLeafPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||||
|
assert.Error(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{smimeLeafPEM.Bytes, intermediatePEM.Bytes, smimeRootPEM.Bytes}, nil)
|
||||||
|
assert.Error(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFingerprintVerifierIntermediate(t *testing.T) {
|
||||||
|
intermediateFingerprint := CalculateFingerprint(intermediatePEM.Bytes)
|
||||||
|
verifier, err := NewFingerprintVerifier(intermediateFingerprint, func() time.Time {
|
||||||
|
return time.Unix(1677615892, 0)
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{leafPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{leafPEM.Bytes, smimeIntermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||||
|
assert.Error(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{leafPEM.Bytes, intermediatePEM.Bytes, smimeRootPEM.Bytes}, nil)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{leafWithInvalidHashPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||||
|
assert.Error(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{smimeLeafPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||||
|
assert.Error(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{smimeLeafPEM.Bytes, intermediatePEM.Bytes, smimeRootPEM.Bytes}, nil)
|
||||||
|
assert.Error(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFingerprintVerifierRoot(t *testing.T) {
|
||||||
|
rootFingerprint := CalculateFingerprint(rootPEM.Bytes)
|
||||||
|
verifier, err := NewFingerprintVerifier(rootFingerprint, func() time.Time {
|
||||||
|
return time.Unix(1677615892, 0)
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{leafPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{leafPEM.Bytes, smimeIntermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||||
|
assert.Error(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{leafPEM.Bytes, intermediatePEM.Bytes, smimeRootPEM.Bytes}, nil)
|
||||||
|
assert.Error(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{leafWithInvalidHashPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||||
|
assert.Error(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{smimeLeafPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||||
|
assert.Error(t, err)
|
||||||
|
|
||||||
|
err = verifier([][]byte{smimeLeafPEM.Bytes, intermediatePEM.Bytes, smimeRootPEM.Bytes}, nil)
|
||||||
|
assert.Error(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var rootPEM, _ = pem.Decode([]byte(gtsRoot))
|
||||||
|
var intermediatePEM, _ = pem.Decode([]byte(gtsIntermediate))
|
||||||
|
var leafPEM, _ = pem.Decode([]byte(googleLeaf))
|
||||||
|
var leafWithInvalidHashPEM, _ = pem.Decode([]byte(googleLeafWithInvalidHash))
|
||||||
|
var smimeRootPEM, _ = pem.Decode([]byte(smimeRoot))
|
||||||
|
var smimeIntermediatePEM, _ = pem.Decode([]byte(smimeIntermediate))
|
||||||
|
var smimeLeafPEM, _ = pem.Decode([]byte(smimeLeaf))
|
||||||
|
|
||||||
|
const gtsIntermediate = `-----BEGIN CERTIFICATE-----
|
||||||
|
MIIFljCCA36gAwIBAgINAgO8U1lrNMcY9QFQZjANBgkqhkiG9w0BAQsFADBHMQsw
|
||||||
|
CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU
|
||||||
|
MBIGA1UEAxMLR1RTIFJvb3QgUjEwHhcNMjAwODEzMDAwMDQyWhcNMjcwOTMwMDAw
|
||||||
|
MDQyWjBGMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp
|
||||||
|
Y2VzIExMQzETMBEGA1UEAxMKR1RTIENBIDFDMzCCASIwDQYJKoZIhvcNAQEBBQAD
|
||||||
|
ggEPADCCAQoCggEBAPWI3+dijB43+DdCkH9sh9D7ZYIl/ejLa6T/belaI+KZ9hzp
|
||||||
|
kgOZE3wJCor6QtZeViSqejOEH9Hpabu5dOxXTGZok3c3VVP+ORBNtzS7XyV3NzsX
|
||||||
|
lOo85Z3VvMO0Q+sup0fvsEQRY9i0QYXdQTBIkxu/t/bgRQIh4JZCF8/ZK2VWNAcm
|
||||||
|
BA2o/X3KLu/qSHw3TT8An4Pf73WELnlXXPxXbhqW//yMmqaZviXZf5YsBvcRKgKA
|
||||||
|
gOtjGDxQSYflispfGStZloEAoPtR28p3CwvJlk/vcEnHXG0g/Zm0tOLKLnf9LdwL
|
||||||
|
tmsTDIwZKxeWmLnwi/agJ7u2441Rj72ux5uxiZ0CAwEAAaOCAYAwggF8MA4GA1Ud
|
||||||
|
DwEB/wQEAwIBhjAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwEgYDVR0T
|
||||||
|
AQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQUinR/r4XN7pXNPZzQ4kYU83E1HScwHwYD
|
||||||
|
VR0jBBgwFoAU5K8rJnEaK0gnhS9SZizv8IkTcT4waAYIKwYBBQUHAQEEXDBaMCYG
|
||||||
|
CCsGAQUFBzABhhpodHRwOi8vb2NzcC5wa2kuZ29vZy9ndHNyMTAwBggrBgEFBQcw
|
||||||
|
AoYkaHR0cDovL3BraS5nb29nL3JlcG8vY2VydHMvZ3RzcjEuZGVyMDQGA1UdHwQt
|
||||||
|
MCswKaAnoCWGI2h0dHA6Ly9jcmwucGtpLmdvb2cvZ3RzcjEvZ3RzcjEuY3JsMFcG
|
||||||
|
A1UdIARQME4wOAYKKwYBBAHWeQIFAzAqMCgGCCsGAQUFBwIBFhxodHRwczovL3Br
|
||||||
|
aS5nb29nL3JlcG9zaXRvcnkvMAgGBmeBDAECATAIBgZngQwBAgIwDQYJKoZIhvcN
|
||||||
|
AQELBQADggIBAIl9rCBcDDy+mqhXlRu0rvqrpXJxtDaV/d9AEQNMwkYUuxQkq/BQ
|
||||||
|
cSLbrcRuf8/xam/IgxvYzolfh2yHuKkMo5uhYpSTld9brmYZCwKWnvy15xBpPnrL
|
||||||
|
RklfRuFBsdeYTWU0AIAaP0+fbH9JAIFTQaSSIYKCGvGjRFsqUBITTcFTNvNCCK9U
|
||||||
|
+o53UxtkOCcXCb1YyRt8OS1b887U7ZfbFAO/CVMkH8IMBHmYJvJh8VNS/UKMG2Yr
|
||||||
|
PxWhu//2m+OBmgEGcYk1KCTd4b3rGS3hSMs9WYNRtHTGnXzGsYZbr8w0xNPM1IER
|
||||||
|
lQCh9BIiAfq0g3GvjLeMcySsN1PCAJA/Ef5c7TaUEDu9Ka7ixzpiO2xj2YC/WXGs
|
||||||
|
Yye5TBeg2vZzFb8q3o/zpWwygTMD0IZRcZk0upONXbVRWPeyk+gB9lm+cZv9TSjO
|
||||||
|
z23HFtz30dZGm6fKa+l3D/2gthsjgx0QGtkJAITgRNOidSOzNIb2ILCkXhAd4FJG
|
||||||
|
AJ2xDx8hcFH1mt0G/FX0Kw4zd8NLQsLxdxP8c4CU6x+7Nz/OAipmsHMdMqUybDKw
|
||||||
|
juDEI/9bfU1lcKwrmz3O2+BtjjKAvpafkmO8l7tdufThcV4q5O8DIrGKZTqPwJNl
|
||||||
|
1IXNDw9bg1kWRxYtnCQ6yICmJhSFm/Y3m6xv+cXDBlHz4n/FsRC6UfTd
|
||||||
|
-----END CERTIFICATE-----`
|
||||||
|
|
||||||
|
const gtsRoot = `-----BEGIN CERTIFICATE-----
|
||||||
|
MIIFVzCCAz+gAwIBAgINAgPlk28xsBNJiGuiFzANBgkqhkiG9w0BAQwFADBHMQsw
|
||||||
|
CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU
|
||||||
|
MBIGA1UEAxMLR1RTIFJvb3QgUjEwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw
|
||||||
|
MDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp
|
||||||
|
Y2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUA
|
||||||
|
A4ICDwAwggIKAoICAQC2EQKLHuOhd5s73L+UPreVp0A8of2C+X0yBoJx9vaMf/vo
|
||||||
|
27xqLpeXo4xL+Sv2sfnOhB2x+cWX3u+58qPpvBKJXqeqUqv4IyfLpLGcY9vXmX7w
|
||||||
|
Cl7raKb0xlpHDU0QM+NOsROjyBhsS+z8CZDfnWQpJSMHobTSPS5g4M/SCYe7zUjw
|
||||||
|
TcLCeoiKu7rPWRnWr4+wB7CeMfGCwcDfLqZtbBkOtdh+JhpFAz2weaSUKK0Pfybl
|
||||||
|
qAj+lug8aJRT7oM6iCsVlgmy4HqMLnXWnOunVmSPlk9orj2XwoSPwLxAwAtcvfaH
|
||||||
|
szVsrBhQf4TgTM2S0yDpM7xSma8ytSmzJSq0SPly4cpk9+aCEI3oncKKiPo4Zor8
|
||||||
|
Y/kB+Xj9e1x3+naH+uzfsQ55lVe0vSbv1gHR6xYKu44LtcXFilWr06zqkUspzBmk
|
||||||
|
MiVOKvFlRNACzqrOSbTqn3yDsEB750Orp2yjj32JgfpMpf/VjsPOS+C12LOORc92
|
||||||
|
wO1AK/1TD7Cn1TsNsYqiA94xrcx36m97PtbfkSIS5r762DL8EGMUUXLeXdYWk70p
|
||||||
|
aDPvOmbsB4om3xPXV2V4J95eSRQAogB/mqghtqmxlbCluQ0WEdrHbEg8QOB+DVrN
|
||||||
|
VjzRlwW5y0vtOUucxD/SVRNuJLDWcfr0wbrM7Rv1/oFB2ACYPTrIrnqYNxgFlQID
|
||||||
|
AQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E
|
||||||
|
FgQU5K8rJnEaK0gnhS9SZizv8IkTcT4wDQYJKoZIhvcNAQEMBQADggIBAJ+qQibb
|
||||||
|
C5u+/x6Wki4+omVKapi6Ist9wTrYggoGxval3sBOh2Z5ofmmWJyq+bXmYOfg6LEe
|
||||||
|
QkEzCzc9zolwFcq1JKjPa7XSQCGYzyI0zzvFIoTgxQ6KfF2I5DUkzps+GlQebtuy
|
||||||
|
h6f88/qBVRRiClmpIgUxPoLW7ttXNLwzldMXG+gnoot7TiYaelpkttGsN/H9oPM4
|
||||||
|
7HLwEXWdyzRSjeZ2axfG34arJ45JK3VmgRAhpuo+9K4l/3wV3s6MJT/KYnAK9y8J
|
||||||
|
ZgfIPxz88NtFMN9iiMG1D53Dn0reWVlHxYciNuaCp+0KueIHoI17eko8cdLiA6Ef
|
||||||
|
MgfdG+RCzgwARWGAtQsgWSl4vflVy2PFPEz0tv/bal8xa5meLMFrUKTX5hgUvYU/
|
||||||
|
Z6tGn6D/Qqc6f1zLXbBwHSs09dR2CQzreExZBfMzQsNhFRAbd03OIozUhfJFfbdT
|
||||||
|
6u9AWpQKXCBfTkBdYiJ23//OYb2MI3jSNwLgjt7RETeJ9r/tSQdirpLsQBqvFAnZ
|
||||||
|
0E6yove+7u7Y/9waLd64NnHi/Hm3lCXRSHNboTXns5lndcEZOitHTtNCjv0xyBZm
|
||||||
|
2tIMPNuzjsmhDYAPexZ3FL//2wmUspO8IFgV6dtxQ/PeEMMA3KgqlbbC1j+Qa3bb
|
||||||
|
bP6MvPJwNQzcmRk13NfIRmPVNnGuV/u3gm3c
|
||||||
|
-----END CERTIFICATE-----`
|
||||||
|
|
||||||
|
const googleLeaf = `-----BEGIN CERTIFICATE-----
|
||||||
|
MIIFUjCCBDqgAwIBAgIQERmRWTzVoz0SMeozw2RM3DANBgkqhkiG9w0BAQsFADBG
|
||||||
|
MQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExM
|
||||||
|
QzETMBEGA1UEAxMKR1RTIENBIDFDMzAeFw0yMzAxMDIwODE5MTlaFw0yMzAzMjcw
|
||||||
|
ODE5MThaMBkxFzAVBgNVBAMTDnd3dy5nb29nbGUuY29tMIIBIjANBgkqhkiG9w0B
|
||||||
|
AQEFAAOCAQ8AMIIBCgKCAQEAq30odrKMT54TJikMKL8S+lwoCMT5geP0u9pWjk6a
|
||||||
|
wdB6i3kO+UE4ijCAmhbcZKeKaLnGJ38weZNwB1ayabCYyX7hDiC/nRcZU49LX5+o
|
||||||
|
55kDVaNn14YKkg2kCeX25HDxSwaOsNAIXKPTqiQL5LPvc4Twhl8HY51hhNWQrTEr
|
||||||
|
N775eYbixEULvyVLq5BLbCOpPo8n0/MTjQ32ku1jQq3GIYMJC/Rf2VW5doF6t9zs
|
||||||
|
KleflAN8OdKp0ME9OHg0T1P3yyb67T7n0SpisHbeG06AmQcKJF9g/9VPJtRf4l1Q
|
||||||
|
WRPDC+6JUqzXCxAGmIRGZ7TNMxPMBW/7DRX6w8oLKVNb0wIDAQABo4ICZzCCAmMw
|
||||||
|
DgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQC
|
||||||
|
MAAwHQYDVR0OBBYEFBnboj3lf9+Xat4oEgo6ZtIMr8ZuMB8GA1UdIwQYMBaAFIp0
|
||||||
|
f6+Fze6VzT2c0OJGFPNxNR0nMGoGCCsGAQUFBwEBBF4wXDAnBggrBgEFBQcwAYYb
|
||||||
|
aHR0cDovL29jc3AucGtpLmdvb2cvZ3RzMWMzMDEGCCsGAQUFBzAChiVodHRwOi8v
|
||||||
|
cGtpLmdvb2cvcmVwby9jZXJ0cy9ndHMxYzMuZGVyMBkGA1UdEQQSMBCCDnd3dy5n
|
||||||
|
b29nbGUuY29tMCEGA1UdIAQaMBgwCAYGZ4EMAQIBMAwGCisGAQQB1nkCBQMwPAYD
|
||||||
|
VR0fBDUwMzAxoC+gLYYraHR0cDovL2NybHMucGtpLmdvb2cvZ3RzMWMzL1FPdkow
|
||||||
|
TjFzVDJBLmNybDCCAQQGCisGAQQB1nkCBAIEgfUEgfIA8AB2AHoyjFTYty22IOo4
|
||||||
|
4FIe6YQWcDIThU070ivBOlejUutSAAABhXHHOiUAAAQDAEcwRQIgBUkikUIXdo+S
|
||||||
|
3T8PP0/cvokhUlumRE3GRWGL4WRMLpcCIQDY+bwK384mZxyXGZ5lwNRTAPNzT8Fx
|
||||||
|
1+//nbaGK3BQMAB2AOg+0No+9QY1MudXKLyJa8kD08vREWvs62nhd31tBr1uAAAB
|
||||||
|
hXHHOfQAAAQDAEcwRQIgLoVydNfMFKV9IoZR+M0UuJ2zOqbxIRum7Sn9RMPOBGMC
|
||||||
|
IQD1/BgzCSDTvYvco6kpB6ifKSbg5gcb5KTnYxQYwRW14TANBgkqhkiG9w0BAQsF
|
||||||
|
AAOCAQEA2bQQu30e3OFu0bmvQHmcqYvXBu6tF6e5b5b+hj4O+Rn7BXTTmaYX3M6p
|
||||||
|
MsfRH4YVJJMB/dc3PROR2VtnKFC6gAZX+RKM6nXnZhIlOdmQnonS1ecOL19PliUd
|
||||||
|
VXbwKjXqAO0Ljd9y9oXaXnyPyHmUJNI5YXAcxE+XXiOZhcZuMYyWmoEKJQ/XlSga
|
||||||
|
zWfTn1IcKhA3IC7A1n/5bkkWD1Xi1mdWFQ6DQDMp//667zz7pKOgFMlB93aPDjvI
|
||||||
|
c78zEqNswn6xGKXpWF5xVwdFcsx9HKhJ6UAi2bQ/KQ1yb7LPUOR6wXXWrG1cLnNP
|
||||||
|
i8eNLnKL9PXQ+5SwJFCzfEhcIZuhzg==
|
||||||
|
-----END CERTIFICATE-----`
|
||||||
|
|
||||||
|
// googleLeafWithInvalidHash is the same as googleLeaf, but the signature
|
||||||
|
// algorithm in the certificate contains a nonsense OID.
|
||||||
|
const googleLeafWithInvalidHash = `-----BEGIN CERTIFICATE-----
|
||||||
|
MIIFUjCCBDqgAwIBAgIQERmRWTzVoz0SMeozw2RM3DANBgkqhkiG9w0BAQ4FADBG
|
||||||
|
MQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExM
|
||||||
|
QzETMBEGA1UEAxMKR1RTIENBIDFDMzAeFw0yMzAxMDIwODE5MTlaFw0yMzAzMjcw
|
||||||
|
ODE5MThaMBkxFzAVBgNVBAMTDnd3dy5nb29nbGUuY29tMIIBIjANBgkqhkiG9w0B
|
||||||
|
AQEFAAOCAQ8AMIIBCgKCAQEAq30odrKMT54TJikMKL8S+lwoCMT5geP0u9pWjk6a
|
||||||
|
wdB6i3kO+UE4ijCAmhbcZKeKaLnGJ38weZNwB1ayabCYyX7hDiC/nRcZU49LX5+o
|
||||||
|
55kDVaNn14YKkg2kCeX25HDxSwaOsNAIXKPTqiQL5LPvc4Twhl8HY51hhNWQrTEr
|
||||||
|
N775eYbixEULvyVLq5BLbCOpPo8n0/MTjQ32ku1jQq3GIYMJC/Rf2VW5doF6t9zs
|
||||||
|
KleflAN8OdKp0ME9OHg0T1P3yyb67T7n0SpisHbeG06AmQcKJF9g/9VPJtRf4l1Q
|
||||||
|
WRPDC+6JUqzXCxAGmIRGZ7TNMxPMBW/7DRX6w8oLKVNb0wIDAQABo4ICZzCCAmMw
|
||||||
|
DgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQC
|
||||||
|
MAAwHQYDVR0OBBYEFBnboj3lf9+Xat4oEgo6ZtIMr8ZuMB8GA1UdIwQYMBaAFIp0
|
||||||
|
f6+Fze6VzT2c0OJGFPNxNR0nMGoGCCsGAQUFBwEBBF4wXDAnBggrBgEFBQcwAYYb
|
||||||
|
aHR0cDovL29jc3AucGtpLmdvb2cvZ3RzMWMzMDEGCCsGAQUFBzAChiVodHRwOi8v
|
||||||
|
cGtpLmdvb2cvcmVwby9jZXJ0cy9ndHMxYzMuZGVyMBkGA1UdEQQSMBCCDnd3dy5n
|
||||||
|
b29nbGUuY29tMCEGA1UdIAQaMBgwCAYGZ4EMAQIBMAwGCisGAQQB1nkCBQMwPAYD
|
||||||
|
VR0fBDUwMzAxoC+gLYYraHR0cDovL2NybHMucGtpLmdvb2cvZ3RzMWMzL1FPdkow
|
||||||
|
TjFzVDJBLmNybDCCAQQGCisGAQQB1nkCBAIEgfUEgfIA8AB2AHoyjFTYty22IOo4
|
||||||
|
4FIe6YQWcDIThU070ivBOlejUutSAAABhXHHOiUAAAQDAEcwRQIgBUkikUIXdo+S
|
||||||
|
3T8PP0/cvokhUlumRE3GRWGL4WRMLpcCIQDY+bwK384mZxyXGZ5lwNRTAPNzT8Fx
|
||||||
|
1+//nbaGK3BQMAB2AOg+0No+9QY1MudXKLyJa8kD08vREWvs62nhd31tBr1uAAAB
|
||||||
|
hXHHOfQAAAQDAEcwRQIgLoVydNfMFKV9IoZR+M0UuJ2zOqbxIRum7Sn9RMPOBGMC
|
||||||
|
IQD1/BgzCSDTvYvco6kpB6ifKSbg5gcb5KTnYxQYwRW14TANBgkqhkiG9w0BAQ4F
|
||||||
|
AAOCAQEA2bQQu30e3OFu0bmvQHmcqYvXBu6tF6e5b5b+hj4O+Rn7BXTTmaYX3M6p
|
||||||
|
MsfRH4YVJJMB/dc3PROR2VtnKFC6gAZX+RKM6nXnZhIlOdmQnonS1ecOL19PliUd
|
||||||
|
VXbwKjXqAO0Ljd9y9oXaXnyPyHmUJNI5YXAcxE+XXiOZhcZuMYyWmoEKJQ/XlSga
|
||||||
|
zWfTn1IcKhA3IC7A1n/5bkkWD1Xi1mdWFQ6DQDMp//667zz7pKOgFMlB93aPDjvI
|
||||||
|
c78zEqNswn6xGKXpWF5xVwdFcsx9HKhJ6UAi2bQ/KQ1yb7LPUOR6wXXWrG1cLnNP
|
||||||
|
i8eNLnKL9PXQ+5SwJFCzfEhcIZuhzg==
|
||||||
|
-----END CERTIFICATE-----`
|
||||||
|
|
||||||
|
const smimeLeaf = `-----BEGIN CERTIFICATE-----
|
||||||
|
MIIIPDCCBiSgAwIBAgIQaMDxFS0pOMxZZeOBxoTJtjANBgkqhkiG9w0BAQsFADCB
|
||||||
|
nTELMAkGA1UEBhMCRVMxFDASBgNVBAoMC0laRU5QRSBTLkEuMTowOAYDVQQLDDFB
|
||||||
|
WlogWml1cnRhZ2lyaSBwdWJsaWtvYSAtIENlcnRpZmljYWRvIHB1YmxpY28gU0NB
|
||||||
|
MTwwOgYDVQQDDDNFQUVrbyBIZXJyaSBBZG1pbmlzdHJhemlvZW4gQ0EgLSBDQSBB
|
||||||
|
QVBQIFZhc2NhcyAoMikwHhcNMTcwNzEyMDg1MzIxWhcNMjEwNzEyMDg1MzIxWjCC
|
||||||
|
AQwxDzANBgNVBAoMBklaRU5QRTE4MDYGA1UECwwvWml1cnRhZ2lyaSBrb3Jwb3Jh
|
||||||
|
dGlib2EtQ2VydGlmaWNhZG8gY29ycG9yYXRpdm8xQzBBBgNVBAsMOkNvbmRpY2lv
|
||||||
|
bmVzIGRlIHVzbyBlbiB3d3cuaXplbnBlLmNvbSBub2xhIGVyYWJpbGkgamFraXRl
|
||||||
|
a28xFzAVBgNVBC4TDi1kbmkgOTk5OTk5ODlaMSQwIgYDVQQDDBtDT1JQT1JBVElW
|
||||||
|
TyBGSUNUSUNJTyBBQ1RJVk8xFDASBgNVBCoMC0NPUlBPUkFUSVZPMREwDwYDVQQE
|
||||||
|
DAhGSUNUSUNJTzESMBAGA1UEBRMJOTk5OTk5ODlaMIIBIjANBgkqhkiG9w0BAQEF
|
||||||
|
AAOCAQ8AMIIBCgKCAQEAwVOMwUDfBtsH0XuxYnb+v/L774jMH8valX7RPH8cl2Lb
|
||||||
|
SiqSo0RchW2RGA2d1yuYHlpChC9jGmt0X/g66/E/+q2hUJlfJtqVDJFwtFYV4u2S
|
||||||
|
yzA3J36V4PRkPQrKxAsbzZriFXAF10XgiHQz9aVeMMJ9GBhmh9+DK8Tm4cMF6i8l
|
||||||
|
+AuC35KdngPF1x0ealTYrYZplpEJFO7CiW42aLi6vQkDR2R7nmZA4AT69teqBWsK
|
||||||
|
0DZ93/f0G/3+vnWwNTBF0lB6dIXoaz8OMSyHLqGnmmAtMrzbjAr/O/WWgbB/BqhR
|
||||||
|
qjJQ7Ui16cuDldXaWQ/rkMzsxmsAox0UF+zdQNvXUQIDAQABo4IDBDCCAwAwgccG
|
||||||
|
A1UdEgSBvzCBvIYVaHR0cDovL3d3dy5pemVucGUuY29tgQ9pbmZvQGl6ZW5wZS5j
|
||||||
|
b22kgZEwgY4xRzBFBgNVBAoMPklaRU5QRSBTLkEuIC0gQ0lGIEEwMTMzNzI2MC1S
|
||||||
|
TWVyYy5WaXRvcmlhLUdhc3RlaXogVDEwNTUgRjYyIFM4MUMwQQYDVQQJDDpBdmRh
|
||||||
|
IGRlbCBNZWRpdGVycmFuZW8gRXRvcmJpZGVhIDE0IC0gMDEwMTAgVml0b3JpYS1H
|
||||||
|
YXN0ZWl6MB4GA1UdEQQXMBWBE2ZpY3RpY2lvQGl6ZW5wZS5ldXMwDgYDVR0PAQH/
|
||||||
|
BAQDAgXgMCkGA1UdJQQiMCAGCCsGAQUFBwMCBggrBgEFBQcDBAYKKwYBBAGCNxQC
|
||||||
|
AjAdBgNVHQ4EFgQUyeoOD4cgcljKY0JvrNuX2waFQLAwHwYDVR0jBBgwFoAUwKlK
|
||||||
|
90clh/+8taaJzoLSRqiJ66MwggEnBgNVHSAEggEeMIIBGjCCARYGCisGAQQB8zkB
|
||||||
|
AQEwggEGMDMGCCsGAQUFBwIBFidodHRwOi8vd3d3Lml6ZW5wZS5jb20vcnBhc2Nh
|
||||||
|
Y29ycG9yYXRpdm8wgc4GCCsGAQUFBwICMIHBGoG+Wml1cnRhZ2lyaWEgRXVza2Fs
|
||||||
|
IEF1dG9ub21pYSBFcmtpZGVnb2tvIHNla3RvcmUgcHVibGlrb2tvIGVyYWt1bmRl
|
||||||
|
ZW4gYmFybmUtc2FyZWV0YW4gYmFrYXJyaWsgZXJhYmlsIGRhaXRla2UuIFVzbyBy
|
||||||
|
ZXN0cmluZ2lkbyBhbCBhbWJpdG8gZGUgcmVkZXMgaW50ZXJuYXMgZGUgRW50aWRh
|
||||||
|
ZGVzIGRlbCBTZWN0b3IgUHVibGljbyBWYXNjbzAyBggrBgEFBQcBAQQmMCQwIgYI
|
||||||
|
KwYBBQUHMAGGFmh0dHA6Ly9vY3NwLml6ZW5wZS5jb20wOgYDVR0fBDMwMTAvoC2g
|
||||||
|
K4YpaHR0cDovL2NybC5pemVucGUuY29tL2NnaS1iaW4vY3JsaW50ZXJuYTIwDQYJ
|
||||||
|
KoZIhvcNAQELBQADggIBAIy5PQ+UZlCRq6ig43vpHwlwuD9daAYeejV0Q+ZbgWAE
|
||||||
|
GtO0kT/ytw95ZEJMNiMw3fYfPRlh27ThqiT0VDXZJDlzmn7JZd6QFcdXkCsiuv4+
|
||||||
|
ZoXAg/QwnA3SGUUO9aVaXyuOIIuvOfb9MzoGp9xk23SMV3eiLAaLMLqwB5DTfBdt
|
||||||
|
BGI7L1MnGJBv8RfP/TL67aJ5bgq2ri4S8vGHtXSjcZ0+rCEOLJtmDNMnTZxancg3
|
||||||
|
/H5edeNd+n6Z48LO+JHRxQufbC4mVNxVLMIP9EkGUejlq4E4w6zb5NwCQczJbSWL
|
||||||
|
i31rk2orsNsDlyaLGsWZp3JSNX6RmodU4KAUPor4jUJuUhrrm3Spb73gKlV/gcIw
|
||||||
|
bCE7mML1Kss3x1ySaXsis6SZtLpGWKkW2iguPWPs0ydV6RPhmsCxieMwPPIJ87vS
|
||||||
|
5IejfgyBae7RSuAIHyNFy4uI5xwvwUFf6OZ7az8qtW7ImFOgng3Ds+W9k1S2CNTx
|
||||||
|
d0cnKTfA6IpjGo8EeHcxnIXT8NPImWaRj0qqonvYady7ci6U4m3lkNSdXNn1afgw
|
||||||
|
mYust+gxVtOZs1gk2MUCgJ1V1X+g7r/Cg7viIn6TLkLrpS1kS1hvMqkl9M+7XqPo
|
||||||
|
Qd95nJKOkusQpy99X4dF/lfbYAQnnjnqh3DLD2gvYObXFaAYFaiBKTiMTV2X72F+
|
||||||
|
-----END CERTIFICATE-----`
|
||||||
|
|
||||||
|
const smimeIntermediate = `-----BEGIN CERTIFICATE-----
|
||||||
|
MIIHNzCCBSGgAwIBAgIQJMXIqlZvjuhMvqcFXOFkpDALBgkqhkiG9w0BAQswODEL
|
||||||
|
MAkGA1UEBhMCRVMxFDASBgNVBAoMC0laRU5QRSBTLkEuMRMwEQYDVQQDDApJemVu
|
||||||
|
cGUuY29tMB4XDTEwMTAyMDA4MjMzM1oXDTM3MTIxMjIzMDAwMFowgZ0xCzAJBgNV
|
||||||
|
BAYTAkVTMRQwEgYDVQQKDAtJWkVOUEUgUy5BLjE6MDgGA1UECwwxQVpaIFppdXJ0
|
||||||
|
YWdpcmkgcHVibGlrb2EgLSBDZXJ0aWZpY2FkbyBwdWJsaWNvIFNDQTE8MDoGA1UE
|
||||||
|
AwwzRUFFa28gSGVycmkgQWRtaW5pc3RyYXppb2VuIENBIC0gQ0EgQUFQUCBWYXNj
|
||||||
|
YXMgKDIpMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAoIM7nEdI0N1h
|
||||||
|
rR5T4xuV/usKDoMIasaiKvfLhbwxaNtTt+a7W/6wV5bv3svQFIy3sUXjjdzV1nG2
|
||||||
|
To2wo/YSPQiOt8exWvOapvL21ogiof+kelWnXFjWaKJI/vThHYLgIYEMj/y4HdtU
|
||||||
|
ojI646rZwqsb4YGAopwgmkDfUh5jOhV2IcYE3TgJAYWVkj6jku9PLaIsHiarAHjD
|
||||||
|
PY8dig8a4SRv0gm5Yk7FXLmW1d14oxQBDeHZ7zOEXfpafxdEDO2SNaRJjpkh8XRr
|
||||||
|
PGqkg2y1Q3gT6b4537jz+StyDIJ3omylmlJsGCwqT7p8mEqjGJ5kC5I2VnjXKuNn
|
||||||
|
soShc72khWZVUJiJo5SGuAkNE2ZXqltBVm5Jv6QweQKsX6bkcMc4IZok4a+hx8FM
|
||||||
|
8IBpGf/I94pU6HzGXqCyc1d46drJgDY9mXa+6YDAJFl3xeXOOW2iGCfwXqhiCrKL
|
||||||
|
MYvyMZzqF3QH5q4nb3ZnehYvraeMFXJXDn+Utqp8vd2r7ShfQJz01KtM4hgKdgSg
|
||||||
|
jtW+shkVVN5ng/fPN85ovfAH2BHXFfHmQn4zKsYnLitpwYM/7S1HxlT61cdQ7Nnk
|
||||||
|
3LZTYEgAoOmEmdheklT40WAYakksXGM5VrzG7x9S7s1Tm+Vb5LSThdHC8bxxwyTb
|
||||||
|
KsDRDNJ84N9fPDO6qHnzaL2upQ43PycCAwEAAaOCAdkwggHVMIHHBgNVHREEgb8w
|
||||||
|
gbyGFWh0dHA6Ly93d3cuaXplbnBlLmNvbYEPaW5mb0BpemVucGUuY29tpIGRMIGO
|
||||||
|
MUcwRQYDVQQKDD5JWkVOUEUgUy5BLiAtIENJRiBBMDEzMzcyNjAtUk1lcmMuVml0
|
||||||
|
b3JpYS1HYXN0ZWl6IFQxMDU1IEY2MiBTODFDMEEGA1UECQw6QXZkYSBkZWwgTWVk
|
||||||
|
aXRlcnJhbmVvIEV0b3JiaWRlYSAxNCAtIDAxMDEwIFZpdG9yaWEtR2FzdGVpejAP
|
||||||
|
BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUwKlK90cl
|
||||||
|
h/+8taaJzoLSRqiJ66MwHwYDVR0jBBgwFoAUHRxlDqjyJXu0kc/ksbHmvVV0bAUw
|
||||||
|
OgYDVR0gBDMwMTAvBgRVHSAAMCcwJQYIKwYBBQUHAgEWGWh0dHA6Ly93d3cuaXpl
|
||||||
|
bnBlLmNvbS9jcHMwNwYIKwYBBQUHAQEEKzApMCcGCCsGAQUFBzABhhtodHRwOi8v
|
||||||
|
b2NzcC5pemVucGUuY29tOjgwOTQwMwYDVR0fBCwwKjAooCagJIYiaHR0cDovL2Ny
|
||||||
|
bC5pemVucGUuY29tL2NnaS1iaW4vYXJsMjALBgkqhkiG9w0BAQsDggIBAMbjc3HM
|
||||||
|
3DG9ubWPkzsF0QsktukpujbTTcGk4h20G7SPRy1DiiTxrRzdAMWGjZioOP3/fKCS
|
||||||
|
M539qH0M+gsySNie+iKlbSZJUyE635T1tKw+G7bDUapjlH1xyv55NC5I6wCXGC6E
|
||||||
|
3TEP5B/E7dZD0s9E4lS511ubVZivFgOzMYo1DO96diny/N/V1enaTCpRl1qH1OyL
|
||||||
|
xUYTijV4ph2gL6exwuG7pxfRcVNHYlrRaXWfTz3F6NBKyULxrI3P/y6JAtN1GqT4
|
||||||
|
VF/+vMygx22n0DufGepBwTQz6/rr1ulSZ+eMnuJiTXgh/BzQnkUsXTb8mHII25iR
|
||||||
|
0oYF2qAsk6ecWbLiDpkHKIDHmML21MZE13MS8NSvTHoqJO4LyAmDe6SaeNHtrPlK
|
||||||
|
b6mzE1BN2ug+ZaX8wLA5IMPFaf0jKhb/Cxu8INsxjt00brsErCc9ip1VNaH0M4bi
|
||||||
|
1tGxfiew2436FaeyUxW7Pl6G5GgkNbuUc7QIoRy06DdU/U38BxW3uyJMY60zwHvS
|
||||||
|
FlKAn0OvYp4niKhAJwaBVN3kowmJuOU5Rid+TUnfyxbJ9cttSgzaF3hP/N4zgMEM
|
||||||
|
5tikXUskeckt8LUK96EH0QyssavAMECUEb/xrupyRdYWwjQGvNLq6T5+fViDGyOw
|
||||||
|
k+lzD44wofy8paAy9uC9Owae0zMEzhcsyRm7
|
||||||
|
-----END CERTIFICATE-----`
|
||||||
|
|
||||||
|
const smimeRoot = `-----BEGIN CERTIFICATE-----
|
||||||
|
MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4
|
||||||
|
MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6
|
||||||
|
ZW5wZS5jb20wHhcNMDcxMjEzMTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYD
|
||||||
|
VQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5j
|
||||||
|
b20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ03rKDx6sp4boFmVq
|
||||||
|
scIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAKClaO
|
||||||
|
xdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6H
|
||||||
|
LmYRY2xU+zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFX
|
||||||
|
uaOKmMPsOzTFlUFpfnXCPCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQD
|
||||||
|
yCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxTOTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+
|
||||||
|
JrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbKF7jJeodWLBoBHmy+E60Q
|
||||||
|
rLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK0GqfvEyN
|
||||||
|
BjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8L
|
||||||
|
hij+0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIB
|
||||||
|
QFqNeb+Lz0vPqhbBleStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+
|
||||||
|
HMh3/1uaD7euBUbl8agW7EekFwIDAQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2lu
|
||||||
|
Zm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+SVpFTlBFIFMuQS4gLSBDSUYg
|
||||||
|
QTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBGNjIgUzgxQzBB
|
||||||
|
BgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx
|
||||||
|
MCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
|
||||||
|
AQYwHQYDVR0OBBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUA
|
||||||
|
A4ICAQB4pgwWSp9MiDrAyw6lFn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWb
|
||||||
|
laQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbgakEyrkgPH7UIBzg/YsfqikuFgba56
|
||||||
|
awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8qhT/AQKM6WfxZSzwo
|
||||||
|
JNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Csg1lw
|
||||||
|
LDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCT
|
||||||
|
VyvehQP5aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGk
|
||||||
|
LhObNA5me0mrZJfQRsN5nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJb
|
||||||
|
UjWumDqtujWTI6cfSN01RpiyEGjkpTHCClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/
|
||||||
|
QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZoQ0iy2+tzJOeRf1SktoA+
|
||||||
|
naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1ZWrOZyGls
|
||||||
|
QyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw==
|
||||||
|
-----END CERTIFICATE-----`
|
||||||
@@ -12,6 +12,8 @@ import (
|
|||||||
"encoding/pem"
|
"encoding/pem"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math/big"
|
"math/big"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Path interface {
|
type Path interface {
|
||||||
@@ -56,6 +58,33 @@ func LoadTLSKeyPair(certificate, privateKey string, path Path) (tls.Certificate,
|
|||||||
return cert, nil
|
return cert, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func LoadCertificates(certificate string, path Path) (*x509.CertPool, error) {
|
||||||
|
pool := x509.NewCertPool()
|
||||||
|
if pool.AppendCertsFromPEM([]byte(certificate)) {
|
||||||
|
return pool, nil
|
||||||
|
}
|
||||||
|
painTextErr := fmt.Errorf("invalid certificate: %s", certificate)
|
||||||
|
if path == nil {
|
||||||
|
return nil, painTextErr
|
||||||
|
}
|
||||||
|
|
||||||
|
certificate = path.Resolve(certificate)
|
||||||
|
var loadErr error
|
||||||
|
if !path.IsSafePath(certificate) {
|
||||||
|
loadErr = path.ErrNotSafePath(certificate)
|
||||||
|
} else {
|
||||||
|
certPEMBlock, err := os.ReadFile(certificate)
|
||||||
|
if pool.AppendCertsFromPEM(certPEMBlock) {
|
||||||
|
return pool, nil
|
||||||
|
}
|
||||||
|
loadErr = err
|
||||||
|
}
|
||||||
|
if loadErr != nil {
|
||||||
|
return nil, fmt.Errorf("parse certificate failed, maybe format error:%s, or path error: %s", painTextErr.Error(), loadErr.Error())
|
||||||
|
}
|
||||||
|
return pool, nil
|
||||||
|
}
|
||||||
|
|
||||||
type KeyPairType string
|
type KeyPairType string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -85,7 +114,11 @@ func NewRandomTLSKeyPair(keyPairType KeyPairType) (certificate string, privateKe
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
template := x509.Certificate{SerialNumber: big.NewInt(1)}
|
template := x509.Certificate{
|
||||||
|
SerialNumber: big.NewInt(1),
|
||||||
|
NotBefore: time.Now().Add(-time.Hour * 24 * 365),
|
||||||
|
NotAfter: time.Now().Add(time.Hour * 24 * 365),
|
||||||
|
}
|
||||||
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, key.Public(), key)
|
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, key.Public(), key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -21,10 +21,10 @@ func bindControl(ifaceIdx int) controlFn {
|
|||||||
var innerErr error
|
var innerErr error
|
||||||
err = c.Control(func(fd uintptr) {
|
err = c.Control(func(fd uintptr) {
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "udp4":
|
case "tcp6", "udp6", "ip6":
|
||||||
innerErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, ifaceIdx)
|
|
||||||
case "tcp6", "udp6":
|
|
||||||
innerErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, ifaceIdx)
|
innerErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, ifaceIdx)
|
||||||
|
default:
|
||||||
|
innerErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, ifaceIdx)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/keepalive"
|
"github.com/metacubex/mihomo/component/keepalive"
|
||||||
@@ -177,6 +178,34 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
|||||||
return dialer.DialContext(ctx, network, address)
|
return dialer.DialContext(ctx, network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ICMPControl(destination netip.Addr) func(network, address string, conn syscall.RawConn) error {
|
||||||
|
return func(network, address string, conn syscall.RawConn) error {
|
||||||
|
if DefaultSocketHook != nil {
|
||||||
|
return DefaultSocketHook(network, address, conn)
|
||||||
|
}
|
||||||
|
dialer := &net.Dialer{}
|
||||||
|
interfaceName := DefaultInterface.Load()
|
||||||
|
if interfaceName == "" {
|
||||||
|
if finder := DefaultInterfaceFinder.Load(); finder != nil {
|
||||||
|
interfaceName = finder.FindInterfaceName(destination)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if interfaceName != "" {
|
||||||
|
if err := bindIfaceToDialer(interfaceName, dialer, network, destination); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
routingMark := int(DefaultRoutingMark.Load())
|
||||||
|
if routingMark != 0 {
|
||||||
|
bindMarkToDialer(routingMark, dialer, network, destination)
|
||||||
|
}
|
||||||
|
if dialer.ControlContext != nil {
|
||||||
|
return dialer.ControlContext(context.TODO(), network, address, conn)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func serialSingleStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt option) (net.Conn, error) {
|
func serialSingleStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt option) (net.Conn, error) {
|
||||||
return serialDialContext(ctx, network, ips, port, opt)
|
return serialDialContext(ctx, network, ips, port, opt)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,6 +50,10 @@ func (c *cachefileStore) FlushFakeIP() error {
|
|||||||
return c.cache.FlushFakeIP()
|
return c.cache.FlushFakeIP()
|
||||||
}
|
}
|
||||||
|
|
||||||
func newCachefileStore(cache *cachefile.CacheFile) *cachefileStore {
|
func newCachefileStore(cache *cachefile.CacheFile, prefix netip.Prefix) *cachefileStore {
|
||||||
return &cachefileStore{cache.FakeIpStore()}
|
if prefix.Addr().Is6() {
|
||||||
|
return &cachefileStore{cache.FakeIpStore6()}
|
||||||
|
} else {
|
||||||
|
return &cachefileStore{cache.FakeIpStore()}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/profile/cachefile"
|
"github.com/metacubex/mihomo/component/profile/cachefile"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
|
|
||||||
"go4.org/netipx"
|
"go4.org/netipx"
|
||||||
)
|
)
|
||||||
@@ -36,8 +35,6 @@ type Pool struct {
|
|||||||
offset netip.Addr
|
offset netip.Addr
|
||||||
cycle bool
|
cycle bool
|
||||||
mux sync.Mutex
|
mux sync.Mutex
|
||||||
host []C.DomainMatcher
|
|
||||||
mode C.FilterMode
|
|
||||||
ipnet netip.Prefix
|
ipnet netip.Prefix
|
||||||
store store
|
store store
|
||||||
}
|
}
|
||||||
@@ -66,24 +63,6 @@ func (p *Pool) LookBack(ip netip.Addr) (string, bool) {
|
|||||||
return p.store.GetByIP(ip)
|
return p.store.GetByIP(ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ShouldSkipped return if domain should be skipped
|
|
||||||
func (p *Pool) ShouldSkipped(domain string) bool {
|
|
||||||
should := p.shouldSkipped(domain)
|
|
||||||
if p.mode == C.FilterWhiteList {
|
|
||||||
return !should
|
|
||||||
}
|
|
||||||
return should
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Pool) shouldSkipped(domain string) bool {
|
|
||||||
for _, matcher := range p.host {
|
|
||||||
if matcher.MatchDomain(domain) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exist returns if given ip exists in fake-ip pool
|
// Exist returns if given ip exists in fake-ip pool
|
||||||
func (p *Pool) Exist(ip netip.Addr) bool {
|
func (p *Pool) Exist(ip netip.Addr) bool {
|
||||||
p.mux.Lock()
|
p.mux.Lock()
|
||||||
@@ -166,8 +145,6 @@ func (p *Pool) restoreState() {
|
|||||||
|
|
||||||
type Options struct {
|
type Options struct {
|
||||||
IPNet netip.Prefix
|
IPNet netip.Prefix
|
||||||
Host []C.DomainMatcher
|
|
||||||
Mode C.FilterMode
|
|
||||||
|
|
||||||
// Size sets the maximum number of entries in memory
|
// Size sets the maximum number of entries in memory
|
||||||
// and does not work if Persistence is true
|
// and does not work if Persistence is true
|
||||||
@@ -197,12 +174,10 @@ func New(options Options) (*Pool, error) {
|
|||||||
last: last,
|
last: last,
|
||||||
offset: first.Prev(),
|
offset: first.Prev(),
|
||||||
cycle: false,
|
cycle: false,
|
||||||
host: options.Host,
|
|
||||||
mode: options.Mode,
|
|
||||||
ipnet: options.IPNet,
|
ipnet: options.IPNet,
|
||||||
}
|
}
|
||||||
if options.Persistence {
|
if options.Persistence {
|
||||||
pool.store = newCachefileStore(cachefile.Cache())
|
pool.store = newCachefileStore(cachefile.Cache(), options.IPNet)
|
||||||
} else {
|
} else {
|
||||||
pool.store = newMemoryStore(options.Size)
|
pool.store = newMemoryStore(options.Size)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,8 +8,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/profile/cachefile"
|
"github.com/metacubex/mihomo/component/profile/cachefile"
|
||||||
"github.com/metacubex/mihomo/component/trie"
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
|
|
||||||
"github.com/metacubex/bbolt"
|
"github.com/metacubex/bbolt"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
@@ -43,7 +41,7 @@ func createCachefileStore(options Options) (*Pool, string, error) {
|
|||||||
return nil, "", err
|
return nil, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
pool.store = newCachefileStore(&cachefile.CacheFile{DB: db})
|
pool.store = newCachefileStore(&cachefile.CacheFile{DB: db}, options.IPNet)
|
||||||
return pool, f.Name(), nil
|
return pool, f.Name(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,47 +144,6 @@ func TestPool_CycleUsed(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPool_Skip(t *testing.T) {
|
|
||||||
ipnet := netip.MustParsePrefix("192.168.0.1/29")
|
|
||||||
tree := trie.New[struct{}]()
|
|
||||||
assert.NoError(t, tree.Insert("example.com", struct{}{}))
|
|
||||||
assert.False(t, tree.IsEmpty())
|
|
||||||
pools, tempfile, err := createPools(Options{
|
|
||||||
IPNet: ipnet,
|
|
||||||
Size: 10,
|
|
||||||
Host: []C.DomainMatcher{tree.NewDomainSet()},
|
|
||||||
})
|
|
||||||
assert.Nil(t, err)
|
|
||||||
defer os.Remove(tempfile)
|
|
||||||
|
|
||||||
for _, pool := range pools {
|
|
||||||
assert.True(t, pool.ShouldSkipped("example.com"))
|
|
||||||
assert.False(t, pool.ShouldSkipped("foo.com"))
|
|
||||||
assert.False(t, pool.shouldSkipped("baz.com"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPool_SkipWhiteList(t *testing.T) {
|
|
||||||
ipnet := netip.MustParsePrefix("192.168.0.1/29")
|
|
||||||
tree := trie.New[struct{}]()
|
|
||||||
assert.NoError(t, tree.Insert("example.com", struct{}{}))
|
|
||||||
assert.False(t, tree.IsEmpty())
|
|
||||||
pools, tempfile, err := createPools(Options{
|
|
||||||
IPNet: ipnet,
|
|
||||||
Size: 10,
|
|
||||||
Host: []C.DomainMatcher{tree.NewDomainSet()},
|
|
||||||
Mode: C.FilterWhiteList,
|
|
||||||
})
|
|
||||||
assert.Nil(t, err)
|
|
||||||
defer os.Remove(tempfile)
|
|
||||||
|
|
||||||
for _, pool := range pools {
|
|
||||||
assert.False(t, pool.ShouldSkipped("example.com"))
|
|
||||||
assert.True(t, pool.ShouldSkipped("foo.com"))
|
|
||||||
assert.True(t, pool.ShouldSkipped("baz.com"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPool_MaxCacheSize(t *testing.T) {
|
func TestPool_MaxCacheSize(t *testing.T) {
|
||||||
ipnet := netip.MustParsePrefix("192.168.0.1/24")
|
ipnet := netip.MustParsePrefix("192.168.0.1/24")
|
||||||
pool, _ := New(Options{
|
pool, _ := New(Options{
|
||||||
|
|||||||
28
component/fakeip/skipper.go
Normal file
28
component/fakeip/skipper.go
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
package fakeip
|
||||||
|
|
||||||
|
import (
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Skipper struct {
|
||||||
|
Host []C.DomainMatcher
|
||||||
|
Mode C.FilterMode
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldSkipped return if domain should be skipped
|
||||||
|
func (p *Skipper) ShouldSkipped(domain string) bool {
|
||||||
|
should := p.shouldSkipped(domain)
|
||||||
|
if p.Mode == C.FilterWhiteList {
|
||||||
|
return !should
|
||||||
|
}
|
||||||
|
return should
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Skipper) shouldSkipped(domain string) bool {
|
||||||
|
for _, matcher := range p.Host {
|
||||||
|
if matcher.MatchDomain(domain) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
35
component/fakeip/skipper_test.go
Normal file
35
component/fakeip/skipper_test.go
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
package fakeip
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/component/trie"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSkipper_BlackList(t *testing.T) {
|
||||||
|
tree := trie.New[struct{}]()
|
||||||
|
assert.NoError(t, tree.Insert("example.com", struct{}{}))
|
||||||
|
assert.False(t, tree.IsEmpty())
|
||||||
|
skipper := &Skipper{
|
||||||
|
Host: []C.DomainMatcher{tree.NewDomainSet()},
|
||||||
|
}
|
||||||
|
assert.True(t, skipper.ShouldSkipped("example.com"))
|
||||||
|
assert.False(t, skipper.ShouldSkipped("foo.com"))
|
||||||
|
assert.False(t, skipper.shouldSkipped("baz.com"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSkipper_WhiteList(t *testing.T) {
|
||||||
|
tree := trie.New[struct{}]()
|
||||||
|
assert.NoError(t, tree.Insert("example.com", struct{}{}))
|
||||||
|
assert.False(t, tree.IsEmpty())
|
||||||
|
skipper := &Skipper{
|
||||||
|
Host: []C.DomainMatcher{tree.NewDomainSet()},
|
||||||
|
Mode: C.FilterWhiteList,
|
||||||
|
}
|
||||||
|
assert.False(t, skipper.ShouldSkipped("example.com"))
|
||||||
|
assert.True(t, skipper.ShouldSkipped("foo.com"))
|
||||||
|
assert.True(t, skipper.ShouldSkipped("baz.com"))
|
||||||
|
}
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
package generater
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/base64"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/ech"
|
|
||||||
|
|
||||||
"github.com/gofrs/uuid/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Main(args []string) {
|
|
||||||
if len(args) < 1 {
|
|
||||||
panic("Using: generate uuid/reality-keypair/wg-keypair/ech-keypair")
|
|
||||||
}
|
|
||||||
switch args[0] {
|
|
||||||
case "uuid":
|
|
||||||
newUUID, err := uuid.NewV4()
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
fmt.Println(newUUID.String())
|
|
||||||
case "reality-keypair":
|
|
||||||
privateKey, err := GeneratePrivateKey()
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
publicKey := privateKey.PublicKey()
|
|
||||||
fmt.Println("PrivateKey: " + base64.RawURLEncoding.EncodeToString(privateKey[:]))
|
|
||||||
fmt.Println("PublicKey: " + base64.RawURLEncoding.EncodeToString(publicKey[:]))
|
|
||||||
case "wg-keypair":
|
|
||||||
privateKey, err := GeneratePrivateKey()
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
fmt.Println("PrivateKey: " + privateKey.String())
|
|
||||||
fmt.Println("PublicKey: " + privateKey.PublicKey().String())
|
|
||||||
case "ech-keypair":
|
|
||||||
if len(args) < 2 {
|
|
||||||
panic("Using: generate ech-keypair <plain_server_name>")
|
|
||||||
}
|
|
||||||
configBase64, keyPem, err := ech.GenECHConfig(args[1])
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
fmt.Println("Config:", configBase64)
|
|
||||||
fmt.Println("Key:", keyPem)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
// Copy from https://github.com/WireGuard/wgctrl-go/blob/a9ab2273dd1075ea74b88c76f8757f8b4003fcbf/wgtypes/types.go#L71-L155
|
|
||||||
|
|
||||||
package generater
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"encoding/base64"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"golang.org/x/crypto/curve25519"
|
|
||||||
)
|
|
||||||
|
|
||||||
// KeyLen is the expected key length for a WireGuard key.
|
|
||||||
const KeyLen = 32 // wgh.KeyLen
|
|
||||||
|
|
||||||
// A Key is a public, private, or pre-shared secret key. The Key constructor
|
|
||||||
// functions in this package can be used to create Keys suitable for each of
|
|
||||||
// these applications.
|
|
||||||
type Key [KeyLen]byte
|
|
||||||
|
|
||||||
// GenerateKey generates a Key suitable for use as a pre-shared secret key from
|
|
||||||
// a cryptographically safe source.
|
|
||||||
//
|
|
||||||
// The output Key should not be used as a private key; use GeneratePrivateKey
|
|
||||||
// instead.
|
|
||||||
func GenerateKey() (Key, error) {
|
|
||||||
b := make([]byte, KeyLen)
|
|
||||||
if _, err := rand.Read(b); err != nil {
|
|
||||||
return Key{}, fmt.Errorf("wgtypes: failed to read random bytes: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewKey(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GeneratePrivateKey generates a Key suitable for use as a private key from a
|
|
||||||
// cryptographically safe source.
|
|
||||||
func GeneratePrivateKey() (Key, error) {
|
|
||||||
key, err := GenerateKey()
|
|
||||||
if err != nil {
|
|
||||||
return Key{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Modify random bytes using algorithm described at:
|
|
||||||
// https://cr.yp.to/ecdh.html.
|
|
||||||
key[0] &= 248
|
|
||||||
key[31] &= 127
|
|
||||||
key[31] |= 64
|
|
||||||
|
|
||||||
return key, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewKey creates a Key from an existing byte slice. The byte slice must be
|
|
||||||
// exactly 32 bytes in length.
|
|
||||||
func NewKey(b []byte) (Key, error) {
|
|
||||||
if len(b) != KeyLen {
|
|
||||||
return Key{}, fmt.Errorf("wgtypes: incorrect key size: %d", len(b))
|
|
||||||
}
|
|
||||||
|
|
||||||
var k Key
|
|
||||||
copy(k[:], b)
|
|
||||||
|
|
||||||
return k, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParseKey parses a Key from a base64-encoded string, as produced by the
|
|
||||||
// Key.String method.
|
|
||||||
func ParseKey(s string) (Key, error) {
|
|
||||||
b, err := base64.StdEncoding.DecodeString(s)
|
|
||||||
if err != nil {
|
|
||||||
return Key{}, fmt.Errorf("wgtypes: failed to parse base64-encoded key: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewKey(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PublicKey computes a public key from the private key k.
|
|
||||||
//
|
|
||||||
// PublicKey should only be called when k is a private key.
|
|
||||||
func (k Key) PublicKey() Key {
|
|
||||||
var (
|
|
||||||
pub [KeyLen]byte
|
|
||||||
priv = [KeyLen]byte(k)
|
|
||||||
)
|
|
||||||
|
|
||||||
// ScalarBaseMult uses the correct base value per https://cr.yp.to/ecdh.html,
|
|
||||||
// so no need to specify it.
|
|
||||||
curve25519.ScalarBaseMult(&pub, &priv)
|
|
||||||
|
|
||||||
return Key(pub)
|
|
||||||
}
|
|
||||||
|
|
||||||
// String returns the base64-encoded string representation of a Key.
|
|
||||||
//
|
|
||||||
// ParseKey can be used to produce a new Key from this string.
|
|
||||||
func (k Key) String() string {
|
|
||||||
return base64.StdEncoding.EncodeToString(k[:])
|
|
||||||
}
|
|
||||||
73
component/generator/cmd.go
Normal file
73
component/generator/cmd.go
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
package generator
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/component/ech"
|
||||||
|
"github.com/metacubex/mihomo/transport/vless/encryption"
|
||||||
|
|
||||||
|
"github.com/gofrs/uuid/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Main(args []string) {
|
||||||
|
if len(args) < 1 {
|
||||||
|
panic("Using: generate uuid/reality-keypair/wg-keypair/ech-keypair/vless-mlkem768/vless-x25519")
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "uuid":
|
||||||
|
newUUID, err := uuid.NewV4()
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Println(newUUID.String())
|
||||||
|
case "reality-keypair":
|
||||||
|
privateKey, err := GenX25519PrivateKey()
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Println("PrivateKey: " + base64.RawURLEncoding.EncodeToString(privateKey.Bytes()))
|
||||||
|
fmt.Println("PublicKey: " + base64.RawURLEncoding.EncodeToString(privateKey.PublicKey().Bytes()))
|
||||||
|
case "wg-keypair":
|
||||||
|
privateKey, err := GenX25519PrivateKey()
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Println("PrivateKey: " + base64.StdEncoding.EncodeToString(privateKey.Bytes()))
|
||||||
|
fmt.Println("PublicKey: " + base64.StdEncoding.EncodeToString(privateKey.PublicKey().Bytes()))
|
||||||
|
case "ech-keypair":
|
||||||
|
if len(args) < 2 {
|
||||||
|
panic("Using: generate ech-keypair <plain_server_name>")
|
||||||
|
}
|
||||||
|
configBase64, keyPem, err := ech.GenECHConfig(args[1])
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Println("Config:", configBase64)
|
||||||
|
fmt.Println("Key:", keyPem)
|
||||||
|
case "vless-mlkem768":
|
||||||
|
var seed string
|
||||||
|
if len(args) > 1 {
|
||||||
|
seed = args[1]
|
||||||
|
}
|
||||||
|
seedBase64, clientBase64, hash32Base64, err := encryption.GenMLKEM768(seed)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Println("Seed: " + seedBase64)
|
||||||
|
fmt.Println("Client: " + clientBase64)
|
||||||
|
fmt.Println("Hash32: " + hash32Base64)
|
||||||
|
case "vless-x25519":
|
||||||
|
var privateKey string
|
||||||
|
if len(args) > 1 {
|
||||||
|
privateKey = args[1]
|
||||||
|
}
|
||||||
|
privateKeyBase64, passwordBase64, hash32Base64, err := encryption.GenX25519(privateKey)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Println("PrivateKey: " + privateKeyBase64)
|
||||||
|
fmt.Println("Password: " + passwordBase64)
|
||||||
|
fmt.Println("Hash32: " + hash32Base64)
|
||||||
|
}
|
||||||
|
}
|
||||||
27
component/generator/x25519.go
Normal file
27
component/generator/x25519.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package generator
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdh"
|
||||||
|
"crypto/rand"
|
||||||
|
)
|
||||||
|
|
||||||
|
const X25519KeySize = 32
|
||||||
|
|
||||||
|
func GenX25519PrivateKey() (*ecdh.PrivateKey, error) {
|
||||||
|
var privateKey [X25519KeySize]byte
|
||||||
|
_, err := rand.Read(privateKey[:])
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Avoid generating equivalent X25519 private keys
|
||||||
|
// https://github.com/XTLS/Xray-core/pull/1747
|
||||||
|
//
|
||||||
|
// Modify random bytes using algorithm described at:
|
||||||
|
// https://cr.yp.to/ecdh.html.
|
||||||
|
privateKey[0] &= 248
|
||||||
|
privateKey[31] &= 127
|
||||||
|
privateKey[31] |= 64
|
||||||
|
|
||||||
|
return ecdh.X25519().NewPrivateKey(privateKey[:])
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@ package http
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -28,11 +27,11 @@ func SetUA(UA string) {
|
|||||||
ua = UA
|
ua = UA
|
||||||
}
|
}
|
||||||
|
|
||||||
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, options ...Option) (*http.Response, error) {
|
||||||
return HttpRequestWithProxy(ctx, url, method, header, body, "")
|
opt := option{}
|
||||||
}
|
for _, o := range options {
|
||||||
|
o(&opt)
|
||||||
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 {
|
||||||
@@ -40,6 +39,10 @@ func HttpRequestWithProxy(ctx context.Context, url, method string, header map[st
|
|||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequest(method, urlRes.String(), body)
|
req, err := http.NewRequest(method, urlRes.String(), body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
for k, v := range header {
|
for k, v := range header {
|
||||||
for _, v := range v {
|
for _, v := range v {
|
||||||
req.Header.Add(k, v)
|
req.Header.Add(k, v)
|
||||||
@@ -50,10 +53,6 @@ func HttpRequestWithProxy(ctx context.Context, url, method string, header map[st
|
|||||||
req.Header.Set("User-Agent", UA())
|
req.Header.Set("User-Agent", UA())
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if user := urlRes.User; user != nil {
|
if user := urlRes.User; user != nil {
|
||||||
password, _ := user.Password()
|
password, _ := user.Password()
|
||||||
req.SetBasicAuth(user.Username(), password)
|
req.SetBasicAuth(user.Username(), password)
|
||||||
@@ -61,6 +60,11 @@ func HttpRequestWithProxy(ctx context.Context, url, method string, header map[st
|
|||||||
|
|
||||||
req = req.WithContext(ctx)
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
|
tlsConfig, err := ca.GetTLSConfig(opt.caOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
transport := &http.Transport{
|
transport := &http.Transport{
|
||||||
// from http.DefaultTransport
|
// from http.DefaultTransport
|
||||||
DisableKeepAlives: runtime.GOOS == "android",
|
DisableKeepAlives: runtime.GOOS == "android",
|
||||||
@@ -69,15 +73,34 @@ func HttpRequestWithProxy(ctx context.Context, url, method string, header map[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(inner.GetTunnel(), address, specialProxy); err == nil {
|
if conn, err := inner.HandleTcp(inner.GetTunnel(), address, opt.specialProxy); err == nil {
|
||||||
return conn, nil
|
return conn, nil
|
||||||
} else {
|
} else {
|
||||||
return dialer.DialContext(ctx, network, address)
|
return dialer.DialContext(ctx, network, address)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
TLSClientConfig: ca.GetGlobalTLSConfig(&tls.Config{}),
|
TLSClientConfig: tlsConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{Transport: transport}
|
client := http.Client{Transport: transport}
|
||||||
return client.Do(req)
|
return client.Do(req)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Option func(opt *option)
|
||||||
|
|
||||||
|
type option struct {
|
||||||
|
specialProxy string
|
||||||
|
caOption ca.Option
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithSpecialProxy(name string) Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
opt.specialProxy = name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithCAOption(caOption ca.Option) Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
opt.caOption = caOption
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,27 +10,27 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
keepAliveIdle = atomic.NewTypedValue[time.Duration](0 * time.Second)
|
keepAliveIdle = atomic.NewInt64(0)
|
||||||
keepAliveInterval = atomic.NewTypedValue[time.Duration](0 * time.Second)
|
keepAliveInterval = atomic.NewInt64(0)
|
||||||
disableKeepAlive = atomic.NewBool(false)
|
disableKeepAlive = atomic.NewBool(false)
|
||||||
|
|
||||||
SetDisableKeepAliveCallback = utils.NewCallback[bool]()
|
SetDisableKeepAliveCallback = utils.NewCallback[bool]()
|
||||||
)
|
)
|
||||||
|
|
||||||
func SetKeepAliveIdle(t time.Duration) {
|
func SetKeepAliveIdle(t time.Duration) {
|
||||||
keepAliveIdle.Store(t)
|
keepAliveIdle.Store(int64(t))
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetKeepAliveInterval(t time.Duration) {
|
func SetKeepAliveInterval(t time.Duration) {
|
||||||
keepAliveInterval.Store(t)
|
keepAliveInterval.Store(int64(t))
|
||||||
}
|
}
|
||||||
|
|
||||||
func KeepAliveIdle() time.Duration {
|
func KeepAliveIdle() time.Duration {
|
||||||
return keepAliveIdle.Load()
|
return time.Duration(keepAliveIdle.Load())
|
||||||
}
|
}
|
||||||
|
|
||||||
func KeepAliveInterval() time.Duration {
|
func KeepAliveInterval() time.Duration {
|
||||||
return keepAliveInterval.Load()
|
return time.Duration(keepAliveInterval.Load())
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetDisableKeepAlive(disable bool) {
|
func SetDisableKeepAlive(disable bool) {
|
||||||
|
|||||||
29
component/memory/memory.go
Normal file
29
component/memory/memory.go
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
// Package memory return MemoryInfoStat
|
||||||
|
// modify from https://github.com/shirou/gopsutil/tree/v4.25.8/process
|
||||||
|
package memory
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrNotImplementedError = errors.New("not implemented yet")
|
||||||
|
|
||||||
|
type MemoryInfoStat struct {
|
||||||
|
RSS uint64 `json:"rss"` // bytes
|
||||||
|
VMS uint64 `json:"vms"` // bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
// PrettyByteSize convert size in bytes to Bytes, Kilobytes, Megabytes, GB and TB
|
||||||
|
// https://gist.github.com/anikitenko/b41206a49727b83a530142c76b1cb82d?permalink_comment_id=4467913#gistcomment-4467913
|
||||||
|
func PrettyByteSize(b uint64) string {
|
||||||
|
bf := float64(b)
|
||||||
|
for _, unit := range []string{"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"} {
|
||||||
|
if math.Abs(bf) < 1024.0 {
|
||||||
|
return fmt.Sprintf("%3.1f%sB", bf, unit)
|
||||||
|
}
|
||||||
|
bf /= 1024.0
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%.1fYiB", bf)
|
||||||
|
}
|
||||||
56
component/memory/memory_darwin.go
Normal file
56
component/memory/memory_darwin.go
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
import (
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/ebitengine/purego"
|
||||||
|
)
|
||||||
|
|
||||||
|
const PROC_PIDTASKINFO = 4
|
||||||
|
|
||||||
|
type ProcTaskInfo struct {
|
||||||
|
Virtual_size uint64
|
||||||
|
Resident_size uint64
|
||||||
|
Total_user uint64
|
||||||
|
Total_system uint64
|
||||||
|
Threads_user uint64
|
||||||
|
Threads_system uint64
|
||||||
|
Policy int32
|
||||||
|
Faults int32
|
||||||
|
Pageins int32
|
||||||
|
Cow_faults int32
|
||||||
|
Messages_sent int32
|
||||||
|
Messages_received int32
|
||||||
|
Syscalls_mach int32
|
||||||
|
Syscalls_unix int32
|
||||||
|
Csw int32
|
||||||
|
Threadnum int32
|
||||||
|
Numrunning int32
|
||||||
|
Priority int32
|
||||||
|
}
|
||||||
|
|
||||||
|
const System = "/usr/lib/libSystem.B.dylib"
|
||||||
|
|
||||||
|
type ProcPidInfoFunc func(pid, flavor int32, arg uint64, buffer uintptr, bufferSize int32) int32
|
||||||
|
|
||||||
|
const ProcPidInfoSym = "proc_pidinfo"
|
||||||
|
|
||||||
|
func GetMemoryInfo(pid int32) (*MemoryInfoStat, error) {
|
||||||
|
lib, err := purego.Dlopen(System, purego.RTLD_LAZY|purego.RTLD_GLOBAL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer purego.Dlclose(lib)
|
||||||
|
|
||||||
|
var procPidInfo ProcPidInfoFunc
|
||||||
|
purego.RegisterLibFunc(&procPidInfo, lib, ProcPidInfoSym)
|
||||||
|
|
||||||
|
var ti ProcTaskInfo
|
||||||
|
procPidInfo(pid, PROC_PIDTASKINFO, 0, uintptr(unsafe.Pointer(&ti)), int32(unsafe.Sizeof(ti)))
|
||||||
|
|
||||||
|
ret := &MemoryInfoStat{
|
||||||
|
RSS: uint64(ti.Resident_size),
|
||||||
|
VMS: uint64(ti.Virtual_size),
|
||||||
|
}
|
||||||
|
return ret, nil
|
||||||
|
}
|
||||||
7
component/memory/memory_falllback.go
Normal file
7
component/memory/memory_falllback.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
//go:build !darwin && !linux && !freebsd && !openbsd && !windows
|
||||||
|
|
||||||
|
package memory
|
||||||
|
|
||||||
|
func GetMemoryInfo(pid int32) (*MemoryInfoStat, error) {
|
||||||
|
return nil, ErrNotImplementedError
|
||||||
|
}
|
||||||
97
component/memory/memory_freebsd.go
Normal file
97
component/memory/memory_freebsd.go
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
CTLKern = 1
|
||||||
|
KernProc = 14
|
||||||
|
KernProcPID = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
func CallSyscall(mib []int32) ([]byte, uint64, error) {
|
||||||
|
mibptr := unsafe.Pointer(&mib[0])
|
||||||
|
miblen := uint64(len(mib))
|
||||||
|
|
||||||
|
// get required buffer size
|
||||||
|
length := uint64(0)
|
||||||
|
_, _, err := unix.Syscall6(
|
||||||
|
unix.SYS___SYSCTL,
|
||||||
|
uintptr(mibptr),
|
||||||
|
uintptr(miblen),
|
||||||
|
0,
|
||||||
|
uintptr(unsafe.Pointer(&length)),
|
||||||
|
0,
|
||||||
|
0)
|
||||||
|
if err != 0 {
|
||||||
|
var b []byte
|
||||||
|
return b, length, err
|
||||||
|
}
|
||||||
|
if length == 0 {
|
||||||
|
var b []byte
|
||||||
|
return b, length, err
|
||||||
|
}
|
||||||
|
// get proc info itself
|
||||||
|
buf := make([]byte, length)
|
||||||
|
_, _, err = unix.Syscall6(
|
||||||
|
unix.SYS___SYSCTL,
|
||||||
|
uintptr(mibptr),
|
||||||
|
uintptr(miblen),
|
||||||
|
uintptr(unsafe.Pointer(&buf[0])),
|
||||||
|
uintptr(unsafe.Pointer(&length)),
|
||||||
|
0,
|
||||||
|
0)
|
||||||
|
if err != 0 {
|
||||||
|
return buf, length, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return buf, length, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseKinfoProc(buf []byte) (KinfoProc, error) {
|
||||||
|
var k KinfoProc
|
||||||
|
br := bytes.NewReader(buf)
|
||||||
|
err := binary.Read(br, binary.LittleEndian, &k)
|
||||||
|
return k, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func getKProc(pid int32) (*KinfoProc, error) {
|
||||||
|
mib := []int32{CTLKern, KernProc, KernProcPID, pid}
|
||||||
|
|
||||||
|
buf, length, err := CallSyscall(mib)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if length != sizeOfKinfoProc {
|
||||||
|
return nil, errors.New("unexpected size of KinfoProc")
|
||||||
|
}
|
||||||
|
|
||||||
|
k, err := parseKinfoProc(buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &k, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetMemoryInfo(pid int32) (*MemoryInfoStat, error) {
|
||||||
|
k, err := getKProc(pid)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
v, err := unix.Sysctl("vm.stats.vm.v_page_size")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pageSize := binary.LittleEndian.Uint16([]byte(v))
|
||||||
|
|
||||||
|
return &MemoryInfoStat{
|
||||||
|
RSS: uint64(k.Rssize) * uint64(pageSize),
|
||||||
|
VMS: uint64(k.Size),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
119
component/memory/memory_freebsd_386.go
Normal file
119
component/memory/memory_freebsd_386.go
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
const sizeOfKinfoProc = 0x300
|
||||||
|
|
||||||
|
type Timeval struct {
|
||||||
|
Sec int32
|
||||||
|
Usec int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type Rusage struct {
|
||||||
|
Utime Timeval
|
||||||
|
Stime Timeval
|
||||||
|
Maxrss int32
|
||||||
|
Ixrss int32
|
||||||
|
Idrss int32
|
||||||
|
Isrss int32
|
||||||
|
Minflt int32
|
||||||
|
Majflt int32
|
||||||
|
Nswap int32
|
||||||
|
Inblock int32
|
||||||
|
Oublock int32
|
||||||
|
Msgsnd int32
|
||||||
|
Msgrcv int32
|
||||||
|
Nsignals int32
|
||||||
|
Nvcsw int32
|
||||||
|
Nivcsw int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type KinfoProc struct {
|
||||||
|
Structsize int32
|
||||||
|
Layout int32
|
||||||
|
Args int32 /* pargs */
|
||||||
|
Paddr int32 /* proc */
|
||||||
|
Addr int32 /* user */
|
||||||
|
Tracep int32 /* vnode */
|
||||||
|
Textvp int32 /* vnode */
|
||||||
|
Fd int32 /* filedesc */
|
||||||
|
Vmspace int32 /* vmspace */
|
||||||
|
Wchan int32
|
||||||
|
Pid int32
|
||||||
|
Ppid int32
|
||||||
|
Pgid int32
|
||||||
|
Tpgid int32
|
||||||
|
Sid int32
|
||||||
|
Tsid int32
|
||||||
|
Jobc int16
|
||||||
|
Spare_short1 int16
|
||||||
|
Tdev uint32
|
||||||
|
Siglist [16]byte /* sigset */
|
||||||
|
Sigmask [16]byte /* sigset */
|
||||||
|
Sigignore [16]byte /* sigset */
|
||||||
|
Sigcatch [16]byte /* sigset */
|
||||||
|
Uid uint32
|
||||||
|
Ruid uint32
|
||||||
|
Svuid uint32
|
||||||
|
Rgid uint32
|
||||||
|
Svgid uint32
|
||||||
|
Ngroups int16
|
||||||
|
Spare_short2 int16
|
||||||
|
Groups [16]uint32
|
||||||
|
Size uint32
|
||||||
|
Rssize int32
|
||||||
|
Swrss int32
|
||||||
|
Tsize int32
|
||||||
|
Dsize int32
|
||||||
|
Ssize int32
|
||||||
|
Xstat uint16
|
||||||
|
Acflag uint16
|
||||||
|
Pctcpu uint32
|
||||||
|
Estcpu uint32
|
||||||
|
Slptime uint32
|
||||||
|
Swtime uint32
|
||||||
|
Cow uint32
|
||||||
|
Runtime uint64
|
||||||
|
Start Timeval
|
||||||
|
Childtime Timeval
|
||||||
|
Flag int32
|
||||||
|
Kiflag int32
|
||||||
|
Traceflag int32
|
||||||
|
Stat int8
|
||||||
|
Nice int8
|
||||||
|
Lock int8
|
||||||
|
Rqindex int8
|
||||||
|
Oncpu uint8
|
||||||
|
Lastcpu uint8
|
||||||
|
Tdname [17]int8
|
||||||
|
Wmesg [9]int8
|
||||||
|
Login [18]int8
|
||||||
|
Lockname [9]int8
|
||||||
|
Comm [20]int8
|
||||||
|
Emul [17]int8
|
||||||
|
Loginclass [18]int8
|
||||||
|
Sparestrings [50]int8
|
||||||
|
Spareints [7]int32
|
||||||
|
Flag2 int32
|
||||||
|
Fibnum int32
|
||||||
|
Cr_flags uint32
|
||||||
|
Jid int32
|
||||||
|
Numthreads int32
|
||||||
|
Tid int32
|
||||||
|
Pri Priority
|
||||||
|
Rusage Rusage
|
||||||
|
Rusage_ch Rusage
|
||||||
|
Pcb int32 /* pcb */
|
||||||
|
Kstack int32
|
||||||
|
Udata int32
|
||||||
|
Tdaddr int32 /* thread */
|
||||||
|
Spareptrs [6]int32
|
||||||
|
Sparelongs [12]int32
|
||||||
|
Sflag int32
|
||||||
|
Tdflags int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type Priority struct {
|
||||||
|
Class uint8
|
||||||
|
Level uint8
|
||||||
|
Native uint8
|
||||||
|
User uint8
|
||||||
|
}
|
||||||
125
component/memory/memory_freebsd_amd64.go
Normal file
125
component/memory/memory_freebsd_amd64.go
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
const sizeOfKinfoProc = 0x440
|
||||||
|
|
||||||
|
type Timeval struct {
|
||||||
|
Sec int64
|
||||||
|
Usec int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type Rusage struct {
|
||||||
|
Utime Timeval
|
||||||
|
Stime Timeval
|
||||||
|
Maxrss int64
|
||||||
|
Ixrss int64
|
||||||
|
Idrss int64
|
||||||
|
Isrss int64
|
||||||
|
Minflt int64
|
||||||
|
Majflt int64
|
||||||
|
Nswap int64
|
||||||
|
Inblock int64
|
||||||
|
Oublock int64
|
||||||
|
Msgsnd int64
|
||||||
|
Msgrcv int64
|
||||||
|
Nsignals int64
|
||||||
|
Nvcsw int64
|
||||||
|
Nivcsw int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type KinfoProc struct {
|
||||||
|
Structsize int32
|
||||||
|
Layout int32
|
||||||
|
Args int64 /* pargs */
|
||||||
|
Paddr int64 /* proc */
|
||||||
|
Addr int64 /* user */
|
||||||
|
Tracep int64 /* vnode */
|
||||||
|
Textvp int64 /* vnode */
|
||||||
|
Fd int64 /* filedesc */
|
||||||
|
Vmspace int64 /* vmspace */
|
||||||
|
Wchan int64
|
||||||
|
Pid int32
|
||||||
|
Ppid int32
|
||||||
|
Pgid int32
|
||||||
|
Tpgid int32
|
||||||
|
Sid int32
|
||||||
|
Tsid int32
|
||||||
|
Jobc int16
|
||||||
|
Spare_short1 int16
|
||||||
|
Tdev_freebsd11 uint32
|
||||||
|
Siglist [16]byte /* sigset */
|
||||||
|
Sigmask [16]byte /* sigset */
|
||||||
|
Sigignore [16]byte /* sigset */
|
||||||
|
Sigcatch [16]byte /* sigset */
|
||||||
|
Uid uint32
|
||||||
|
Ruid uint32
|
||||||
|
Svuid uint32
|
||||||
|
Rgid uint32
|
||||||
|
Svgid uint32
|
||||||
|
Ngroups int16
|
||||||
|
Spare_short2 int16
|
||||||
|
Groups [16]uint32
|
||||||
|
Size uint64
|
||||||
|
Rssize int64
|
||||||
|
Swrss int64
|
||||||
|
Tsize int64
|
||||||
|
Dsize int64
|
||||||
|
Ssize int64
|
||||||
|
Xstat uint16
|
||||||
|
Acflag uint16
|
||||||
|
Pctcpu uint32
|
||||||
|
Estcpu uint32
|
||||||
|
Slptime uint32
|
||||||
|
Swtime uint32
|
||||||
|
Cow uint32
|
||||||
|
Runtime uint64
|
||||||
|
Start Timeval
|
||||||
|
Childtime Timeval
|
||||||
|
Flag int64
|
||||||
|
Kiflag int64
|
||||||
|
Traceflag int32
|
||||||
|
Stat int8
|
||||||
|
Nice int8
|
||||||
|
Lock int8
|
||||||
|
Rqindex int8
|
||||||
|
Oncpu_old uint8
|
||||||
|
Lastcpu_old uint8
|
||||||
|
Tdname [17]int8
|
||||||
|
Wmesg [9]int8
|
||||||
|
Login [18]int8
|
||||||
|
Lockname [9]int8
|
||||||
|
Comm [20]int8
|
||||||
|
Emul [17]int8
|
||||||
|
Loginclass [18]int8
|
||||||
|
Moretdname [4]int8
|
||||||
|
Sparestrings [46]int8
|
||||||
|
Spareints [2]int32
|
||||||
|
Tdev uint64
|
||||||
|
Oncpu int32
|
||||||
|
Lastcpu int32
|
||||||
|
Tracer int32
|
||||||
|
Flag2 int32
|
||||||
|
Fibnum int32
|
||||||
|
Cr_flags uint32
|
||||||
|
Jid int32
|
||||||
|
Numthreads int32
|
||||||
|
Tid int32
|
||||||
|
Pri Priority
|
||||||
|
Rusage Rusage
|
||||||
|
Rusage_ch Rusage
|
||||||
|
Pcb int64 /* pcb */
|
||||||
|
Kstack int64
|
||||||
|
Udata int64
|
||||||
|
Tdaddr int64 /* thread */
|
||||||
|
Pd int64 /* pwddesc, not accurate */
|
||||||
|
Spareptrs [5]int64
|
||||||
|
Sparelongs [12]int64
|
||||||
|
Sflag int64
|
||||||
|
Tdflags int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type Priority struct {
|
||||||
|
Class uint8
|
||||||
|
Level uint8
|
||||||
|
Native uint8
|
||||||
|
User uint8
|
||||||
|
}
|
||||||
119
component/memory/memory_freebsd_arm.go
Normal file
119
component/memory/memory_freebsd_arm.go
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
const sizeOfKinfoProc = 0x440
|
||||||
|
|
||||||
|
type Timeval struct {
|
||||||
|
Sec int64
|
||||||
|
Usec int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type Rusage struct {
|
||||||
|
Utime Timeval
|
||||||
|
Stime Timeval
|
||||||
|
Maxrss int32
|
||||||
|
Ixrss int32
|
||||||
|
Idrss int32
|
||||||
|
Isrss int32
|
||||||
|
Minflt int32
|
||||||
|
Majflt int32
|
||||||
|
Nswap int32
|
||||||
|
Inblock int32
|
||||||
|
Oublock int32
|
||||||
|
Msgsnd int32
|
||||||
|
Msgrcv int32
|
||||||
|
Nsignals int32
|
||||||
|
Nvcsw int32
|
||||||
|
Nivcsw int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type KinfoProc struct {
|
||||||
|
Structsize int32
|
||||||
|
Layout int32
|
||||||
|
Args int32 /* pargs */
|
||||||
|
Paddr int32 /* proc */
|
||||||
|
Addr int32 /* user */
|
||||||
|
Tracep int32 /* vnode */
|
||||||
|
Textvp int32 /* vnode */
|
||||||
|
Fd int32 /* filedesc */
|
||||||
|
Vmspace int32 /* vmspace */
|
||||||
|
Wchan int32
|
||||||
|
Pid int32
|
||||||
|
Ppid int32
|
||||||
|
Pgid int32
|
||||||
|
Tpgid int32
|
||||||
|
Sid int32
|
||||||
|
Tsid int32
|
||||||
|
Jobc int16
|
||||||
|
Spare_short1 int16
|
||||||
|
Tdev uint32
|
||||||
|
Siglist [16]byte /* sigset */
|
||||||
|
Sigmask [16]byte /* sigset */
|
||||||
|
Sigignore [16]byte /* sigset */
|
||||||
|
Sigcatch [16]byte /* sigset */
|
||||||
|
Uid uint32
|
||||||
|
Ruid uint32
|
||||||
|
Svuid uint32
|
||||||
|
Rgid uint32
|
||||||
|
Svgid uint32
|
||||||
|
Ngroups int16
|
||||||
|
Spare_short2 int16
|
||||||
|
Groups [16]uint32
|
||||||
|
Size uint32
|
||||||
|
Rssize int32
|
||||||
|
Swrss int32
|
||||||
|
Tsize int32
|
||||||
|
Dsize int32
|
||||||
|
Ssize int32
|
||||||
|
Xstat uint16
|
||||||
|
Acflag uint16
|
||||||
|
Pctcpu uint32
|
||||||
|
Estcpu uint32
|
||||||
|
Slptime uint32
|
||||||
|
Swtime uint32
|
||||||
|
Cow uint32
|
||||||
|
Runtime uint64
|
||||||
|
Start Timeval
|
||||||
|
Childtime Timeval
|
||||||
|
Flag int32
|
||||||
|
Kiflag int32
|
||||||
|
Traceflag int32
|
||||||
|
Stat int8
|
||||||
|
Nice int8
|
||||||
|
Lock int8
|
||||||
|
Rqindex int8
|
||||||
|
Oncpu uint8
|
||||||
|
Lastcpu uint8
|
||||||
|
Tdname [17]int8
|
||||||
|
Wmesg [9]int8
|
||||||
|
Login [18]int8
|
||||||
|
Lockname [9]int8
|
||||||
|
Comm [20]int8
|
||||||
|
Emul [17]int8
|
||||||
|
Loginclass [18]int8
|
||||||
|
Sparestrings [50]int8
|
||||||
|
Spareints [4]int32
|
||||||
|
Flag2 int32
|
||||||
|
Fibnum int32
|
||||||
|
Cr_flags uint32
|
||||||
|
Jid int32
|
||||||
|
Numthreads int32
|
||||||
|
Tid int32
|
||||||
|
Pri Priority
|
||||||
|
Rusage Rusage
|
||||||
|
Rusage_ch Rusage
|
||||||
|
Pcb int32 /* pcb */
|
||||||
|
Kstack int32
|
||||||
|
Udata int32
|
||||||
|
Tdaddr int32 /* thread */
|
||||||
|
Spareptrs [6]int64
|
||||||
|
Sparelongs [12]int64
|
||||||
|
Sflag int64
|
||||||
|
Tdflags int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type Priority struct {
|
||||||
|
Class uint8
|
||||||
|
Level uint8
|
||||||
|
Native uint8
|
||||||
|
User uint8
|
||||||
|
}
|
||||||
125
component/memory/memory_freebsd_arm64.go
Normal file
125
component/memory/memory_freebsd_arm64.go
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
const sizeOfKinfoProc = 0x440
|
||||||
|
|
||||||
|
type Timeval struct {
|
||||||
|
Sec int64
|
||||||
|
Usec int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type Rusage struct {
|
||||||
|
Utime Timeval
|
||||||
|
Stime Timeval
|
||||||
|
Maxrss int64
|
||||||
|
Ixrss int64
|
||||||
|
Idrss int64
|
||||||
|
Isrss int64
|
||||||
|
Minflt int64
|
||||||
|
Majflt int64
|
||||||
|
Nswap int64
|
||||||
|
Inblock int64
|
||||||
|
Oublock int64
|
||||||
|
Msgsnd int64
|
||||||
|
Msgrcv int64
|
||||||
|
Nsignals int64
|
||||||
|
Nvcsw int64
|
||||||
|
Nivcsw int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type KinfoProc struct {
|
||||||
|
Structsize int32
|
||||||
|
Layout int32
|
||||||
|
Args int64 /* pargs */
|
||||||
|
Paddr int64 /* proc */
|
||||||
|
Addr int64 /* user */
|
||||||
|
Tracep int64 /* vnode */
|
||||||
|
Textvp int64 /* vnode */
|
||||||
|
Fd int64 /* filedesc */
|
||||||
|
Vmspace int64 /* vmspace */
|
||||||
|
Wchan int64
|
||||||
|
Pid int32
|
||||||
|
Ppid int32
|
||||||
|
Pgid int32
|
||||||
|
Tpgid int32
|
||||||
|
Sid int32
|
||||||
|
Tsid int32
|
||||||
|
Jobc int16
|
||||||
|
Spare_short1 int16
|
||||||
|
Tdev_freebsd11 uint32
|
||||||
|
Siglist [16]byte /* sigset */
|
||||||
|
Sigmask [16]byte /* sigset */
|
||||||
|
Sigignore [16]byte /* sigset */
|
||||||
|
Sigcatch [16]byte /* sigset */
|
||||||
|
Uid uint32
|
||||||
|
Ruid uint32
|
||||||
|
Svuid uint32
|
||||||
|
Rgid uint32
|
||||||
|
Svgid uint32
|
||||||
|
Ngroups int16
|
||||||
|
Spare_short2 int16
|
||||||
|
Groups [16]uint32
|
||||||
|
Size uint64
|
||||||
|
Rssize int64
|
||||||
|
Swrss int64
|
||||||
|
Tsize int64
|
||||||
|
Dsize int64
|
||||||
|
Ssize int64
|
||||||
|
Xstat uint16
|
||||||
|
Acflag uint16
|
||||||
|
Pctcpu uint32
|
||||||
|
Estcpu uint32
|
||||||
|
Slptime uint32
|
||||||
|
Swtime uint32
|
||||||
|
Cow uint32
|
||||||
|
Runtime uint64
|
||||||
|
Start Timeval
|
||||||
|
Childtime Timeval
|
||||||
|
Flag int64
|
||||||
|
Kiflag int64
|
||||||
|
Traceflag int32
|
||||||
|
Stat uint8
|
||||||
|
Nice int8
|
||||||
|
Lock uint8
|
||||||
|
Rqindex uint8
|
||||||
|
Oncpu_old uint8
|
||||||
|
Lastcpu_old uint8
|
||||||
|
Tdname [17]uint8
|
||||||
|
Wmesg [9]uint8
|
||||||
|
Login [18]uint8
|
||||||
|
Lockname [9]uint8
|
||||||
|
Comm [20]int8 // changed from uint8 by hand
|
||||||
|
Emul [17]uint8
|
||||||
|
Loginclass [18]uint8
|
||||||
|
Moretdname [4]uint8
|
||||||
|
Sparestrings [46]uint8
|
||||||
|
Spareints [2]int32
|
||||||
|
Tdev uint64
|
||||||
|
Oncpu int32
|
||||||
|
Lastcpu int32
|
||||||
|
Tracer int32
|
||||||
|
Flag2 int32
|
||||||
|
Fibnum int32
|
||||||
|
Cr_flags uint32
|
||||||
|
Jid int32
|
||||||
|
Numthreads int32
|
||||||
|
Tid int32
|
||||||
|
Pri Priority
|
||||||
|
Rusage Rusage
|
||||||
|
Rusage_ch Rusage
|
||||||
|
Pcb int64 /* pcb */
|
||||||
|
Kstack int64
|
||||||
|
Udata int64
|
||||||
|
Tdaddr int64 /* thread */
|
||||||
|
Pd int64 /* pwddesc, not accurate */
|
||||||
|
Spareptrs [5]int64
|
||||||
|
Sparelongs [12]int64
|
||||||
|
Sflag int64
|
||||||
|
Tdflags int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type Priority struct {
|
||||||
|
Class uint8
|
||||||
|
Level uint8
|
||||||
|
Native uint8
|
||||||
|
User uint8
|
||||||
|
}
|
||||||
37
component/memory/memory_linux.go
Normal file
37
component/memory/memory_linux.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var pageSize = uint64(os.Getpagesize())
|
||||||
|
|
||||||
|
func GetMemoryInfo(pid int32) (*MemoryInfoStat, error) {
|
||||||
|
proc := os.Getenv("HOST_PROC")
|
||||||
|
if proc == "" {
|
||||||
|
proc = "/proc"
|
||||||
|
}
|
||||||
|
memPath := filepath.Join(proc, strconv.Itoa(int(pid)), "statm")
|
||||||
|
contents, err := os.ReadFile(memPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
fields := strings.Split(string(contents), " ")
|
||||||
|
|
||||||
|
vms, err := strconv.ParseUint(fields[0], 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rss, err := strconv.ParseUint(fields[1], 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
memInfo := &MemoryInfoStat{
|
||||||
|
RSS: rss * pageSize,
|
||||||
|
VMS: vms * pageSize,
|
||||||
|
}
|
||||||
|
return memInfo, nil
|
||||||
|
}
|
||||||
95
component/memory/memory_openbsd.go
Normal file
95
component/memory/memory_openbsd.go
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
CTLKern = 1
|
||||||
|
KernProc = 14
|
||||||
|
KernProcPID = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
func callKernProcSyscall(op int32, arg int32) ([]byte, uint64, error) {
|
||||||
|
mib := []int32{CTLKern, KernProc, op, arg, sizeOfKinfoProc, 0}
|
||||||
|
mibptr := unsafe.Pointer(&mib[0])
|
||||||
|
miblen := uint64(len(mib))
|
||||||
|
length := uint64(0)
|
||||||
|
_, _, err := unix.Syscall6(
|
||||||
|
unix.SYS___SYSCTL,
|
||||||
|
uintptr(mibptr),
|
||||||
|
uintptr(miblen),
|
||||||
|
0,
|
||||||
|
uintptr(unsafe.Pointer(&length)),
|
||||||
|
0,
|
||||||
|
0)
|
||||||
|
if err != 0 {
|
||||||
|
return nil, length, err
|
||||||
|
}
|
||||||
|
|
||||||
|
count := int32(length / uint64(sizeOfKinfoProc))
|
||||||
|
mib = []int32{CTLKern, KernProc, op, arg, sizeOfKinfoProc, count}
|
||||||
|
mibptr = unsafe.Pointer(&mib[0])
|
||||||
|
miblen = uint64(len(mib))
|
||||||
|
// get proc info itself
|
||||||
|
buf := make([]byte, length)
|
||||||
|
_, _, err = unix.Syscall6(
|
||||||
|
unix.SYS___SYSCTL,
|
||||||
|
uintptr(mibptr),
|
||||||
|
uintptr(miblen),
|
||||||
|
uintptr(unsafe.Pointer(&buf[0])),
|
||||||
|
uintptr(unsafe.Pointer(&length)),
|
||||||
|
0,
|
||||||
|
0)
|
||||||
|
if err != 0 {
|
||||||
|
return buf, length, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return buf, length, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseKinfoProc(buf []byte) (KinfoProc, error) {
|
||||||
|
var k KinfoProc
|
||||||
|
br := bytes.NewReader(buf)
|
||||||
|
err := binary.Read(br, binary.LittleEndian, &k)
|
||||||
|
return k, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func getKProc(pid int32) (*KinfoProc, error) {
|
||||||
|
buf, length, err := callKernProcSyscall(KernProcPID, pid)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if length != sizeOfKinfoProc {
|
||||||
|
return nil, errors.New("unexpected size of KinfoProc")
|
||||||
|
}
|
||||||
|
|
||||||
|
k, err := parseKinfoProc(buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &k, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetMemoryInfo(pid int32) (*MemoryInfoStat, error) {
|
||||||
|
k, err := getKProc(pid)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
uvmexp, err := unix.SysctlUvmexp("vm.uvmexp")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pageSize := uint64(uvmexp.Pagesize)
|
||||||
|
|
||||||
|
return &MemoryInfoStat{
|
||||||
|
RSS: uint64(k.Vm_rssize) * pageSize,
|
||||||
|
VMS: uint64(k.Vm_tsize) + uint64(k.Vm_dsize) +
|
||||||
|
uint64(k.Vm_ssize),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
99
component/memory/memory_openbsd_386.go
Normal file
99
component/memory/memory_openbsd_386.go
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
const sizeOfKinfoProc = 0x264
|
||||||
|
|
||||||
|
type KinfoProc struct {
|
||||||
|
Forw uint64
|
||||||
|
Back uint64
|
||||||
|
Paddr uint64
|
||||||
|
Addr uint64
|
||||||
|
Fd uint64
|
||||||
|
Stats uint64
|
||||||
|
Limit uint64
|
||||||
|
Vmspace uint64
|
||||||
|
Sigacts uint64
|
||||||
|
Sess uint64
|
||||||
|
Tsess uint64
|
||||||
|
Ru uint64
|
||||||
|
Eflag int32
|
||||||
|
Exitsig int32
|
||||||
|
Flag int32
|
||||||
|
Pid int32
|
||||||
|
Ppid int32
|
||||||
|
Sid int32
|
||||||
|
X_pgid int32
|
||||||
|
Tpgid int32
|
||||||
|
Uid uint32
|
||||||
|
Ruid uint32
|
||||||
|
Gid uint32
|
||||||
|
Rgid uint32
|
||||||
|
Groups [16]uint32
|
||||||
|
Ngroups int16
|
||||||
|
Jobc int16
|
||||||
|
Tdev uint32
|
||||||
|
Estcpu uint32
|
||||||
|
Rtime_sec uint32
|
||||||
|
Rtime_usec uint32
|
||||||
|
Cpticks int32
|
||||||
|
Pctcpu uint32
|
||||||
|
Swtime uint32
|
||||||
|
Slptime uint32
|
||||||
|
Schedflags int32
|
||||||
|
Uticks uint64
|
||||||
|
Sticks uint64
|
||||||
|
Iticks uint64
|
||||||
|
Tracep uint64
|
||||||
|
Traceflag int32
|
||||||
|
Holdcnt int32
|
||||||
|
Siglist int32
|
||||||
|
Sigmask uint32
|
||||||
|
Sigignore uint32
|
||||||
|
Sigcatch uint32
|
||||||
|
Stat int8
|
||||||
|
Priority uint8
|
||||||
|
Usrpri uint8
|
||||||
|
Nice uint8
|
||||||
|
Xstat uint16
|
||||||
|
Acflag uint16
|
||||||
|
Comm [24]int8
|
||||||
|
Wmesg [8]int8
|
||||||
|
Wchan uint64
|
||||||
|
Login [32]int8
|
||||||
|
Vm_rssize int32
|
||||||
|
Vm_tsize int32
|
||||||
|
Vm_dsize int32
|
||||||
|
Vm_ssize int32
|
||||||
|
Uvalid int64
|
||||||
|
Ustart_sec uint64
|
||||||
|
Ustart_usec uint32
|
||||||
|
Uutime_sec uint32
|
||||||
|
Uutime_usec uint32
|
||||||
|
Ustime_sec uint32
|
||||||
|
Ustime_usec uint32
|
||||||
|
Uru_maxrss uint64
|
||||||
|
Uru_ixrss uint64
|
||||||
|
Uru_idrss uint64
|
||||||
|
Uru_isrss uint64
|
||||||
|
Uru_minflt uint64
|
||||||
|
Uru_majflt uint64
|
||||||
|
Uru_nswap uint64
|
||||||
|
Uru_inblock uint64
|
||||||
|
Uru_oublock uint64
|
||||||
|
Uru_msgsnd uint64
|
||||||
|
Uru_msgrcv uint64
|
||||||
|
Uru_nsignals uint64
|
||||||
|
Uru_nvcsw uint64
|
||||||
|
Uru_nivcsw uint64
|
||||||
|
Uctime_sec uint32
|
||||||
|
Uctime_usec uint32
|
||||||
|
Psflags int32
|
||||||
|
Spare int32
|
||||||
|
Svuid uint32
|
||||||
|
Svgid uint32
|
||||||
|
Emul [8]int8
|
||||||
|
Rlim_rss_cur uint64
|
||||||
|
Cpuid uint64
|
||||||
|
Vm_map_size uint64
|
||||||
|
Tid int32
|
||||||
|
Rtableid uint32
|
||||||
|
}
|
||||||
100
component/memory/memory_openbsd_amd64.go
Normal file
100
component/memory/memory_openbsd_amd64.go
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
const sizeOfKinfoProc = 0x268
|
||||||
|
|
||||||
|
type KinfoProc struct {
|
||||||
|
Forw uint64
|
||||||
|
Back uint64
|
||||||
|
Paddr uint64
|
||||||
|
Addr uint64
|
||||||
|
Fd uint64
|
||||||
|
Stats uint64
|
||||||
|
Limit uint64
|
||||||
|
Vmspace uint64
|
||||||
|
Sigacts uint64
|
||||||
|
Sess uint64
|
||||||
|
Tsess uint64
|
||||||
|
Ru uint64
|
||||||
|
Eflag int32
|
||||||
|
Exitsig int32
|
||||||
|
Flag int32
|
||||||
|
Pid int32
|
||||||
|
Ppid int32
|
||||||
|
Sid int32
|
||||||
|
X_pgid int32
|
||||||
|
Tpgid int32
|
||||||
|
Uid uint32
|
||||||
|
Ruid uint32
|
||||||
|
Gid uint32
|
||||||
|
Rgid uint32
|
||||||
|
Groups [16]uint32
|
||||||
|
Ngroups int16
|
||||||
|
Jobc int16
|
||||||
|
Tdev uint32
|
||||||
|
Estcpu uint32
|
||||||
|
Rtime_sec uint32
|
||||||
|
Rtime_usec uint32
|
||||||
|
Cpticks int32
|
||||||
|
Pctcpu uint32
|
||||||
|
Swtime uint32
|
||||||
|
Slptime uint32
|
||||||
|
Schedflags int32
|
||||||
|
Uticks uint64
|
||||||
|
Sticks uint64
|
||||||
|
Iticks uint64
|
||||||
|
Tracep uint64
|
||||||
|
Traceflag int32
|
||||||
|
Holdcnt int32
|
||||||
|
Siglist int32
|
||||||
|
Sigmask uint32
|
||||||
|
Sigignore uint32
|
||||||
|
Sigcatch uint32
|
||||||
|
Stat int8
|
||||||
|
Priority uint8
|
||||||
|
Usrpri uint8
|
||||||
|
Nice uint8
|
||||||
|
Xstat uint16
|
||||||
|
Acflag uint16
|
||||||
|
Comm [24]int8
|
||||||
|
Wmesg [8]int8
|
||||||
|
Wchan uint64
|
||||||
|
Login [32]int8
|
||||||
|
Vm_rssize int32
|
||||||
|
Vm_tsize int32
|
||||||
|
Vm_dsize int32
|
||||||
|
Vm_ssize int32
|
||||||
|
Uvalid int64
|
||||||
|
Ustart_sec uint64
|
||||||
|
Ustart_usec uint32
|
||||||
|
Uutime_sec uint32
|
||||||
|
Uutime_usec uint32
|
||||||
|
Ustime_sec uint32
|
||||||
|
Ustime_usec uint32
|
||||||
|
Pad_cgo_0 [4]byte
|
||||||
|
Uru_maxrss uint64
|
||||||
|
Uru_ixrss uint64
|
||||||
|
Uru_idrss uint64
|
||||||
|
Uru_isrss uint64
|
||||||
|
Uru_minflt uint64
|
||||||
|
Uru_majflt uint64
|
||||||
|
Uru_nswap uint64
|
||||||
|
Uru_inblock uint64
|
||||||
|
Uru_oublock uint64
|
||||||
|
Uru_msgsnd uint64
|
||||||
|
Uru_msgrcv uint64
|
||||||
|
Uru_nsignals uint64
|
||||||
|
Uru_nvcsw uint64
|
||||||
|
Uru_nivcsw uint64
|
||||||
|
Uctime_sec uint32
|
||||||
|
Uctime_usec uint32
|
||||||
|
Psflags int32
|
||||||
|
Spare int32
|
||||||
|
Svuid uint32
|
||||||
|
Svgid uint32
|
||||||
|
Emul [8]int8
|
||||||
|
Rlim_rss_cur uint64
|
||||||
|
Cpuid uint64
|
||||||
|
Vm_map_size uint64
|
||||||
|
Tid int32
|
||||||
|
Rtableid uint32
|
||||||
|
}
|
||||||
99
component/memory/memory_openbsd_arm.go
Normal file
99
component/memory/memory_openbsd_arm.go
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
const sizeOfKinfoProc = 0x264
|
||||||
|
|
||||||
|
type KinfoProc struct {
|
||||||
|
Forw uint64
|
||||||
|
Back uint64
|
||||||
|
Paddr uint64
|
||||||
|
Addr uint64
|
||||||
|
Fd uint64
|
||||||
|
Stats uint64
|
||||||
|
Limit uint64
|
||||||
|
Vmspace uint64
|
||||||
|
Sigacts uint64
|
||||||
|
Sess uint64
|
||||||
|
Tsess uint64
|
||||||
|
Ru uint64
|
||||||
|
Eflag int32
|
||||||
|
Exitsig int32
|
||||||
|
Flag int32
|
||||||
|
Pid int32
|
||||||
|
Ppid int32
|
||||||
|
Sid int32
|
||||||
|
X_pgid int32
|
||||||
|
Tpgid int32
|
||||||
|
Uid uint32
|
||||||
|
Ruid uint32
|
||||||
|
Gid uint32
|
||||||
|
Rgid uint32
|
||||||
|
Groups [16]uint32
|
||||||
|
Ngroups int16
|
||||||
|
Jobc int16
|
||||||
|
Tdev uint32
|
||||||
|
Estcpu uint32
|
||||||
|
Rtime_sec uint32
|
||||||
|
Rtime_usec uint32
|
||||||
|
Cpticks int32
|
||||||
|
Pctcpu uint32
|
||||||
|
Swtime uint32
|
||||||
|
Slptime uint32
|
||||||
|
Schedflags int32
|
||||||
|
Uticks uint64
|
||||||
|
Sticks uint64
|
||||||
|
Iticks uint64
|
||||||
|
Tracep uint64
|
||||||
|
Traceflag int32
|
||||||
|
Holdcnt int32
|
||||||
|
Siglist int32
|
||||||
|
Sigmask uint32
|
||||||
|
Sigignore uint32
|
||||||
|
Sigcatch uint32
|
||||||
|
Stat int8
|
||||||
|
Priority uint8
|
||||||
|
Usrpri uint8
|
||||||
|
Nice uint8
|
||||||
|
Xstat uint16
|
||||||
|
Acflag uint16
|
||||||
|
Comm [24]int8
|
||||||
|
Wmesg [8]int8
|
||||||
|
Wchan uint64
|
||||||
|
Login [32]int8
|
||||||
|
Vm_rssize int32
|
||||||
|
Vm_tsize int32
|
||||||
|
Vm_dsize int32
|
||||||
|
Vm_ssize int32
|
||||||
|
Uvalid int64
|
||||||
|
Ustart_sec uint64
|
||||||
|
Ustart_usec uint32
|
||||||
|
Uutime_sec uint32
|
||||||
|
Uutime_usec uint32
|
||||||
|
Ustime_sec uint32
|
||||||
|
Ustime_usec uint32
|
||||||
|
Uru_maxrss uint64
|
||||||
|
Uru_ixrss uint64
|
||||||
|
Uru_idrss uint64
|
||||||
|
Uru_isrss uint64
|
||||||
|
Uru_minflt uint64
|
||||||
|
Uru_majflt uint64
|
||||||
|
Uru_nswap uint64
|
||||||
|
Uru_inblock uint64
|
||||||
|
Uru_oublock uint64
|
||||||
|
Uru_msgsnd uint64
|
||||||
|
Uru_msgrcv uint64
|
||||||
|
Uru_nsignals uint64
|
||||||
|
Uru_nvcsw uint64
|
||||||
|
Uru_nivcsw uint64
|
||||||
|
Uctime_sec uint32
|
||||||
|
Uctime_usec uint32
|
||||||
|
Psflags int32
|
||||||
|
Spare int32
|
||||||
|
Svuid uint32
|
||||||
|
Svgid uint32
|
||||||
|
Emul [8]int8
|
||||||
|
Rlim_rss_cur uint64
|
||||||
|
Cpuid uint64
|
||||||
|
Vm_map_size uint64
|
||||||
|
Tid int32
|
||||||
|
Rtableid uint32
|
||||||
|
}
|
||||||
100
component/memory/memory_openbsd_arm64.go
Normal file
100
component/memory/memory_openbsd_arm64.go
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
const sizeOfKinfoProc = 0x270
|
||||||
|
|
||||||
|
type KinfoProc struct {
|
||||||
|
Forw uint64
|
||||||
|
Back uint64
|
||||||
|
Paddr uint64
|
||||||
|
Addr uint64
|
||||||
|
Fd uint64
|
||||||
|
Stats uint64
|
||||||
|
Limit uint64
|
||||||
|
Vmspace uint64
|
||||||
|
Sigacts uint64
|
||||||
|
Sess uint64
|
||||||
|
Tsess uint64
|
||||||
|
Ru uint64
|
||||||
|
Eflag int32
|
||||||
|
Exitsig int32
|
||||||
|
Flag int32
|
||||||
|
Pid int32
|
||||||
|
Ppid int32
|
||||||
|
Sid int32
|
||||||
|
X_pgid int32
|
||||||
|
Tpgid int32
|
||||||
|
Uid uint32
|
||||||
|
Ruid uint32
|
||||||
|
Gid uint32
|
||||||
|
Rgid uint32
|
||||||
|
Groups [16]uint32
|
||||||
|
Ngroups int16
|
||||||
|
Jobc int16
|
||||||
|
Tdev uint32
|
||||||
|
Estcpu uint32
|
||||||
|
Rtime_sec uint32
|
||||||
|
Rtime_usec uint32
|
||||||
|
Cpticks int32
|
||||||
|
Pctcpu uint32
|
||||||
|
Swtime uint32
|
||||||
|
Slptime uint32
|
||||||
|
Schedflags int32
|
||||||
|
Uticks uint64
|
||||||
|
Sticks uint64
|
||||||
|
Iticks uint64
|
||||||
|
Tracep uint64
|
||||||
|
Traceflag int32
|
||||||
|
Holdcnt int32
|
||||||
|
Siglist int32
|
||||||
|
Sigmask uint32
|
||||||
|
Sigignore uint32
|
||||||
|
Sigcatch uint32
|
||||||
|
Stat int8
|
||||||
|
Priority uint8
|
||||||
|
Usrpri uint8
|
||||||
|
Nice uint8
|
||||||
|
Xstat uint16
|
||||||
|
Acflag uint16
|
||||||
|
Comm [24]int8
|
||||||
|
Wmesg [8]uint8
|
||||||
|
Wchan uint64
|
||||||
|
Login [32]uint8
|
||||||
|
Vm_rssize int32
|
||||||
|
Vm_tsize int32
|
||||||
|
Vm_dsize int32
|
||||||
|
Vm_ssize int32
|
||||||
|
Uvalid int64
|
||||||
|
Ustart_sec uint64
|
||||||
|
Ustart_usec uint32
|
||||||
|
Uutime_sec uint32
|
||||||
|
Uutime_usec uint32
|
||||||
|
Ustime_sec uint32
|
||||||
|
Ustime_usec uint32
|
||||||
|
Uru_maxrss uint64
|
||||||
|
Uru_ixrss uint64
|
||||||
|
Uru_idrss uint64
|
||||||
|
Uru_isrss uint64
|
||||||
|
Uru_minflt uint64
|
||||||
|
Uru_majflt uint64
|
||||||
|
Uru_nswap uint64
|
||||||
|
Uru_inblock uint64
|
||||||
|
Uru_oublock uint64
|
||||||
|
Uru_msgsnd uint64
|
||||||
|
Uru_msgrcv uint64
|
||||||
|
Uru_nsignals uint64
|
||||||
|
Uru_nvcsw uint64
|
||||||
|
Uru_nivcsw uint64
|
||||||
|
Uctime_sec uint32
|
||||||
|
Uctime_usec uint32
|
||||||
|
Psflags uint32
|
||||||
|
Spare int32
|
||||||
|
Svuid uint32
|
||||||
|
Svgid uint32
|
||||||
|
Emul [8]uint8
|
||||||
|
Rlim_rss_cur uint64
|
||||||
|
Cpuid uint64
|
||||||
|
Vm_map_size uint64
|
||||||
|
Tid int32
|
||||||
|
Rtableid uint32
|
||||||
|
Pledge uint64
|
||||||
|
}
|
||||||
101
component/memory/memory_openbsd_riscv64.go
Normal file
101
component/memory/memory_openbsd_riscv64.go
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
const sizeOfKinfoProc = 0x288
|
||||||
|
|
||||||
|
type KinfoProc struct {
|
||||||
|
Forw uint64
|
||||||
|
Back uint64
|
||||||
|
Paddr uint64
|
||||||
|
Addr uint64
|
||||||
|
Fd uint64
|
||||||
|
Stats uint64
|
||||||
|
Limit uint64
|
||||||
|
Vmspace uint64
|
||||||
|
Sigacts uint64
|
||||||
|
Sess uint64
|
||||||
|
Tsess uint64
|
||||||
|
Ru uint64
|
||||||
|
Eflag int32
|
||||||
|
Exitsig int32
|
||||||
|
Flag int32
|
||||||
|
Pid int32
|
||||||
|
Ppid int32
|
||||||
|
Sid int32
|
||||||
|
X_pgid int32
|
||||||
|
Tpgid int32
|
||||||
|
Uid uint32
|
||||||
|
Ruid uint32
|
||||||
|
Gid uint32
|
||||||
|
Rgid uint32
|
||||||
|
Groups [16]uint32
|
||||||
|
Ngroups int16
|
||||||
|
Jobc int16
|
||||||
|
Tdev uint32
|
||||||
|
Estcpu uint32
|
||||||
|
Rtime_sec uint32
|
||||||
|
Rtime_usec uint32
|
||||||
|
Cpticks int32
|
||||||
|
Pctcpu uint32
|
||||||
|
Swtime uint32
|
||||||
|
Slptime uint32
|
||||||
|
Schedflags int32
|
||||||
|
Uticks uint64
|
||||||
|
Sticks uint64
|
||||||
|
Iticks uint64
|
||||||
|
Tracep uint64
|
||||||
|
Traceflag int32
|
||||||
|
Holdcnt int32
|
||||||
|
Siglist int32
|
||||||
|
Sigmask uint32
|
||||||
|
Sigignore uint32
|
||||||
|
Sigcatch uint32
|
||||||
|
Stat int8
|
||||||
|
Priority uint8
|
||||||
|
Usrpri uint8
|
||||||
|
Nice uint8
|
||||||
|
Xstat uint16
|
||||||
|
Spare uint16
|
||||||
|
Comm [24]int8
|
||||||
|
Wmesg [8]uint8
|
||||||
|
Wchan uint64
|
||||||
|
Login [32]uint8
|
||||||
|
Vm_rssize int32
|
||||||
|
Vm_tsize int32
|
||||||
|
Vm_dsize int32
|
||||||
|
Vm_ssize int32
|
||||||
|
Uvalid int64
|
||||||
|
Ustart_sec uint64
|
||||||
|
Ustart_usec uint32
|
||||||
|
Uutime_sec uint32
|
||||||
|
Uutime_usec uint32
|
||||||
|
Ustime_sec uint32
|
||||||
|
Ustime_usec uint32
|
||||||
|
Uru_maxrss uint64
|
||||||
|
Uru_ixrss uint64
|
||||||
|
Uru_idrss uint64
|
||||||
|
Uru_isrss uint64
|
||||||
|
Uru_minflt uint64
|
||||||
|
Uru_majflt uint64
|
||||||
|
Uru_nswap uint64
|
||||||
|
Uru_inblock uint64
|
||||||
|
Uru_oublock uint64
|
||||||
|
Uru_msgsnd uint64
|
||||||
|
Uru_msgrcv uint64
|
||||||
|
Uru_nsignals uint64
|
||||||
|
Uru_nvcsw uint64
|
||||||
|
Uru_nivcsw uint64
|
||||||
|
Uctime_sec uint32
|
||||||
|
Uctime_usec uint32
|
||||||
|
Psflags uint32
|
||||||
|
Acflag uint32
|
||||||
|
Svuid uint32
|
||||||
|
Svgid uint32
|
||||||
|
Emul [8]uint8
|
||||||
|
Rlim_rss_cur uint64
|
||||||
|
Cpuid uint64
|
||||||
|
Vm_map_size uint64
|
||||||
|
Tid int32
|
||||||
|
Rtableid uint32
|
||||||
|
Pledge uint64
|
||||||
|
Name [24]uint8
|
||||||
|
}
|
||||||
23
component/memory/memory_test.go
Normal file
23
component/memory/memory_test.go
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMemoryInfo(t *testing.T) {
|
||||||
|
v, err := GetMemoryInfo(int32(os.Getpid()))
|
||||||
|
if errors.Is(err, ErrNotImplementedError) {
|
||||||
|
t.Skip("not implemented")
|
||||||
|
}
|
||||||
|
require.NoErrorf(t, err, "getting memory info error %v", err)
|
||||||
|
empty := MemoryInfoStat{}
|
||||||
|
if v == nil || *v == empty {
|
||||||
|
t.Errorf("could not get memory info %v", v)
|
||||||
|
} else {
|
||||||
|
t.Logf("memory info {RSS:%s, VMS:%s}", PrettyByteSize(v.RSS), PrettyByteSize(v.VMS))
|
||||||
|
}
|
||||||
|
}
|
||||||
66
component/memory/memory_windows.go
Normal file
66
component/memory/memory_windows.go
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
modpsapi = windows.NewLazySystemDLL("psapi.dll")
|
||||||
|
procGetProcessMemoryInfo = modpsapi.NewProc("GetProcessMemoryInfo")
|
||||||
|
)
|
||||||
|
|
||||||
|
const processQueryInformation = windows.PROCESS_QUERY_LIMITED_INFORMATION
|
||||||
|
|
||||||
|
type PROCESS_MEMORY_COUNTERS struct {
|
||||||
|
CB uint32
|
||||||
|
PageFaultCount uint32
|
||||||
|
PeakWorkingSetSize uint64
|
||||||
|
WorkingSetSize uint64
|
||||||
|
QuotaPeakPagedPoolUsage uint64
|
||||||
|
QuotaPagedPoolUsage uint64
|
||||||
|
QuotaPeakNonPagedPoolUsage uint64
|
||||||
|
QuotaNonPagedPoolUsage uint64
|
||||||
|
PagefileUsage uint64
|
||||||
|
PeakPagefileUsage uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProcessMemoryInfo(h windows.Handle, mem *PROCESS_MEMORY_COUNTERS) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall(procGetProcessMemoryInfo.Addr(), 3, uintptr(h), uintptr(unsafe.Pointer(mem)), uintptr(unsafe.Sizeof(*mem)))
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func getMemoryInfo(pid int32) (PROCESS_MEMORY_COUNTERS, error) {
|
||||||
|
var mem PROCESS_MEMORY_COUNTERS
|
||||||
|
c, err := windows.OpenProcess(processQueryInformation, false, uint32(pid))
|
||||||
|
if err != nil {
|
||||||
|
return mem, err
|
||||||
|
}
|
||||||
|
defer windows.CloseHandle(c)
|
||||||
|
if err := getProcessMemoryInfo(c, &mem); err != nil {
|
||||||
|
return mem, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return mem, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetMemoryInfo(pid int32) (*MemoryInfoStat, error) {
|
||||||
|
mem, err := getMemoryInfo(pid)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ret := &MemoryInfoStat{
|
||||||
|
RSS: uint64(mem.WorkingSetSize),
|
||||||
|
VMS: uint64(mem.PagefileUsage),
|
||||||
|
}
|
||||||
|
return ret, nil
|
||||||
|
}
|
||||||
@@ -19,6 +19,7 @@ var (
|
|||||||
|
|
||||||
bucketSelected = []byte("selected")
|
bucketSelected = []byte("selected")
|
||||||
bucketFakeip = []byte("fakeip")
|
bucketFakeip = []byte("fakeip")
|
||||||
|
bucketFakeip6 = []byte("fakeip6")
|
||||||
bucketETag = []byte("etag")
|
bucketETag = []byte("etag")
|
||||||
bucketSubscriptionInfo = []byte("subscriptioninfo")
|
bucketSubscriptionInfo = []byte("subscriptioninfo")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -10,10 +10,15 @@ import (
|
|||||||
|
|
||||||
type FakeIpStore struct {
|
type FakeIpStore struct {
|
||||||
*CacheFile
|
*CacheFile
|
||||||
|
bucketName []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *CacheFile) FakeIpStore() *FakeIpStore {
|
func (c *CacheFile) FakeIpStore() *FakeIpStore {
|
||||||
return &FakeIpStore{c}
|
return &FakeIpStore{c, bucketFakeip}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *CacheFile) FakeIpStore6() *FakeIpStore {
|
||||||
|
return &FakeIpStore{c, bucketFakeip6}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *FakeIpStore) GetByHost(host string) (ip netip.Addr, exist bool) {
|
func (c *FakeIpStore) GetByHost(host string) (ip netip.Addr, exist bool) {
|
||||||
@@ -21,7 +26,7 @@ func (c *FakeIpStore) GetByHost(host string) (ip netip.Addr, exist bool) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.DB.View(func(t *bbolt.Tx) error {
|
c.DB.View(func(t *bbolt.Tx) error {
|
||||||
if bucket := t.Bucket(bucketFakeip); bucket != nil {
|
if bucket := t.Bucket(c.bucketName); bucket != nil {
|
||||||
if v := bucket.Get([]byte(host)); v != nil {
|
if v := bucket.Get([]byte(host)); v != nil {
|
||||||
ip, exist = netip.AddrFromSlice(v)
|
ip, exist = netip.AddrFromSlice(v)
|
||||||
}
|
}
|
||||||
@@ -36,7 +41,7 @@ func (c *FakeIpStore) PutByHost(host string, ip netip.Addr) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
err := c.DB.Batch(func(t *bbolt.Tx) error {
|
err := c.DB.Batch(func(t *bbolt.Tx) error {
|
||||||
bucket, err := t.CreateBucketIfNotExists(bucketFakeip)
|
bucket, err := t.CreateBucketIfNotExists(c.bucketName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -52,7 +57,7 @@ func (c *FakeIpStore) GetByIP(ip netip.Addr) (host string, exist bool) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.DB.View(func(t *bbolt.Tx) error {
|
c.DB.View(func(t *bbolt.Tx) error {
|
||||||
if bucket := t.Bucket(bucketFakeip); bucket != nil {
|
if bucket := t.Bucket(c.bucketName); bucket != nil {
|
||||||
if v := bucket.Get(ip.AsSlice()); v != nil {
|
if v := bucket.Get(ip.AsSlice()); v != nil {
|
||||||
host, exist = string(v), true
|
host, exist = string(v), true
|
||||||
}
|
}
|
||||||
@@ -67,7 +72,7 @@ func (c *FakeIpStore) PutByIP(ip netip.Addr, host string) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
err := c.DB.Batch(func(t *bbolt.Tx) error {
|
err := c.DB.Batch(func(t *bbolt.Tx) error {
|
||||||
bucket, err := t.CreateBucketIfNotExists(bucketFakeip)
|
bucket, err := t.CreateBucketIfNotExists(c.bucketName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -85,7 +90,7 @@ func (c *FakeIpStore) DelByIP(ip netip.Addr) {
|
|||||||
|
|
||||||
addr := ip.AsSlice()
|
addr := ip.AsSlice()
|
||||||
err := c.DB.Batch(func(t *bbolt.Tx) error {
|
err := c.DB.Batch(func(t *bbolt.Tx) error {
|
||||||
bucket, err := t.CreateBucketIfNotExists(bucketFakeip)
|
bucket, err := t.CreateBucketIfNotExists(c.bucketName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -105,11 +110,11 @@ func (c *FakeIpStore) DelByIP(ip netip.Addr) {
|
|||||||
|
|
||||||
func (c *FakeIpStore) FlushFakeIP() error {
|
func (c *FakeIpStore) FlushFakeIP() error {
|
||||||
err := c.DB.Batch(func(t *bbolt.Tx) error {
|
err := c.DB.Batch(func(t *bbolt.Tx) error {
|
||||||
bucket := t.Bucket(bucketFakeip)
|
bucket := t.Bucket(c.bucketName)
|
||||||
if bucket == nil {
|
if bucket == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return t.DeleteBucket(bucketFakeip)
|
return t.DeleteBucket(c.bucketName)
|
||||||
})
|
})
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,15 +6,15 @@ import (
|
|||||||
D "github.com/miekg/dns"
|
D "github.com/miekg/dns"
|
||||||
)
|
)
|
||||||
|
|
||||||
var DefaultLocalServer LocalServer
|
var DefaultService Service
|
||||||
|
|
||||||
type LocalServer interface {
|
type Service interface {
|
||||||
ServeMsg(ctx context.Context, msg *D.Msg) (*D.Msg, error)
|
ServeMsg(ctx context.Context, msg *D.Msg) (*D.Msg, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServeMsg with a dns.Msg, return resolve dns.Msg
|
// ServeMsg with a dns.Msg, return resolve dns.Msg
|
||||||
func ServeMsg(ctx context.Context, msg *D.Msg) (*D.Msg, error) {
|
func ServeMsg(ctx context.Context, msg *D.Msg) (*D.Msg, error) {
|
||||||
if server := DefaultLocalServer; server != nil {
|
if server := DefaultService; server != nil {
|
||||||
return server.ServeMsg(ctx, msg)
|
return server.ServeMsg(ctx, msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
|
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/slowdown"
|
"github.com/metacubex/mihomo/component/slowdown"
|
||||||
types "github.com/metacubex/mihomo/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
"github.com/metacubex/fswatch"
|
"github.com/metacubex/fswatch"
|
||||||
@@ -22,7 +22,7 @@ type Fetcher[V any] struct {
|
|||||||
ctxCancel context.CancelFunc
|
ctxCancel context.CancelFunc
|
||||||
resourceType string
|
resourceType string
|
||||||
name string
|
name string
|
||||||
vehicle types.Vehicle
|
vehicle P.Vehicle
|
||||||
updatedAt time.Time
|
updatedAt time.Time
|
||||||
hash utils.HashType
|
hash utils.HashType
|
||||||
parser Parser[V]
|
parser Parser[V]
|
||||||
@@ -37,11 +37,11 @@ func (f *Fetcher[V]) Name() string {
|
|||||||
return f.name
|
return f.name
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fetcher[V]) Vehicle() types.Vehicle {
|
func (f *Fetcher[V]) Vehicle() P.Vehicle {
|
||||||
return f.vehicle
|
return f.vehicle
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fetcher[V]) VehicleType() types.VehicleType {
|
func (f *Fetcher[V]) VehicleType() P.VehicleType {
|
||||||
return f.vehicle.Type()
|
return f.vehicle.Type()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,7 +88,7 @@ func (f *Fetcher[V]) Update() (V, bool, error) {
|
|||||||
f.backoff.AddAttempt() // add a failed attempt to backoff
|
f.backoff.AddAttempt() // add a failed attempt to backoff
|
||||||
return lo.Empty[V](), false, err
|
return lo.Empty[V](), false, err
|
||||||
}
|
}
|
||||||
return f.loadBuf(buf, hash, f.vehicle.Type() != types.File)
|
return f.loadBuf(buf, hash, f.vehicle.Type() != P.File)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fetcher[V]) SideUpdate(buf []byte) (V, bool, error) {
|
func (f *Fetcher[V]) SideUpdate(buf []byte) (V, bool, error) {
|
||||||
@@ -180,10 +180,9 @@ func (f *Fetcher[V]) pullLoop(forceUpdate bool) {
|
|||||||
|
|
||||||
func (f *Fetcher[V]) startPullLoop(forceUpdate bool) (err error) {
|
func (f *Fetcher[V]) startPullLoop(forceUpdate bool) (err error) {
|
||||||
// pull contents automatically
|
// pull contents automatically
|
||||||
if f.vehicle.Type() == types.File {
|
if f.vehicle.Type() == P.File {
|
||||||
f.watcher, err = fswatch.NewWatcher(fswatch.Options{
|
f.watcher, err = fswatch.NewWatcher(fswatch.Options{
|
||||||
Path: []string{f.vehicle.Path()},
|
Path: []string{f.vehicle.Path()},
|
||||||
Direct: true,
|
|
||||||
Callback: f.updateCallback,
|
Callback: f.updateCallback,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -219,7 +218,7 @@ func (f *Fetcher[V]) updateWithLog() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewFetcher[V any](name string, interval time.Duration, vehicle types.Vehicle, parser Parser[V], onUpdate func(V)) *Fetcher[V] {
|
func NewFetcher[V any](name string, interval time.Duration, vehicle P.Vehicle, parser Parser[V], onUpdate func(V)) *Fetcher[V] {
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
minBackoff := 10 * time.Second
|
minBackoff := 10 * time.Second
|
||||||
if interval < minBackoff {
|
if interval < minBackoff {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import (
|
|||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
mihomoHttp "github.com/metacubex/mihomo/component/http"
|
mihomoHttp "github.com/metacubex/mihomo/component/http"
|
||||||
"github.com/metacubex/mihomo/component/profile/cachefile"
|
"github.com/metacubex/mihomo/component/profile/cachefile"
|
||||||
types "github.com/metacubex/mihomo/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -50,8 +50,8 @@ type FileVehicle struct {
|
|||||||
path string
|
path string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *FileVehicle) Type() types.VehicleType {
|
func (f *FileVehicle) Type() P.VehicleType {
|
||||||
return types.File
|
return P.File
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *FileVehicle) Path() string {
|
func (f *FileVehicle) Path() string {
|
||||||
@@ -91,15 +91,15 @@ type HTTPVehicle struct {
|
|||||||
timeout time.Duration
|
timeout time.Duration
|
||||||
sizeLimit int64
|
sizeLimit int64
|
||||||
inRead func(response *http.Response)
|
inRead func(response *http.Response)
|
||||||
provider types.ProxyProvider
|
provider P.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *HTTPVehicle) Url() string {
|
func (h *HTTPVehicle) Url() string {
|
||||||
return h.url
|
return h.url
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *HTTPVehicle) Type() types.VehicleType {
|
func (h *HTTPVehicle) Type() P.VehicleType {
|
||||||
return types.HTTP
|
return P.HTTP
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *HTTPVehicle) Path() string {
|
func (h *HTTPVehicle) Path() string {
|
||||||
@@ -135,7 +135,7 @@ func (h *HTTPVehicle) Read(ctx context.Context, oldHash utils.HashType) (buf []b
|
|||||||
setIfNoneMatch = true
|
setIfNoneMatch = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
resp, err := mihomoHttp.HttpRequestWithProxy(ctx, h.url, http.MethodGet, header, nil, h.proxy)
|
resp, err := mihomoHttp.HttpRequest(ctx, h.url, http.MethodGet, header, nil, mihomoHttp.WithSpecialProxy(h.proxy))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
45
component/tls/auth.go
Normal file
45
component/tls/auth.go
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package tls
|
||||||
|
|
||||||
|
import (
|
||||||
|
utls "github.com/metacubex/utls"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ClientAuthType = utls.ClientAuthType
|
||||||
|
|
||||||
|
const (
|
||||||
|
NoClientCert = utls.NoClientCert
|
||||||
|
RequestClientCert = utls.RequestClientCert
|
||||||
|
RequireAnyClientCert = utls.RequireAnyClientCert
|
||||||
|
VerifyClientCertIfGiven = utls.VerifyClientCertIfGiven
|
||||||
|
RequireAndVerifyClientCert = utls.RequireAndVerifyClientCert
|
||||||
|
)
|
||||||
|
|
||||||
|
func ClientAuthTypeFromString(s string) ClientAuthType {
|
||||||
|
switch s {
|
||||||
|
case "request":
|
||||||
|
return RequestClientCert
|
||||||
|
case "require-any":
|
||||||
|
return RequireAnyClientCert
|
||||||
|
case "verify-if-given":
|
||||||
|
return VerifyClientCertIfGiven
|
||||||
|
case "require-and-verify":
|
||||||
|
return RequireAndVerifyClientCert
|
||||||
|
default:
|
||||||
|
return NoClientCert
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ClientAuthTypeToString(t ClientAuthType) string {
|
||||||
|
switch t {
|
||||||
|
case RequestClientCert:
|
||||||
|
return "request"
|
||||||
|
case RequireAnyClientCert:
|
||||||
|
return "require-any"
|
||||||
|
case VerifyClientCertIfGiven:
|
||||||
|
return "verify-if-given"
|
||||||
|
case RequireAndVerifyClientCert:
|
||||||
|
return "require-and-verify"
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,7 +24,6 @@ import (
|
|||||||
|
|
||||||
"github.com/metacubex/randv2"
|
"github.com/metacubex/randv2"
|
||||||
utls "github.com/metacubex/utls"
|
utls "github.com/metacubex/utls"
|
||||||
"golang.org/x/crypto/chacha20poly1305"
|
|
||||||
"golang.org/x/crypto/hkdf"
|
"golang.org/x/crypto/hkdf"
|
||||||
"golang.org/x/net/http2"
|
"golang.org/x/net/http2"
|
||||||
)
|
)
|
||||||
@@ -107,13 +106,8 @@ func GetRealityConn(ctx context.Context, conn net.Conn, fingerprint UClientHello
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
var aeadCipher cipher.AEAD
|
aesBlock, _ := aes.NewCipher(authKey)
|
||||||
if utls.AesgcmPreferred(hello.CipherSuites) {
|
aeadCipher, _ := cipher.NewGCM(aesBlock)
|
||||||
aesBlock, _ := aes.NewCipher(authKey)
|
|
||||||
aeadCipher, _ = cipher.NewGCM(aesBlock)
|
|
||||||
} else {
|
|
||||||
aeadCipher, _ = chacha20poly1305.New(authKey)
|
|
||||||
}
|
|
||||||
aeadCipher.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw)
|
aeadCipher.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw)
|
||||||
copy(hello.Raw[39:], hello.SessionId)
|
copy(hello.Raw[39:], hello.SessionId)
|
||||||
//log.Debugln("REALITY hello.sessionId: %v", hello.SessionId)
|
//log.Debugln("REALITY hello.sessionId: %v", hello.SessionId)
|
||||||
@@ -170,7 +164,7 @@ type realityVerifier struct {
|
|||||||
//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 {
|
||||||
//log.Debugln("REALITY localAddr: %v\t is using X25519MLKEM768 for TLS' communication: %v", c.RemoteAddr(), c.HandshakeState.ServerHello.SelectedGroup == utls.X25519MLKEM768)
|
log.Debugln("REALITY localAddr: %v is using X25519MLKEM768 for TLS' communication: %v", c.RemoteAddr(), c.HandshakeState.ServerHello.ServerShare.Group == utls.X25519MLKEM768)
|
||||||
//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()
|
certs := c.Conn.PeerCertificates()
|
||||||
@@ -185,6 +179,7 @@ func (c *realityVerifier) VerifyPeerCertificate(rawCerts [][]byte, verifiedChain
|
|||||||
opts := x509.VerifyOptions{
|
opts := x509.VerifyOptions{
|
||||||
DNSName: c.serverName,
|
DNSName: c.serverName,
|
||||||
Intermediates: x509.NewCertPool(),
|
Intermediates: x509.NewCertPool(),
|
||||||
|
CurrentTime: ntp.Now(),
|
||||||
}
|
}
|
||||||
for _, cert := range certs[1:] {
|
for _, cert := range certs[1:] {
|
||||||
opts.Intermediates.AddCert(cert)
|
opts.Intermediates.AddCert(cert)
|
||||||
|
|||||||
@@ -135,6 +135,8 @@ func UConfig(config *tls.Config) *utls.Config {
|
|||||||
RootCAs: config.RootCAs,
|
RootCAs: config.RootCAs,
|
||||||
NextProtos: config.NextProtos,
|
NextProtos: config.NextProtos,
|
||||||
ServerName: config.ServerName,
|
ServerName: config.ServerName,
|
||||||
|
ClientAuth: utls.ClientAuthType(config.ClientAuth),
|
||||||
|
ClientCAs: config.ClientCAs,
|
||||||
InsecureSkipVerify: config.InsecureSkipVerify,
|
InsecureSkipVerify: config.InsecureSkipVerify,
|
||||||
CipherSuites: config.CipherSuites,
|
CipherSuites: config.CipherSuites,
|
||||||
MinVersion: config.MinVersion,
|
MinVersion: config.MinVersion,
|
||||||
|
|||||||
@@ -8,12 +8,14 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
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/constant/features"
|
"github.com/metacubex/mihomo/constant/features"
|
||||||
@@ -33,6 +35,11 @@ const (
|
|||||||
MaxPackageFileSize = 32 * 1024 * 1024
|
MaxPackageFileSize = 32 * 1024 * 1024
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
ReleaseChannel = "release"
|
||||||
|
AlphaChannel = "alpha"
|
||||||
|
)
|
||||||
|
|
||||||
// CoreUpdater is the mihomo updater.
|
// CoreUpdater is the mihomo updater.
|
||||||
// modify from https://github.com/AdguardTeam/AdGuardHome/blob/595484e0b3fb4c457f9bb727a6b94faa78a66c5f/internal/updater/updater.go
|
// modify from https://github.com/AdguardTeam/AdGuardHome/blob/595484e0b3fb4c457f9bb727a6b94faa78a66c5f/internal/updater/updater.go
|
||||||
type CoreUpdater struct {
|
type CoreUpdater struct {
|
||||||
@@ -69,20 +76,28 @@ func (u *CoreUpdater) CoreBaseName() string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *CoreUpdater) Update(currentExePath string) (err error) {
|
func (u *CoreUpdater) Update(currentExePath string, channel string, force bool) (err error) {
|
||||||
u.mu.Lock()
|
u.mu.Lock()
|
||||||
defer u.mu.Unlock()
|
defer u.mu.Unlock()
|
||||||
|
|
||||||
_, err = os.Stat(currentExePath)
|
info, err := os.Stat(currentExePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("check currentExePath %q: %w", currentExePath, err)
|
return fmt.Errorf("check currentExePath %q: %w", currentExePath, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
baseURL := baseAlphaURL
|
baseURL := baseAlphaURL
|
||||||
versionURL := versionAlphaURL
|
versionURL := versionAlphaURL
|
||||||
if !strings.HasPrefix(C.Version, "alpha") {
|
switch strings.ToLower(channel) {
|
||||||
|
case ReleaseChannel:
|
||||||
baseURL = baseReleaseURL
|
baseURL = baseReleaseURL
|
||||||
versionURL = versionReleaseURL
|
versionURL = versionReleaseURL
|
||||||
|
case AlphaChannel:
|
||||||
|
break
|
||||||
|
default: // auto
|
||||||
|
if !strings.HasPrefix(C.Version, "alpha") {
|
||||||
|
baseURL = baseReleaseURL
|
||||||
|
versionURL = versionReleaseURL
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
latestVersion, err := u.getLatestVersion(versionURL)
|
latestVersion, err := u.getLatestVersion(versionURL)
|
||||||
@@ -91,7 +106,7 @@ func (u *CoreUpdater) Update(currentExePath string) (err error) {
|
|||||||
}
|
}
|
||||||
log.Infoln("current version %s, latest version %s", C.Version, latestVersion)
|
log.Infoln("current version %s, latest version %s", C.Version, latestVersion)
|
||||||
|
|
||||||
if latestVersion == C.Version {
|
if latestVersion == C.Version && !force {
|
||||||
// don't change this output, some downstream dependencies on the upgrader's output fields
|
// don't change this output, some downstream dependencies on the upgrader's output fields
|
||||||
return fmt.Errorf("update error: already using latest version %s", C.Version)
|
return fmt.Errorf("update error: already using latest version %s", C.Version)
|
||||||
}
|
}
|
||||||
@@ -136,7 +151,7 @@ func (u *CoreUpdater) Update(currentExePath string) (err error) {
|
|||||||
return fmt.Errorf("downloading: %w", err)
|
return fmt.Errorf("downloading: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = u.unpack(updateDir, packagePath)
|
err = u.unpack(updateDir, packagePath, info.Mode())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("unpacking: %w", err)
|
return fmt.Errorf("unpacking: %w", err)
|
||||||
}
|
}
|
||||||
@@ -146,7 +161,7 @@ func (u *CoreUpdater) Update(currentExePath string) (err error) {
|
|||||||
return fmt.Errorf("backuping: %w", err)
|
return fmt.Errorf("backuping: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = u.replace(updateExePath, currentExePath)
|
err = u.copyFile(updateExePath, currentExePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("replacing: %w", err)
|
return fmt.Errorf("replacing: %w", err)
|
||||||
}
|
}
|
||||||
@@ -157,7 +172,7 @@ func (u *CoreUpdater) Update(currentExePath string) (err error) {
|
|||||||
func (u *CoreUpdater) getLatestVersion(versionURL string) (version string, err error) {
|
func (u *CoreUpdater) getLatestVersion(versionURL string) (version string, err error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
resp, err := mihomoHttp.HttpRequest(ctx, versionURL, http.MethodGet, nil, nil)
|
resp, err := mihomoHttp.HttpRequest(ctx, versionURL, http.MethodGet, nil, nil, mihomoHttp.WithCAOption(ca.Option{ZeroTrust: true}))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@@ -180,7 +195,7 @@ func (u *CoreUpdater) getLatestVersion(versionURL string) (version string, err e
|
|||||||
func (u *CoreUpdater) download(updateDir, packagePath, packageURL string) (err error) {
|
func (u *CoreUpdater) download(updateDir, packagePath, packageURL string) (err error) {
|
||||||
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, packageURL, http.MethodGet, nil, nil)
|
resp, err := mihomoHttp.HttpRequest(ctx, packageURL, http.MethodGet, nil, nil, mihomoHttp.WithCAOption(ca.Option{ZeroTrust: true}))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("http request failed: %w", err)
|
return fmt.Errorf("http request failed: %w", err)
|
||||||
}
|
}
|
||||||
@@ -230,16 +245,16 @@ func (u *CoreUpdater) download(updateDir, packagePath, packageURL string) (err e
|
|||||||
}
|
}
|
||||||
|
|
||||||
// unpack extracts the files from the downloaded archive.
|
// unpack extracts the files from the downloaded archive.
|
||||||
func (u *CoreUpdater) unpack(updateDir, packagePath string) error {
|
func (u *CoreUpdater) unpack(updateDir, packagePath string, fileMode os.FileMode) error {
|
||||||
log.Infoln("updater: unpacking package")
|
log.Infoln("updater: unpacking package")
|
||||||
if strings.HasSuffix(packagePath, ".zip") {
|
if strings.HasSuffix(packagePath, ".zip") {
|
||||||
_, err := u.zipFileUnpack(packagePath, updateDir)
|
_, err := u.zipFileUnpack(packagePath, updateDir, fileMode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf(".zip unpack failed: %w", err)
|
return fmt.Errorf(".zip unpack failed: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if strings.HasSuffix(packagePath, ".gz") {
|
} else if strings.HasSuffix(packagePath, ".gz") {
|
||||||
_, err := u.gzFileUnpack(packagePath, updateDir)
|
_, err := u.gzFileUnpack(packagePath, updateDir, fileMode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf(".gz unpack failed: %w", err)
|
return fmt.Errorf(".gz unpack failed: %w", err)
|
||||||
}
|
}
|
||||||
@@ -271,21 +286,6 @@ func (u *CoreUpdater) backup(currentExePath, backupExePath, backupDir string) (e
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// replace moves the current executable with the updated one
|
|
||||||
func (u *CoreUpdater) replace(updateExePath, currentExePath string) error {
|
|
||||||
log.Infoln("replacing: %s to %s", updateExePath, currentExePath)
|
|
||||||
|
|
||||||
// Use copyFile to retain the original file attributes
|
|
||||||
err := u.copyFile(updateExePath, currentExePath)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Infoln("updater: copy: %s to %s", updateExePath, currentExePath)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// clean removes the temporary directory itself and all it's contents.
|
// clean removes the temporary directory itself and all it's contents.
|
||||||
func (u *CoreUpdater) clean(updateDir string) {
|
func (u *CoreUpdater) clean(updateDir string) {
|
||||||
_ = os.RemoveAll(updateDir)
|
_ = os.RemoveAll(updateDir)
|
||||||
@@ -295,7 +295,7 @@ func (u *CoreUpdater) clean(updateDir string) {
|
|||||||
// Existing files are overwritten
|
// Existing files are overwritten
|
||||||
// All files are created inside outDir, subdirectories are not created
|
// All files are created inside outDir, subdirectories are not created
|
||||||
// Return the output file name
|
// Return the output file name
|
||||||
func (u *CoreUpdater) gzFileUnpack(gzfile, outDir string) (outputName string, err error) {
|
func (u *CoreUpdater) gzFileUnpack(gzfile, outDir string, fileMode os.FileMode) (outputName string, err error) {
|
||||||
f, err := os.Open(gzfile)
|
f, err := os.Open(gzfile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("os.Open(): %w", err)
|
return "", fmt.Errorf("os.Open(): %w", err)
|
||||||
@@ -330,7 +330,7 @@ func (u *CoreUpdater) gzFileUnpack(gzfile, outDir string) (outputName string, er
|
|||||||
outputName = filepath.Join(outDir, originalName)
|
outputName = filepath.Join(outDir, originalName)
|
||||||
|
|
||||||
// Create the output file
|
// Create the output file
|
||||||
wc, err := os.OpenFile(outputName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
|
wc, err := os.OpenFile(outputName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fileMode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("os.OpenFile(%s): %w", outputName, err)
|
return "", fmt.Errorf("os.OpenFile(%s): %w", outputName, err)
|
||||||
}
|
}
|
||||||
@@ -355,7 +355,7 @@ func (u *CoreUpdater) gzFileUnpack(gzfile, outDir string) (outputName string, er
|
|||||||
// Existing files are overwritten
|
// Existing files are overwritten
|
||||||
// All files are created inside 'outDir', subdirectories are not created
|
// All files are created inside 'outDir', subdirectories are not created
|
||||||
// Return the output file name
|
// Return the output file name
|
||||||
func (u *CoreUpdater) zipFileUnpack(zipfile, outDir string) (outputName string, err error) {
|
func (u *CoreUpdater) zipFileUnpack(zipfile, outDir string, fileMode os.FileMode) (outputName string, err error) {
|
||||||
zrc, err := zip.OpenReader(zipfile)
|
zrc, err := zip.OpenReader(zipfile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("zip.OpenReader(): %w", err)
|
return "", fmt.Errorf("zip.OpenReader(): %w", err)
|
||||||
@@ -394,7 +394,7 @@ func (u *CoreUpdater) zipFileUnpack(zipfile, outDir string) (outputName string,
|
|||||||
}
|
}
|
||||||
|
|
||||||
var wc io.WriteCloser
|
var wc io.WriteCloser
|
||||||
wc, err = os.OpenFile(outputName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fi.Mode())
|
wc, err = os.OpenFile(outputName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fileMode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("os.OpenFile(): %w", err)
|
return "", fmt.Errorf("os.OpenFile(): %w", err)
|
||||||
}
|
}
|
||||||
@@ -437,7 +437,16 @@ func (u *CoreUpdater) copyFile(src, dst string) (err error) {
|
|||||||
// otherwise truncates it before writing, without changing permissions.
|
// otherwise truncates it before writing, without changing permissions.
|
||||||
wc, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, info.Mode())
|
wc, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, info.Mode())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("os.OpenFile(%s): %w", dst, err)
|
// On some file system (such as Android's /data) maybe return error: "text file busy"
|
||||||
|
// Let's delete the target file and recreate it
|
||||||
|
err = os.Remove(dst)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("os.Remove(%s): %w", dst, err)
|
||||||
|
}
|
||||||
|
wc, err = os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, info.Mode())
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("os.OpenFile(%s): %w", dst, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
@@ -452,5 +461,13 @@ func (u *CoreUpdater) copyFile(src, dst string) (err error) {
|
|||||||
return fmt.Errorf("io.Copy(): %w", err)
|
return fmt.Errorf("io.Copy(): %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if runtime.GOOS == "darwin" {
|
||||||
|
err = exec.Command("/usr/bin/codesign", "--sign", "-", dst).Run()
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("codesign failed: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Infoln("updater: copy: %s to %s", src, dst)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"archive/zip"
|
"archive/zip"
|
||||||
"bytes"
|
"bytes"
|
||||||
"compress/gzip"
|
"compress/gzip"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
@@ -12,6 +13,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
@@ -308,7 +310,16 @@ func moveDir(src string, dst string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, dirEntry := range dirEntryList {
|
for _, dirEntry := range dirEntryList {
|
||||||
err = os.Rename(filepath.Join(src, dirEntry.Name()), filepath.Join(dst, dirEntry.Name()))
|
srcPath := filepath.Join(src, dirEntry.Name())
|
||||||
|
dstPath := filepath.Join(dst, dirEntry.Name())
|
||||||
|
err = os.Rename(srcPath, dstPath)
|
||||||
|
if err != nil {
|
||||||
|
// Fallback for invalid cross-device link (errno:18).
|
||||||
|
if errors.Is(err, syscall.Errno(18)) {
|
||||||
|
err = copyAll(srcPath, dstPath)
|
||||||
|
_ = os.RemoveAll(srcPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -316,6 +327,50 @@ func moveDir(src string, dst string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// copyAll copy the src path and any children it contains to dst
|
||||||
|
// modify from [os.CopyFS]
|
||||||
|
func copyAll(src, dst string) error {
|
||||||
|
return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fpath, err := filepath.Rel(src, path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
newPath := filepath.Join(dst, fpath)
|
||||||
|
|
||||||
|
switch info.Mode().Type() {
|
||||||
|
case os.ModeDir:
|
||||||
|
return os.MkdirAll(newPath, info.Mode().Perm())
|
||||||
|
case os.ModeSymlink:
|
||||||
|
target, err := os.Readlink(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Symlink(target, newPath)
|
||||||
|
case 0:
|
||||||
|
r, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer r.Close()
|
||||||
|
w, err := os.OpenFile(newPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, info.Mode().Perm())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.Copy(w, r); err != nil {
|
||||||
|
w.Close()
|
||||||
|
return &os.PathError{Op: "Copy", Path: newPath, Err: err}
|
||||||
|
}
|
||||||
|
return w.Close()
|
||||||
|
default:
|
||||||
|
return &os.PathError{Op: "CopyFS", Path: path, Err: os.ErrInvalid}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func inDest(fpath, dest string) bool {
|
func inDest(fpath, dest string) bool {
|
||||||
if rel, err := filepath.Rel(dest, fpath); err == nil {
|
if rel, err := filepath.Rel(dest, fpath); err == nil {
|
||||||
if filepath.IsLocal(rel) {
|
if filepath.IsLocal(rel) {
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
// Package wildcard modified IGLOU-EU/go-wildcard to support:
|
||||||
|
//
|
||||||
|
// `*` matches zero or more characters
|
||||||
|
// `?` matches exactly one character
|
||||||
|
//
|
||||||
|
// The original go-wildcard library used `.` to match exactly one character, and `?` to match zero or one character.
|
||||||
|
// `.` is a valid delimiter in domain name matching and should not be used as a wildcard.
|
||||||
|
// The `?` matching logic strictly matches only one character in most scenarios.
|
||||||
|
// So, the `?` matching logic in the original go-wildcard library has been removed and its wildcard `.` has been replaced with `?`.
|
||||||
package wildcard
|
package wildcard
|
||||||
|
|
||||||
// copy and modified from https://github.com/IGLOU-EU/go-wildcard/tree/ce22b7af48e487517a492d3727d9386492043e21
|
// copy and modified from https://github.com/IGLOU-EU/go-wildcard/tree/ce22b7af48e487517a492d3727d9386492043e21
|
||||||
@@ -16,12 +25,10 @@ func Match(pattern, s string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func matchByString(pattern, s string) bool {
|
func matchByString(pattern, s string) bool {
|
||||||
var lastErotemeCluster byte
|
var patternIndex, sIndex, lastStar int
|
||||||
var patternIndex, sIndex, lastStar, lastEroteme int
|
|
||||||
patternLen := len(pattern)
|
patternLen := len(pattern)
|
||||||
sLen := len(s)
|
sLen := len(s)
|
||||||
star := -1
|
star := -1
|
||||||
eroteme := -1
|
|
||||||
|
|
||||||
Loop:
|
Loop:
|
||||||
if sIndex >= sLen {
|
if sIndex >= sLen {
|
||||||
@@ -38,14 +45,8 @@ Loop:
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
switch pattern[patternIndex] {
|
switch pattern[patternIndex] {
|
||||||
// Removed dot matching as it conflicts with dot in domains.
|
|
||||||
// case '.':
|
|
||||||
// It matches any single character. So, we don't need to check anything.
|
|
||||||
case '?':
|
case '?':
|
||||||
// '?' matches one character. Store its position and match exactly one character in the string.
|
// It matches any single character. So, we don't need to check anything.
|
||||||
eroteme = patternIndex
|
|
||||||
lastEroteme = sIndex
|
|
||||||
lastErotemeCluster = byte(s[sIndex])
|
|
||||||
case '*':
|
case '*':
|
||||||
// '*' matches zero or more characters. Store its position and increment the pattern index.
|
// '*' matches zero or more characters. Store its position and increment the pattern index.
|
||||||
star = patternIndex
|
star = patternIndex
|
||||||
@@ -53,15 +54,8 @@ Loop:
|
|||||||
patternIndex++
|
patternIndex++
|
||||||
goto Loop
|
goto Loop
|
||||||
default:
|
default:
|
||||||
// If the characters don't match, check if there was a previous '?' or '*' to backtrack.
|
// If the characters don't match, check if there was a previous '*' to backtrack.
|
||||||
if pattern[patternIndex] != s[sIndex] {
|
if pattern[patternIndex] != s[sIndex] {
|
||||||
if eroteme != -1 {
|
|
||||||
patternIndex = eroteme + 1
|
|
||||||
sIndex = lastEroteme
|
|
||||||
eroteme = -1
|
|
||||||
goto Loop
|
|
||||||
}
|
|
||||||
|
|
||||||
if star != -1 {
|
if star != -1 {
|
||||||
patternIndex = star + 1
|
patternIndex = star + 1
|
||||||
lastStar++
|
lastStar++
|
||||||
@@ -71,29 +65,18 @@ Loop:
|
|||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// If the characters match, check if it was not the same to validate the eroteme.
|
|
||||||
if eroteme != -1 && lastErotemeCluster != byte(s[sIndex]) {
|
|
||||||
eroteme = -1
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
patternIndex++
|
patternIndex++
|
||||||
sIndex++
|
sIndex++
|
||||||
goto Loop
|
goto Loop
|
||||||
|
|
||||||
// Check if the remaining pattern characters are '*' or '?', which can match the end of the string.
|
// Check if the remaining pattern characters are '*', which can match the end of the string.
|
||||||
checkPattern:
|
checkPattern:
|
||||||
if patternIndex < patternLen {
|
if patternIndex < patternLen {
|
||||||
if pattern[patternIndex] == '*' {
|
if pattern[patternIndex] == '*' {
|
||||||
patternIndex++
|
patternIndex++
|
||||||
goto checkPattern
|
goto checkPattern
|
||||||
} else if pattern[patternIndex] == '?' {
|
|
||||||
if sIndex >= sLen {
|
|
||||||
sIndex--
|
|
||||||
}
|
|
||||||
patternIndex++
|
|
||||||
goto checkPattern
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,31 +25,17 @@ func TestMatch(t *testing.T) {
|
|||||||
{"", "", true},
|
{"", "", true},
|
||||||
{"", "*", true},
|
{"", "*", true},
|
||||||
{"", "**", true},
|
{"", "**", true},
|
||||||
{"", "?", true},
|
{"", "?", false},
|
||||||
{"", "??", true},
|
{"", "?*", false},
|
||||||
{"", "?*", true},
|
{"", "*?", false},
|
||||||
{"", "*?", true},
|
|
||||||
{"", ".", false},
|
|
||||||
{"", ".?", false},
|
|
||||||
{"", "?.", false},
|
|
||||||
{"", ".*", false},
|
|
||||||
{"", "*.", false},
|
|
||||||
{"", "*.?", false},
|
|
||||||
{"", "?.*", false},
|
|
||||||
|
|
||||||
{"a", "", false},
|
{"a", "", false},
|
||||||
{"a", "a", true},
|
{"a", "a", true},
|
||||||
{"a", "*", true},
|
{"a", "*", true},
|
||||||
{"a", "**", true},
|
{"a", "**", true},
|
||||||
{"a", "?", true},
|
{"a", "?", true},
|
||||||
{"a", "??", true},
|
{"a", "?*", true},
|
||||||
{"a", ".", false},
|
{"a", "*?", true},
|
||||||
{"a", ".?", false},
|
|
||||||
{"a", "?.", false},
|
|
||||||
{"a", ".*", false},
|
|
||||||
{"a", "*.", false},
|
|
||||||
{"a", "*.?", false},
|
|
||||||
{"a", "?.*", false},
|
|
||||||
|
|
||||||
{"match the exact string", "match the exact string", true},
|
{"match the exact string", "match the exact string", true},
|
||||||
{"do not match a different string", "this is a different string", false},
|
{"do not match a different string", "this is a different string", false},
|
||||||
@@ -68,22 +54,27 @@ func TestMatch(t *testing.T) {
|
|||||||
|
|
||||||
{"match a string with a ?", "match ? string with a ?", true},
|
{"match a string with a ?", "match ? string with a ?", true},
|
||||||
{"match a string with a ? at the beginning", "?atch a string with a ? at the beginning", true},
|
{"match a string with a ? at the beginning", "?atch a string with a ? at the beginning", true},
|
||||||
{"match a string with two ?", "match a string with two ??", true},
|
{"match a string with two ?", "match a ??ring with two ?", true},
|
||||||
{"match a optional char with a ?", "match a optional? char with a ?", true},
|
{"do not match a string with extra ?", "do not match a string with extra ??", false},
|
||||||
{"match a optional char with a ?", "match a optional? char with a ?", true},
|
|
||||||
{"do not match a string with extra and a ?", "do not match ? string with extra and a ? like this", false},
|
|
||||||
|
|
||||||
{"do not match a string with a .", "do not match . string with a .", false},
|
{"abc.edf.hjg", "abc.edf.hjg", true},
|
||||||
{"do not match a string with a . at the beginning", "do not .atch a string with a . at the beginning", false},
|
{"abc.edf.hjg", "ab.cedf.hjg", false},
|
||||||
{"do not match a string with two .", "do not match a ..ring with two .", false},
|
{"abc.edf.hjg", "abc.edfh.jg", false},
|
||||||
{"do not match a string with extra .", "do not match a string with extra ..", false},
|
{"abc.edf.hjg", "abc.edf.hjq", false},
|
||||||
|
|
||||||
{"A big brown fox jumps over the lazy dog, with all there wildcards friends", ". big?brown fox jumps over * wildcard. friend??", false},
|
{"abc.edf.hjg", "abc.*.hjg", true},
|
||||||
{"A big brown fox fails to jump over the lazy dog, with all there wildcards friends", ". big?brown fox jumps over * wildcard. friend??", false},
|
{"abc.edf.hjg", "abc.*.hjq", false},
|
||||||
|
{"abc.edf.hjg", "abc*hjg", true},
|
||||||
|
{"abc.edf.hjg", "abc*hjq", false},
|
||||||
|
{"abc.edf.hjg", "a*g", true},
|
||||||
|
{"abc.edf.hjg", "a*q", false},
|
||||||
|
|
||||||
{"domain a.b.c", "domain a.b.c", true},
|
{"abc.edf.hjg", "ab?.edf.hjg", true},
|
||||||
{"domain adb.c", "domain a.b.c", false},
|
{"abc.edf.hjg", "?b?.edf.hjg", true},
|
||||||
{"aaaa", "a*a", true},
|
{"abc.edf.hjg", "??c.edf.hjg", true},
|
||||||
|
{"abc.edf.hjg", "a??.edf.hjg", true},
|
||||||
|
{"abc.edf.hjg", "ab??.edf.hjg", false},
|
||||||
|
{"abc.edf.hjg", "??.edf.hjg", false},
|
||||||
}
|
}
|
||||||
|
|
||||||
for i, c := range cases {
|
for i, c := range cases {
|
||||||
@@ -96,10 +87,106 @@ func TestMatch(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func match(pattern, name string) bool { // https://research.swtch.com/glob
|
||||||
|
px := 0
|
||||||
|
nx := 0
|
||||||
|
nextPx := 0
|
||||||
|
nextNx := 0
|
||||||
|
for px < len(pattern) || nx < len(name) {
|
||||||
|
if px < len(pattern) {
|
||||||
|
c := pattern[px]
|
||||||
|
switch c {
|
||||||
|
default: // ordinary character
|
||||||
|
if nx < len(name) && name[nx] == c {
|
||||||
|
px++
|
||||||
|
nx++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
case '?': // single-character wildcard
|
||||||
|
if nx < len(name) {
|
||||||
|
px++
|
||||||
|
nx++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
case '*': // zero-or-more-character wildcard
|
||||||
|
// Try to match at nx.
|
||||||
|
// If that doesn't work out,
|
||||||
|
// restart at nx+1 next.
|
||||||
|
nextPx = px
|
||||||
|
nextNx = nx + 1
|
||||||
|
px++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Mismatch. Maybe restart.
|
||||||
|
if 0 < nextNx && nextNx <= len(name) {
|
||||||
|
px = nextPx
|
||||||
|
nx = nextNx
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// Matched all of pattern to all of name. Success.
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func FuzzMatch(f *testing.F) {
|
func FuzzMatch(f *testing.F) {
|
||||||
f.Fuzz(func(t *testing.T, s string) {
|
f.Fuzz(func(t *testing.T, pattern, name string) {
|
||||||
if !Match(string(s), string(s)) {
|
result1 := Match(pattern, name)
|
||||||
t.Fatalf("%s does not match %s", s, s)
|
result2 := match(pattern, name)
|
||||||
|
if result1 != result2 {
|
||||||
|
t.Fatalf("Match failed for pattern `%s` and name `%s`", pattern, name)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkMatch(b *testing.B) {
|
||||||
|
cases := []struct {
|
||||||
|
s string
|
||||||
|
pattern string
|
||||||
|
result bool
|
||||||
|
}{
|
||||||
|
{"abc.edf.hjg", "abc.edf.hjg", true},
|
||||||
|
{"abc.edf.hjg", "ab.cedf.hjg", false},
|
||||||
|
{"abc.edf.hjg", "abc.edfh.jg", false},
|
||||||
|
{"abc.edf.hjg", "abc.edf.hjq", false},
|
||||||
|
|
||||||
|
{"abc.edf.hjg", "abc.*.hjg", true},
|
||||||
|
{"abc.edf.hjg", "abc.*.hjq", false},
|
||||||
|
{"abc.edf.hjg", "abc*hjg", true},
|
||||||
|
{"abc.edf.hjg", "abc*hjq", false},
|
||||||
|
{"abc.edf.hjg", "a*g", true},
|
||||||
|
{"abc.edf.hjg", "a*q", false},
|
||||||
|
|
||||||
|
{"abc.edf.hjg", "ab?.edf.hjg", true},
|
||||||
|
{"abc.edf.hjg", "?b?.edf.hjg", true},
|
||||||
|
{"abc.edf.hjg", "??c.edf.hjg", true},
|
||||||
|
{"abc.edf.hjg", "a??.edf.hjg", true},
|
||||||
|
{"abc.edf.hjg", "ab??.edf.hjg", false},
|
||||||
|
{"abc.edf.hjg", "??.edf.hjg", false},
|
||||||
|
|
||||||
|
{"r4.cdn-aa-wow-this-is-long-a1.video-yajusenpai1145141919810-oh-hell-yeah-this-is-also-very-long-and-sukka-the-fox-has-a-very-big-fluffy-fox-tail-ao-wu-ao-wu-regex-and-wildcard-both-might-have-deadly-back-tracing-issue-be-careful-or-use-linear-matching.com", "*.cdn-*-*.video**.com", true},
|
||||||
|
}
|
||||||
|
|
||||||
|
b.Run("Match", func(b *testing.B) {
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
for _, c := range cases {
|
||||||
|
result := Match(c.pattern, c.s)
|
||||||
|
if c.result != result {
|
||||||
|
b.Errorf("Test %d: Expected `%v`, found `%v`; With Pattern: `%s` and String: `%s`", i+1, c.result, result, c.pattern, c.s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
b.Run("match", func(b *testing.B) {
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
for _, c := range cases {
|
||||||
|
result := match(c.pattern, c.s)
|
||||||
|
if c.result != result {
|
||||||
|
b.Errorf("Test %d: Expected `%v`, found `%v`; With Pattern: `%s` and String: `%s`", i+1, c.result, result, c.pattern, c.s)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
299
config/config.go
299
config/config.go
@@ -20,15 +20,15 @@ import (
|
|||||||
"github.com/metacubex/mihomo/component/cidr"
|
"github.com/metacubex/mihomo/component/cidr"
|
||||||
"github.com/metacubex/mihomo/component/fakeip"
|
"github.com/metacubex/mihomo/component/fakeip"
|
||||||
"github.com/metacubex/mihomo/component/geodata"
|
"github.com/metacubex/mihomo/component/geodata"
|
||||||
P "github.com/metacubex/mihomo/component/process"
|
"github.com/metacubex/mihomo/component/process"
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
"github.com/metacubex/mihomo/component/sniffer"
|
"github.com/metacubex/mihomo/component/sniffer"
|
||||||
"github.com/metacubex/mihomo/component/trie"
|
"github.com/metacubex/mihomo/component/trie"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
providerTypes "github.com/metacubex/mihomo/constant/provider"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
snifferTypes "github.com/metacubex/mihomo/constant/sniffer"
|
snifferTypes "github.com/metacubex/mihomo/constant/sniffer"
|
||||||
"github.com/metacubex/mihomo/dns"
|
"github.com/metacubex/mihomo/dns"
|
||||||
L "github.com/metacubex/mihomo/listener"
|
"github.com/metacubex/mihomo/listener"
|
||||||
LC "github.com/metacubex/mihomo/listener/config"
|
LC "github.com/metacubex/mihomo/listener/config"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
R "github.com/metacubex/mihomo/rules"
|
R "github.com/metacubex/mihomo/rules"
|
||||||
@@ -44,27 +44,27 @@ import (
|
|||||||
// General config
|
// General config
|
||||||
type General struct {
|
type General struct {
|
||||||
Inbound
|
Inbound
|
||||||
Mode T.TunnelMode `json:"mode"`
|
Mode T.TunnelMode `json:"mode"`
|
||||||
UnifiedDelay bool `json:"unified-delay"`
|
UnifiedDelay bool `json:"unified-delay"`
|
||||||
LogLevel log.LogLevel `json:"log-level"`
|
LogLevel log.LogLevel `json:"log-level"`
|
||||||
IPv6 bool `json:"ipv6"`
|
IPv6 bool `json:"ipv6"`
|
||||||
Interface string `json:"interface-name"`
|
Interface string `json:"interface-name"`
|
||||||
RoutingMark int `json:"routing-mark"`
|
RoutingMark int `json:"routing-mark"`
|
||||||
GeoXUrl GeoXUrl `json:"geox-url"`
|
GeoXUrl GeoXUrl `json:"geox-url"`
|
||||||
GeoAutoUpdate bool `json:"geo-auto-update"`
|
GeoAutoUpdate bool `json:"geo-auto-update"`
|
||||||
GeoUpdateInterval int `json:"geo-update-interval"`
|
GeoUpdateInterval int `json:"geo-update-interval"`
|
||||||
GeodataMode bool `json:"geodata-mode"`
|
GeodataMode bool `json:"geodata-mode"`
|
||||||
GeodataLoader string `json:"geodata-loader"`
|
GeodataLoader string `json:"geodata-loader"`
|
||||||
GeositeMatcher string `json:"geosite-matcher"`
|
GeositeMatcher string `json:"geosite-matcher"`
|
||||||
TCPConcurrent bool `json:"tcp-concurrent"`
|
TCPConcurrent bool `json:"tcp-concurrent"`
|
||||||
FindProcessMode P.FindProcessMode `json:"find-process-mode"`
|
FindProcessMode process.FindProcessMode `json:"find-process-mode"`
|
||||||
Sniffing bool `json:"sniffing"`
|
Sniffing bool `json:"sniffing"`
|
||||||
GlobalClientFingerprint string `json:"global-client-fingerprint"`
|
GlobalClientFingerprint string `json:"global-client-fingerprint"`
|
||||||
GlobalUA string `json:"global-ua"`
|
GlobalUA string `json:"global-ua"`
|
||||||
ETagSupport bool `json:"etag-support"`
|
ETagSupport bool `json:"etag-support"`
|
||||||
KeepAliveIdle int `json:"keep-alive-idle"`
|
KeepAliveIdle int `json:"keep-alive-idle"`
|
||||||
KeepAliveInterval int `json:"keep-alive-interval"`
|
KeepAliveInterval int `json:"keep-alive-interval"`
|
||||||
DisableKeepAlive bool `json:"disable-keep-alive"`
|
DisableKeepAlive bool `json:"disable-keep-alive"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inbound config
|
// Inbound config
|
||||||
@@ -117,7 +117,6 @@ type Cors struct {
|
|||||||
|
|
||||||
// Experimental config
|
// Experimental config
|
||||||
type Experimental struct {
|
type Experimental struct {
|
||||||
Fingerprints []string
|
|
||||||
QUICGoDisableGSO bool
|
QUICGoDisableGSO bool
|
||||||
QUICGoDisableECN bool
|
QUICGoDisableECN bool
|
||||||
IP4PEnable bool
|
IP4PEnable bool
|
||||||
@@ -147,6 +146,7 @@ type DNS struct {
|
|||||||
PreferH3 bool
|
PreferH3 bool
|
||||||
IPv6 bool
|
IPv6 bool
|
||||||
IPv6Timeout uint
|
IPv6Timeout uint
|
||||||
|
UseHosts bool
|
||||||
UseSystemHosts bool
|
UseSystemHosts bool
|
||||||
NameServer []dns.NameServer
|
NameServer []dns.NameServer
|
||||||
Fallback []dns.NameServer
|
Fallback []dns.NameServer
|
||||||
@@ -157,8 +157,11 @@ type DNS struct {
|
|||||||
DefaultNameserver []dns.NameServer
|
DefaultNameserver []dns.NameServer
|
||||||
CacheAlgorithm string
|
CacheAlgorithm string
|
||||||
CacheMaxSize int
|
CacheMaxSize int
|
||||||
FakeIPRange *fakeip.Pool
|
FakeIPRange netip.Prefix
|
||||||
Hosts *trie.DomainTrie[resolver.HostValue]
|
FakeIPPool *fakeip.Pool
|
||||||
|
FakeIPRange6 netip.Prefix
|
||||||
|
FakeIPPool6 *fakeip.Pool
|
||||||
|
FakeIPSkipper *fakeip.Skipper
|
||||||
NameServerPolicy []dns.Policy
|
NameServerPolicy []dns.Policy
|
||||||
ProxyServerNameserver []dns.NameServer
|
ProxyServerNameserver []dns.NameServer
|
||||||
DirectNameServer []dns.NameServer
|
DirectNameServer []dns.NameServer
|
||||||
@@ -175,6 +178,8 @@ type Profile struct {
|
|||||||
type TLS struct {
|
type TLS struct {
|
||||||
Certificate string
|
Certificate string
|
||||||
PrivateKey string
|
PrivateKey string
|
||||||
|
ClientAuthType string
|
||||||
|
ClientAuthCert string
|
||||||
EchKey string
|
EchKey string
|
||||||
CustomTrustCert []string
|
CustomTrustCert []string
|
||||||
}
|
}
|
||||||
@@ -194,8 +199,8 @@ type Config struct {
|
|||||||
Users []auth.AuthUser
|
Users []auth.AuthUser
|
||||||
Proxies map[string]C.Proxy
|
Proxies map[string]C.Proxy
|
||||||
Listeners map[string]C.InboundListener
|
Listeners map[string]C.InboundListener
|
||||||
Providers map[string]providerTypes.ProxyProvider
|
Providers map[string]P.ProxyProvider
|
||||||
RuleProviders map[string]providerTypes.RuleProvider
|
RuleProviders map[string]P.RuleProvider
|
||||||
Tunnels []LC.Tunnel
|
Tunnels []LC.Tunnel
|
||||||
Sniffer *sniffer.Config
|
Sniffer *sniffer.Config
|
||||||
TLS *TLS
|
TLS *TLS
|
||||||
@@ -220,6 +225,7 @@ type RawDNS struct {
|
|||||||
Listen string `yaml:"listen" json:"listen"`
|
Listen string `yaml:"listen" json:"listen"`
|
||||||
EnhancedMode C.DNSMode `yaml:"enhanced-mode" json:"enhanced-mode"`
|
EnhancedMode C.DNSMode `yaml:"enhanced-mode" json:"enhanced-mode"`
|
||||||
FakeIPRange string `yaml:"fake-ip-range" json:"fake-ip-range"`
|
FakeIPRange string `yaml:"fake-ip-range" json:"fake-ip-range"`
|
||||||
|
FakeIPRange6 string `yaml:"fake-ip-range6" json:"fake-ip-range6"`
|
||||||
FakeIPFilter []string `yaml:"fake-ip-filter" json:"fake-ip-filter"`
|
FakeIPFilter []string `yaml:"fake-ip-filter" json:"fake-ip-filter"`
|
||||||
FakeIPFilterMode C.FilterMode `yaml:"fake-ip-filter-mode" json:"fake-ip-filter-mode"`
|
FakeIPFilterMode C.FilterMode `yaml:"fake-ip-filter-mode" json:"fake-ip-filter-mode"`
|
||||||
DefaultNameserver []string `yaml:"default-nameserver" json:"default-nameserver"`
|
DefaultNameserver []string `yaml:"default-nameserver" json:"default-nameserver"`
|
||||||
@@ -292,6 +298,7 @@ type RawTun struct {
|
|||||||
ExcludePackage []string `yaml:"exclude-package" json:"exclude-package,omitempty"`
|
ExcludePackage []string `yaml:"exclude-package" json:"exclude-package,omitempty"`
|
||||||
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"`
|
||||||
|
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
|
||||||
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
|
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
|
||||||
|
|
||||||
Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
|
Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
|
||||||
@@ -368,56 +375,58 @@ type RawSniffingConfig struct {
|
|||||||
type RawTLS struct {
|
type RawTLS struct {
|
||||||
Certificate string `yaml:"certificate" json:"certificate"`
|
Certificate string `yaml:"certificate" json:"certificate"`
|
||||||
PrivateKey string `yaml:"private-key" json:"private-key"`
|
PrivateKey string `yaml:"private-key" json:"private-key"`
|
||||||
|
ClientAuthType string `yaml:"client-auth-type" json:"client-auth-type"`
|
||||||
|
ClientAuthCert string `yaml:"client-auth-cert" json:"client-auth-cert"`
|
||||||
EchKey string `yaml:"ech-key" json:"ech-key"`
|
EchKey string `yaml:"ech-key" json:"ech-key"`
|
||||||
CustomTrustCert []string `yaml:"custom-certifactes" json:"custom-certifactes"`
|
CustomTrustCert []string `yaml:"custom-certifactes" json:"custom-certifactes"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type RawConfig struct {
|
type RawConfig struct {
|
||||||
Port int `yaml:"port" json:"port"`
|
Port int `yaml:"port" json:"port"`
|
||||||
SocksPort int `yaml:"socks-port" json:"socks-port"`
|
SocksPort int `yaml:"socks-port" json:"socks-port"`
|
||||||
RedirPort int `yaml:"redir-port" json:"redir-port"`
|
RedirPort int `yaml:"redir-port" json:"redir-port"`
|
||||||
TProxyPort int `yaml:"tproxy-port" json:"tproxy-port"`
|
TProxyPort int `yaml:"tproxy-port" json:"tproxy-port"`
|
||||||
MixedPort int `yaml:"mixed-port" json:"mixed-port"`
|
MixedPort int `yaml:"mixed-port" json:"mixed-port"`
|
||||||
ShadowSocksConfig string `yaml:"ss-config" json:"ss-config"`
|
ShadowSocksConfig string `yaml:"ss-config" json:"ss-config"`
|
||||||
VmessConfig string `yaml:"vmess-config" json:"vmess-config"`
|
VmessConfig string `yaml:"vmess-config" json:"vmess-config"`
|
||||||
InboundTfo bool `yaml:"inbound-tfo" json:"inbound-tfo"`
|
InboundTfo bool `yaml:"inbound-tfo" json:"inbound-tfo"`
|
||||||
InboundMPTCP bool `yaml:"inbound-mptcp" json:"inbound-mptcp"`
|
InboundMPTCP bool `yaml:"inbound-mptcp" json:"inbound-mptcp"`
|
||||||
Authentication []string `yaml:"authentication" json:"authentication"`
|
Authentication []string `yaml:"authentication" json:"authentication"`
|
||||||
SkipAuthPrefixes []netip.Prefix `yaml:"skip-auth-prefixes" json:"skip-auth-prefixes"`
|
SkipAuthPrefixes []netip.Prefix `yaml:"skip-auth-prefixes" json:"skip-auth-prefixes"`
|
||||||
LanAllowedIPs []netip.Prefix `yaml:"lan-allowed-ips" json:"lan-allowed-ips"`
|
LanAllowedIPs []netip.Prefix `yaml:"lan-allowed-ips" json:"lan-allowed-ips"`
|
||||||
LanDisAllowedIPs []netip.Prefix `yaml:"lan-disallowed-ips" json:"lan-disallowed-ips"`
|
LanDisAllowedIPs []netip.Prefix `yaml:"lan-disallowed-ips" json:"lan-disallowed-ips"`
|
||||||
AllowLan bool `yaml:"allow-lan" json:"allow-lan"`
|
AllowLan bool `yaml:"allow-lan" json:"allow-lan"`
|
||||||
BindAddress string `yaml:"bind-address" json:"bind-address"`
|
BindAddress string `yaml:"bind-address" json:"bind-address"`
|
||||||
Mode T.TunnelMode `yaml:"mode" json:"mode"`
|
Mode T.TunnelMode `yaml:"mode" json:"mode"`
|
||||||
UnifiedDelay bool `yaml:"unified-delay" json:"unified-delay"`
|
UnifiedDelay bool `yaml:"unified-delay" json:"unified-delay"`
|
||||||
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" json:"external-controller"`
|
ExternalController string `yaml:"external-controller" json:"external-controller"`
|
||||||
ExternalControllerPipe string `yaml:"external-controller-pipe" json:"external-controller-pipe"`
|
ExternalControllerPipe string `yaml:"external-controller-pipe" json:"external-controller-pipe"`
|
||||||
ExternalControllerUnix string `yaml:"external-controller-unix" json:"external-controller-unix"`
|
ExternalControllerUnix string `yaml:"external-controller-unix" json:"external-controller-unix"`
|
||||||
ExternalControllerTLS string `yaml:"external-controller-tls" json:"external-controller-tls"`
|
ExternalControllerTLS string `yaml:"external-controller-tls" json:"external-controller-tls"`
|
||||||
ExternalControllerCors RawCors `yaml:"external-controller-cors" json:"external-controller-cors"`
|
ExternalControllerCors RawCors `yaml:"external-controller-cors" json:"external-controller-cors"`
|
||||||
ExternalUI string `yaml:"external-ui" json:"external-ui"`
|
ExternalUI string `yaml:"external-ui" json:"external-ui"`
|
||||||
ExternalUIURL string `yaml:"external-ui-url" json:"external-ui-url"`
|
ExternalUIURL string `yaml:"external-ui-url" json:"external-ui-url"`
|
||||||
ExternalUIName string `yaml:"external-ui-name" json:"external-ui-name"`
|
ExternalUIName string `yaml:"external-ui-name" json:"external-ui-name"`
|
||||||
ExternalDohServer string `yaml:"external-doh-server" json:"external-doh-server"`
|
ExternalDohServer string `yaml:"external-doh-server" json:"external-doh-server"`
|
||||||
Secret string `yaml:"secret" json:"secret"`
|
Secret string `yaml:"secret" json:"secret"`
|
||||||
Interface string `yaml:"interface-name" json:"interface-name"`
|
Interface string `yaml:"interface-name" json:"interface-name"`
|
||||||
RoutingMark int `yaml:"routing-mark" json:"routing-mark"`
|
RoutingMark int `yaml:"routing-mark" json:"routing-mark"`
|
||||||
Tunnels []LC.Tunnel `yaml:"tunnels" json:"tunnels"`
|
Tunnels []LC.Tunnel `yaml:"tunnels" json:"tunnels"`
|
||||||
GeoAutoUpdate bool `yaml:"geo-auto-update" json:"geo-auto-update"`
|
GeoAutoUpdate bool `yaml:"geo-auto-update" json:"geo-auto-update"`
|
||||||
GeoUpdateInterval int `yaml:"geo-update-interval" json:"geo-update-interval"`
|
GeoUpdateInterval int `yaml:"geo-update-interval" json:"geo-update-interval"`
|
||||||
GeodataMode bool `yaml:"geodata-mode" json:"geodata-mode"`
|
GeodataMode bool `yaml:"geodata-mode" json:"geodata-mode"`
|
||||||
GeodataLoader string `yaml:"geodata-loader" json:"geodata-loader"`
|
GeodataLoader string `yaml:"geodata-loader" json:"geodata-loader"`
|
||||||
GeositeMatcher string `yaml:"geosite-matcher" json:"geosite-matcher"`
|
GeositeMatcher string `yaml:"geosite-matcher" json:"geosite-matcher"`
|
||||||
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
|
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
|
||||||
FindProcessMode P.FindProcessMode `yaml:"find-process-mode" json:"find-process-mode"`
|
FindProcessMode process.FindProcessMode `yaml:"find-process-mode" json:"find-process-mode"`
|
||||||
GlobalClientFingerprint string `yaml:"global-client-fingerprint" json:"global-client-fingerprint"`
|
GlobalClientFingerprint string `yaml:"global-client-fingerprint" json:"global-client-fingerprint"`
|
||||||
GlobalUA string `yaml:"global-ua" json:"global-ua"`
|
GlobalUA string `yaml:"global-ua" json:"global-ua"`
|
||||||
ETagSupport bool `yaml:"etag-support" json:"etag-support"`
|
ETagSupport bool `yaml:"etag-support" json:"etag-support"`
|
||||||
KeepAliveIdle int `yaml:"keep-alive-idle" json:"keep-alive-idle"`
|
KeepAliveIdle int `yaml:"keep-alive-idle" json:"keep-alive-idle"`
|
||||||
KeepAliveInterval int `yaml:"keep-alive-interval" json:"keep-alive-interval"`
|
KeepAliveInterval int `yaml:"keep-alive-interval" json:"keep-alive-interval"`
|
||||||
DisableKeepAlive bool `yaml:"disable-keep-alive" json:"disable-keep-alive"`
|
DisableKeepAlive bool `yaml:"disable-keep-alive" json:"disable-keep-alive"`
|
||||||
|
|
||||||
ProxyProvider map[string]map[string]any `yaml:"proxy-providers" json:"proxy-providers"`
|
ProxyProvider map[string]map[string]any `yaml:"proxy-providers" json:"proxy-providers"`
|
||||||
RuleProvider map[string]map[string]any `yaml:"rule-providers" json:"rule-providers"`
|
RuleProvider map[string]map[string]any `yaml:"rule-providers" json:"rule-providers"`
|
||||||
@@ -470,7 +479,7 @@ func DefaultRawConfig() *RawConfig {
|
|||||||
Proxy: []map[string]any{},
|
Proxy: []map[string]any{},
|
||||||
ProxyGroup: []map[string]any{},
|
ProxyGroup: []map[string]any{},
|
||||||
TCPConcurrent: false,
|
TCPConcurrent: false,
|
||||||
FindProcessMode: P.FindProcessStrict,
|
FindProcessMode: process.FindProcessStrict,
|
||||||
GlobalUA: "clash.meta/" + C.Version,
|
GlobalUA: "clash.meta/" + C.Version,
|
||||||
ETagSupport: true,
|
ETagSupport: true,
|
||||||
DNS: RawDNS{
|
DNS: RawDNS{
|
||||||
@@ -644,11 +653,11 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
config.Proxies = proxies
|
config.Proxies = proxies
|
||||||
config.Providers = providers
|
config.Providers = providers
|
||||||
|
|
||||||
listener, err := parseListeners(rawCfg)
|
listeners, err := parseListeners(rawCfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
config.Listeners = listener
|
config.Listeners = listeners
|
||||||
|
|
||||||
log.Infoln("Geodata Loader mode: %s", geodata.LoaderName())
|
log.Infoln("Geodata Loader mode: %s", geodata.LoaderName())
|
||||||
log.Infoln("Geosite Matcher implementation: %s", geodata.SiteMatcherName())
|
log.Infoln("Geosite Matcher implementation: %s", geodata.SiteMatcherName())
|
||||||
@@ -676,13 +685,15 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
}
|
}
|
||||||
config.Hosts = hosts
|
config.Hosts = hosts
|
||||||
|
|
||||||
dnsCfg, err := parseDNS(rawCfg, hosts, ruleProviders)
|
parseIPV6(rawCfg) // must before DNS and Tun
|
||||||
|
|
||||||
|
dnsCfg, err := parseDNS(rawCfg, ruleProviders)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
config.DNS = dnsCfg
|
config.DNS = dnsCfg
|
||||||
|
|
||||||
err = parseTun(rawCfg.Tun, config.General)
|
err = parseTun(rawCfg.Tun, dnsCfg, config.General)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -790,7 +801,6 @@ func parseController(cfg *RawConfig) (*Controller, error) {
|
|||||||
|
|
||||||
func parseExperimental(cfg *RawConfig) (*Experimental, error) {
|
func parseExperimental(cfg *RawConfig) (*Experimental, error) {
|
||||||
return &Experimental{
|
return &Experimental{
|
||||||
Fingerprints: cfg.Experimental.Fingerprints,
|
|
||||||
QUICGoDisableGSO: cfg.Experimental.QUICGoDisableGSO,
|
QUICGoDisableGSO: cfg.Experimental.QUICGoDisableGSO,
|
||||||
QUICGoDisableECN: cfg.Experimental.QUICGoDisableECN,
|
QUICGoDisableECN: cfg.Experimental.QUICGoDisableECN,
|
||||||
IP4PEnable: cfg.Experimental.IP4PEnable,
|
IP4PEnable: cfg.Experimental.IP4PEnable,
|
||||||
@@ -828,14 +838,16 @@ func parseTLS(cfg *RawConfig) (*TLS, error) {
|
|||||||
return &TLS{
|
return &TLS{
|
||||||
Certificate: cfg.TLS.Certificate,
|
Certificate: cfg.TLS.Certificate,
|
||||||
PrivateKey: cfg.TLS.PrivateKey,
|
PrivateKey: cfg.TLS.PrivateKey,
|
||||||
|
ClientAuthType: cfg.TLS.ClientAuthType,
|
||||||
|
ClientAuthCert: cfg.TLS.ClientAuthCert,
|
||||||
EchKey: cfg.TLS.EchKey,
|
EchKey: cfg.TLS.EchKey,
|
||||||
CustomTrustCert: cfg.TLS.CustomTrustCert,
|
CustomTrustCert: cfg.TLS.CustomTrustCert,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[string]providerTypes.ProxyProvider, err error) {
|
func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[string]P.ProxyProvider, err error) {
|
||||||
proxies = make(map[string]C.Proxy)
|
proxies = make(map[string]C.Proxy)
|
||||||
providersMap = make(map[string]providerTypes.ProxyProvider)
|
providersMap = make(map[string]P.ProxyProvider)
|
||||||
proxiesConfig := cfg.Proxy
|
proxiesConfig := cfg.Proxy
|
||||||
groupsConfig := cfg.ProxyGroup
|
groupsConfig := cfg.ProxyGroup
|
||||||
providersConfig := cfg.ProxyProvider
|
providersConfig := cfg.ProxyProvider
|
||||||
@@ -935,7 +947,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
&outboundgroup.GroupCommonOption{
|
&outboundgroup.GroupCommonOption{
|
||||||
Name: "GLOBAL",
|
Name: "GLOBAL",
|
||||||
},
|
},
|
||||||
[]providerTypes.ProxyProvider{pd},
|
[]P.ProxyProvider{pd},
|
||||||
)
|
)
|
||||||
proxies["GLOBAL"] = adapter.NewProxy(global)
|
proxies["GLOBAL"] = adapter.NewProxy(global)
|
||||||
}
|
}
|
||||||
@@ -945,24 +957,25 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
func parseListeners(cfg *RawConfig) (listeners map[string]C.InboundListener, err error) {
|
func parseListeners(cfg *RawConfig) (listeners map[string]C.InboundListener, err error) {
|
||||||
listeners = make(map[string]C.InboundListener)
|
listeners = make(map[string]C.InboundListener)
|
||||||
for index, mapping := range cfg.Listeners {
|
for index, mapping := range cfg.Listeners {
|
||||||
listener, err := L.ParseListener(mapping)
|
inboundListener, err := listener.ParseListener(mapping)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("proxy %d: %w", index, err)
|
return nil, fmt.Errorf("proxy %d: %w", index, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, exist := mapping[listener.Name()]; exist {
|
name := inboundListener.Name()
|
||||||
return nil, fmt.Errorf("listener %s is the duplicate name", listener.Name())
|
if _, exist := mapping[name]; exist {
|
||||||
|
return nil, fmt.Errorf("listener %s is the duplicate name", name)
|
||||||
}
|
}
|
||||||
|
|
||||||
listeners[listener.Name()] = listener
|
listeners[name] = inboundListener
|
||||||
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]providerTypes.RuleProvider, err error) {
|
func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]P.RuleProvider, err error) {
|
||||||
RP.SetTunnel(T.Tunnel)
|
RP.SetTunnel(T.Tunnel)
|
||||||
ruleProviders = map[string]providerTypes.RuleProvider{}
|
ruleProviders = map[string]P.RuleProvider{}
|
||||||
// parse rule provider
|
// parse rule provider
|
||||||
for name, mapping := range cfg.RuleProvider {
|
for name, mapping := range cfg.RuleProvider {
|
||||||
rp, err := RP.ParseRuleProvider(name, mapping, R.ParseRule)
|
rp, err := RP.ParseRuleProvider(name, mapping, R.ParseRule)
|
||||||
@@ -975,7 +988,7 @@ func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]providerTypes.
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseSubRules(cfg *RawConfig, proxies map[string]C.Proxy, ruleProviders map[string]providerTypes.RuleProvider) (subRules map[string][]C.Rule, err error) {
|
func parseSubRules(cfg *RawConfig, proxies map[string]C.Proxy, ruleProviders map[string]P.RuleProvider) (subRules map[string][]C.Rule, err error) {
|
||||||
subRules = map[string][]C.Rule{}
|
subRules = map[string][]C.Rule{}
|
||||||
for name := range cfg.SubRules {
|
for name := range cfg.SubRules {
|
||||||
subRules[name] = make([]C.Rule, 0)
|
subRules[name] = make([]C.Rule, 0)
|
||||||
@@ -1038,7 +1051,7 @@ func verifySubRuleCircularReferences(n string, subRules map[string][]C.Rule, arr
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRules(rulesConfig []string, proxies map[string]C.Proxy, ruleProviders map[string]providerTypes.RuleProvider, subRules map[string][]C.Rule, format string) ([]C.Rule, error) {
|
func parseRules(rulesConfig []string, proxies map[string]C.Proxy, ruleProviders map[string]P.RuleProvider, subRules map[string][]C.Rule, format string) ([]C.Rule, error) {
|
||||||
var rules []C.Rule
|
var rules []C.Rule
|
||||||
|
|
||||||
// parse rules
|
// parse rules
|
||||||
@@ -1261,7 +1274,7 @@ func parsePureDNSServer(server string) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseNameServerPolicy(nsPolicy *orderedmap.OrderedMap[string, any], ruleProviders map[string]providerTypes.RuleProvider, respectRules bool, preferH3 bool) ([]dns.Policy, error) {
|
func parseNameServerPolicy(nsPolicy *orderedmap.OrderedMap[string, any], ruleProviders map[string]P.RuleProvider, respectRules bool, preferH3 bool) ([]dns.Policy, error) {
|
||||||
var policy []dns.Policy
|
var policy []dns.Policy
|
||||||
|
|
||||||
for pair := nsPolicy.Oldest(); pair != nil; pair = pair.Next() {
|
for pair := nsPolicy.Oldest(); pair != nil; pair = pair.Next() {
|
||||||
@@ -1336,7 +1349,7 @@ func parseNameServerPolicy(nsPolicy *orderedmap.OrderedMap[string, any], rulePro
|
|||||||
return policy, nil
|
return policy, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie[resolver.HostValue], ruleProviders map[string]providerTypes.RuleProvider) (*DNS, error) {
|
func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS, error) {
|
||||||
cfg := rawCfg.DNS
|
cfg := rawCfg.DNS
|
||||||
if cfg.Enable && len(cfg.NameServer) == 0 {
|
if cfg.Enable && len(cfg.NameServer) == 0 {
|
||||||
return nil, fmt.Errorf("if DNS configuration is turned on, NameServer cannot be empty")
|
return nil, fmt.Errorf("if DNS configuration is turned on, NameServer cannot be empty")
|
||||||
@@ -1352,6 +1365,7 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie[resolver.HostValue], rul
|
|||||||
PreferH3: cfg.PreferH3,
|
PreferH3: cfg.PreferH3,
|
||||||
IPv6Timeout: cfg.IPv6Timeout,
|
IPv6Timeout: cfg.IPv6Timeout,
|
||||||
IPv6: cfg.IPv6,
|
IPv6: cfg.IPv6,
|
||||||
|
UseHosts: cfg.UseHosts,
|
||||||
UseSystemHosts: cfg.UseSystemHosts,
|
UseSystemHosts: cfg.UseSystemHosts,
|
||||||
EnhancedMode: cfg.EnhancedMode,
|
EnhancedMode: cfg.EnhancedMode,
|
||||||
CacheAlgorithm: cfg.CacheAlgorithm,
|
CacheAlgorithm: cfg.CacheAlgorithm,
|
||||||
@@ -1401,13 +1415,27 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie[resolver.HostValue], rul
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fakeIPRange, err := netip.ParsePrefix(cfg.FakeIPRange)
|
if cfg.FakeIPRange != "" {
|
||||||
T.SetFakeIPRange(fakeIPRange)
|
dnsCfg.FakeIPRange, err = netip.ParsePrefix(cfg.FakeIPRange)
|
||||||
if cfg.EnhancedMode == C.DNSFakeIP {
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if !dnsCfg.FakeIPRange.Addr().Is4() {
|
||||||
|
return nil, errors.New("dns.fake-ip-range must be a IPv4 prefix")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.FakeIPRange6 != "" {
|
||||||
|
dnsCfg.FakeIPRange6, err = netip.ParsePrefix(cfg.FakeIPRange6)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !dnsCfg.FakeIPRange6.Addr().Is6() {
|
||||||
|
return nil, errors.New("dns.fake-ip-range6 must be a IPv6 prefix")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.EnhancedMode == C.DNSFakeIP {
|
||||||
var fakeIPTrie *trie.DomainTrie[struct{}]
|
var fakeIPTrie *trie.DomainTrie[struct{}]
|
||||||
if len(dnsCfg.Fallback) != 0 {
|
if len(dnsCfg.Fallback) != 0 {
|
||||||
fakeIPTrie = trie.New[struct{}]()
|
fakeIPTrie = trie.New[struct{}]()
|
||||||
@@ -1425,18 +1453,39 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie[resolver.HostValue], rul
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
pool, err := fakeip.New(fakeip.Options{
|
skipper := &fakeip.Skipper{
|
||||||
IPNet: fakeIPRange,
|
Host: host,
|
||||||
Size: 1000,
|
Mode: cfg.FakeIPFilterMode,
|
||||||
Host: host,
|
}
|
||||||
Mode: cfg.FakeIPFilterMode,
|
dnsCfg.FakeIPSkipper = skipper
|
||||||
Persistence: rawCfg.Profile.StoreFakeIP,
|
|
||||||
})
|
if dnsCfg.FakeIPRange.IsValid() {
|
||||||
if err != nil {
|
pool, err := fakeip.New(fakeip.Options{
|
||||||
return nil, err
|
IPNet: dnsCfg.FakeIPRange,
|
||||||
|
Size: 1000,
|
||||||
|
Persistence: rawCfg.Profile.StoreFakeIP,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
dnsCfg.FakeIPPool = pool
|
||||||
}
|
}
|
||||||
|
|
||||||
dnsCfg.FakeIPRange = pool
|
if dnsCfg.FakeIPRange6.IsValid() {
|
||||||
|
pool6, err := fakeip.New(fakeip.Options{
|
||||||
|
IPNet: dnsCfg.FakeIPRange6,
|
||||||
|
Size: 1000,
|
||||||
|
Persistence: rawCfg.Profile.StoreFakeIP,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
dnsCfg.FakeIPPool6 = pool6
|
||||||
|
}
|
||||||
|
|
||||||
|
if dnsCfg.FakeIPPool == nil && dnsCfg.FakeIPPool6 == nil {
|
||||||
|
return nil, errors.New("disallow `fake-ip-range` and `fake-ip-range6` both empty with fake-ip mode")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(cfg.Fallback) != 0 {
|
if len(cfg.Fallback) != 0 {
|
||||||
@@ -1485,10 +1534,6 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie[resolver.HostValue], rul
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if cfg.UseHosts {
|
|
||||||
dnsCfg.Hosts = hosts
|
|
||||||
}
|
|
||||||
|
|
||||||
return dnsCfg, nil
|
return dnsCfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1502,17 +1547,20 @@ func parseAuthentication(rawRecords []string) []auth.AuthUser {
|
|||||||
return users
|
return users
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseTun(rawTun RawTun, general *General) error {
|
func parseIPV6(rawCfg *RawConfig) {
|
||||||
tunAddressPrefix := T.FakeIPRange()
|
if !rawCfg.IPv6 || !verifyIP6() {
|
||||||
|
rawCfg.DNS.FakeIPRange6 = ""
|
||||||
|
rawCfg.Tun.Inet6Address = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseTun(rawTun RawTun, dns *DNS, general *General) error {
|
||||||
|
tunAddressPrefix := dns.FakeIPRange
|
||||||
if !tunAddressPrefix.IsValid() {
|
if !tunAddressPrefix.IsValid() {
|
||||||
tunAddressPrefix = netip.MustParsePrefix("198.18.0.1/16")
|
tunAddressPrefix = netip.MustParsePrefix("198.18.0.1/16")
|
||||||
}
|
}
|
||||||
tunAddressPrefix = netip.PrefixFrom(tunAddressPrefix.Addr(), 30)
|
tunAddressPrefix = netip.PrefixFrom(tunAddressPrefix.Addr(), 30)
|
||||||
|
|
||||||
if !general.IPv6 || !verifyIP6() {
|
|
||||||
rawTun.Inet6Address = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
general.Tun = LC.Tun{
|
general.Tun = LC.Tun{
|
||||||
Enable: rawTun.Enable,
|
Enable: rawTun.Enable,
|
||||||
Device: rawTun.Device,
|
Device: rawTun.Device,
|
||||||
@@ -1552,6 +1600,7 @@ func parseTun(rawTun RawTun, general *General) error {
|
|||||||
ExcludePackage: rawTun.ExcludePackage,
|
ExcludePackage: rawTun.ExcludePackage,
|
||||||
EndpointIndependentNat: rawTun.EndpointIndependentNat,
|
EndpointIndependentNat: rawTun.EndpointIndependentNat,
|
||||||
UDPTimeout: rawTun.UDPTimeout,
|
UDPTimeout: rawTun.UDPTimeout,
|
||||||
|
DisableICMPForwarding: rawTun.DisableICMPForwarding,
|
||||||
FileDescriptor: rawTun.FileDescriptor,
|
FileDescriptor: rawTun.FileDescriptor,
|
||||||
|
|
||||||
Inet4RouteAddress: rawTun.Inet4RouteAddress,
|
Inet4RouteAddress: rawTun.Inet4RouteAddress,
|
||||||
@@ -1584,7 +1633,7 @@ func parseTuicServer(rawTuic RawTuicServer, general *General) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseSniffer(snifferRaw RawSniffer, ruleProviders map[string]providerTypes.RuleProvider) (*sniffer.Config, error) {
|
func parseSniffer(snifferRaw RawSniffer, ruleProviders map[string]P.RuleProvider) (*sniffer.Config, error) {
|
||||||
snifferConfig := &sniffer.Config{
|
snifferConfig := &sniffer.Config{
|
||||||
Enable: snifferRaw.Enable,
|
Enable: snifferRaw.Enable,
|
||||||
ForceDnsMapping: snifferRaw.ForceDnsMapping,
|
ForceDnsMapping: snifferRaw.ForceDnsMapping,
|
||||||
@@ -1674,7 +1723,7 @@ func parseSniffer(snifferRaw RawSniffer, ruleProviders map[string]providerTypes.
|
|||||||
return snifferConfig, nil
|
return snifferConfig, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseIPCIDR(addresses []string, cidrSet *cidr.IpCidrSet, adapterName string, ruleProviders map[string]providerTypes.RuleProvider) (matchers []C.IpMatcher, err error) {
|
func parseIPCIDR(addresses []string, cidrSet *cidr.IpCidrSet, adapterName string, ruleProviders map[string]P.RuleProvider) (matchers []C.IpMatcher, err error) {
|
||||||
var matcher C.IpMatcher
|
var matcher C.IpMatcher
|
||||||
for _, ipcidr := range addresses {
|
for _, ipcidr := range addresses {
|
||||||
ipcidrLower := strings.ToLower(ipcidr)
|
ipcidrLower := strings.ToLower(ipcidr)
|
||||||
@@ -1721,7 +1770,7 @@ func parseIPCIDR(addresses []string, cidrSet *cidr.IpCidrSet, adapterName string
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseDomain(domains []string, domainTrie *trie.DomainTrie[struct{}], adapterName string, ruleProviders map[string]providerTypes.RuleProvider) (matchers []C.DomainMatcher, err error) {
|
func parseDomain(domains []string, domainTrie *trie.DomainTrie[struct{}], adapterName string, ruleProviders map[string]P.RuleProvider) (matchers []C.DomainMatcher, err error) {
|
||||||
var matcher C.DomainMatcher
|
var matcher C.DomainMatcher
|
||||||
for _, domain := range domains {
|
for _, domain := range domains {
|
||||||
domainLower := strings.ToLower(domain)
|
domainLower := strings.ToLower(domain)
|
||||||
@@ -1764,14 +1813,14 @@ func parseDomain(domains []string, domainTrie *trie.DomainTrie[struct{}], adapte
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseIPRuleSet(domainSetName string, adapterName string, ruleProviders map[string]providerTypes.RuleProvider) (C.IpMatcher, error) {
|
func parseIPRuleSet(domainSetName string, adapterName string, ruleProviders map[string]P.RuleProvider) (C.IpMatcher, error) {
|
||||||
if rp, ok := ruleProviders[domainSetName]; !ok {
|
if rp, ok := ruleProviders[domainSetName]; !ok {
|
||||||
return nil, fmt.Errorf("not found rule-set: %s", domainSetName)
|
return nil, fmt.Errorf("not found rule-set: %s", domainSetName)
|
||||||
} else {
|
} else {
|
||||||
switch rp.Behavior() {
|
switch rp.Behavior() {
|
||||||
case providerTypes.Domain:
|
case P.Domain:
|
||||||
return nil, fmt.Errorf("rule provider type error, except ipcidr,actual %s", rp.Behavior())
|
return nil, fmt.Errorf("rule provider type error, except ipcidr,actual %s", rp.Behavior())
|
||||||
case providerTypes.Classical:
|
case P.Classical:
|
||||||
log.Warnln("%s provider is %s, only matching it contain ip rule", rp.Name(), rp.Behavior())
|
log.Warnln("%s provider is %s, only matching it contain ip rule", rp.Name(), rp.Behavior())
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
@@ -1779,14 +1828,14 @@ func parseIPRuleSet(domainSetName string, adapterName string, ruleProviders map[
|
|||||||
return RP.NewRuleSet(domainSetName, adapterName, false, true)
|
return RP.NewRuleSet(domainSetName, adapterName, false, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseDomainRuleSet(domainSetName string, adapterName string, ruleProviders map[string]providerTypes.RuleProvider) (C.DomainMatcher, error) {
|
func parseDomainRuleSet(domainSetName string, adapterName string, ruleProviders map[string]P.RuleProvider) (C.DomainMatcher, error) {
|
||||||
if rp, ok := ruleProviders[domainSetName]; !ok {
|
if rp, ok := ruleProviders[domainSetName]; !ok {
|
||||||
return nil, fmt.Errorf("not found rule-set: %s", domainSetName)
|
return nil, fmt.Errorf("not found rule-set: %s", domainSetName)
|
||||||
} else {
|
} else {
|
||||||
switch rp.Behavior() {
|
switch rp.Behavior() {
|
||||||
case providerTypes.IPCIDR:
|
case P.IPCIDR:
|
||||||
return nil, fmt.Errorf("rule provider type error, except domain,actual %s", rp.Behavior())
|
return nil, fmt.Errorf("rule provider type error, except domain,actual %s", rp.Behavior())
|
||||||
case providerTypes.Classical:
|
case P.Classical:
|
||||||
log.Warnln("%s provider is %s, only matching it contain domain rule", rp.Name(), rp.Behavior())
|
log.Warnln("%s provider is %s, only matching it contain domain rule", rp.Name(), rp.Behavior())
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -155,6 +155,10 @@ func verifyIP6() bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
// eg: Calling net.InterfaceAddrs() fails on Android SDK 30
|
||||||
|
// https://github.com/golang/go/issues/40569
|
||||||
|
return true // just ignore
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -139,8 +139,11 @@ type ProxyAdapter interface {
|
|||||||
// SupportUOT return UDP over TCP support
|
// SupportUOT return UDP over TCP support
|
||||||
SupportUOT() bool
|
SupportUOT() bool
|
||||||
|
|
||||||
|
// SupportWithDialer only for deprecated relay group, the new protocol does not need to be implemented.
|
||||||
SupportWithDialer() NetWork
|
SupportWithDialer() NetWork
|
||||||
|
// DialContextWithDialer only for deprecated relay group, the new protocol does not need to be implemented.
|
||||||
DialContextWithDialer(ctx context.Context, dialer Dialer, metadata *Metadata) (Conn, error)
|
DialContextWithDialer(ctx context.Context, dialer Dialer, metadata *Metadata) (Conn, error)
|
||||||
|
// ListenPacketWithDialer only for deprecated relay group, the new protocol does not need to be implemented.
|
||||||
ListenPacketWithDialer(ctx context.Context, dialer Dialer, metadata *Metadata) (PacketConn, error)
|
ListenPacketWithDialer(ctx context.Context, dialer Dialer, metadata *Metadata) (PacketConn, error)
|
||||||
|
|
||||||
// IsL3Protocol return ProxyAdapter working in L3 (tell dns module not pass the domain to avoid loopback)
|
// IsL3Protocol return ProxyAdapter working in L3 (tell dns module not pass the domain to avoid loopback)
|
||||||
@@ -178,12 +181,6 @@ type Proxy interface {
|
|||||||
ExtraDelayHistories() map[string]ProxyState
|
ExtraDelayHistories() map[string]ProxyState
|
||||||
LastDelayForTestUrl(url string) uint16
|
LastDelayForTestUrl(url string) uint16
|
||||||
URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (uint16, error)
|
URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (uint16, error)
|
||||||
|
|
||||||
// Deprecated: use DialContext instead.
|
|
||||||
Dial(metadata *Metadata) (Conn, error)
|
|
||||||
|
|
||||||
// Deprecated: use DialPacketConn instead.
|
|
||||||
DialUDP(metadata *Metadata) (PacketConn, error)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AdapterType is enum of adapter type
|
// AdapterType is enum of adapter type
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ const (
|
|||||||
TUIC
|
TUIC
|
||||||
HYSTERIA2
|
HYSTERIA2
|
||||||
ANYTLS
|
ANYTLS
|
||||||
|
MIERU
|
||||||
INNER
|
INNER
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -109,6 +110,8 @@ func (t Type) String() string {
|
|||||||
return "Hysteria2"
|
return "Hysteria2"
|
||||||
case ANYTLS:
|
case ANYTLS:
|
||||||
return "AnyTLS"
|
return "AnyTLS"
|
||||||
|
case MIERU:
|
||||||
|
return "Mieru"
|
||||||
case INNER:
|
case INNER:
|
||||||
return "Inner"
|
return "Inner"
|
||||||
default:
|
default:
|
||||||
@@ -149,6 +152,8 @@ func ParseType(t string) (*Type, error) {
|
|||||||
res = HYSTERIA2
|
res = HYSTERIA2
|
||||||
case "ANYTLS":
|
case "ANYTLS":
|
||||||
res = ANYTLS
|
res = ANYTLS
|
||||||
|
case "MIERU":
|
||||||
|
res = MIERU
|
||||||
case "INNER":
|
case "INNER":
|
||||||
res = INNER
|
res = INNER
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ package context
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
|
||||||
"github.com/gofrs/uuid/v5"
|
"github.com/gofrs/uuid/v5"
|
||||||
"github.com/miekg/dns"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -17,17 +17,15 @@ const (
|
|||||||
type DNSContext struct {
|
type DNSContext struct {
|
||||||
context.Context
|
context.Context
|
||||||
|
|
||||||
id uuid.UUID
|
id uuid.UUID
|
||||||
msg *dns.Msg
|
tp string
|
||||||
tp string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDNSContext(ctx context.Context, msg *dns.Msg) *DNSContext {
|
func NewDNSContext(ctx context.Context) *DNSContext {
|
||||||
return &DNSContext{
|
return &DNSContext{
|
||||||
Context: ctx,
|
Context: ctx,
|
||||||
|
|
||||||
id: utils.NewUUIDV4(),
|
id: utils.NewUUIDV4(),
|
||||||
msg: msg,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,35 +16,23 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type client struct {
|
type client struct {
|
||||||
*D.Client
|
port string
|
||||||
port string
|
host string
|
||||||
host string
|
dialer *dnsDialer
|
||||||
dialer *dnsDialer
|
schema string
|
||||||
addr string
|
skipCertVerify bool
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ dnsClient = (*client)(nil)
|
var _ dnsClient = (*client)(nil)
|
||||||
|
|
||||||
// Address implements dnsClient
|
// Address implements dnsClient
|
||||||
func (c *client) Address() string {
|
func (c *client) Address() string {
|
||||||
if len(c.addr) != 0 {
|
return fmt.Sprintf("%s://%s", c.schema, net.JoinHostPort(c.host, c.port))
|
||||||
return c.addr
|
|
||||||
}
|
|
||||||
schema := "udp"
|
|
||||||
if strings.HasPrefix(c.Client.Net, "tcp") {
|
|
||||||
schema = "tcp"
|
|
||||||
if strings.HasSuffix(c.Client.Net, "tls") {
|
|
||||||
schema = "tls"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
c.addr = fmt.Sprintf("%s://%s", schema, net.JoinHostPort(c.host, c.port))
|
|
||||||
return c.addr
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error) {
|
func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error) {
|
||||||
network := "udp"
|
network := "udp"
|
||||||
if strings.HasPrefix(c.Client.Net, "tcp") {
|
if c.schema != "udp" {
|
||||||
network = "tcp"
|
network = "tcp"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,9 +41,24 @@ func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error)
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer func() {
|
defer conn.Close()
|
||||||
_ = conn.Close()
|
|
||||||
}()
|
if c.schema == "tls" {
|
||||||
|
tlsConfig, err := ca.GetTLSConfig(ca.Option{
|
||||||
|
TLSConfig: &tls.Config{
|
||||||
|
ServerName: c.host,
|
||||||
|
InsecureSkipVerify: c.skipCertVerify,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tlsConn := tls.Client(conn, tlsConfig)
|
||||||
|
if err := tlsConn.HandshakeContext(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
conn = tlsConn
|
||||||
|
}
|
||||||
|
|
||||||
// miekg/dns ExchangeContext doesn't respond to context cancel.
|
// miekg/dns ExchangeContext doesn't respond to context cancel.
|
||||||
// this is a workaround
|
// this is a workaround
|
||||||
@@ -65,34 +68,30 @@ func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error)
|
|||||||
}
|
}
|
||||||
ch := make(chan result, 1)
|
ch := make(chan result, 1)
|
||||||
go func() {
|
go func() {
|
||||||
if strings.HasSuffix(c.Client.Net, "tls") {
|
dClient := &D.Client{
|
||||||
conn = tls.Client(conn, ca.GetGlobalTLSConfig(c.Client.TLSConfig))
|
UDPSize: 4096,
|
||||||
|
Timeout: 5 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
dConn := &D.Conn{
|
dConn := &D.Conn{
|
||||||
Conn: conn,
|
Conn: conn,
|
||||||
UDPSize: c.Client.UDPSize,
|
UDPSize: dClient.UDPSize,
|
||||||
TsigSecret: c.Client.TsigSecret,
|
|
||||||
TsigProvider: c.Client.TsigProvider,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
msg, _, err := c.Client.ExchangeWithConn(m, dConn)
|
msg, _, err := dClient.ExchangeWithConn(m, dConn)
|
||||||
|
|
||||||
// Resolvers MUST resend queries over TCP if they receive a truncated UDP response (with TC=1 set)!
|
// Resolvers MUST resend queries over TCP if they receive a truncated UDP response (with TC=1 set)!
|
||||||
if msg != nil && msg.Truncated && network == "udp" {
|
if msg != nil && msg.Truncated && network == "udp" {
|
||||||
tcpClient := *c.Client // copy a client
|
|
||||||
tcpClient.Net = "tcp"
|
|
||||||
network = "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())
|
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 = c.dialer.DialContext(ctx, network, addr)
|
var tcpConn net.Conn
|
||||||
|
tcpConn, err = c.dialer.DialContext(ctx, network, addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ch <- result{msg, err}
|
ch <- result{msg, err}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer func() {
|
defer tcpConn.Close()
|
||||||
_ = conn.Close()
|
dConn.Conn = tcpConn
|
||||||
}()
|
msg, _, err = dClient.ExchangeWithConn(m, dConn)
|
||||||
msg, _, err = tcpClient.ExchangeWithConn(m, dConn)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ch <- result{msg, err}
|
ch <- result{msg, err}
|
||||||
@@ -111,20 +110,19 @@ func (c *client) ResetConnection() {}
|
|||||||
func newClient(addr string, resolver *Resolver, netType string, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *client {
|
func newClient(addr string, resolver *Resolver, netType string, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *client {
|
||||||
host, port, _ := net.SplitHostPort(addr)
|
host, port, _ := net.SplitHostPort(addr)
|
||||||
c := &client{
|
c := &client{
|
||||||
Client: &D.Client{
|
|
||||||
Net: netType,
|
|
||||||
TLSConfig: &tls.Config{
|
|
||||||
ServerName: host,
|
|
||||||
},
|
|
||||||
UDPSize: 4096,
|
|
||||||
Timeout: 5 * time.Second,
|
|
||||||
},
|
|
||||||
port: port,
|
port: port,
|
||||||
host: host,
|
host: host,
|
||||||
dialer: newDNSDialer(resolver, proxyAdapter, proxyName),
|
dialer: newDNSDialer(resolver, proxyAdapter, proxyName),
|
||||||
|
schema: "udp",
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(netType, "tcp") {
|
||||||
|
c.schema = "tcp"
|
||||||
|
if strings.HasSuffix(netType, "tls") {
|
||||||
|
c.schema = "tls"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if params["skip-cert-verify"] == "true" {
|
if params["skip-cert-verify"] == "true" {
|
||||||
c.TLSConfig.InsecureSkipVerify = true
|
c.skipCertVerify = true
|
||||||
}
|
}
|
||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user