Compare commits

..
107 Commits
Author SHA1 Message Date
Livy Yao 100ff73ae7 fix: correct msftncsi hostname typo in default fake-ip-filter (#3481)
dns.msftnsci.com / www.msftnsci.com are transposed; NCSI probes dns.msftncsi.com and www.msftncsi.com. Under fake-ip, the unfiltered real probe host resolves to 198.18.x.x and Windows 10 reports "no internet".
2026-11-20 08:18:09 +08:00
i40e 024152115c feat: allow disable redir-host mapping in fake-ip mode (#3496)
When a real IP is returned from fake-ip-filter, subsequent connection
toward the real IP will be mapped back to domain (redir-host behavior).
For configurations with a small number of filtered real IP, the real IP
returned is functionally equivalent to a fake IP.

Add a configuration option to disable the redir-host behavior in fake
IP mode.
2026-11-20 07:44:34 +08:00
Esko Mobius 2be2f08909 fix: skip expired entries when picking reusable connections for xhttp (#3479) 2026-11-18 09:37:53 +08:00
SoulOriginal 0976eb6ac1 fix: PROCESS-NAME/PROCESS-PATH rules miss when any process exits during the /proc search on Linux
https://github.com/MetaCubeX/mihomo/issues/3469
2026-11-18 08:18:10 +08:00
wwqgtxx 7907040f27 chore: ignored invalid dns-mode for tun 2026-11-18 08:06:41 +08:00
wwqgtxx 3c0d10a503 chore: adjust internal function 2026-11-15 17:48:09 +08:00
wwqgtxx 184857ce21 fix: ss none packet write 2026-11-14 23:28:18 +08:00
wwqgtxx 7e73a9448b fix: ShadowTLS v2 not work with X25519MLKEM768
The v2 server authenticates the client only if its HMAC covers all the
data relayed from the handshake server, or all but the last write. The
client hashed only the bytes the TLS stack asked for, which end at the
server Finished record, so session tickets sent in the same flight were
left out whenever the stack's last read did not happen to pick them up.
With an X25519MLKEM768 ServerHello this happened on every connection to
a Go crypto/tls handshake server, and the chrome fingerprint always fell
back. Read the socket through a 16 KiB buffer and hash everything each
read returns, as the original implementation does.
2026-11-14 23:09:45 +08:00
wwqgtxx a9e5c456e3 chore: adjust randomization weights 2026-11-14 23:09:19 +08:00
wwqgtxx 4c57a4a600 chore: remove unnecessary forwarding code 2026-11-14 16:05:41 +08:00
CatMsg d569d9eba7 feat: support optional userkey for Snell v6 outbound (#3460) 2026-11-14 15:57:54 +08:00
AaronChen0 12b81d465a fix: use correct format verb for subscription-userinfo parse errors (#3455) 2026-11-12 09:13:57 +08:00
MiaM1ku 0455d0d28c chore: bump embedded easytier-go core to keep guest memory off the Go heap (#3454)
go.mod / go.sum: github.com/easytier/easytier/easytier-go
  v0.0.0-20260910071355-3d0c9c3ca5e2
  -> v0.0.0-20261111015056-2abb1676b475

Upstream: easytier/easytier#2782 (690b6be4778f). Guest linear memory now lives
outside the Go heap (PROT_NONE reservation committed in place), Hosts share one
wazero CompilationCache, and the first compile is followed by FreeOSMemory.

Measured on Alpha (one easytier outbound, 4 peers: 2 tcp + 2 udp, persistent
flows through mihomo's SOCKS5 inbound, VmRSS):
  200 flows: 389.9 MiB -> 205.1 MiB
  400 flows: 702.0 MiB -> 287.9 MiB
  first dial: 220.1 MiB -> 107.8 MiB
  second outbound: +49.4 MiB / 2.0 s -> +12.4 MiB / 76 ms
2026-11-11 13:53:39 +08:00
wwqgtxx f7ec2b9a4b chore: update utls to go1.26-based 2026-11-11 10:23:01 +08:00
Sloan Gray c3bdf7798a fix: skip empty age secret key in DecryptBytes (#3450)
A proxy-provider without its own age-secret-key passes "" to
age.DecryptBytes, which failed with "no identities found" before the
global secret keys were tried.
2026-11-11 09:45:40 +08:00
wwqgtxx 478af2a57c fix: auto route rules for tun 2026-11-06 10:47:06 +08:00
wwqgtxx 9466681813 chore: code cleanup 2026-11-06 10:40:07 +08:00
Romanov Caesar 2d1a22e311 feat: support multiple users for shadowsocks listener (#3383)
Add `users` (username: password) to the shadowsocks listener so that
multiple users can share one port. The matched username is set as
InUser, so IN-USER rules work for both TCP and UDP.

- 2022-blake3-aes-*: `password` is the server PSK and each user password
  is the user PSK, clients use "iPSK:uPSK".
- legacy AEAD: user passwords are used directly, `password` must be empty.
- other methods return an error when `users` is set.
2026-11-06 10:11:14 +08:00
Aleksey Fedorov e9b9a1a87f fix: convert httpupgrade share links to ws with v2ray-http-upgrade (#3415) 2026-11-06 09:19:19 +08:00
Chikage0o0 9002a4fed3 fix: easytier drain unused host packets to prevent data-plane stalls (#3400)
Consume raw host/TUN packet egress for each running instance so the bounded EasyTier packet sink cannot backpressure the data plane. Stop receiving when the instance closes or the adapter is canceled, and document packet ownership.
2026-11-05 21:41:32 +08:00
YONG f1f640b12f feat: add Snell version 6 support (outbound + inbound) (#3410) 2026-11-05 18:29:11 +08:00
Gtio 69c16319b1 fix: keep bytes that arrive with the HTTP proxy's CONNECT response (#3382) 2026-10-30 17:22:37 +08:00
wwqgtxx ca8d7c41bf fix: ssh clients do not close when underlying connection writing errors 2026-10-28 19:15:53 +08:00
Zephyruso ff179c43a1 feat: add ss-password generation functionality to the command line tool (#3372) 2026-10-28 15:17:00 +08:00
wwqgtxx de439c8812 fix: drain cached data before reading upstream 2026-10-28 14:43:41 +08:00
wwqgtxx 5b79f3c367 fix: tfo-go not working on go1.26.9+ and go1.27.2+ 2026-10-26 23:36:36 +08:00
wwqgtxx b6a15182c2 fix: i386 struct define of PROCESS_MEMORY_COUNTERS 2026-10-26 12:29:58 +08:00
SaladDay 6780eeeb27 fix: prevent SOCKS domain length arithmetic overflow (#3359) 2026-10-25 08:13:14 +08:00
enfein 91e85eebf0 chore: allow mieru inbound to actively close idle TCP connection (#3354) 2026-10-24 08:12:35 +08:00
saba-futai 3f27ef39f8 chore: refactored and fixed issues for sudoku while also improving performance (#3333) 2026-10-21 23:51:58 +08:00
Chenx Dust 2df147b906 feat: support dns-mode for tun (#3288) 2026-10-21 23:44:35 +08:00
wwqgtxx c4e818694c fix: CVE-2026-97031 for crypto/tls 2026-10-21 23:24:35 +08:00
Token 94b13aed49 fix: dialer-proxy cycle check takes quadratic time and memory (#3315) 2026-10-13 20:38:16 +08:00
Token df1b07af2c fix: a sub-millisecond URL test is reported as a failure (#3316) 2026-10-13 20:10:59 +08:00
Token 349af19116 fix: the embedded shadowsocks listener can't be closed (#3314) 2026-10-13 20:02:16 +08:00
enfein bc76c1398c chore: update mieru version (#3304)
Mainly fixes an issue of infinite TCP read retry when using QUIC like Hy2
as mieru's dialer proxy. The issue was reported by a user of mihomo 1.19.32.

Also includes other improvements.
2026-10-11 09:38:59 +08:00
Younes Beriane e4dd968de9 fix: keep fake-ip allocation state when cloning the pool on reload (#3283) 2026-10-08 15:57:16 +08:00
Cassian433 80101933c0 fix: bound doh dials so ones the query gave up on cannot pile up (#3274) 2026-10-08 15:04:41 +08:00
wwqgtxx 1354e52e6f fix: unpassed loadbalance test 2026-10-06 21:27:20 +08:00
wwqgtxx 9f053c4907 chore: lazy init wireguard device and stack 2026-10-02 13:06:43 +08:00
Jiawen Geng 88dcbf7f16 fix: default listener tun to mips stack (#3264) 2026-09-30 22:35:49 +08:00
BESTRUI ac652970fe fix: nil pconn deref when ctx is canceled during h2 ClientConn setup 2026-09-30 21:40:50 +08:00
artbred 409ee57ef2 fix: populate HWCap from auxv on linux 2026-09-30 21:37:59 +08:00
proxi 8fa048d376 fix: half-close in sing-mux 2026-09-30 21:22:40 +08:00
wwqgtxx 134176994f chore: support RX checksum offload for mipstack 2026-09-30 15:47:24 +08:00
wwqgtxx 60f70cec63 fix: align unconnected UDP and raw IP ICMP errors with Linux for mipstack 2026-09-30 00:08:22 +08:00
wwqgtxx 63bd52ec79 chore: change default IP stack mode to mips and support congestion-controller option for tun 2026-09-27 09:11:59 +08:00
enfein f103639c80 chore: update mieru version (#3242)
v3.38.0 reduces CPU usage when UDP session is idle.
2026-09-25 08:10:26 +08:00
FlyingSB 8d57a8c57c fix: exclude opcode from P_DATA_V1 AEAD additional data for OpenVPN (#3237)
OpenVPN authenticates the opcode/peer-id header as AEAD additional data
only for P_DATA_V2. For P_DATA_V1 the additional data is the packet ID
alone. We included the opcode for both, so every data packet exchanged
with a server that does not push peer-id (e.g. SoftEther) failed
authentication and was silently dropped after a successful handshake.
2026-09-25 00:24:38 +08:00
wwqgtxx 41b8a05915 fix: account for TCP options in effective MSS 2026-09-24 21:36:47 +08:00
简直蠢丶 3025efad06 feat: add load-balance hash-key to pin a session on the inbound user (#3133) 2026-09-24 20:32:42 +08:00
Peter Solomon 3c947c76d4 chore: convert support xhttp extra.headers (#3230) 2026-09-22 21:25:29 +08:00
Ryoma Dev afe94dafef fix: set udp InUser metadata for mieru inbound (#3236) 2026-09-22 20:46:47 +08:00
wwqgtxx 91dd03a9e5 chore: support lazy receive buffer reads for mipstack and gvisor 2026-09-22 17:07:49 +08:00
Chenx Dust 5019cc090e fix: potential race condition in c.idleSession.Len() in idleCleanupExpTime() for anytls (#3225) 2026-09-19 22:02:11 +08:00
MiaM1ku fbb674227d fix: restart EasyTier outbound after silent overlay failure (#3215) 2026-09-16 00:51:29 +08:00
wwqgtxx ab405bad5b feat: support stack: mips in tun configuration 2026-09-14 19:59:30 +08:00
wwqgtxx dc66a8a180 fix: close connection after error handling in handleContextListener 2026-09-14 14:24:43 +08:00
wwqgtxx 78210c9c72 fix: close connection after error handling in kcptun 2026-09-14 14:11:18 +08:00
wwqgtxx 06b2c5b887 fix: close connection after error handling in mkcp outbound 2026-09-14 13:57:17 +08:00
wwqgtxx 187c6342c4 fix: close connection after error handling in snell outbound 2026-09-14 13:54:21 +08:00
wwqgtxx 0436650753 fix: close connection after error handling in doq 2026-09-14 13:49:12 +08:00
wwqgtxx 7d7532d49f fix: error using of safeConnClose in sudoku outbound 2026-09-14 11:34:28 +08:00
wwqgtxx faeb537ae2 fix: close connection after error handling in tuic server 2026-09-14 11:34:27 +08:00
wwqgtxx e0f1d2b2fd fix: close udp endpoint in mieru server 2026-09-14 11:34:27 +08:00
wwqgtxx 1cdca1a015 fix: handle decryption handshake errors in server 2026-09-14 11:24:37 +08:00
Huffer c210be21e0 chore: buffer geodata reads with a 16 KiB reader (#3185)
Batch small GeoSite and GeoIP reads, reuse prefetched bytes when skipping
records, and reconstruct the matched prefix without seeking backward.
Report EOF after a matched prefix as a truncated record.
2026-09-14 08:43:14 +08:00
enfein 94ccba5661 fix: mieru listener doesn't obey "listen" config (#3205)
Previously, mieru server always listen to 0.0.0.0.
Version 3.37.0 allow the server listen to a user provided IP address.
2026-09-14 07:51:40 +08:00
MiaM1ku dca26db017 feat: add EasyTier outbound (#3194) 2026-09-11 09:41:09 +08:00
wwqgtxx b59a7e7baf chore: sharing synthetic datasets used for build benchmarking 2026-09-11 07:53:18 +08:00
wwqgtxx ebf82e2962 chore: reuse queues during DomainSet build
Build the succinct domain index one level at a time and alternate two reusable queues instead of retaining every processed node until construction completes.

Keep explicit node IDs to preserve terminal ordering, Foreach output, and binary serialization. Query logic and the serialized layout remain unchanged.

This reduces peak build memory and improves construction time for DomainMap. In isolated measurements, the mixed 100k-rule workload used about 53% less peak memory and completed about 11% faster, while deep 100k-rule input used about 72% less peak memory and completed about 24% faster.
2026-09-11 06:51:26 +08:00
wwqgtxx f6a038ce0f chore: add some benchmark code for new DomainMap 2026-09-11 00:05:21 +08:00
wwqgtxx d37f58e768 chore: add new DomainMap implement based on succinct DomainSet 2026-09-10 22:49:36 +08:00
wwqgtxx 6087521e60 chore: avoid a separate rule slice in DumpMrs
DomainSet emits at most one exact entry and one suffix-only entry for each domain. Sorting without the leading dot makes matching pairs adjacent, so they can be combined in place.

Replace per-entry binary searches and the separate rule slice with an adjacent pairing pass. Merge pairs into +.domain, remove consumed entries from the original slice, and sort the resulting rules by their full text.

Add regression coverage for multiple pairs and wildcard ordering. Output semantics and early termination remain unchanged.
2026-09-10 22:28:36 +08:00
Aethersailor 518c7036df chore: convert support REALITY ML-KEM option (#3199)
Parse support-x25519mlkem768 from VLESS and VMess AEAD share links.
Only set it when a REALITY public key and a valid boolean are present,
preserving existing behavior for links without the parameter.

Add coverage for plain and Base64 subscriptions and adapter parsing.
2026-09-10 21:54:48 +08:00
wwqgtxx 77b9393c32 fix: preserve domain rules across Foreach round trips
The +.domain syntax includes both the domain itself and its subdomains. Using it for a suffix-only terminal adds an unintended exact match when the output is reinserted and can overwrite a separately stored exact value.

Emit .domain for suffix-only entries in DomainTrie and DomainSet Foreach, keeping exact entries separate. Preserve the internal '+' marker when converting Trie to Set, and combine MRS entries into +.domain only when both exact and suffix entries exist.

Add regression coverage for matching behavior and distinct values after reinsertion, as well as MRS deduplication and compact output. Query logic and binary layouts remain unchanged.
2026-09-10 18:52:49 +08:00
wwqgtxx 4aa9cc17fc chore: avoid redundant select calculations in DomainSet
Once the key is exhausted, a terminal node completes the match; otherwise only saved wildcard branches can still succeed. No input remains to match the current node's child edges, so their starting position is unnecessary.

Defer the child-edge select in Has until more input needs matching, both after matching a byte and when restoring a wildcard. Keep the node-terminator select needed to resume saved wildcard branches.

Earlier candidate benchmarks show median query times ~3%/~1% lower for short/long queries and ~11%/~8% lower for exact/mixed-rule workloads, with no additional allocations or changes to the index layout.
2026-09-10 09:25:15 +08:00
wwqgtxx 8e2f18a1a9 chore: avoid redundant rank calculations in DomainSet
Child edges are 0 bits and each node ends with a 1 bit in labelBitmap. An edge of nodeId has exactly nodeId preceding 1 bits, so its label index is bmIdx - nodeId. Child nodes follow the same order as labels, starting at 1 because node 0 is the root. Therefore, the child node ID is bmIdx - nodeId + 1.

Use this identity in Has and keys instead of countZeros. Keep rank for wildcard restoration, where the cursor lacks the parent node ID.

Existing short/long query benchmarks take ~12%/~11% less time, with no additional allocations or changes to the index layout.
2026-09-10 09:04:52 +08:00
wwqgtxx 5f9510988c fix: DomainSet wildcard matching with overlapping rules
These queries now correctly return true:

- Query: a.example.com
  Rules: [*.example.com, dead.a.example.com]

- Query: b.a.example.com
  Rules: [*.*.example.com, dead.*.a.example.com, dead.b.a.example.com]

- Query: b.c.a.example.com
  Rules: [*.*.*.example.com, *.a.example.com]
2026-09-10 08:19:36 +08:00
浅小沫 20bcda2d1a fix: avoid VLESS decryption cleanup panic (#3195) 2026-09-10 07:22:33 +08:00
wwqgtxx d5f57a5e29 fix: missing NeedHandshake for shadowsocks none 2026-09-08 18:12:47 +08:00
wwqgtxx 390870c7b4 feat: support identity-secret for ZeroTier 2026-09-08 17:31:05 +08:00
wwqgtxx 5183232e7f fix: RandomPaddingAddition and DisableCookies for AmneziaWG v3 2026-09-08 15:26:38 +08:00
NuoFang a91201f1fc fix: correct android amd64 core asset name in updater (#3167) 2026-09-08 14:22:19 +08:00
Token 6d179a1c45 fix: openvpn derive the tls-auth HMAC digest from auth instead of hard-coding SHA-1 (#3189) 2026-09-08 12:10:15 +08:00
wwqgtxx bbb8cb924b chore: add standalone DomainSetBuilder 2026-09-08 10:27:49 +08:00
saba-futai 8f54283e97 chore: updated sudoku to v0.5.0 (#3187) 2026-09-07 08:46:46 +08:00
wwqgtxx 92433dbafc chore: reduce gVisor memory usage 2026-09-07 07:31:32 +08:00
wwqgtxx fd74ecb6e2 fix: trusttunnel client not waiting for TCP connection established 2026-09-05 09:36:30 +08:00
wwqgtxx 634b31991c fix: hysteria2 UDP sessions not closed on connection close 2026-09-05 07:55:05 +08:00
Chenx Dust 0159cf47ed fix: restore hysteria v1 udp handling (#3178)
Fixed two Hysteria v1 UDP regressions introduced in 48c1b1cdb2 :
- Mark UDP session requests correctly with UDP: true.
- Initialize the packet buffer with zero length and preallocated capacity to prevent leading zero bytes.
2026-09-04 22:06:21 +08:00
8Mi_Yile 810b014ee9 action: update-tag action v1->v3 (#3172) 2026-09-03 00:24:20 +08:00
wwqgtxx 2ecceb5b8a chore: improve mipstack under device backpressure 2026-09-02 23:29:53 +08:00
CyberVacation 68ec4fae65 fix: ipv6 url parse in xhttp (#3160) 2026-08-31 15:26:17 +08:00
beck 65287f0e0f chore: reduce memory usage in converter (#3159) 2026-08-29 21:05:32 +08:00
wwqgtxx 061966e797 chore: OpenVPN no longer relies on the underlying conn deadline functions 2026-08-27 15:36:11 +08:00
Sinspired 99c49780fd fix: prevent nil pointer dereference in WireGuard initialization (#3148) 2026-08-27 00:38:13 +08:00
wwqgtxx 4dfaa9027d chore: align the APIs between mipstack and gvisor 2026-08-26 19:10:46 +08:00
Kosta fb66af813b fix: typo in config.yaml (#3145) 2026-08-25 18:09:54 +08:00
wwqgtxx f295ba6da4 chore: update mipstack for api adjustment 2026-08-23 01:27:41 +08:00
wwqgtxx 8e6738fad4 chore: update tailscale to v1.102.3 2026-08-22 00:04:51 +08:00
wwqgtxx 2fe7ecbfe7 chore: change yaml library to go.yaml.in/yaml/v3 2026-08-21 21:54:31 +08:00
wwqgtxx c0e43ebecf fix: tailscale should always use UserDial for upstream TCP DNS server 2026-08-21 08:36:02 +08:00
wwqgtxx dd26c52463 chore: reduce connection memory and actor stack overhead for mipstack 2026-08-20 20:03:17 +08:00
wwqgtxx 127b1392b8 fix: split-DNS UDP queries fail silently in tsnet mode when upstream is a tailnet peer 2026-08-20 15:48:56 +08:00
enfein fe22fdd2cc chore: update mieru version (#3119)
v3.36.0 optimizes server user matching speed and reduces GC pressure.
2026-08-18 07:42:32 +08:00
wwqgtxx 2f7eae5a26 chore: report detailed errors for invalid Clash-style domain patterns 2026-08-17 09:35:10 +08:00
173 changed files with 14088 additions and 5467 deletions

No files matched your search

+2 -2
View File
@@ -358,7 +358,7 @@ jobs:
shell: bash
- name: Tag Repo
uses: richardsimko/update-tag@v1
uses: richardsimko/update-tag@v3
with:
tag_name: Prerelease-${{ github.ref_name }}
env:
@@ -537,4 +537,4 @@ jobs:
linux/arm64
linux/arm/v7
tags: ${{ steps.meta_release.outputs.tags }}
labels: ${{ steps.meta_release.outputs.labels }}
labels: ${{ steps.meta_release.outputs.labels }}
+5
View File
@@ -275,6 +275,11 @@ func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.In
satisfied = resp != nil && (expectedStatus == nil || expectedStatus.Check(uint16(resp.StatusCode)))
t = uint16(time.Since(start) / time.Millisecond)
if t == 0 {
// a zero delay means a failed test to callers, so report a test
// that completed in under a millisecond as 1 ms
t = 1
}
return
}
+4 -2
View File
@@ -16,9 +16,11 @@ func parseSocksAddr(target socks5.Addr) *C.Metadata {
switch target[0] {
case socks5.AtypDomainName:
// Convert before arithmetic so long domain lengths cannot overflow a byte.
domainEnd := 2 + int(target[1])
// trim for FQDN
metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".")
metadata.DstPort = uint16((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
metadata.Host = strings.TrimRight(string(target[2:domainEnd]), ".")
metadata.DstPort = uint16(target[domainEnd])<<8 | uint16(target[domainEnd+1])
case socks5.AtypIPv4:
metadata.DstIP, _ = netip.AddrFromSlice(target[1 : 1+net.IPv4len])
metadata.DstPort = uint16((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
+33
View File
@@ -0,0 +1,33 @@
package inbound
import (
"fmt"
"strings"
"testing"
"github.com/metacubex/mihomo/transport/socks5"
)
func TestParseSocksAddrDomainLengths(t *testing.T) {
for length := 0; length <= 255; length++ {
t.Run(fmt.Sprint(length), func(t *testing.T) {
host := strings.Repeat("a", length)
addr := append(socks5.Addr{socks5.AtypDomainName, byte(length)}, []byte(host)...)
addr = append(addr, 0x12, 0x34)
got := parseSocksAddr(addr)
if got.Host != host || got.DstPort != 0x1234 {
t.Fatalf("length %d: host=%q port=%d", length, got.Host, got.DstPort)
}
})
}
}
func TestParseSocksAddrFQDN(t *testing.T) {
host := "example.com."
addr := append(socks5.Addr{socks5.AtypDomainName, byte(len(host))}, []byte(host)...)
addr = append(addr, 0x01, 0xbb)
got := parseSocksAddr(addr)
if got.Host != "example.com" || got.DstPort != 443 {
t.Fatalf("host=%q port=%d", got.Host, got.DstPort)
}
}
+19 -2
View File
@@ -274,8 +274,20 @@ func (c *conn) AddRef(ref any) {
c.ExtendedConn = N.NewRefConn(c.ExtendedConn, ref) // add ref for autoCloseProxyAdapter
}
// ipstackConn is a common experimental API interface implemented by:
// *mipstack.TCPConn, *mipstack.UDPConn, *mipstack.IPConn
// it's also implemented by our gVisor fork
type ipstackConn interface {
ReadWithBuffer(getBuffer func(sizeHint int) []byte) (int, error)
}
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
if _, ok := c.(syscall.Conn); !ok { // exclusion system conn like *net.TCPConn
switch c.(type) {
case syscall.Conn: // exclusion system conn like *net.TCPConn
break
case ipstackConn: // exclusion *mipstack.TCPConn
break
default:
c = N.NewDeadlineConn(c) // most conn from outbound can't handle readDeadline correctly
}
cc := &conn{N.NewExtendedConn(c), nil, nil, a.Addr()}
@@ -341,7 +353,12 @@ func (c *packetConn) AddRef(ref any) {
func NewPacketConn(pc net.PacketConn, a ProxyAdapter) C.PacketConn {
epc := N.NewEnhancePacketConn(pc)
if _, ok := pc.(syscall.Conn); !ok { // exclusion system conn like *net.UDPConn
switch pc.(type) {
case syscall.Conn: // exclusion system conn like *net.UDPConn
break
case ipstackConn: // exclusion *mipstack.UDPConn
break
default:
epc = N.NewDeadlineEnhancePacketConn(epc) // most conn from outbound can't handle readDeadline correctly
}
cpc := &packetConn{epc, nil, nil, a.Name(), utils.NewUUIDV4().String(), a.Addr(), a.ResolveUDP}
+625
View File
@@ -0,0 +1,625 @@
//go:build !no_easytier
package outbound
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/metacubex/mihomo/component/easytier"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/dns"
"github.com/metacubex/mihomo/log"
corehost "github.com/easytier/easytier/easytier-go"
D "github.com/miekg/dns"
)
const (
easyTierDefaultStateDir = "easytier"
easyTierInstanceIDFile = "instance_id"
easyTierDNSTTL = 60
easyTierMinBackoff = time.Second
easyTierMaxBackoff = 30 * time.Second
)
var errEasyTierClosed = errors.New("easytier outbound closed")
type EasyTier struct {
*Base
option EasyTierOption
configTOML string
stateDir string
instanceID string
zone string
ctx context.Context
cancel context.CancelFunc
loopOnce sync.Once
startMu sync.Mutex
closed bool
readyCh chan struct{}
mu sync.Mutex
host *corehost.Host
instance *corehost.Instance
unregister func()
}
type EasyTierOption struct {
BasicOption
Name string `proxy:"name"`
NetworkName string `proxy:"network-name,omitempty"`
NetworkSecret string `proxy:"network-secret,omitempty"`
Hostname string `proxy:"hostname,omitempty"`
IPv4 string `proxy:"ipv4,omitempty"`
DHCP bool `proxy:"dhcp,omitempty"`
Peers []string `proxy:"peers,omitempty"`
Listeners []string `proxy:"listeners,omitempty"`
NoListener *bool `proxy:"no-listener,omitempty"`
MappedListeners []string `proxy:"mapped-listeners,omitempty"`
ExitNodes []string `proxy:"exit-nodes,omitempty"`
ProxyNetworks []string `proxy:"proxy-networks,omitempty"`
InstanceName string `proxy:"instance-name,omitempty"`
StateDir string `proxy:"state-dir,omitempty"`
UDP bool `proxy:"udp,omitempty"`
AcceptDNS *bool `proxy:"accept-dns,omitempty"`
EnableExitNode *bool `proxy:"enable-exit-node,omitempty"`
EnableEncryption *bool `proxy:"enable-encryption,omitempty"`
EncryptionAlgorithm string `proxy:"encryption-algorithm,omitempty"`
PrivateMode *bool `proxy:"private-mode,omitempty"`
LatencyFirst *bool `proxy:"latency-first,omitempty"`
DisableP2P *bool `proxy:"disable-p2p,omitempty"`
EnableKCPProxy *bool `proxy:"enable-kcp-proxy,omitempty"`
DisableKCPInput *bool `proxy:"disable-kcp-input,omitempty"`
EnableQUICProxy *bool `proxy:"enable-quic-proxy,omitempty"`
DisableQUICInput *bool `proxy:"disable-quic-input,omitempty"`
MTU int `proxy:"mtu,omitempty"`
TLDDNSZone string `proxy:"tld-dns-zone,omitempty"`
SecureMode *bool `proxy:"secure-mode,omitempty"`
LocalPrivateKey string `proxy:"local-private-key,omitempty"`
LocalPublicKey string `proxy:"local-public-key,omitempty"`
}
func (o EasyTierOption) structuredConfig() easytier.Config {
instanceName := o.InstanceName
if instanceName == "" {
instanceName = o.Name
}
return easytier.Config{
NetworkName: o.NetworkName,
NetworkSecret: o.NetworkSecret,
Hostname: o.Hostname,
IPv4: o.IPv4,
DHCP: o.DHCP,
Peers: o.Peers,
Listeners: o.Listeners,
NoListener: o.NoListener,
MappedListeners: o.MappedListeners,
ExitNodes: o.ExitNodes,
ProxyNetworks: o.ProxyNetworks,
InstanceName: instanceName,
AcceptDNS: o.AcceptDNS,
EnableExitNode: o.EnableExitNode,
EnableEncryption: o.EnableEncryption,
EncryptionAlgorithm: o.EncryptionAlgorithm,
PrivateMode: o.PrivateMode,
LatencyFirst: o.LatencyFirst,
DisableP2P: o.DisableP2P,
EnableKCPProxy: o.EnableKCPProxy,
DisableKCPInput: o.DisableKCPInput,
EnableQUICProxy: o.EnableQUICProxy,
DisableQUICInput: o.DisableQUICInput,
MTU: o.MTU,
TLDDNSZone: o.TLDDNSZone,
SecureMode: o.SecureMode,
LocalPrivateKey: o.LocalPrivateKey,
LocalPublicKey: o.LocalPublicKey,
}
}
func NewEasyTier(option EasyTierOption) (*EasyTier, error) {
configTOML, err := option.structuredConfig().RenderTOML()
if err != nil {
return nil, err
}
configTOML = easytier.ApplyRequiredFlags(configTOML)
stateDir := option.StateDir
if stateDir == "" {
stateDir = filepath.Join(easyTierDefaultStateDir, option.Name)
}
stateDir = C.Path.Resolve(stateDir)
if !C.Path.IsSafePath(stateDir) {
return nil, C.Path.ErrNotSafePath(stateDir)
}
addr := option.NetworkName
if addr == "" {
addr = "easytier"
}
ctx, cancel := context.WithCancel(context.Background())
outbound := &EasyTier{
Base: NewBase(BaseOption{
Name: option.Name,
Addr: addr,
Type: C.EasyTier,
ProviderName: option.ProviderName,
UDP: option.UDP,
Interface: option.Interface,
RoutingMark: option.RoutingMark,
Prefer: option.IPVersion,
}),
option: option,
configTOML: configTOML,
stateDir: stateDir,
zone: easytier.NormalizeZone(option.TLDDNSZone),
ctx: ctx,
cancel: cancel,
}
outbound.dialer = option.NewDialer(outbound.DialOptions())
outbound.unregister = dns.RegisterEasyTierDnsClient(option.Name, easyTierDNSTransport{easytier: outbound})
return outbound, nil
}
func (e *EasyTier) ensureStarted(ctx context.Context) error {
e.loopOnce.Do(func() {
go e.loop()
})
for {
if err := e.ctx.Err(); err != nil {
return errEasyTierClosed
}
e.startMu.Lock()
closed := e.closed
readyCh := e.readyCh
e.startMu.Unlock()
if closed {
return errEasyTierClosed
}
e.mu.Lock()
instance := e.instance
e.mu.Unlock()
if instance != nil && instance.State() == corehost.StateRunning {
return nil
}
if readyCh == nil {
e.startMu.Lock()
if e.readyCh == nil {
e.readyCh = make(chan struct{})
}
readyCh = e.readyCh
e.startMu.Unlock()
}
select {
case <-ctx.Done():
return ctx.Err()
case <-e.ctx.Done():
return errEasyTierClosed
case <-readyCh:
}
}
}
func (e *EasyTier) signalReady() {
e.startMu.Lock()
if e.readyCh != nil {
close(e.readyCh)
e.readyCh = nil
}
e.startMu.Unlock()
}
func (e *EasyTier) loop() {
backoff := easyTierMinBackoff
for {
if e.ctx.Err() != nil {
return
}
e.startMu.Lock()
closed := e.closed
e.startMu.Unlock()
if closed {
return
}
err := e.init()
if err != nil {
log.Warnln("[EasyTier](%s) start failed: %v; retry in %s", e.Name(), err, backoff)
_ = e.shutdown()
timer := time.NewTimer(backoff)
select {
case <-e.ctx.Done():
timer.Stop()
return
case <-timer.C:
}
if backoff < easyTierMaxBackoff {
backoff *= 2
if backoff > easyTierMaxBackoff {
backoff = easyTierMaxBackoff
}
}
continue
}
backoff = easyTierMinBackoff
e.signalReady()
reason := e.serve()
_ = e.shutdown()
if e.ctx.Err() != nil {
return
}
e.startMu.Lock()
closed = e.closed
e.startMu.Unlock()
if closed {
return
}
if reason == "" {
reason = "instance stopped"
}
log.Warnln("[EasyTier](%s) %s; restarting in %s", e.Name(), reason, backoff)
timer := time.NewTimer(backoff)
select {
case <-e.ctx.Done():
timer.Stop()
return
case <-timer.C:
}
if backoff < easyTierMaxBackoff {
backoff *= 2
if backoff > easyTierMaxBackoff {
backoff = easyTierMaxBackoff
}
}
}
}
func (e *EasyTier) init() error {
if err := os.MkdirAll(e.stateDir, 0o755); err != nil {
return fmt.Errorf("easytier: create state-dir: %w", err)
}
instanceID := loadInstanceID(e.stateDir)
instanceName := e.option.InstanceName
if instanceName == "" {
instanceName = e.option.Name
}
host, err := corehost.New(e.ctx, corehost.Options{
Platform: easytier.Services(e.dialer),
})
if err != nil {
return err
}
e.mu.Lock()
e.host = host
e.mu.Unlock()
instance, err := host.CreateInstanceTOML(e.ctx, instanceName, instanceID, e.configTOML)
if err != nil {
return err
}
e.mu.Lock()
e.instance = instance
e.instanceID = instance.ID()
e.mu.Unlock()
if err := writeInstanceID(e.stateDir, instance.ID()); err != nil {
return err
}
if err := instance.Start(e.ctx); err != nil {
return err
}
log.Infoln("[EasyTier](%s) instance %s running", e.Name(), instance.ID())
go e.drainHostPackets(instance)
return nil
}
// The outbound uses the core's netstack, not a host TUN device. Drain unused
// raw IP packets so the bounded host packet queue cannot stall the data plane.
// ReceivePacket unblocks when the instance closes or the adapter is canceled.
func (e *EasyTier) drainHostPackets(instance *corehost.Instance) {
for {
if _, err := instance.ReceivePacket(e.ctx); err != nil {
return
}
}
}
func (e *EasyTier) currentInstance() (*corehost.Instance, error) {
e.mu.Lock()
defer e.mu.Unlock()
if e.instance == nil {
return nil, errors.New("easytier instance is not ready")
}
return e.instance, nil
}
func (e *EasyTier) serve() string {
e.mu.Lock()
instance := e.instance
e.mu.Unlock()
if instance == nil {
return "instance is not ready"
}
// Manual connectors retry inside core (reconnect_interval, default 1s).
// Events() is best-effort: a full host queue drops the event and does not
// stall the guest. Drain it for logs; recreate only when the stream closes.
events := instance.Events()
if events == nil {
if err := instance.Wait(e.ctx); err != nil && e.ctx.Err() == nil {
return err.Error()
}
return "instance stopped"
}
for {
select {
case <-e.ctx.Done():
return ""
case event, ok := <-events:
if !ok {
return "instance stopped"
}
switch event.Kind {
case "peer_added", "peer_removed":
log.Infoln("[EasyTier](%s) %s: %s", e.Name(), event.Kind, event.Message)
default:
log.Debugln("[EasyTier](%s) %s: %s", e.Name(), event.Kind, event.Message)
}
}
}
}
func (e *EasyTier) overlayNodes(ctx context.Context) ([]easytier.Node, error) {
instance, err := e.currentInstance()
if err != nil {
return nil, err
}
var nodes []easytier.Node
info, err := instance.ShowNodeInfo(ctx)
if err == nil && info != nil {
node := easytier.Node{Hostname: info.GetHostname()}
if ip, parseErr := easytier.ParseNodeIPv4(info.GetIpv4Addr()); parseErr == nil {
node.IPv4 = ip
}
if node.Hostname != "" || node.IPv4.IsValid() {
nodes = append(nodes, node)
}
}
routes, err := instance.ListRoute(ctx)
if err != nil {
if len(nodes) == 0 {
return nil, err
}
return nodes, nil
}
for _, route := range routes {
if route == nil {
continue
}
inet := route.GetIpv4Addr()
if inet == nil || inet.GetAddress() == nil {
continue
}
nodes = append(nodes, easytier.Node{
Hostname: route.GetHostname(),
IPv4: easytier.IPv4FromUint32(inet.GetAddress().GetAddr()),
})
}
return nodes, nil
}
func (e *EasyTier) resolveIPv4(ctx context.Context, host string) (netip.Addr, error) {
if ip, err := netip.ParseAddr(host); err == nil {
ip = ip.Unmap()
if !ip.Is4() {
return netip.Addr{}, fmt.Errorf("easytier: overlay dial supports IPv4 only")
}
return ip, nil
}
nodes, err := e.overlayNodes(ctx)
if err != nil {
return netip.Addr{}, err
}
if ip, ok := easytier.LookupOverlayHost(host, e.zone, nodes); ok {
return ip, nil
}
if easytier.IsMagicDNS(host, e.zone) {
return netip.Addr{}, fmt.Errorf("easytier: overlay hostname %q was not found", host)
}
ips, err := resolver.LookupIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
if err != nil {
return netip.Addr{}, err
}
if len(ips) == 0 {
return netip.Addr{}, fmt.Errorf("easytier: resolve %q: no IPv4 address", host)
}
return ips[0], nil
}
func (e *EasyTier) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
if err = e.ensureStarted(ctx); err != nil {
return nil, err
}
host := metadata.Host
if host == "" && metadata.DstIP.IsValid() {
host = metadata.DstIP.String()
}
ip, err := e.resolveIPv4(ctx, host)
if err != nil {
return nil, err
}
instance, err := e.currentInstance()
if err != nil {
return nil, err
}
address := net.JoinHostPort(ip.String(), fmt.Sprintf("%d", metadata.DstPort))
conn, err := instance.Dial(ctx, "tcp4", address)
if err != nil {
return nil, err
}
if conn == nil {
return nil, errors.New("conn is nil")
}
return NewConn(conn, e), nil
}
func (e *EasyTier) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
if err = e.ensureStarted(ctx); err != nil {
return nil, err
}
if err = e.ResolveUDP(ctx, metadata); err != nil {
return nil, err
}
instance, err := e.currentInstance()
if err != nil {
return nil, err
}
pc, err := instance.ListenPacket("udp4", ":0")
if err != nil {
return nil, err
}
if pc == nil {
return nil, errors.New("packetConn is nil")
}
return NewPacketConn(pc, e), nil
}
func (e *EasyTier) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
if metadata.Host != "" {
ip, err := e.resolveIPv4(ctx, metadata.Host)
if err != nil {
return fmt.Errorf("can't resolve ip: %w", err)
}
metadata.DstIP = ip
return nil
}
if metadata.DstIP.IsValid() && !metadata.DstIP.Is4() {
return fmt.Errorf("easytier: overlay dial supports IPv4 only")
}
return nil
}
func (e *EasyTier) ProxyInfo() C.ProxyInfo {
info := e.Base.ProxyInfo()
info.DialerProxy = e.option.DialerProxy
return info
}
func (e *EasyTier) IsL3Protocol(*C.Metadata) bool {
return true
}
func (e *EasyTier) Close() error {
e.cancel()
if e.unregister != nil {
e.unregister()
}
e.startMu.Lock()
e.closed = true
if e.readyCh != nil {
close(e.readyCh)
e.readyCh = nil
}
e.startMu.Unlock()
return e.shutdown()
}
func (e *EasyTier) shutdown() error {
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
defer cancel()
e.mu.Lock()
instance := e.instance
host := e.host
e.instance = nil
e.host = nil
e.mu.Unlock()
var err error
if instance != nil {
err = instance.Close(ctx)
}
if host != nil {
if hostErr := host.Close(ctx); err == nil {
err = hostErr
}
}
return err
}
type easyTierDNSTransport struct {
easytier *EasyTier
}
func (t easyTierDNSTransport) Address() string {
return "easytier://" + t.easytier.Name()
}
func (t easyTierDNSTransport) ResetConnection() {}
func (t easyTierDNSTransport) ExchangeContext(ctx context.Context, msg *D.Msg) (*D.Msg, error) {
if len(msg.Question) == 0 {
return nil, errors.New("should have one question at least")
}
if err := t.easytier.ensureStarted(ctx); err != nil {
return nil, err
}
q := msg.Question[0]
nodes, err := t.easytier.overlayNodes(ctx)
if err != nil {
return nil, err
}
reply := new(D.Msg)
reply.SetReply(msg)
reply.Authoritative = true
reply.RecursionAvailable = true
switch q.Qtype {
case D.TypeA:
ip, ok := easytier.LookupOverlayHost(q.Name, t.easytier.zone, nodes)
if !ok {
reply.Rcode = D.RcodeNameError
return reply, nil
}
reply.Answer = append(reply.Answer, &D.A{
Hdr: D.RR_Header{Name: q.Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: easyTierDNSTTL},
A: ip.AsSlice(),
})
case D.TypePTR:
ip, ok := easytier.ParsePTRIPv4(q.Name)
if !ok {
reply.Rcode = D.RcodeNameError
return reply, nil
}
name, ok := easytier.LookupOverlayPTR(ip, t.easytier.zone, nodes)
if !ok {
reply.Rcode = D.RcodeNameError
return reply, nil
}
reply.Answer = append(reply.Answer, &D.PTR{
Hdr: D.RR_Header{Name: q.Name, Rrtype: D.TypePTR, Class: D.ClassINET, Ttl: easyTierDNSTTL},
Ptr: name,
})
default:
reply.Rcode = D.RcodeSuccess
}
return reply, nil
}
func loadInstanceID(stateDir string) string {
contents, err := os.ReadFile(filepath.Join(stateDir, easyTierInstanceIDFile))
if err != nil {
return ""
}
return strings.TrimSpace(string(contents))
}
func writeInstanceID(stateDir, id string) error {
if id == "" {
return nil
}
path := filepath.Join(stateDir, easyTierInstanceIDFile)
return os.WriteFile(path, []byte(id+"\n"), 0o600)
}
+48
View File
@@ -0,0 +1,48 @@
//go:build no_easytier
package outbound
import "fmt"
type EasyTier struct {
*Base
}
type EasyTierOption struct {
BasicOption
Name string `proxy:"name"`
NetworkName string `proxy:"network-name,omitempty"`
NetworkSecret string `proxy:"network-secret,omitempty"`
Hostname string `proxy:"hostname,omitempty"`
IPv4 string `proxy:"ipv4,omitempty"`
DHCP bool `proxy:"dhcp,omitempty"`
Peers []string `proxy:"peers,omitempty"`
Listeners []string `proxy:"listeners,omitempty"`
NoListener *bool `proxy:"no-listener,omitempty"`
MappedListeners []string `proxy:"mapped-listeners,omitempty"`
ExitNodes []string `proxy:"exit-nodes,omitempty"`
ProxyNetworks []string `proxy:"proxy-networks,omitempty"`
InstanceName string `proxy:"instance-name,omitempty"`
StateDir string `proxy:"state-dir,omitempty"`
UDP bool `proxy:"udp,omitempty"`
AcceptDNS *bool `proxy:"accept-dns,omitempty"`
EnableExitNode *bool `proxy:"enable-exit-node,omitempty"`
EnableEncryption *bool `proxy:"enable-encryption,omitempty"`
EncryptionAlgorithm string `proxy:"encryption-algorithm,omitempty"`
PrivateMode *bool `proxy:"private-mode,omitempty"`
LatencyFirst *bool `proxy:"latency-first,omitempty"`
DisableP2P *bool `proxy:"disable-p2p,omitempty"`
EnableKCPProxy *bool `proxy:"enable-kcp-proxy,omitempty"`
DisableKCPInput *bool `proxy:"disable-kcp-input,omitempty"`
EnableQUICProxy *bool `proxy:"enable-quic-proxy,omitempty"`
DisableQUICInput *bool `proxy:"disable-quic-input,omitempty"`
MTU int `proxy:"mtu,omitempty"`
TLDDNSZone string `proxy:"tld-dns-zone,omitempty"`
SecureMode *bool `proxy:"secure-mode,omitempty"`
LocalPrivateKey string `proxy:"local-private-key,omitempty"`
LocalPublicKey string `proxy:"local-public-key,omitempty"`
}
func NewEasyTier(EasyTierOption) (*EasyTier, error) {
return nil, fmt.Errorf("EasyTier support is disabled by \"no_easytier\" build tag")
}
+7 -4
View File
@@ -53,10 +53,13 @@ func (h *Http) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Me
}
}
if err := h.shakeHandContext(ctx, c, metadata); err != nil {
// The proxy may send the target's first bytes right behind its response.
// They can end up in br, so the returned conn reads them first.
br := bufio.NewReader(c)
if err := h.shakeHandContext(ctx, c, br, metadata); err != nil {
return nil, err
}
return c, nil
return N.WarpConnWithBioReader(c, br), nil
}
// DialContext implements C.ProxyAdapter
@@ -85,7 +88,7 @@ func (h *Http) ProxyInfo() C.ProxyInfo {
return info
}
func (h *Http) shakeHandContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (err error) {
func (h *Http) shakeHandContext(ctx context.Context, c net.Conn, br *bufio.Reader, metadata *C.Metadata) (err error) {
if ctx.Done() != nil {
done := N.SetupContextForConn(ctx, c)
defer done(&err)
@@ -120,7 +123,7 @@ func (h *Http) shakeHandContext(ctx context.Context, c net.Conn, metadata *C.Met
return err
}
resp, err := http.ReadResponse(bufio.NewReader(c), nil)
resp, err := http.ReadResponse(br, nil)
if err != nil {
return err
+44 -4
View File
@@ -20,12 +20,14 @@ type Snell struct {
*Base
option *SnellOption
psk []byte
userKey []byte
pool *snell.Pool
obfsOption *simpleObfsOption
shadowTLSOption *shadowtls.ShadowTLSOption
restlsConfig *restls.Config
jlsConfig *jls.ClientConfig
version int
v6Mode snell.V6Mode
reuse bool
}
@@ -35,9 +37,11 @@ type SnellOption struct {
Server string `proxy:"server"`
Port int `proxy:"port"`
Psk string `proxy:"psk"`
UserKey string `proxy:"userkey,omitempty"`
UDP bool `proxy:"udp,omitempty"`
Version int `proxy:"version,omitempty"`
Reuse bool `proxy:"reuse,omitempty"`
Mode string `proxy:"mode,omitempty"` // v6 only: default / unshaped / unsafe-raw
ObfsOpts map[string]any `proxy:"obfs-opts,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
}
@@ -66,6 +70,9 @@ func (s *Snell) streamConnContext(ctx context.Context, c net.Conn) (*snell.Snell
return nil, err
}
}
if s.version == snell.Version6 {
return snell.StreamConnV6(c, s.psk, s.v6Mode), nil
}
return snell.StreamConn(c, s.psk, s.version), nil
}
@@ -86,7 +93,7 @@ func (s *Snell) writeHeaderContext(ctx context.Context, c net.Conn, metadata *C.
}
if metadata.NetWork == C.UDP {
err = snell.WriteUDPHeader(c, s.version)
err = snell.WriteUDPHeader(c, s.version, s.userKey)
if err == nil && s.version >= snell.Version4 {
if sc, ok := c.(*snell.Snell); ok {
err = sc.ReadReply()
@@ -94,7 +101,7 @@ func (s *Snell) writeHeaderContext(ctx context.Context, c net.Conn, metadata *C.
}
return
}
err = snell.WriteHeaderWithReuse(c, metadata.String(), uint(metadata.DstPort), s.version, s.reuse)
err = snell.WriteHeader(c, metadata.String(), metadata.DstPort, s.version, s.reuse, s.userKey)
return
}
@@ -249,16 +256,42 @@ func NewSnell(option SnellOption) (*Snell, error) {
// Snell v5 servers are backward-compatible with v4 clients.
option.Version = snell.Version4
}
reuse := option.Version == snell.Version2 || (option.Version == snell.Version4 && option.Reuse)
userKey := []byte(option.UserKey)
if len(userKey) > snell.MaxClientIDLength {
return nil, fmt.Errorf("snell %s userkey must be at most 255 bytes", addr)
}
if len(userKey) > 0 && option.Version != snell.Version6 {
return nil, fmt.Errorf("snell %s userkey is only supported on version 6", addr)
}
reuse := option.Version == snell.Version2 ||
((option.Version == snell.Version4 || option.Version == snell.Version6) && option.Reuse)
var v6Mode snell.V6Mode
switch option.Version {
case snell.Version1, snell.Version2:
if option.UDP {
return nil, fmt.Errorf("snell version %d not support UDP", option.Version)
}
case snell.Version3, snell.Version4:
case snell.Version6:
if err := snell.ValidateV6PSK(psk); err != nil {
return nil, fmt.Errorf("snell %s %w", addr, err)
}
switch obfsOption.Mode {
case "tls", "http":
// v6 replaced the simple-obfs layer with PSK-derived traffic shaping
return nil, fmt.Errorf("snell %s version 6 does not support obfs mode %s", addr, obfsOption.Mode)
}
var err error
v6Mode, err = snell.ParseV6Mode(option.Mode)
if err != nil {
return nil, fmt.Errorf("snell %s %w", addr, err)
}
default:
return nil, fmt.Errorf("snell version error: %d", option.Version)
}
if option.Mode != "" && option.Version != snell.Version6 {
return nil, fmt.Errorf("snell %s mode is only supported on version 6", addr)
}
s := &Snell{
Base: NewBase(BaseOption{
@@ -275,11 +308,13 @@ func NewSnell(option SnellOption) (*Snell, error) {
}),
option: &option,
psk: psk,
userKey: userKey,
obfsOption: obfsOption,
shadowTLSOption: shadowTLSOpt,
restlsConfig: restlsConfig,
jlsConfig: jlsConfig,
version: option.Version,
v6Mode: v6Mode,
reuse: reuse,
}
s.dialer = option.NewDialer(s.DialOptions())
@@ -291,7 +326,12 @@ func NewSnell(option SnellOption) (*Snell, error) {
return nil, err
}
return s.streamConnContext(ctx, c)
sc, err := s.streamConnContext(ctx, c)
if err != nil {
_ = c.Close()
return nil, err
}
return sc, nil
})
}
return s, nil
+19
View File
@@ -74,6 +74,13 @@ func (s *Ssh) connect(ctx context.Context, addr string) (client *ssh.Client, err
defer done(&err)
}
// Force the SSH transport to shut down when the underlying connection write
// fails. handshakeTransport caches this error without closing the transport,
// which can leave the shared client permanently unusable while Wait remains
// blocked. Closing the connection lets the read and mux loops exit so the
// cached client can be discarded and replaced.
c = closeOnWriteErrorConn{Conn: c}
clientConn, chans, reqs, err := ssh.NewClientConn(c, addr, s.config)
if err != nil {
return nil, err
@@ -95,6 +102,18 @@ func (s *Ssh) connect(ctx context.Context, addr string) (client *ssh.Client, err
return client, nil
}
type closeOnWriteErrorConn struct {
net.Conn
}
func (c closeOnWriteErrorConn) Write(p []byte) (int, error) {
n, err := c.Conn.Write(p)
if err != nil {
_ = c.Conn.Close()
}
return n, err
}
// ProxyInfo implements C.ProxyAdapter
func (s *Ssh) ProxyInfo() C.ProxyInfo {
info := s.Base.ProxyInfo()
+9 -3
View File
@@ -77,7 +77,9 @@ func (s *Sudoku) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Con
if err != nil {
return nil, err
}
defer func() { safeConnClose(c, err) }()
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
addrBuf, err := sudoku.EncodeAddress(cfg.TargetAddress)
if err != nil {
@@ -300,7 +302,6 @@ func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfi
PathRoot: cfg.HTTPMaskPathRoot,
AuthKey: sudoku.ClientAEADSeed(cfg.Key),
Upgrade: upgrade,
Multiplex: muxMode,
DialContext: s.dialer.DialContext,
})
if err != nil {
@@ -322,7 +323,9 @@ func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfi
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
}
defer func() { safeConnClose(c, err) }()
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
if ctx.Done() != nil {
done := N.SetupContextForConn(ctx, c)
@@ -350,6 +353,9 @@ func (s *Sudoku) resetHTTPMaskClient() {
s.httpMaskMu.Lock()
defer s.httpMaskMu.Unlock()
if s.httpMaskClient != nil {
// A failed session must not tear down the shared transport used by
// concurrent sessions. Close only idle connections here; the adapter's
// final Close owns the permanent client shutdown.
s.httpMaskClient.CloseIdleConnections()
s.httpMaskClient = nil
s.httpMaskKey = ""
+7
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net"
"net/netip"
"strconv"
"strings"
"time"
@@ -618,6 +619,9 @@ func NewVless(option VlessOption) (*Vless, error) {
} else {
requestHost = v.option.Server
}
if ip, err := netip.ParseAddr(requestHost); err == nil && ip.Is6() {
requestHost = "[" + requestHost + "]"
}
}
var hKeepAlivePeriod time.Duration
@@ -797,6 +801,9 @@ func NewVless(option VlessOption) (*Vless, error) {
} else {
downloadHost = downloadServer
}
if ip, err := netip.ParseAddr(downloadHost); err == nil && ip.Is6() {
downloadHost = "[" + downloadHost + "]"
}
}
downloadHKeepAlivePeriod := hKeepAlivePeriod
+8 -2
View File
@@ -386,11 +386,17 @@ func (v *Vmess) dialContext(ctx context.Context) (c net.Conn, err error) {
case "mekya":
return v.mekyaClient.Dial(ctx)
case "mkcp", "kcp":
rawConn, err := v.dialer.DialContext(ctx, "udp", v.addr)
var raw net.Conn
raw, err = v.dialer.DialContext(ctx, "udp", v.addr)
if err != nil {
return nil, err
}
return mkcp.Dial(ctx, rawConn, v.option.MKCPOpts.Build())
c, err = mkcp.Dial(ctx, raw, v.option.MKCPOpts.Build())
if err != nil {
_ = raw.Close()
return nil, err
}
return c, nil
default:
}
return v.dialer.DialContext(ctx, "tcp", v.addr)
+78 -43
View File
@@ -54,6 +54,9 @@ type WireGuard struct {
tunDevice wireguardDevice
resolver resolver.Resolver
runCtx context.Context
runCancel context.CancelFunc
deviceMutex sync.Mutex
initOk atomic.Bool
initMutex sync.Mutex
initErr error
@@ -163,7 +166,7 @@ func (o IPStackOption) validate() error {
default:
return fmt.Errorf("invalid IP stack mode %q; expected auto, gvisor, or mips", o.Mode)
}
switch mipstack.CongestionControl(o.CongestionController) {
switch o.CongestionController {
case "", mipstack.CongestionControlCUBIC, mipstack.CongestionControlReno, mipstack.CongestionControlBBR, mipstack.CongestionControlBBR3:
return nil
default:
@@ -177,7 +180,10 @@ type ipStack interface {
Start() error
DialTCP(ctx context.Context, network string, source, destination netip.AddrPort) (net.Conn, error)
DialUDP(ctx context.Context, network string, source, destination netip.AddrPort) (net.Conn, error)
DialIP(ctx context.Context, network string, source, destination netip.Addr) (net.Conn, error)
ListenTCP(ctx context.Context, network string, local netip.AddrPort) (net.Listener, error)
ListenUDP(ctx context.Context, network string, local netip.AddrPort) (net.PacketConn, error)
ListenIP(ctx context.Context, network string, local netip.Addr) (net.PacketConn, error)
Read(buffers [][]byte, sizes []int, offset int) (int, error)
Write(buffers [][]byte, offset int) (int, error)
MTU() (int, error)
@@ -190,11 +196,7 @@ type ipStack interface {
func newIPStack(option IPStackOption, localAddresses []netip.Prefix, mtu uint32) (ipStack, error) {
mode := option.Mode
if mode == ipStackAuto {
if features.WithGVisor {
mode = ipStackGVisor
} else {
mode = ipStackMips
}
mode = ipStackMips
}
switch mode {
case ipStackGVisor:
@@ -204,7 +206,7 @@ func newIPStack(option IPStackOption, localAddresses []netip.Prefix, mtu uint32)
LocalAddresses: localAddresses,
MTU: mtu,
TCP: mipstack.TCPSocketDefaults{
CongestionControl: mipstack.CongestionControl(option.CongestionController),
CongestionControl: option.CongestionController,
// Align with sing-wireguard: enable keepalive with 15-second
// idle/interval timing and gVisor's default probe count.
KeepAlive: true,
@@ -212,6 +214,11 @@ func newIPStack(option IPStackOption, localAddresses []netip.Prefix, mtu uint32)
Idle: 15 * time.Second, Interval: 15 * time.Second, Count: 9,
},
},
IP: mipstack.IPSocketDefaults{
// Align with sing-wireguard: fellow its IP socket semantics
IPHeaderIncludedOnRead: true,
IPHeaderIncludedOnWrite: true,
},
})
default:
return nil, errors.New("invalid IP stack mode")
@@ -376,7 +383,12 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
outbound.connectAddr = option.Addr()
}
}
outbound.bind = wireguard.NewClientBind(context.Background(), wgSingErrorHandler{outbound.Name()}, singDialer, isConnect, outbound.connectAddr.AddrPort(), reserved)
outbound.runCtx, outbound.runCancel = context.WithCancel(context.Background())
outbound.bind = wireguard.NewClientBind(outbound.runCtx, wgSingErrorHandler{outbound.Name()}, singDialer, isConnect, outbound.connectAddr.AddrPort(), reserved)
if outbound.bind == nil {
return nil, E.New("failed to create wireguard client bind")
}
var err error
outbound.localPrefixes, err = option.Prefixes()
@@ -442,11 +454,8 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
}
option.AmneziaWGOption.HeaderProtectionKey = hex.EncodeToString(bytes)
}
outbound.option = option
mtu := option.MTU
if mtu == 0 {
mtu = 1408
if option.MTU == 0 {
option.MTU = 1408
}
option.IPStack.normalize()
if err = option.IPStack.validate(); err != nil {
@@ -456,33 +465,9 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
return nil, E.New("missing local address")
}
stack, err := newIPStack(option.IPStack, outbound.localPrefixes, uint32(mtu))
if err != nil {
return nil, E.Cause(err, "create WireGuard stack")
}
outbound.tunDevice, err = newWireguardDevice(stack)
if err != nil {
_ = stack.Close()
return nil, E.Cause(err, "create WireGuard device")
}
logger := &device.Logger{
Verbosef: func(format string, args ...interface{}) {
log.SingLogger.Debug(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
},
Errorf: func(format string, args ...interface{}) {
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
},
}
outbound.option = option
if option.AmneziaWGOption != nil {
outbound.bind.SetParseReserved(false) // AmneziaWG don't need parse reserved
if option.AmneziaWGOption.Version == 3 {
outbound.device = amneziav3.NewDevice(outbound.tunDevice, outbound.bind, logger, option.Workers)
} else {
outbound.device = amnezia.NewDevice(outbound.tunDevice, outbound.bind, logger, option.Workers)
}
} else {
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, logger, option.Workers)
}
var has6 bool
@@ -532,7 +517,7 @@ func (w *WireGuard) init(ctx context.Context) error {
return nil
}
func (w *WireGuard) init0(ctx context.Context) error {
func (w *WireGuard) init0(ctx context.Context) (err error) {
if w.initOk.Load() {
return nil
}
@@ -554,23 +539,69 @@ func (w *WireGuard) init0(ctx context.Context) error {
// let us can retry domain resolve in next time
return err
}
if err = ctx.Err(); err != nil {
return err
}
stack, err := newIPStack(w.option.IPStack, w.localPrefixes, uint32(w.option.MTU))
if err != nil {
w.initErr = E.Cause(err, "create WireGuard stack")
return w.initErr
}
tunDevice, err := newWireguardDevice(stack)
if err != nil {
_ = stack.Close()
w.initErr = E.Cause(err, "create WireGuard device")
return w.initErr
}
logger := &device.Logger{
Verbosef: func(format string, args ...interface{}) {
log.SingLogger.Debug(fmt.Sprintf("[WG](%s) %s", w.option.Name, fmt.Sprintf(format, args...)))
},
Errorf: func(format string, args ...interface{}) {
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", w.option.Name, fmt.Sprintf(format, args...)))
},
}
var wgDevice wireguardGoDevice
if w.option.AmneziaWGOption != nil {
if w.option.AmneziaWGOption.Version == 3 {
wgDevice = amneziav3.NewDevice(tunDevice, w.bind, logger, w.option.Workers)
} else {
wgDevice = amnezia.NewDevice(tunDevice, w.bind, logger, w.option.Workers)
}
} else {
wgDevice = device.NewDevice(tunDevice, w.bind, logger, w.option.Workers)
}
defer func() {
if err != nil {
wgDevice.Close()
}
}()
if debug.Enabled {
log.SingLogger.Trace(fmt.Sprintf("[WG](%s) created wireguard ipc conf: \n %s", w.option.Name, ipcConf))
}
err = w.device.IpcSet(ipcConf)
err = wgDevice.IpcSet(ipcConf)
if err != nil {
w.initErr = E.Cause(err, "setup wireguard")
return w.initErr
}
w.serverAddrTime.Store(time.Now())
err = w.tunDevice.Start()
err = tunDevice.Start()
if err != nil {
w.initErr = err
return w.initErr
}
w.deviceMutex.Lock()
defer w.deviceMutex.Unlock()
err = w.runCtx.Err()
if err != nil {
return err
}
w.device, w.tunDevice = wgDevice, tunDevice
w.initOk.Store(true)
return nil
}
@@ -773,8 +804,12 @@ func (w *WireGuard) genIpcConf(ctx context.Context, updateOnly bool) (string, er
// Close implements C.ProxyAdapter
func (w *WireGuard) Close() error {
if w.device != nil {
w.device.Close()
w.runCancel()
w.deviceMutex.Lock()
wgDevice := w.device
w.deviceMutex.Unlock()
if wgDevice != nil {
wgDevice.Close()
}
return nil
}
+70 -28
View File
@@ -37,6 +37,10 @@ const (
// and IP-stack delivery while retaining callback order.
zeroTierFrameBatchSize = 64
zeroTierFrameDropLogInterval = 10 * time.Second
// A configured identity cannot be rotated after a collision. Retrying at a
// bounded rate lets it recover after the other node goes away without
// repeatedly recreating the local runtime.
zeroTierIdentityCollisionRetryInterval = 30 * time.Second
)
var errZeroTierClosed = errors.New("ZeroTier outbound closed")
@@ -45,15 +49,16 @@ var errZeroTierStaleConfig = errors.New("stale ZeroTier network configuration")
type ZeroTier struct {
*Base
option ZeroTierOption
networkID uint64
planet *ZT.World
orbits []zeroTierOrbit
remoteTraceTarget ZT.Address
stateStore ZT.StateStore
dns []dns.NameServer
ctx context.Context
cancel context.CancelFunc
option ZeroTierOption
networkID uint64
configuredIdentity ZT.Identity
planet *ZT.World
orbits []zeroTierOrbit
remoteTraceTarget ZT.Address
stateStore ZT.StateStore
dns []dns.NameServer
ctx context.Context
cancel context.CancelFunc
// Lock acquisition rules. Rows are locks already held; columns are locks to
// acquire next. Any lock may be acquired when no ZeroTier lock is held.
@@ -72,9 +77,10 @@ type ZeroTier struct {
// goroutine. Control-plane operations take the write lock, while data-plane
// use of mutable IP-link configuration takes the read lock. stateMu is only a
// short-lived field lock and is never held while acquiring operationMu.
operationMu sync.RWMutex
closed bool
backgroundStarted bool
operationMu sync.RWMutex
closed bool
backgroundStarted bool
identityCollisionRetryAt time.Time
frameCh chan zeroTierInboundFrame
configCh chan struct{}
@@ -104,6 +110,7 @@ type ZeroTierOption struct {
Name string `proxy:"name"`
Network string `proxy:"network"`
StateDir string `proxy:"state-dir,omitempty"`
IdentitySecret string `proxy:"identity-secret,omitempty"`
Planet string `proxy:"planet,omitempty"`
MTU int `proxy:"mtu,omitempty"`
IPStack IPStackOption `proxy:"ip-stack,omitempty"`
@@ -196,6 +203,19 @@ func NewZeroTier(option ZeroTierOption) (*ZeroTier, error) {
if err != nil {
return nil, err
}
var configuredIdentity ZT.Identity
if option.IdentitySecret != "" {
configuredIdentity, err = ZT.ParseIdentity(option.IdentitySecret)
if err != nil {
return nil, fmt.Errorf("parse ZeroTier identity-secret: %w", err)
}
if !configuredIdentity.HasPrivate() {
return nil, fmt.Errorf("ZeroTier identity-secret must contain private keys: %w", ZT.ErrPrivateKey)
}
if err = configuredIdentity.Validate(); err != nil {
return nil, fmt.Errorf("validate ZeroTier identity-secret: %w", err)
}
}
if option.MTU != 0 && (option.MTU < ZT.MinNetworkMTU || option.MTU > ZT.MaxNetworkMTU) {
return nil, fmt.Errorf("ZeroTier MTU must be between %d and %d", ZT.MinNetworkMTU, ZT.MaxNetworkMTU)
}
@@ -285,18 +305,19 @@ func NewZeroTier(option ZeroTierOption) (*ZeroTier, error) {
RoutingMark: option.RoutingMark,
Prefer: option.IPVersion,
}),
option: option,
networkID: networkID,
planet: planet,
orbits: orbits,
remoteTraceTarget: remoteTraceTarget,
stateStore: stateStore,
dns: nameServers,
ctx: ctx,
cancel: cancel,
frameCh: make(chan zeroTierInboundFrame, zeroTierFrameQueueSize),
configCh: make(chan struct{}, 1),
stateCh: make(chan struct{}),
option: option,
networkID: networkID,
configuredIdentity: configuredIdentity,
planet: planet,
orbits: orbits,
remoteTraceTarget: remoteTraceTarget,
stateStore: stateStore,
dns: nameServers,
ctx: ctx,
cancel: cancel,
frameCh: make(chan zeroTierInboundFrame, zeroTierFrameQueueSize),
configCh: make(chan struct{}, 1),
stateCh: make(chan struct{}),
}
outbound.dialer = option.NewDialer(outbound.DialOptions())
wireConfig, err := outbound.wireTransportConfig()
@@ -434,6 +455,17 @@ func (z *ZeroTier) startLocked() error {
if z.closed || z.ctx.Err() != nil {
return errZeroTierClosed
}
if !z.identityCollisionRetryAt.IsZero() {
retryAfter := time.Until(z.identityCollisionRetryAt)
if retryAfter > 0 {
retryAfter = retryAfter.Round(time.Second)
if retryAfter < time.Second {
retryAfter = time.Second
}
return fmt.Errorf("configured ZeroTier identity %s can retry in %s: %w", z.configuredIdentity.Address(), retryAfter, ZT.ErrIdentityCollision)
}
z.identityCollisionRetryAt = time.Time{}
}
z.stateMu.RLock()
started := z.runtime != nil
z.stateMu.RUnlock()
@@ -458,9 +490,10 @@ func (z *ZeroTier) startLocked() error {
last time.Time
}
node, err := ZT.NewNode(ZT.NodeConfig{
Store: z.stateStore,
Sender: wireTransport,
Planet: z.planet,
Identity: z.configuredIdentity,
Store: z.stateStore,
Sender: wireTransport,
Planet: z.planet,
OnEvent: func(event ZT.Event) {
z.handleNodeEvent(runtime, event)
},
@@ -757,10 +790,19 @@ func (z *ZeroTier) recoverIdentityCollision(source *zeroTierRuntime, address ZT.
return
}
runtime, device := z.detachRuntimeLocked()
z.resetNetworkStateLocked(nil)
var collisionErr error
if !z.configuredIdentity.Address().IsZero() {
collisionErr = fmt.Errorf("configured ZeroTier identity %s: %w", address, ZT.ErrIdentityCollision)
z.identityCollisionRetryAt = time.Now().Add(zeroTierIdentityCollisionRetryInterval)
}
z.resetNetworkStateLocked(collisionErr)
z.stateMu.Unlock()
_ = runtime.close(device)
if collisionErr != nil {
log.Warnln("[ZeroTier](%s) %v; the next use can retry in %s", z.Name(), collisionErr, zeroTierIdentityCollisionRetryInterval)
return
}
if err := ZT.RotateIdentityState(z.stateStore); err != nil {
log.Warnln("[ZeroTier](%s) unable to rotate collided identity: %v", z.Name(), err)
}
+1
View File
@@ -13,6 +13,7 @@ type ZeroTierOption struct {
Name string `proxy:"name"`
Network string `proxy:"network"`
StateDir string `proxy:"state-dir,omitempty"`
IdentitySecret string `proxy:"identity-secret,omitempty"`
Planet string `proxy:"planet,omitempty"`
MTU int `proxy:"mtu,omitempty"`
IPStack IPStackOption `proxy:"ip-stack,omitempty"`
+53 -6
View File
@@ -21,6 +21,7 @@ import (
type LoadBalanceOption struct {
Strategy string `group:"strategy,omitempty"`
HashKey string `group:"hash-key,omitempty"`
}
type LoadBalance struct {
@@ -34,6 +35,10 @@ type LoadBalance struct {
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy
var errStrategy = errors.New("unsupported strategy")
var errHashKey = errors.New("unsupported hash-key")
// keyFn derives the value a hashing strategy pins a request on.
type keyFn = func(metadata *C.Metadata) string
func getKey(metadata *C.Metadata) string {
if metadata == nil {
@@ -68,6 +73,39 @@ func getKeyWithSrcAndDst(metadata *C.Metadata) string {
return fmt.Sprintf("%s%s", src, dst)
}
// getKeyWithInUser pins on the authenticated inbound user instead of on an
// address. Both address-derived keys assume one client's traffic to one
// destination is one unit of work, which is false for a client whose single
// unit of work walks several destinations: the hash moves with the host, and
// the egress IP changes underneath a session the destination is tracking.
// The inbound user is the only identity the client itself controls, and
// `IN-USER` rules already match on it -- hence the option value `in-user`,
// which names the same thing those rules do. An unauthenticated request keeps
// the strategy's own key rather than collapsing every such request onto one
// node.
func getKeyWithInUser(fallback keyFn) keyFn {
return func(metadata *C.Metadata) string {
if metadata != nil && metadata.InUser != "" {
return metadata.InUser
}
return fallback(metadata)
}
}
// hashKey resolves the `hash-key` option into a decorator over whichever key
// the chosen strategy derives by default.
func hashKey(name string) (func(keyFn) keyFn, error) {
switch name {
case "":
return func(fn keyFn) keyFn { return fn }, nil
case "in-user":
return getKeyWithInUser, nil
}
return nil, fmt.Errorf("%w: %s", errHashKey, name)
}
func jumpHash(key uint64, buckets int32) int32 {
var b, j int64
@@ -155,10 +193,10 @@ func strategyRoundRobin(url string) strategyFn {
}
}
func strategyConsistentHashing(url string) strategyFn {
func strategyConsistentHashing(url string, keyOf keyFn) strategyFn {
maxRetry := 5
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
key := utils.MapHash(getKey(metadata))
key := utils.MapHash(keyOf(metadata))
buckets := int32(len(proxies))
for i := 0; i < maxRetry; i, key = i+1, key+1 {
idx := jumpHash(key, buckets)
@@ -179,14 +217,14 @@ func strategyConsistentHashing(url string) strategyFn {
}
}
func strategyStickySessions(url string) strategyFn {
func strategyStickySessions(url string, keyOf keyFn) strategyFn {
ttl := time.Minute * 10
maxRetry := 5
lruCache := lru.New[uint64, int](
lru.WithAge[uint64, int](int64(ttl.Seconds())),
lru.WithSize[uint64, int](1000))
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
key := utils.MapHash(getKeyWithSrcAndDst(metadata))
key := utils.MapHash(keyOf(metadata))
length := len(proxies)
idx, has := lruCache.Get(key)
if !has || idx >= length {
@@ -249,13 +287,22 @@ func (lb *LoadBalance) Now() string {
func NewLoadBalance(option GroupCommonOption, loadBalanceOption LoadBalanceOption, emptyFallback C.Proxy, providers []P.ProxyProvider) (lb *LoadBalance, err error) {
var strategyFn strategyFn
withKey, err := hashKey(loadBalanceOption.HashKey)
if err != nil {
return nil, err
}
switch loadBalanceOption.Strategy {
case "", "consistent-hashing":
strategyFn = strategyConsistentHashing(option.URL)
strategyFn = strategyConsistentHashing(option.URL, withKey(getKey))
case "round-robin":
// Rejected rather than ignored: round-robin hashes nothing, so a
// hash-key here means the config expects stickiness it will not get.
if loadBalanceOption.HashKey != "" {
return nil, fmt.Errorf("%w: round-robin does not hash", errHashKey)
}
strategyFn = strategyRoundRobin(option.URL)
case "sticky-sessions":
strategyFn = strategyStickySessions(option.URL)
strategyFn = strategyStickySessions(option.URL, withKey(getKeyWithSrcAndDst))
default:
return nil, fmt.Errorf("%w: %s", errStrategy, loadBalanceOption.Strategy)
}
+143
View File
@@ -0,0 +1,143 @@
package outboundgroup
import (
"net/netip"
"testing"
"github.com/metacubex/mihomo/adapter"
"github.com/metacubex/mihomo/adapter/outbound"
C "github.com/metacubex/mihomo/constant"
"github.com/stretchr/testify/require"
)
const testUrl = "https://www.gstatic.com/generate_204"
func balancedProxies(count int) []C.Proxy {
proxies := make([]C.Proxy, 0, count)
for i := 0; i < count; i++ {
proxies = append(proxies, adapter.NewProxy(outbound.NewDirect()))
}
return proxies
}
// The proxies are indistinguishable by name, so identity is the pointer.
func indexOf(t *testing.T, proxies []C.Proxy, selected C.Proxy) int {
t.Helper()
for i, proxy := range proxies {
if proxy == selected {
return i
}
}
require.Fail(t, "selected proxy is not a member of the group")
return -1
}
func request(user, host string) *C.Metadata {
return &C.Metadata{
NetWork: C.TCP,
Host: host,
DstPort: 443,
SrcIP: netip.MustParseAddr("127.0.0.1"),
InUser: user,
}
}
// One unit of work walking several destinations is the case both address-derived
// keys get wrong: the group is meant to hold that work on one egress, and the
// default key changes as soon as the host changes.
func TestLoadBalanceHashKeyInUserSurvivesADestinationChange(t *testing.T) {
proxies := balancedProxies(8)
hosts := []string{"a.example.com", "b.example.org", "c.example.net", "d.example.io"}
byUser := strategyConsistentHashing(testUrl, getKeyWithInUser(getKey))
pinned := indexOf(t, proxies, byUser(proxies, request("job-1", hosts[0]), false))
for _, host := range hosts {
selected := byUser(proxies, request("job-1", host), false)
require.Equal(t, pinned, indexOf(t, proxies, selected),
"hash-key: user must ignore the destination")
}
// Distinct destination keys are the deterministic contract of the fallback
// key. Distinct keys may still legally land in the same consistent-hash
// bucket, so asserting on selected proxy indexes would make this test flaky.
seenKeys := map[string]struct{}{}
for _, host := range hosts {
seenKeys[getKey(request("job-1", host))] = struct{}{}
}
require.Len(t, seenKeys, len(hosts),
"the default key must change with the destination")
}
// Pinning must preserve distinct inbound identities. Consistent hashing may
// legally put several distinct keys in one bucket, so this test checks the
// identity key before hashing instead of asserting a random bucket spread.
func TestLoadBalanceHashKeyInUserKeepsUsersDistinct(t *testing.T) {
keyed := getKeyWithInUser(getKey)
users := []string{"job-1", "job-2", "job-3", "job-4", "job-5", "job-6"}
seenKeys := map[string]struct{}{}
for _, user := range users {
seenKeys[keyed(request(user, "a.example.com"))] = struct{}{}
}
require.Len(t, seenKeys, len(users))
}
// Sticky sessions keys on source and destination; a client behind one source
// address cannot separate its own concurrent jobs without a supplied identity.
func TestLoadBalanceHashKeyInUserSeparatesJobsSharingASourceAddress(t *testing.T) {
proxies := balancedProxies(8)
strategy := strategyStickySessions(testUrl, getKeyWithInUser(getKeyWithSrcAndDst))
first := indexOf(t, proxies, strategy(proxies, request("job-1", "a.example.com"), false))
require.Equal(t, first,
indexOf(t, proxies, strategy(proxies, request("job-1", "b.example.org"), false)))
shared := strategyStickySessions(testUrl, getKeyWithSrcAndDst)
require.Equal(t,
indexOf(t, proxies, shared(proxies, request("job-1", "a.example.com"), false)),
indexOf(t, proxies, shared(proxies, request("job-2", "a.example.com"), false)),
"without a supplied key the two jobs are one session")
}
// An unauthenticated request keeps the strategy's own key. Returning a constant
// instead would herd every anonymous request onto one member.
func TestLoadBalanceHashKeyInUserFallsBackWhenUnauthenticated(t *testing.T) {
keyed := getKeyWithInUser(getKey)
require.Equal(t, "example.com", keyed(request("", "a.example.com")))
require.Equal(t, "job-1", keyed(request("job-1", "a.example.com")))
require.Equal(t, getKey(nil), keyed(nil))
}
// The option name is the contract with the config file, and nothing else here
// exercises it: every other test reaches the decorator directly, so renaming
// the case would leave them all green while `hash-key: in-user` stopped working.
func TestLoadBalanceHashKeyResolvesTheOptionName(t *testing.T) {
withInUser, err := hashKey("in-user")
require.NoError(t, err)
require.Equal(t, "job-1", withInUser(getKey)(request("job-1", "a.example.com")))
identity, err := hashKey("")
require.NoError(t, err)
require.Equal(t, getKey(request("job-1", "a.example.com")),
identity(getKey)(request("job-1", "a.example.com")))
}
func TestLoadBalanceHashKeyRejectsUnusableConfigs(t *testing.T) {
_, err := hashKey("session")
require.ErrorIs(t, err, errHashKey)
// `user` was the name this option carried before review. Rejecting it keeps
// the rename honest: without this the case above could still read `user`
// and every test here would stay green.
_, err = hashKey("user")
require.ErrorIs(t, err, errHashKey)
_, err = NewLoadBalance(GroupCommonOption{Name: "lb"},
LoadBalanceOption{Strategy: "round-robin", HashKey: "in-user"}, nil, nil)
require.ErrorIs(t, err, errHashKey)
_, err = NewLoadBalance(GroupCommonOption{Name: "lb"},
LoadBalanceOption{Strategy: "consistent-hashing", HashKey: "nonsense"}, nil, nil)
require.ErrorIs(t, err, errHashKey)
}
+7
View File
@@ -216,6 +216,13 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error)
break
}
proxy, err = outbound.NewZeroTier(*zeroTierOption)
case "easytier":
easyTierOption := &outbound.EasyTierOption{BasicOption: basicOption}
err = decoder.Decode(mapping, easyTierOption)
if err != nil {
break
}
proxy, err = outbound.NewEasyTier(*easyTierOption)
default:
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
}
+1 -1
View File
@@ -27,7 +27,7 @@ func NewSubscriptionInfo(userinfo string) (si *SubscriptionInfo) {
intValue, err := parseValue(value)
if err != nil {
log.Warnln("[Provider] get subscription-userinfo: %e", err)
log.Warnln("[Provider] get subscription-userinfo: %s", err)
continue
}
+13 -5
View File
@@ -16,13 +16,13 @@ import (
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
data := DecodeBase64(buf)
arr := strings.Split(string(data), "\n")
rawLines := bytes.Split(data, []byte("\n"))
proxies := make([]map[string]any, 0, len(arr))
proxies := make([]map[string]any, 0, len(rawLines))
names := make(map[string]int, 200)
for _, line := range arr {
line = strings.TrimRight(line, " \r")
for _, raw := range rawLines {
line := strings.TrimRight(string(raw), " \r")
if line == "" {
continue
}
@@ -190,7 +190,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
}
switch network {
case "ws":
case "ws", "httpupgrade":
headers := make(map[string]any)
wsOpts := make(map[string]any)
@@ -198,6 +198,10 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
wsOpts["path"] = query.Get("path")
wsOpts["headers"] = headers
if network == "httpupgrade" {
trojan["network"] = "ws"
wsOpts["v2ray-http-upgrade"] = true
}
trojan["ws-opts"] = wsOpts
@@ -357,6 +361,10 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
headers := make(map[string]any)
wsOpts := make(map[string]any)
wsOpts["path"] = "/"
if network == "httpupgrade" {
vmess["network"] = "ws"
wsOpts["v2ray-http-upgrade"] = true
}
if host, ok := values["host"].(string); ok && host != "" {
headers["Host"] = host
}
+145
View File
@@ -1,6 +1,7 @@
package convert_test
import (
"encoding/base64"
"testing"
"github.com/metacubex/mihomo/adapter"
@@ -194,6 +195,51 @@ func TestConvertsV2RayVlessRealityVisionTCPWithoutHeaderType(t *testing.T) {
assert.NoError(t, err)
}
func TestConvertsV2RayRealityMLKEM768(t *testing.T) {
const publicKey = "ppQ9FwLrLIa0AOrp1WvcyiaQ37vg2WSy_CD4bIdiTUw"
tests := []struct {
name, query, publicKey string
want any
}{
{"absent", "", publicKey, nil},
{"empty", "&support-x25519mlkem768=", publicKey, nil},
{"true", "&support-x25519mlkem768=true", publicKey, true},
{"one", "&support-x25519mlkem768=1", publicKey, true},
{"false", "&support-x25519mlkem768=false", publicKey, false},
{"zero", "&support-x25519mlkem768=0", publicKey, false},
{"invalid", "&support-x25519mlkem768=invalid", publicKey, nil},
{"no-public-key", "&support-x25519mlkem768=true", "", nil},
}
for _, scheme := range []string{"vless", "vmess"} {
for _, tt := range tests {
t.Run(scheme+"/"+tt.name, func(t *testing.T) {
uri := scheme + "://b831381d-6324-4d53-ad4f-8cda48b30811@example.com:443" +
"?security=reality&type=tcp&sid=00112233&pbk=" + tt.publicKey + tt.query
for _, input := range []string{uri, base64.StdEncoding.EncodeToString([]byte(uri))} {
proxies, err := ConvertsV2Ray([]byte(input))
if !assert.NoError(t, err) || !assert.Len(t, proxies, 1) {
return
}
if tt.publicKey == "" {
assert.NotContains(t, proxies[0], "reality-opts")
} else {
expected := map[string]any{
"public-key": tt.publicKey,
"short-id": "00112233",
}
if tt.want != nil {
expected["support-x25519mlkem768"] = tt.want
}
assert.Equal(t, expected, proxies[0]["reality-opts"])
}
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
})
}
}
}
func TestConvertsV2RayVlessTCPHTTPHeaderType(t *testing.T) {
vlessTest := "vless://uuid@example.com:443?security=tls&type=tcp&headerType=http&host=cdn.example.com&path=%2Fedge&method=POST#vless-http"
@@ -283,3 +329,102 @@ func TestConvertsV2RayVmessBase64HTTPRemappedToH2Transport(t *testing.T) {
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
// httpupgrade is a ws-opts mode of the ws transport, not a network of its
// own, so links with type=httpupgrade must become network ws with
// v2ray-http-upgrade set.
func TestConvertsV2RayVlessHTTPUpgrade(t *testing.T) {
for _, tt := range []struct {
name string
link string
fastOpen bool
}{
{"without ed", "vless://uuid@example.com:443?security=tls&type=httpupgrade&host=cdn.example.com&path=%2Fup#vless-hu", false},
{"with ed", "vless://uuid@example.com:443?security=tls&type=httpupgrade&host=cdn.example.com&path=%2Fup&ed=2048#vless-hu", true},
} {
t.Run(tt.name, func(t *testing.T) {
proxies, err := ConvertsV2Ray([]byte(tt.link))
assert.Nil(t, err)
assert.Len(t, proxies, 1)
assert.Equal(t, "ws", proxies[0]["network"])
wsOpts, ok := proxies[0]["ws-opts"].(map[string]any)
assert.True(t, ok)
assert.Equal(t, true, wsOpts["v2ray-http-upgrade"])
assert.Equal(t, "/up", wsOpts["path"])
assert.Equal(t, "cdn.example.com", wsOpts["headers"].(map[string]any)["Host"])
if tt.fastOpen {
assert.Equal(t, true, wsOpts["v2ray-http-upgrade-fast-open"])
} else {
assert.NotContains(t, wsOpts, "v2ray-http-upgrade-fast-open")
}
assert.NotContains(t, wsOpts, "max-early-data")
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
})
}
}
func TestConvertsV2RayVlessWSNotHTTPUpgrade(t *testing.T) {
proxies, err := ConvertsV2Ray([]byte("vless://uuid@example.com:443?security=tls&type=ws&host=cdn.example.com&path=%2Fws&ed=2048#vless-ws"))
assert.Nil(t, err)
assert.Len(t, proxies, 1)
assert.Equal(t, "ws", proxies[0]["network"])
wsOpts := proxies[0]["ws-opts"].(map[string]any)
assert.NotContains(t, wsOpts, "v2ray-http-upgrade")
assert.Equal(t, 2048, wsOpts["max-early-data"])
}
func TestConvertsV2RayVmessBase64HTTPUpgrade(t *testing.T) {
for _, tt := range []struct {
name string
path string
fastOpen bool
}{
{"without ed", "/up", false},
{"with ed", "/up?ed=2048", true},
} {
t.Run(tt.name, func(t *testing.T) {
payload := `{"v":"2","ps":"vmess-hu","add":"server.example.com","port":"443",` +
`"id":"b831381d-6324-4d53-ad4f-8cda48b30811","aid":"0","scy":"auto",` +
`"net":"httpupgrade","type":"none","host":"cdn.example.com","path":"` + tt.path + `","tls":"tls"}`
vmessTest := "vmess://" + base64.StdEncoding.EncodeToString([]byte(payload))
proxies, err := ConvertsV2Ray([]byte(vmessTest))
assert.Nil(t, err)
assert.Len(t, proxies, 1)
assert.Equal(t, "ws", proxies[0]["network"])
wsOpts, ok := proxies[0]["ws-opts"].(map[string]any)
assert.True(t, ok)
assert.Equal(t, true, wsOpts["v2ray-http-upgrade"])
assert.Equal(t, "/up", wsOpts["path"])
assert.Equal(t, map[string]any{"Host": "cdn.example.com"}, wsOpts["headers"])
if tt.fastOpen {
assert.Equal(t, true, wsOpts["v2ray-http-upgrade-fast-open"])
} else {
assert.NotContains(t, wsOpts, "v2ray-http-upgrade-fast-open")
}
assert.NotContains(t, wsOpts, "max-early-data")
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
})
}
}
func TestConvertsV2RayTrojanHTTPUpgrade(t *testing.T) {
proxies, err := ConvertsV2Ray([]byte("trojan://secret@example.com:443?security=tls&type=httpupgrade&host=cdn.example.com&path=%2Fup#trojan-hu"))
assert.Nil(t, err)
assert.Len(t, proxies, 1)
assert.Equal(t, "ws", proxies[0]["network"])
wsOpts, ok := proxies[0]["ws-opts"].(map[string]any)
assert.True(t, ok)
assert.Equal(t, true, wsOpts["v2ray-http-upgrade"])
assert.Equal(t, "/up", wsOpts["path"])
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
+15 -1
View File
@@ -44,10 +44,16 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
proxy["servername"] = sni
}
if realityPublicKey := query.Get("pbk"); realityPublicKey != "" {
proxy["reality-opts"] = map[string]any{
realityOpts := map[string]any{
"public-key": realityPublicKey,
"short-id": query.Get("sid"),
}
if value := query.Get("support-x25519mlkem768"); value != "" {
if enabled, err := strconv.ParseBool(value); err == nil {
realityOpts["support-x25519mlkem768"] = enabled
}
}
proxy["reality-opts"] = realityOpts
}
switch query.Get("packetEncoding") {
@@ -108,6 +114,10 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
headers["Host"] = query.Get("host")
wsOpts["path"] = query.Get("path")
wsOpts["headers"] = headers
if network == "httpupgrade" {
proxy["network"] = "ws"
wsOpts["v2ray-http-upgrade"] = true
}
if earlyData := query.Get("ed"); earlyData != "" {
med, err := strconv.Atoi(earlyData)
@@ -190,6 +200,10 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
return reuse
}
if headers, ok := extra["headers"].(map[string]any); ok && len(headers) > 0 {
opts["headers"] = headers
}
if v, ok := extra["noGRPCHeader"].(bool); ok && v {
opts["no-grpc-header"] = true
}
+1
View File
@@ -32,6 +32,7 @@ func (l *handleContextListener) init() {
if l.panicLog != nil {
l.panicLog(r)
}
_ = c.Close()
}
}()
if conn, err := l.handle(l.ctx, c); err == nil {
+3
View File
@@ -25,6 +25,9 @@ func NewEnhancePacketConn(pc net.PacketConn) EnhancePacketConn {
if singPC, isSingPC := pc.(SingPacketConn); isSingPC {
return newEnhanceSingPacketConn(singPC)
}
if withBufferPC, isWithBufferPC := pc.(withBufferPacketConn); isWithBufferPC {
return &enhanceWithBufferPacketConn{withBufferPacketConn: withBufferPC}
}
return &enhancePacketConn{PacketConn: pc}
}
+48
View File
@@ -0,0 +1,48 @@
package packet
import (
"net"
"github.com/metacubex/mihomo/common/pool"
)
type withBufferPacketConn interface {
net.PacketConn
ReadFromWithBuffer(func(sizeHint int) []byte) (int, net.Addr, error)
}
type enhanceWithBufferPacketConn struct {
withBufferPacketConn
}
func (c *enhanceWithBufferPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
var readBuf []byte
getBuffer := func(sizeHint int) []byte {
readBuf = pool.Get(sizeHint)
put = func() {
_ = pool.Put(readBuf)
}
return readBuf
}
var readN int
readN, addr, err = c.ReadFromWithBuffer(getBuffer)
if readN > 0 && readBuf != nil {
data = readBuf[:readN]
} else if put != nil {
put()
put = nil
}
return
}
func (c *enhanceWithBufferPacketConn) Upstream() any {
return c.withBufferPacketConn
}
func (c *enhanceWithBufferPacketConn) WriterReplaceable() bool {
return true
}
func (c *enhanceWithBufferPacketConn) ReaderReplaceable() bool {
return true
}
+1 -1
View File
@@ -3,7 +3,7 @@ package orderedmap
import (
"fmt"
"gopkg.in/yaml.v3"
"go.yaml.in/yaml/v3"
)
var (
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
"go.yaml.in/yaml/v3"
)
func FuzzRoundTripYAML(f *testing.F) {
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
"go.yaml.in/yaml/v3"
)
func TestMarshalYAML(t *testing.T) {
+1 -1
View File
@@ -2,7 +2,7 @@
package yaml
import (
"gopkg.in/yaml.v3"
"go.yaml.in/yaml/v3"
)
func Unmarshal(in []byte, out any) (err error) {
+3
View File
@@ -89,6 +89,9 @@ func DecryptBytes(data []byte, secretKeys ...string) ([]byte, error) {
}
var identities []age.Identity
for _, secretKey := range secretKeys {
if secretKey == "" { // e.g. a proxy-provider without its own age-secret-key
continue // the empty key must be skipped so the global secret keys are still used.
}
identity, err := parseIdentities(secretKey)
if err != nil {
return nil, err
+29 -3
View File
@@ -79,6 +79,23 @@ func DialContext(ctx context.Context, network, address string, options ...Option
func ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort, options ...Option) (net.PacketConn, error) {
opt := applyOptions(options...)
lc, address, err := listenConfig(network, address, rAddrPort, opt)
if err != nil {
return nil, err
}
return lc.ListenPacket(ctx, network, address)
}
// Listen creates a TCP listener with the same socket policy as ListenPacket.
func Listen(ctx context.Context, network, address string, options ...Option) (net.Listener, error) {
lc, address, err := listenConfig(network, address, netip.AddrPort{}, applyOptions(options...))
if err != nil {
return nil, err
}
return lc.Listen(ctx, network, address)
}
func listenConfig(network, address string, rAddrPort netip.AddrPort, opt option) (*net.ListenConfig, string, error) {
lc := &net.ListenConfig{}
if opt.addrReuse {
addrReuseToListenConfig(lc)
@@ -94,7 +111,7 @@ func ListenPacket(ctx context.Context, network, address string, rAddrPort netip.
opt.interfaceName = finder.FindInterfaceName(rAddrPort.Addr().Unmap())
}
}
if rAddrPort.Addr().Unmap().IsLoopback() {
if rAddrPort.Addr().Unmap().IsLoopback() || listenAddressIsLoopback(address) {
// avoid "The requested address is not valid in its context."
opt.interfaceName = ""
}
@@ -105,7 +122,7 @@ func ListenPacket(ctx context.Context, network, address string, rAddrPort netip.
}
addr, err := bind(opt.interfaceName, lc, network, address, rAddrPort)
if err != nil {
return nil, err
return nil, "", err
}
address = addr
}
@@ -117,7 +134,7 @@ func ListenPacket(ctx context.Context, network, address string, rAddrPort netip.
}
}
return lc.ListenPacket(ctx, network, address)
return lc, address, nil
}
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt option) (net.Conn, error) {
@@ -390,6 +407,15 @@ func parseAddr(ctx context.Context, network, address string, preferResolver reso
return ips, port, nil
}
func listenAddressIsLoopback(address string) bool {
host, _, err := net.SplitHostPort(address)
if err != nil {
host = address
}
ip, err := netip.ParseAddr(host)
return err == nil && ip.Unmap().IsLoopback()
}
type Dialer struct {
Opt option
}
+138
View File
@@ -0,0 +1,138 @@
package easytier
import (
"encoding/binary"
"fmt"
"net/netip"
"strconv"
"strings"
)
const DefaultTLDDNSZone = "et.net."
// Node describes one overlay IPv4 hostname mapping.
type Node struct {
Hostname string
IPv4 netip.Addr
}
// NormalizeDNSName lowercases a name and strips a trailing dot.
func NormalizeDNSName(name string) string {
return strings.ToLower(strings.TrimSuffix(strings.TrimSpace(name), "."))
}
// NormalizeZone returns a MagicDNS zone without a trailing dot.
func NormalizeZone(zone string) string {
zone = NormalizeDNSName(zone)
if zone == "" {
return NormalizeDNSName(DefaultTLDDNSZone)
}
return zone
}
// OverlayNames returns hostname forms that MagicDNS may use.
func OverlayNames(hostname, zone string) []string {
hostname = NormalizeDNSName(hostname)
if hostname == "" {
return nil
}
zone = NormalizeZone(zone)
names := []string{hostname}
if hostname != zone && !strings.HasSuffix(hostname, "."+zone) {
names = append(names, hostname+"."+zone)
}
return names
}
// IsMagicDNS reports whether host should stay on the overlay resolver.
func IsMagicDNS(host, zone string) bool {
host = NormalizeDNSName(host)
if host == "" {
return false
}
zone = NormalizeZone(zone)
return host == zone || strings.HasSuffix(host, "."+zone)
}
// LookupOverlayHost finds an overlay IPv4 address for host.
func LookupOverlayHost(host, zone string, nodes []Node) (netip.Addr, bool) {
host = NormalizeDNSName(host)
if host == "" {
return netip.Addr{}, false
}
for _, node := range nodes {
if !node.IPv4.IsValid() || !node.IPv4.Is4() {
continue
}
for _, name := range OverlayNames(node.Hostname, zone) {
if host == name {
return node.IPv4, true
}
}
}
return netip.Addr{}, false
}
// LookupOverlayPTR finds a MagicDNS name for an overlay IPv4 address.
func LookupOverlayPTR(ip netip.Addr, zone string, nodes []Node) (string, bool) {
if !ip.IsValid() || !ip.Is4() {
return "", false
}
zone = NormalizeZone(zone)
for _, node := range nodes {
if node.IPv4 != ip {
continue
}
names := OverlayNames(node.Hostname, zone)
if len(names) == 0 {
continue
}
return names[len(names)-1] + ".", true
}
return "", false
}
// ParseNodeIPv4 parses a node IPv4 address or CIDR such as "10.144.0.1/24".
func ParseNodeIPv4(value string) (netip.Addr, error) {
value = strings.TrimSpace(value)
if value == "" {
return netip.Addr{}, fmt.Errorf("easytier: empty overlay IPv4 address")
}
if prefix, err := netip.ParsePrefix(value); err == nil {
return prefix.Addr().Unmap(), nil
}
ip, err := netip.ParseAddr(value)
if err != nil {
return netip.Addr{}, err
}
return ip.Unmap(), nil
}
// IPv4FromUint32 converts a big-endian IPv4 integer to an address.
func IPv4FromUint32(addr uint32) netip.Addr {
var bytes [4]byte
binary.BigEndian.PutUint32(bytes[:], addr)
return netip.AddrFrom4(bytes)
}
// ParsePTRIPv4 parses an IPv4 PTR name such as "2.0.144.10.in-addr.arpa.".
func ParsePTRIPv4(name string) (netip.Addr, bool) {
name = NormalizeDNSName(name)
const suffix = ".in-addr.arpa"
if !strings.HasSuffix(name, suffix) {
return netip.Addr{}, false
}
labels := strings.Split(strings.TrimSuffix(name, suffix), ".")
if len(labels) != 4 {
return netip.Addr{}, false
}
var bytes [4]byte
for i := 0; i < 4; i++ {
part, err := strconv.Atoi(labels[3-i])
if err != nil || part < 0 || part > 255 {
return netip.Addr{}, false
}
bytes[i] = byte(part)
}
return netip.AddrFrom4(bytes), true
}
+41
View File
@@ -0,0 +1,41 @@
package easytier
import (
"net/netip"
"testing"
)
func TestLookupOverlayHost(t *testing.T) {
ip := netip.MustParseAddr("10.144.0.2")
nodes := []Node{{Hostname: "peer", IPv4: ip}}
got, ok := LookupOverlayHost("peer.et.net.", "et.net.", nodes)
if !ok || got != ip {
t.Fatalf("got %v %v", got, ok)
}
if _, ok := LookupOverlayHost("missing", "et.net.", nodes); ok {
t.Fatal("expected miss")
}
}
func TestParsePTRAndNodeIPv4(t *testing.T) {
ip, ok := ParsePTRIPv4("2.0.144.10.in-addr.arpa.")
if !ok || ip.String() != "10.144.0.2" {
t.Fatalf("ptr: %v %v", ip, ok)
}
got, err := ParseNodeIPv4("10.144.0.1/24")
if err != nil || got.String() != "10.144.0.1" {
t.Fatalf("cidr: %v %v", got, err)
}
}
func TestIsMagicDNS(t *testing.T) {
if IsMagicDNS("peer", "et.net.") {
t.Fatal("single-label name should not be magic dns")
}
if !IsMagicDNS("peer.et.net", "") {
t.Fatal("expected magic dns")
}
if IsMagicDNS("example.com", "et.net.") {
t.Fatal("public name should not be magic dns")
}
}
+218
View File
@@ -0,0 +1,218 @@
package easytier
import (
"context"
"fmt"
"net"
"net/netip"
"strings"
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
"github.com/easytier/easytier/easytier-go/platform"
D "github.com/miekg/dns"
)
// Services wraps a mihomo dialer as EasyTier platform capabilities.
func Services(d C.Dialer) platform.Services {
return platform.Services{
Sockets: SocketFactory{Dialer: d},
DNS: DNSResolver{},
Environment: ConnectorEnvironment{Dialer: d},
}
}
// SocketFactory creates sockets through mihomo's dialer.
//
// EasyTier BindDevice/SocketMark/reuse options are ignored so hole punching
// can bind local UDP ports. Interface, routing-mark, and dialer-proxy stay on
// the mihomo dialer. Internal TCP reservations bind locally even when
// dialer-proxy is set. FakeTCP is not supported.
type SocketFactory struct {
Dialer C.Dialer
}
func (s SocketFactory) ConnectTCP(ctx context.Context, options platform.TCPConnectOptions) (net.Conn, error) {
if options.Purpose == platform.TCPConnectFake {
return nil, fmt.Errorf("easytier: FakeTCP is not supported")
}
if options.RemoteAddr == nil {
return nil, fmt.Errorf("easytier: TCP connect is missing a remote address")
}
network := tcpNetwork(options.Bind)
return s.Dialer.DialContext(ctx, network, options.RemoteAddr.String())
}
func (s SocketFactory) BindUDP(ctx context.Context, options platform.UDPBindOptions) (net.PacketConn, error) {
network, address := udpBind(options)
return s.Dialer.ListenPacket(ctx, network, address, netip.AddrPort{})
}
func (s SocketFactory) ListenTCP(ctx context.Context, options platform.TCPListenOptions) (net.Listener, error) {
if options.Bind.Context.NetNS != nil {
return nil, fmt.Errorf("easytier: network namespaces are not supported")
}
address := ":0"
if options.Bind.LocalAddr != nil {
address = options.Bind.LocalAddr.String()
}
network := tcpNetwork(options.Bind)
reuse := options.Bind.ReusePort || options.Bind.ReuseAddr != nil && *options.Bind.ReuseAddr
listenOpts := []dialer.Option{dialer.WithAddrReuse(reuse)}
if direct, ok := s.Dialer.(dialer.Dialer); ok {
return dialer.Listen(ctx, network, address, append(listenOpts, dialer.WithOption(direct.Opt))...)
}
if externalTCPListen(options.Purpose) {
return nil, fmt.Errorf("easytier: TCP listeners are unavailable through a proxy or custom dialer")
}
// ProxyNAT, port leases, and hole-punch reservations must bind on the host
// even when peer traffic uses dialer-proxy.
return dialer.Listen(ctx, network, address, listenOpts...)
}
func externalTCPListen(purpose platform.TCPListenPurpose) bool {
switch purpose {
case platform.TCPListenDirect, platform.TCPListenManual:
return true
default:
return false
}
}
func tcpNetwork(options platform.TCPBindOptions) string {
if options.LocalAddr != nil && options.LocalAddr.IP.To4() != nil {
return "tcp4"
}
if options.OnlyV6 || options.Context.IPVersion == platform.IPVersionV6 {
return "tcp6"
}
if options.Context.IPVersion == platform.IPVersionV4 {
return "tcp4"
}
return "tcp"
}
func udpBind(options platform.UDPBindOptions) (network, address string) {
if options.LocalAddr != nil {
address = options.LocalAddr.String()
if options.LocalAddr.IP.To4() != nil {
return "udp4", address
}
if len(options.LocalAddr.IP) != 0 {
if options.OnlyV6 || options.LocalAddr.IP.To16() != nil && options.LocalAddr.IP.To4() == nil {
return "udp6", address
}
return "udp", address
}
if options.OnlyV6 || options.Context.IPVersion == platform.IPVersionV6 {
return "udp6", address
}
if options.Context.IPVersion == platform.IPVersionV4 {
return "udp4", address
}
return "udp", address
}
switch {
case options.OnlyV6 || options.Context.IPVersion == platform.IPVersionV6:
return "udp6", "[::]:0"
case options.Context.IPVersion == platform.IPVersionV4:
return "udp4", "0.0.0.0:0"
default:
return "udp", ":0"
}
}
// DNSResolver resolves EasyTier control-plane names through the proxy-server resolver.
type DNSResolver struct{}
func (DNSResolver) LookupIP(ctx context.Context, query platform.DNSQuery) ([]netip.Addr, error) {
if address, err := netip.ParseAddr(query.Host); err == nil {
return []netip.Addr{address.Unmap()}, nil
}
switch query.IPVersion {
case 4:
return resolver.LookupIPv4WithResolver(ctx, query.Host, resolver.ProxyServerHostResolver)
case 6:
return resolver.LookupIPv6WithResolver(ctx, query.Host, resolver.ProxyServerHostResolver)
default:
return resolver.LookupIPWithResolver(ctx, query.Host, resolver.ProxyServerHostResolver)
}
}
func exchangeDNS(ctx context.Context, host string, qtype uint16) (*D.Msg, error) {
r := resolver.ProxyServerHostResolver
if r == nil || !r.Invalid() {
r = resolver.SystemResolver
}
if r == nil {
return nil, fmt.Errorf("easytier: DNS resolver is unavailable")
}
request := new(D.Msg)
request.SetQuestion(D.Fqdn(host), qtype)
reply, err := r.ExchangeContext(ctx, request)
if err != nil {
return nil, err
}
if reply == nil {
return nil, fmt.Errorf("easytier: empty DNS response for %q", host)
}
if reply.Rcode != D.RcodeSuccess {
return nil, fmt.Errorf("easytier: DNS query for %q returned %s", host, D.RcodeToString[reply.Rcode])
}
return reply, nil
}
func (DNSResolver) LookupTXT(ctx context.Context, query platform.DNSQuery) (string, error) {
reply, err := exchangeDNS(ctx, query.Host, D.TypeTXT)
if err != nil {
return "", err
}
for _, answer := range reply.Answer {
if txt, ok := answer.(*D.TXT); ok {
return strings.Join(txt.Txt, ""), nil
}
}
return "", fmt.Errorf("easytier: DNS TXT query for %q returned no records", query.Host)
}
func (DNSResolver) LookupSRV(ctx context.Context, query platform.DNSQuery) ([]*net.SRV, error) {
reply, err := exchangeDNS(ctx, query.Host, D.TypeSRV)
if err != nil {
return nil, err
}
var records []*net.SRV
for _, answer := range reply.Answer {
if srv, ok := answer.(*D.SRV); ok {
records = append(records, &net.SRV{Target: srv.Target, Port: srv.Port, Priority: srv.Priority, Weight: srv.Weight})
}
}
if len(records) == 0 {
return nil, fmt.Errorf("easytier: DNS SRV query for %q returned no records", query.Host)
}
return records, nil
}
// ConnectorEnvironment reports the local address used toward a remote UDP peer.
type ConnectorEnvironment struct {
Dialer C.Dialer
}
func (e ConnectorEnvironment) LocalAddrForRemote(ctx context.Context, remote *net.UDPAddr, _ platform.SocketContext) (net.Addr, error) {
if remote == nil {
return nil, fmt.Errorf("easytier: missing remote address")
}
network := "udp"
if remote.IP.To4() != nil {
network = "udp4"
} else if remote.IP.To16() != nil {
network = "udp6"
}
conn, err := e.Dialer.DialContext(ctx, network, remote.String())
if err != nil {
return nil, err
}
defer conn.Close()
return conn.LocalAddr(), nil
}
+98
View File
@@ -0,0 +1,98 @@
package easytier
import (
"context"
"errors"
"net"
"net/netip"
"testing"
"time"
"github.com/metacubex/mihomo/component/resolver"
"github.com/easytier/easytier/easytier-go/platform"
D "github.com/miekg/dns"
)
type testDNSResolver struct {
resolver.Resolver
exchange func(context.Context, *D.Msg) (*D.Msg, error)
}
func (*testDNSResolver) Invalid() bool { return true }
func (r *testDNSResolver) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error) {
return r.exchange(ctx, m)
}
func TestDNSRecordsUseMihomoResolver(t *testing.T) {
oldProxy, oldDefault := resolver.ProxyServerHostResolver, net.DefaultResolver
t.Cleanup(func() {
resolver.ProxyServerHostResolver = oldProxy
net.DefaultResolver = oldDefault
})
net.DefaultResolver = &net.Resolver{
PreferGo: true,
Dial: func(context.Context, string, string) (net.Conn, error) {
t.Error("net.DefaultResolver was used")
return nil, errors.New("forbidden resolver")
},
}
resolver.ProxyServerHostResolver = &testDNSResolver{exchange: func(_ context.Context, m *D.Msg) (*D.Msg, error) {
reply := new(D.Msg).SetReply(m)
switch m.Question[0].Qtype {
case D.TypeTXT:
reply.Answer = []D.RR{&D.TXT{Txt: []string{"ok"}}}
case D.TypeSRV:
reply.Answer = []D.RR{&D.SRV{Target: "peer.example.", Port: 11010}}
}
return reply, nil
}}
txt, err := (DNSResolver{}).LookupTXT(context.Background(), platform.DNSQuery{Host: "example"})
if err != nil || txt != "ok" {
t.Fatalf("TXT: %q %v", txt, err)
}
srv, err := (DNSResolver{}).LookupSRV(context.Background(), platform.DNSQuery{Host: "example"})
if err != nil || len(srv) != 1 || srv[0].Target != "peer.example." || srv[0].Port != 11010 {
t.Fatalf("SRV: %v %v", srv, err)
}
}
func TestUDPBindPreservesWildcardPort(t *testing.T) {
_, address := udpBind(platform.UDPBindOptions{LocalAddr: &net.UDPAddr{Port: 45678}})
_, port, err := net.SplitHostPort(address)
if err != nil || port != "45678" {
t.Fatalf("%s: %v", address, err)
}
}
type forbiddenDialer struct{}
func (forbiddenDialer) DialContext(context.Context, string, string) (net.Conn, error) {
panic("unexpected proxy session")
}
func (forbiddenDialer) ListenPacket(context.Context, string, string, netip.AddrPort) (net.PacketConn, error) {
panic("unexpected proxy socket")
}
func TestListenTCPInternalAllowedThroughProxyDialer(t *testing.T) {
factory := SocketFactory{Dialer: forbiddenDialer{}}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
listener, err := factory.ListenTCP(ctx, platform.TCPListenOptions{
Bind: platform.TCPBindOptions{LocalAddr: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}},
Purpose: platform.TCPListenProxyNAT,
})
if err != nil {
t.Fatal(err)
}
defer listener.Close()
if _, err := factory.ListenTCP(ctx, platform.TCPListenOptions{
Bind: platform.TCPBindOptions{LocalAddr: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}},
Purpose: platform.TCPListenDirect,
}); err == nil {
t.Fatal("external listener through proxy must fail")
}
}
+377
View File
@@ -0,0 +1,377 @@
package easytier
import (
"encoding/json"
"fmt"
"net/url"
"strings"
)
const defaultListener = "tcp://0.0.0.0:11010"
type requiredFlag struct {
key string
value string
}
// Config is the structured EasyTier outbound configuration rendered to TOML.
type Config struct {
NetworkName string
NetworkSecret string
Hostname string
IPv4 string
DHCP bool
Peers []string
Listeners []string
NoListener *bool
MappedListeners []string
ExitNodes []string
ProxyNetworks []string
InstanceName string
AcceptDNS *bool
EnableExitNode *bool
EnableEncryption *bool
EncryptionAlgorithm string
PrivateMode *bool
LatencyFirst *bool
DisableP2P *bool
EnableKCPProxy *bool
DisableKCPInput *bool
EnableQUICProxy *bool
DisableQUICInput *bool
MTU int
TLDDNSZone string
SecureMode *bool
LocalPrivateKey string
LocalPublicKey string
}
// Peer is one EasyTier [[peer]] table after URI query parameters are extracted.
type Peer struct {
URI string
PeerPublicKey string
}
func (c Config) listeners() []string {
if c.NoListener != nil && *c.NoListener {
return []string{}
}
if len(c.Listeners) > 0 {
return c.Listeners
}
if c.NoListener != nil && !*c.NoListener {
return []string{defaultListener}
}
return []string{}
}
// ValidateStructured checks structured fields before rendering TOML.
func (c Config) ValidateStructured() error {
if strings.TrimSpace(c.NetworkName) == "" {
return fmt.Errorf("easytier: network-name is required")
}
if c.NoListener != nil && *c.NoListener && len(c.Listeners) > 0 {
return fmt.Errorf("easytier: no-listener cannot be combined with listeners")
}
if len(c.Peers) == 0 && len(c.listeners()) == 0 {
return fmt.Errorf("easytier: peers is required when listeners are empty; implicit public.easytier.top is disabled")
}
if _, err := c.parsedPeers(); err != nil {
return err
}
if c.LocalPublicKey != "" && c.LocalPrivateKey == "" {
return fmt.Errorf("easytier: local-public-key requires local-private-key")
}
if c.SecureMode != nil && !*c.SecureMode && c.hasSecureModeMaterial() {
return fmt.Errorf("easytier: local keys and peer-public-key require secure-mode")
}
return nil
}
func (c Config) parsedPeers() ([]Peer, error) {
out := make([]Peer, 0, len(c.Peers))
for i, raw := range c.Peers {
peer, err := parsePeerURI(raw)
if err != nil {
return nil, fmt.Errorf("easytier: peers[%d]: %w", i, err)
}
out = append(out, peer)
}
return out, nil
}
func parsePeerURI(raw string) (Peer, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return Peer{}, fmt.Errorf("uri is required")
}
u, err := url.Parse(raw)
if err != nil {
return Peer{}, fmt.Errorf("invalid uri: %w", err)
}
if u.RawQuery == "" {
return Peer{URI: raw}, nil
}
kept := make([]string, 0)
key := ""
stripped := false
for _, pair := range strings.Split(u.RawQuery, "&") {
if pair == "" {
continue
}
name, value, _ := strings.Cut(pair, "=")
decodedName, err := url.PathUnescape(name)
if err != nil {
return Peer{}, fmt.Errorf("invalid uri query: %w", err)
}
switch decodedName {
case "peer-public-key", "peer_public_key":
decodedValue, err := url.PathUnescape(value)
if err != nil {
return Peer{}, fmt.Errorf("invalid peer-public-key: %w", err)
}
key = decodedValue
stripped = true
default:
kept = append(kept, pair)
}
}
if !stripped {
return Peer{URI: raw}, nil
}
u.RawQuery = strings.Join(kept, "&")
return Peer{URI: u.String(), PeerPublicKey: key}, nil
}
func (c Config) hasSecureModeMaterial() bool {
if c.LocalPrivateKey != "" || c.LocalPublicKey != "" {
return true
}
peers, err := c.parsedPeers()
if err != nil {
return false
}
for _, peer := range peers {
if peer.PeerPublicKey != "" {
return true
}
}
return false
}
func (c Config) secureModeEnabled() bool {
if c.SecureMode != nil {
return *c.SecureMode
}
return c.hasSecureModeMaterial()
}
// RenderTOML converts structured fields to EasyTier TOML.
func (c Config) RenderTOML() (string, error) {
if err := c.ValidateStructured(); err != nil {
return "", err
}
var encoded strings.Builder
if c.InstanceName != "" {
writeTOMLStringField(&encoded, "instance_name", c.InstanceName)
}
if c.Hostname != "" {
writeTOMLStringField(&encoded, "hostname", c.Hostname)
}
if strings.TrimSpace(c.IPv4) != "" {
writeTOMLStringField(&encoded, "ipv4", c.IPv4)
}
if c.DHCP || strings.TrimSpace(c.IPv4) == "" {
writeTOMLBoolField(&encoded, "dhcp", true)
}
writeTOMLStringArrayField(&encoded, "listeners", c.listeners())
if len(c.MappedListeners) > 0 {
writeTOMLStringArrayField(&encoded, "mapped_listeners", c.MappedListeners)
}
if len(c.ExitNodes) > 0 {
writeTOMLStringArrayField(&encoded, "exit_nodes", c.ExitNodes)
}
encoded.WriteByte('\n')
encoded.WriteString("[network_identity]\n")
writeTOMLStringField(&encoded, "network_name", c.NetworkName)
writeTOMLStringField(&encoded, "network_secret", c.NetworkSecret)
peers, err := c.parsedPeers()
if err != nil {
return "", err
}
if c.secureModeEnabled() {
encoded.WriteString("\n[secure_mode]\n")
writeTOMLBoolField(&encoded, "enabled", true)
if c.LocalPrivateKey != "" {
writeTOMLStringField(&encoded, "local_private_key", c.LocalPrivateKey)
}
if c.LocalPublicKey != "" {
writeTOMLStringField(&encoded, "local_public_key", c.LocalPublicKey)
}
}
for _, peer := range peers {
encoded.WriteString("\n[[peer]]\n")
writeTOMLStringField(&encoded, "uri", peer.URI)
if peer.PeerPublicKey != "" {
writeTOMLStringField(&encoded, "peer_public_key", peer.PeerPublicKey)
}
}
for _, network := range c.ProxyNetworks {
encoded.WriteString("\n[[proxy_network]]\n")
writeTOMLStringField(&encoded, "cidr", network)
}
encoded.WriteString("\n[flags]\n")
writeTOMLBoolField(&encoded, "no_tun", true)
writeTOMLBoolField(&encoded, "bind_device", false)
writeOptionalBoolField(&encoded, "accept_dns", c.AcceptDNS)
writeOptionalBoolField(&encoded, "enable_exit_node", c.EnableExitNode)
writeOptionalBoolField(&encoded, "enable_encryption", c.EnableEncryption)
if c.EncryptionAlgorithm != "" {
writeTOMLStringField(&encoded, "encryption_algorithm", c.EncryptionAlgorithm)
}
writeOptionalBoolField(&encoded, "private_mode", c.PrivateMode)
writeOptionalBoolField(&encoded, "latency_first", c.LatencyFirst)
writeOptionalBoolField(&encoded, "disable_p2p", c.DisableP2P)
writeOptionalBoolField(&encoded, "enable_kcp_proxy", c.EnableKCPProxy)
writeOptionalBoolField(&encoded, "disable_kcp_input", c.DisableKCPInput)
writeOptionalBoolField(&encoded, "enable_quic_proxy", c.EnableQUICProxy)
writeOptionalBoolField(&encoded, "disable_quic_input", c.DisableQUICInput)
if c.MTU > 0 {
fmt.Fprintf(&encoded, "mtu = %d\n", c.MTU)
}
if c.TLDDNSZone != "" {
writeTOMLStringField(&encoded, "tld_dns_zone", c.TLDDNSZone)
}
return encoded.String(), nil
}
func requiredFlags() []requiredFlag {
return []requiredFlag{
{key: "no_tun", value: "true"},
{key: "bind_device", value: "false"},
}
}
// ApplyRequiredFlags forces no_tun and bind_device=false.
func ApplyRequiredFlags(configTOML string) string {
flags := requiredFlags()
required := make(map[string]string, len(flags))
for _, flag := range flags {
required[flag.key] = flag.value
}
lines := strings.Split(configTOML, "\n")
var out []string
section := ""
seen := map[string]bool{}
wroteFlags := false
flushFlags := func() {
if section != "flags" {
return
}
for _, flag := range flags {
if !seen[flag.key] {
out = append(out, flag.key+" = "+flag.value)
}
}
wroteFlags = true
seen = map[string]bool{}
}
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if isTOMLSection(trimmed) {
flushFlags()
section = sectionName(trimmed)
out = append(out, line)
continue
}
if section == "flags" {
key := flagKey(trimmed)
if value, ok := required[key]; ok {
out = append(out, key+" = "+value)
seen[key] = true
continue
}
}
out = append(out, line)
}
flushFlags()
if !wroteFlags {
if len(out) > 0 && strings.TrimSpace(out[len(out)-1]) != "" {
out = append(out, "")
}
out = append(out, "[flags]")
for _, flag := range flags {
out = append(out, flag.key+" = "+flag.value)
}
}
return strings.TrimSpace(strings.Join(out, "\n")) + "\n"
}
func isTOMLSection(trimmed string) bool {
if !strings.HasPrefix(trimmed, "[") {
return false
}
end := strings.IndexByte(trimmed, ']')
if end < 0 {
return false
}
rest := strings.TrimSpace(trimmed[end+1:])
return rest == "" || strings.HasPrefix(rest, "#")
}
func sectionName(trimmed string) string {
end := strings.IndexByte(trimmed, ']')
if end < 0 {
return ""
}
name := strings.TrimSpace(trimmed[:end+1])
name = strings.TrimPrefix(name, "[[")
name = strings.TrimPrefix(name, "[")
name = strings.TrimSuffix(name, "]]")
name = strings.TrimSuffix(name, "]")
return strings.Trim(name, `"'`)
}
func flagKey(trimmed string) string {
if idx := strings.IndexByte(trimmed, '='); idx >= 0 {
return strings.Trim(strings.TrimSpace(trimmed[:idx]), `"'`)
}
return ""
}
func writeOptionalBoolField(encoded *strings.Builder, name string, value *bool) {
if value != nil {
writeTOMLBoolField(encoded, name, *value)
}
}
func writeTOMLStringField(encoded *strings.Builder, name string, value string) {
fmt.Fprintf(encoded, "%s = %s\n", name, quoteTOMLString(value))
}
func writeTOMLBoolField(encoded *strings.Builder, name string, value bool) {
fmt.Fprintf(encoded, "%s = %t\n", name, value)
}
func writeTOMLStringArrayField(encoded *strings.Builder, name string, values []string) {
fmt.Fprintf(encoded, "%s = [", name)
for index, value := range values {
if index != 0 {
encoded.WriteString(", ")
}
encoded.WriteString(quoteTOMLString(value))
}
encoded.WriteString("]\n")
}
func quoteTOMLString(value string) string {
encoded, err := json.Marshal(value)
if err != nil {
panic("encoding a validated Go string as JSON cannot fail")
}
return string(encoded)
}
+301
View File
@@ -0,0 +1,301 @@
package easytier
import (
"strings"
"testing"
)
func boolPtr(v bool) *bool { return &v }
func peers(uris ...string) []string { return uris }
func TestRenderTOMLDefaultNoListenerRequiresPeers(t *testing.T) {
_, err := Config{NetworkName: "example"}.RenderTOML()
if err == nil {
t.Fatal("expected missing peers to fail")
}
}
func TestRenderTOMLNoListenerFalseDefaultListener(t *testing.T) {
toml, err := Config{
NetworkName: "example",
NoListener: boolPtr(false),
}.RenderTOML()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(toml, `listeners = ["tcp://0.0.0.0:11010"]`) {
t.Fatalf("missing default listener:\n%s", toml)
}
if !strings.Contains(toml, "no_tun = true") || !strings.Contains(toml, "bind_device = false") {
t.Fatalf("missing required flags:\n%s", toml)
}
}
func TestRenderTOMLExplicitEmptyListenersWithPeers(t *testing.T) {
toml, err := Config{
NetworkName: "example",
NetworkSecret: "secret",
Peers: peers("tcp://192.0.2.10:11010"),
Hostname: "node-a",
IPv4: "10.144.0.1/24",
}.RenderTOML()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(toml, "listeners = []") {
t.Fatalf("expected empty listeners:\n%s", toml)
}
if !strings.Contains(toml, "[[peer]]") || !strings.Contains(toml, `uri = "tcp://192.0.2.10:11010"`) {
t.Fatalf("missing peer:\n%s", toml)
}
}
func TestApplyRequiredFlagsInjectsNoTun(t *testing.T) {
got := ApplyRequiredFlags("[network_identity]\nnetwork_name = \"n\"\n")
if !strings.Contains(got, "[flags]") || !strings.Contains(got, "no_tun = true") {
t.Fatalf("did not inject no_tun:\n%s", got)
}
if !strings.Contains(got, "bind_device = false") {
t.Fatalf("missing bind_device:\n%s", got)
}
}
func TestApplyRequiredFlagsReplacesNoTun(t *testing.T) {
got := ApplyRequiredFlags("[flags]\nno_tun = false\nmtu = 1200\n")
if !strings.Contains(got, "no_tun = true") {
t.Fatalf("did not replace no_tun:\n%s", got)
}
if !strings.Contains(got, "bind_device = false") {
t.Fatalf("missing bind_device:\n%s", got)
}
if !strings.Contains(got, "mtu = 1200") {
t.Fatalf("lost existing flag:\n%s", got)
}
}
func TestNoListenerConflict(t *testing.T) {
err := Config{
NetworkName: "example",
NoListener: boolPtr(true),
Listeners: []string{"tcp://0.0.0.0:11010"},
}.ValidateStructured()
if err == nil {
t.Fatal("expected conflict")
}
}
func TestRenderTOMLManualIPv4WithoutPrefix(t *testing.T) {
toml, err := Config{
NetworkName: "example",
NetworkSecret: "example",
IPv4: "10.144.0.10",
Peers: peers("tcp://192.0.2.10:11010"),
}.RenderTOML()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(toml, `ipv4 = "10.144.0.10"`) {
t.Fatalf("missing manual ipv4:\n%s", toml)
}
if !strings.Contains(toml, `uri = "tcp://192.0.2.10:11010"`) {
t.Fatalf("missing peer:\n%s", toml)
}
}
func TestRenderTOMLMultiplePeers(t *testing.T) {
toml, err := Config{
NetworkName: "example",
NetworkSecret: "secret",
Peers: peers(
"tcp://192.0.2.10:11010",
"udp://192.0.2.11:11010",
),
}.RenderTOML()
if err != nil {
t.Fatal(err)
}
if strings.Count(toml, "[[peer]]") != 2 {
t.Fatalf("want 2 peer tables:\n%s", toml)
}
if !strings.Contains(toml, `uri = "tcp://192.0.2.10:11010"`) || !strings.Contains(toml, `uri = "udp://192.0.2.11:11010"`) {
t.Fatalf("missing peer uris:\n%s", toml)
}
}
func TestApplyRequiredFlagsSectionComment(t *testing.T) {
got := ApplyRequiredFlags("[flags] # tun flags\nno_tun = false\nmtu = 1200\n")
if strings.Count(got, "[flags]") != 1 {
t.Fatalf("duplicate flags table:\n%s", got)
}
if !strings.Contains(got, "no_tun = true") || !strings.Contains(got, "mtu = 1200") {
t.Fatalf("did not rewrite flags:\n%s", got)
}
}
func TestApplyRequiredFlagsQuotedKey(t *testing.T) {
got := ApplyRequiredFlags("[flags]\n\"no_tun\" = false\n")
if strings.Count(got, "no_tun") != 1 {
t.Fatalf("duplicate no_tun:\n%s", got)
}
if !strings.Contains(got, "no_tun = true") {
t.Fatalf("did not replace quoted no_tun:\n%s", got)
}
}
func TestRenderTOMLDefaultsDHCPWhenIPv4Omitted(t *testing.T) {
toml, err := Config{
NetworkName: "example",
NetworkSecret: "secret",
Peers: peers("tcp://192.0.2.10:11010"),
}.RenderTOML()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(toml, "dhcp = true") {
t.Fatalf("expected default dhcp:\n%s", toml)
}
if strings.Contains(toml, "ipv4") {
t.Fatalf("did not expect static ipv4:\n%s", toml)
}
}
func TestRenderTOMLStaticIPv4OmitsDHCP(t *testing.T) {
toml, err := Config{
NetworkName: "example",
NetworkSecret: "secret",
IPv4: "10.144.0.10",
Peers: peers("tcp://192.0.2.10:11010"),
}.RenderTOML()
if err != nil {
t.Fatal(err)
}
if strings.Contains(toml, "dhcp = true") {
t.Fatalf("did not expect dhcp with static ipv4:\n%s", toml)
}
}
func TestRenderTOMLWritesTLDDNSZone(t *testing.T) {
toml, err := Config{
NetworkName: "example",
NetworkSecret: "secret",
Peers: peers("tcp://192.0.2.10:11010"),
TLDDNSZone: "overlay.example.",
}.RenderTOML()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(toml, `tld_dns_zone = "overlay.example."`) {
t.Fatalf("missing tld_dns_zone:\n%s", toml)
}
}
func TestRenderTOMLSecureMode(t *testing.T) {
toml, err := Config{
NetworkName: "example",
NetworkSecret: "secret",
Peers: peers("tcp://192.0.2.10:11010"),
SecureMode: boolPtr(true),
LocalPrivateKey: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
LocalPublicKey: "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=",
}.RenderTOML()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(toml, "[secure_mode]") || !strings.Contains(toml, "enabled = true") {
t.Fatalf("missing secure_mode:\n%s", toml)
}
if !strings.Contains(toml, `local_private_key = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="`) {
t.Fatalf("missing local_private_key:\n%s", toml)
}
if !strings.Contains(toml, `local_public_key = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB="`) {
t.Fatalf("missing local_public_key:\n%s", toml)
}
}
func TestRenderTOMLPeerPublicKeyEnablesSecureMode(t *testing.T) {
toml, err := Config{
NetworkName: "example",
NetworkSecret: "secret",
Peers: peers("tcp://relay.example.com:11010?peer-public-key=CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC="),
}.RenderTOML()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(toml, "[secure_mode]") || !strings.Contains(toml, "enabled = true") {
t.Fatalf("pinning should enable secure_mode:\n%s", toml)
}
if !strings.Contains(toml, `uri = "tcp://relay.example.com:11010"`) {
t.Fatalf("missing peer uri:\n%s", toml)
}
if strings.Contains(toml, "peer-public-key=") {
t.Fatalf("peer-public-key should be stripped from uri:\n%s", toml)
}
if !strings.Contains(toml, `peer_public_key = "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC="`) {
t.Fatalf("missing peer_public_key:\n%s", toml)
}
}
func TestRenderTOMLSecureModeFalseRejectsPinnedPeer(t *testing.T) {
err := Config{
NetworkName: "example",
NetworkSecret: "secret",
SecureMode: boolPtr(false),
Peers: peers("tcp://relay.example.com:11010?peer-public-key=CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC="),
}.ValidateStructured()
if err == nil {
t.Fatal("expected pinned peer without secure-mode to fail")
}
}
func TestRenderTOMLLocalPublicKeyRequiresPrivateKey(t *testing.T) {
err := Config{
NetworkName: "example",
NetworkSecret: "secret",
Peers: peers("tcp://192.0.2.10:11010"),
LocalPublicKey: "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=",
}.ValidateStructured()
if err == nil {
t.Fatal("expected local-public-key without private key to fail")
}
}
func TestRenderTOMLEmptyPeerURI(t *testing.T) {
err := Config{
NetworkName: "example",
NetworkSecret: "secret",
Peers: []string{""},
}.ValidateStructured()
if err == nil {
t.Fatal("expected empty peer uri to fail")
}
}
func TestParsePeerURIQuery(t *testing.T) {
peer, err := parsePeerURI(" tcp://relay.example.com:11010?foo=1&peer-public-key=CC%2BCC/CC=&bar=2 ")
if err != nil {
t.Fatal(err)
}
if peer.URI != "tcp://relay.example.com:11010?foo=1&bar=2" {
t.Fatalf("uri: %q", peer.URI)
}
if peer.PeerPublicKey != "CC+CC/CC=" {
t.Fatalf("key: %q", peer.PeerPublicKey)
}
peer, err = parsePeerURI("tcp://relay.example.com:11010?peer_public_key=CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC=")
if err != nil {
t.Fatal(err)
}
if peer.URI != "tcp://relay.example.com:11010" || peer.PeerPublicKey == "" {
t.Fatalf("snake_case: %+v", peer)
}
peer, err = parsePeerURI("tcp://192.0.2.10:11010?foo=1")
if err != nil {
t.Fatal(err)
}
if peer.URI != "tcp://192.0.2.10:11010?foo=1" || peer.PeerPublicKey != "" {
t.Fatalf("other query: %+v", peer)
}
}
+11
View File
@@ -88,7 +88,18 @@ func (p *Pool) IPNet() netip.Prefix {
// CloneFrom clone cache from old pool
func (p *Pool) CloneFrom(o *Pool) {
p.mux.Lock()
defer p.mux.Unlock()
o.mux.Lock()
defer o.mux.Unlock()
o.store.CloneTo(p.store)
// the allocation state only matches the cloned entries if both pools cover the same range
if o.first == p.first && o.last == p.last {
p.offset, p.cycle = o.offset, o.cycle
}
}
func (p *Pool) get(host string) netip.Addr {
+27
View File
@@ -212,6 +212,33 @@ func TestPool_Clone(t *testing.T) {
assert.True(t, lastExist)
}
func TestPool_CloneKeepsAllocationState(t *testing.T) {
ipnet := netip.MustParsePrefix("192.168.0.1/24")
pool, _ := New(Options{
IPNet: ipnet,
Size: 10,
})
foo := pool.Lookup("foo.com")
bar := pool.Lookup("bar.com")
newPool, _ := New(Options{
IPNet: ipnet,
Size: 10,
})
newPool.CloneFrom(pool)
// a fresh allocation must not overwrite the retained mappings
baz := newPool.Lookup("baz.com")
assert.NotEqual(t, foo, baz)
assert.NotEqual(t, bar, baz)
assert.Equal(t, foo, newPool.Lookup("foo.com"))
assert.Equal(t, bar, newPool.Lookup("bar.com"))
host, ok := newPool.LookBack(foo)
assert.True(t, ok)
assert.Equal(t, "foo.com", host)
}
func TestPool_Error(t *testing.T) {
ipnet := netip.MustParsePrefix("192.168.0.1/31")
_, err := New(Options{
+8 -8
View File
@@ -10,11 +10,11 @@ import (
)
func TestSkipper_BlackList(t *testing.T) {
tree := trie.New[struct{}]()
assert.NoError(t, tree.Insert("example.com", struct{}{}))
assert.False(t, tree.IsEmpty())
var builder trie.DomainSetBuilder
assert.NoError(t, builder.Insert("example.com"))
assert.False(t, builder.IsEmpty())
skipper := &Skipper{
Host: []C.DomainMatcher{tree.NewDomainSet()},
Host: []C.DomainMatcher{builder.Build()},
}
assert.True(t, skipper.ShouldSkipped("example.com"))
assert.False(t, skipper.ShouldSkipped("foo.com"))
@@ -22,11 +22,11 @@ func TestSkipper_BlackList(t *testing.T) {
}
func TestSkipper_WhiteList(t *testing.T) {
tree := trie.New[struct{}]()
assert.NoError(t, tree.Insert("example.com", struct{}{}))
assert.False(t, tree.IsEmpty())
var builder trie.DomainSetBuilder
assert.NoError(t, builder.Insert("example.com"))
assert.False(t, builder.IsEmpty())
skipper := &Skipper{
Host: []C.DomainMatcher{tree.NewDomainSet()},
Host: []C.DomainMatcher{builder.Build()},
Mode: C.FilterWhiteList,
}
assert.False(t, skipper.ShouldSkipped("example.com"))
+15 -1
View File
@@ -3,6 +3,7 @@ package generator
import (
"encoding/base64"
"fmt"
"strconv"
"github.com/metacubex/mihomo/component/ech"
"github.com/metacubex/mihomo/transport/sudoku"
@@ -13,7 +14,7 @@ import (
func Main(args []string) {
if len(args) < 1 {
panic("Using: generate uuid/reality-keypair/wg-keypair/ech-keypair/vless-mlkem768/vless-x25519/sudoku-keypair")
panic("Using: generate uuid/ss-password/reality-keypair/wg-keypair/ech-keypair/vless-mlkem768/vless-x25519/sudoku-keypair")
}
switch args[0] {
case "uuid":
@@ -22,6 +23,19 @@ func Main(args []string) {
panic(err)
}
fmt.Println(newUUID.String())
case "ss-password":
if len(args) != 2 {
panic("Using: generate ss-password <128|256|512>")
}
bits, err := strconv.Atoi(args[1])
if err != nil || (bits != 128 && bits != 256 && bits != 512) {
panic("Using: generate ss-password <128|256|512>")
}
password, err := GenShadowsocksPassword(bits)
if err != nil {
panic(err)
}
fmt.Println(password)
case "reality-keypair":
privateKey, err := GenX25519PrivateKey()
if err != nil {
+18
View File
@@ -0,0 +1,18 @@
package generator
import (
"crypto/rand"
"encoding/base64"
"errors"
)
func GenShadowsocksPassword(bits int) (string, error) {
if bits%8 != 0 {
return "", errors.New("bits must be multiple of 8")
}
password := make([]byte, bits/8)
if _, err := rand.Read(password); err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(password), nil
}
+76 -63
View File
@@ -1,6 +1,7 @@
package memconservative
import (
"bufio"
"errors"
"fmt"
"io"
@@ -19,75 +20,87 @@ var (
)
func emitBytes(f io.ReadSeeker, code string) ([]byte, error) {
count := 1
isInner := false
tempContainer := make([]byte, 0, 5)
var result []byte
var advancedN uint64 = 1
var geoDataVarintLength, codeVarintLength, varintLenByteLen uint64 = 0, 0, 0
Loop:
reader := bufio.NewReaderSize(f, 16*1024)
readError := func(err error) error {
switch err {
case io.EOF:
return errCodeNotFound
case io.ErrUnexpectedEOF:
return errFailedToReadExpectedLenBytes
default:
return errFailedToReadBytes
}
}
var lengthBytes []byte
readLength := func() (uint64, error) {
lengthBytes = lengthBytes[:0]
for {
b, err := reader.ReadByte()
if err != nil {
return 0, readError(err)
}
lengthBytes = append(lengthBytes, b)
if b < 128 {
n, size := protowire.ConsumeVarint(lengthBytes)
if size < 0 {
return 0, errInvalidGeodataVarintLength
}
return n, nil
}
}
}
for {
container := make([]byte, advancedN)
bytesRead, err := f.Read(container)
if err == io.EOF {
return nil, errCodeNotFound
b, err := reader.ReadByte()
if err != nil {
return nil, readError(err)
}
if b != 10 {
return nil, errInvalidGeodataFile
}
length, err := readLength()
if err != nil {
return nil, err
}
b, err = reader.ReadByte()
if err != nil {
return nil, readError(err)
}
if b != 10 {
return nil, errInvalidGeodataFile
}
codeLength, err := readLength()
if err != nil {
return nil, err
}
name := make([]byte, codeLength)
if _, err := io.ReadFull(reader, name); err != nil {
return nil, readError(err)
}
prefixLength := 1 + uint64(len(lengthBytes)) + codeLength
if strings.EqualFold(string(name), code) {
result := make([]byte, length)
n := copy(result, []byte{10})
n += copy(result[n:], lengthBytes)
n += copy(result[n:], name)
if _, err := io.ReadFull(reader, result[n:]); err != nil {
if err == io.EOF {
return nil, errFailedToReadExpectedLenBytes
}
return nil, readError(err)
}
return result, nil
}
offset := int64(length) - int64(prefixLength)
if offset >= 0 && offset <= int64(reader.Buffered()) {
_, err = reader.Discard(int(offset))
} else {
_, err = f.Seek(offset-int64(reader.Buffered()), io.SeekCurrent)
reader.Reset(f)
}
if err != nil {
return nil, errFailedToReadBytes
}
if bytesRead != len(container) {
return nil, errFailedToReadExpectedLenBytes
}
switch count {
case 1, 3: // data type ((field_number << 3) | wire_type)
if container[0] != 10 { // byte `0A` equals to `10` in decimal
return nil, errInvalidGeodataFile
}
advancedN = 1
count++
case 2, 4: // data length
tempContainer = append(tempContainer, container...)
if container[0] > 127 { // max one-byte-length byte `7F`(0FFF FFFF) equals to `127` in decimal
advancedN = 1
goto Loop
}
lenVarint, n := protowire.ConsumeVarint(tempContainer)
if n < 0 {
return nil, errInvalidGeodataVarintLength
}
tempContainer = nil
if !isInner {
isInner = true
geoDataVarintLength = lenVarint
advancedN = 1
} else {
isInner = false
codeVarintLength = lenVarint
varintLenByteLen = uint64(n)
advancedN = codeVarintLength
}
count++
case 5: // data value
if strings.EqualFold(string(container), code) {
count++
offset := -(1 + int64(varintLenByteLen) + int64(codeVarintLength))
_, _ = f.Seek(offset, 1) // back to the start of GeoIP or GeoSite varint
advancedN = geoDataVarintLength // the number of bytes to be read in next round
} else {
count = 1
offset := int64(geoDataVarintLength) - int64(codeVarintLength) - int64(varintLenByteLen) - 1
_, _ = f.Seek(offset, 1) // skip the unmatched GeoIP or GeoSite varint
advancedN = 1 // the next round will be the start of another GeoIPList or GeoSiteList
}
case 6: // matched GeoIP or GeoSite varint
result = container
break Loop
}
}
return result, nil
}
func Decode(filename, code string) ([]byte, error) {
+4 -4
View File
@@ -60,7 +60,7 @@ func (m *succinctDomainMatcher) Count() int {
}
func NewSuccinctMatcherGroup(domains []*Domain) (DomainMatcher, error) {
t := trie.New[struct{}]()
var builder trie.DomainSetBuilder
m := &succinctDomainMatcher{
count: len(domains),
}
@@ -74,19 +74,19 @@ func NewSuccinctMatcherGroup(domains []*Domain) (DomainMatcher, error) {
m.otherMatchers = append(m.otherMatchers, matcher)
case Domain_Domain:
err := t.Insert("+."+d.Value, struct{}{})
err := builder.Insert("+." + d.Value)
if err != nil {
return nil, err
}
case Domain_Full:
err := t.Insert(d.Value, struct{}{})
err := builder.Insert(d.Value)
if err != nil {
return nil, err
}
}
}
m.set = t.NewDomainSet()
m.set = builder.Build()
return m, nil
}
+9 -9
View File
@@ -17,18 +17,18 @@ 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
PeakWorkingSetSize uintptr
WorkingSetSize uintptr
QuotaPeakPagedPoolUsage uintptr
QuotaPagedPoolUsage uintptr
QuotaPeakNonPagedPoolUsage uintptr
QuotaNonPagedPoolUsage uintptr
PagefileUsage uintptr
PeakPagefileUsage uintptr
}
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)))
r1, _, e1 := syscall.SyscallN(procGetProcessMemoryInfo.Addr(), uintptr(h), uintptr(unsafe.Pointer(mem)), uintptr(unsafe.Sizeof(*mem)))
if r1 == 0 {
if e1 != 0 {
err = error(e1)
+1 -1
View File
@@ -190,7 +190,7 @@ func resolveProcessNameByProcSearch(inode, uid uint32) (string, error) {
info, err := f.Info()
if err != nil {
return "", err
continue
}
if info.Sys().(*syscall.Stat_t).Uid != uid {
continue
+2 -1
View File
@@ -63,7 +63,6 @@ var randomFingerprint = once.OnceValue(func() UClientHelloID {
chooser, _ := weightedrand.NewChooser(
weightedrand.NewChoice("chrome", 6),
weightedrand.NewChoice("safari", 3),
weightedrand.NewChoice("ios", 2),
weightedrand.NewChoice("firefox", 1),
)
initClient := chooser.Pick()
@@ -104,6 +103,8 @@ func init() {
weights := utls.DefaultWeights
weights.TLSVersMax_Set_VersionTLS13 = 1
weights.FirstKeyShare_Set_CurveP256 = 0
weights.CurveIDs_Append_X25519 = 1
weights.KeyShare_Append_RandomGroups = 1
randomized := utls.HelloRandomized
randomized.Seed, _ = utls.NewPRNGSeed()
randomized.Weights = &weights
+46 -29
View File
@@ -2,6 +2,7 @@ package trie
import (
"errors"
"fmt"
"strings"
"unicode"
"unicode/utf8"
@@ -14,7 +15,7 @@ const (
domainStep = "."
)
// ErrInvalidDomain means insert domain is invalid
// ErrInvalidDomain means a domain pattern is invalid.
var ErrInvalidDomain = errors.New("invalid domain")
// DomainTrie contains the main logic for adding and searching nodes for domain segments.
@@ -24,24 +25,29 @@ type DomainTrie[T any] struct {
}
// ValidAndSplitDomain lower-cases and splits a domain into its dot-separated
// parts, reporting whether it is a well-formed pattern. It returns false for a
// trailing dot ("a.com."), leading/trailing whitespace, or an empty segment,
// as well as for misplaced wildcards (see below).
func ValidAndSplitDomain(domain string) ([]string, bool) {
// parts, reporting whether it is a well-formed pattern. It returns an error for
// a trailing dot ("a.com."), leading/trailing whitespace, or an empty segment,
// as well as for misplaced wildcards (see below). The error describes why the
// invalid Clash-style domain pattern was rejected.
func ValidAndSplitDomain(domain string) ([]string, error) {
originalDomain := domain
if domain == "" {
return nil, invalidDomainError(originalDomain, "domain is empty")
}
// A trailing dot would produce an empty final segment; reject it up front.
if domain != "" && domain[len(domain)-1] == '.' {
return nil, false
if domain[len(domain)-1] == '.' {
return nil, invalidDomainError(originalDomain, "trailing dot is not allowed")
}
// Reject leading/trailing whitespace (a common copy-paste artifact) so it
// isn't silently baked into a label.
if domain != "" {
if r, _ := utf8.DecodeRuneInString(domain); unicode.IsSpace(r) {
return nil, false
}
if r, _ := utf8.DecodeLastRuneInString(domain); unicode.IsSpace(r) {
return nil, false
}
if r, _ := utf8.DecodeRuneInString(domain); unicode.IsSpace(r) {
return nil, invalidDomainError(originalDomain, "leading whitespace is not allowed")
}
if r, _ := utf8.DecodeLastRuneInString(domain); unicode.IsSpace(r) {
return nil, invalidDomainError(originalDomain, "trailing whitespace is not allowed")
}
domain = strings.ToLower(domain)
parts := strings.Split(domain, domainStep)
// A single part must be non-empty (rejects ""); for multi-part domains every
@@ -49,12 +55,12 @@ func ValidAndSplitDomain(domain string) ([]string, bool) {
// while an empty first segment is allowed as the ".example.com" dot-wildcard.
if len(parts) == 1 {
if parts[0] == "" {
return nil, false
return nil, invalidDomainError(originalDomain, "domain is empty")
}
} else {
for _, part := range parts[1:] {
for i, part := range parts[1:] {
if part == "" {
return nil, false
return nil, invalidDomainError(originalDomain, fmt.Sprintf("label %d is empty", i+2))
}
}
}
@@ -69,16 +75,25 @@ func ValidAndSplitDomain(domain string) ([]string, bool) {
// as "*a" or "a*b" is rejected.
for i, part := range parts {
if strings.Contains(part, complexWildcard) {
if part != complexWildcard || i != 0 || len(parts) == 1 {
return nil, false
switch {
case part != complexWildcard:
return nil, invalidDomainError(originalDomain, fmt.Sprintf("%q wildcard must occupy the entire label %d", complexWildcard, i+1))
case i != 0:
return nil, invalidDomainError(originalDomain, fmt.Sprintf("%q wildcard is only allowed in the first label", complexWildcard))
case len(parts) == 1:
return nil, invalidDomainError(originalDomain, fmt.Sprintf("%q wildcard must be followed by another label", complexWildcard))
}
}
if strings.Contains(part, wildcard) && part != wildcard {
return nil, false
return nil, invalidDomainError(originalDomain, fmt.Sprintf("%q wildcard must occupy the entire label %d", wildcard, i+1))
}
}
return parts, true
return parts, nil
}
func invalidDomainError(domain, reason string) error {
return fmt.Errorf("%w %q: %s", ErrInvalidDomain, domain, reason)
}
// Insert adds a node to the trie.
@@ -89,9 +104,9 @@ func ValidAndSplitDomain(domain string) ([]string, bool) {
// 4. .example.com
// 5. +.example.com
func (t *DomainTrie[T]) Insert(domain string, data T) error {
parts, valid := ValidAndSplitDomain(domain)
if !valid {
return ErrInvalidDomain
parts, err := ValidAndSplitDomain(domain)
if err != nil {
return err
}
if parts[0] == complexWildcard {
@@ -122,8 +137,8 @@ func (t *DomainTrie[T]) insert(parts []string, data T) {
// 2. wildcard domain
// 2. dot wildcard domain
func (t *DomainTrie[T]) Search(domain string) *Node[T] {
parts, valid := ValidAndSplitDomain(domain)
if !valid || parts[0] == "" {
parts, err := ValidAndSplitDomain(domain)
if err != nil || parts[0] == "" {
return nil
}
@@ -160,6 +175,11 @@ func (t *DomainTrie[T]) Optimize() {
t.root.optimize()
}
// Foreach iterates over the stored domain patterns and their associated values
// in unspecified order. Patterns use lowercase labels, "*" for a single-label
// wildcard, and a leading "." for subdomain-only matching. Exact and suffix-only
// patterns are separate entries; "+." shorthand is not emitted. Each pattern
// and its value can be passed to Insert independently to reproduce the mappings.
func (t *DomainTrie[T]) Foreach(fn func(domain string, data T) bool) {
for key, data := range t.root.getChildren() {
recursion([]string{key}, data, fn)
@@ -183,9 +203,6 @@ func recursion[T any](items []string, node *Node[T], fn func(domain string, data
newItems := append([]string{key}, items...)
if !data.isEmpty() {
domain := joinDomain(newItems)
if domain[0] == domainStepByte {
domain = complexWildcard + domain
}
if !fn(domain, data.Data()) {
return false
}
+231
View File
@@ -0,0 +1,231 @@
package trie
import (
"strings"
"unicode/utf8"
"github.com/metacubex/mihomo/common/utils"
"github.com/openacid/low/bitmap"
)
const domainMapSelectOverflow = ^uint8(0)
// DomainMap is an immutable domain-pattern index with values. Lookup prefers
// exact labels, then single-label wildcards, then suffix wildcards.
// The zero value and a nil *DomainMap are empty. Values are copied, not deep-copied.
type DomainMap[T any] struct {
index domainMapIndex
leafRanks []int32
values []T
}
type domainMapIndex struct {
*DomainSet
selectDeltas []uint8
}
// DomainMapBuilder collects patterns and values. Its zero value is ready to use.
// Insert and Build must not run concurrently on the same builder.
type DomainMapBuilder[T any] struct {
set DomainSetBuilder
valueKeys map[string]T
}
// Insert accepts the same patterns as DomainTrie.Insert. The last insertion wins
// for each expanded terminal; +.domain assigns both the exact and suffix values.
func (builder *DomainMapBuilder[T]) Insert(domain string, value T) error {
begin := len(builder.set.keys)
if err := builder.set.Insert(domain); err != nil {
return err
}
if builder.valueKeys == nil {
builder.valueKeys = make(map[string]T)
}
for _, key := range builder.set.keys[begin:] {
builder.valueKeys[key] = value
}
return nil
}
// IsEmpty reports whether the builder has any domain paths. A nil builder is empty.
func (builder *DomainMapBuilder[T]) IsEmpty() bool {
return builder == nil || builder.set.IsEmpty()
}
// Reset discards pending patterns and values without changing previously built maps.
func (builder *DomainMapBuilder[T]) Reset() {
builder.set.Reset()
builder.valueKeys = nil
}
// Build consumes the builder's inputs and creates an immutable map. It returns nil
// for an empty or nil builder. The builder can be reused without changing earlier maps.
func (builder *DomainMapBuilder[T]) Build() *DomainMap[T] {
if builder == nil {
return nil
}
keys, valueKeys := builder.set.keys, builder.valueKeys
builder.Reset()
if len(keys) == 0 {
return nil
}
mapping := &DomainMap[T]{values: make([]T, 0, len(valueKeys))}
mapping.index.DomainSet = buildDomainSet(keys, func(key string) {
mapping.values = append(mapping.values, valueKeys[key])
})
mapping.init()
return mapping
}
// IsEmpty reports whether the map contains any values. A nil map is empty.
func (mapping *DomainMap[T]) IsEmpty() bool {
return mapping == nil || len(mapping.values) == 0
}
// DomainSet returns the underlying domain set without copying it.
// The returned set is read-only. A zero or nil map returns nil.
func (mapping *DomainMap[T]) DomainSet() *DomainSet {
if mapping == nil {
return nil
}
return mapping.index.DomainSet
}
// Lookup returns the most specific matching value and whether it was found.
// A stored zero or nil value is still a match. Like DomainSet.Has, Lookup matches
// names without validating query syntax.
func (mapping *DomainMap[T]) Lookup(domain string) (T, bool) {
var zero T
if mapping.IsEmpty() {
return zero, false
}
nodeID := mapping.index.match(0, domain)
if nodeID < 0 {
return zero, false
}
rank, _ := bitmap.Rank64(mapping.index.leaves, mapping.leafRanks, int32(nodeID))
return mapping.values[rank], true
}
// Foreach iterates over the stored domain patterns and their associated values
// in unspecified order. Patterns use lowercase labels, "*" for a single-label
// wildcard, and a leading "." for subdomain-only matching. Exact and suffix-only
// patterns are separate entries; "+." shorthand is not emitted. Each pattern
// and its value can be passed to DomainMapBuilder.Insert independently to
// reproduce the mappings. Returning false stops iteration. Empty or nil maps
// do not call fn.
func (mapping *DomainMap[T]) Foreach(fn func(domain string, value T) bool) {
if mapping.IsEmpty() {
return
}
mapping.index.keys(func(key string, nodeID int) bool {
rank, _ := bitmap.Rank64(mapping.index.leaves, mapping.leafRanks, int32(nodeID))
// Internal keys are reversed, with a trailing '+' for suffix wildcards.
// Removing that marker leaves the leading-dot syntax after reversal.
return fn(utils.Reverse(strings.TrimSuffix(key, complexWildcard)), mapping.values[rank])
})
}
// init builds pre-calculated cache to speed up rank() and select()
func (mapping *DomainMap[T]) init() {
mapping.leafRanks = bitmap.IndexRank64(mapping.index.leaves)
mapping.index.initSelectDeltas()
}
func (index *domainMapIndex) initSelectDeltas() {
index.selectDeltas = make([]uint8, len(index.labels))
for ordinal := range index.selectDeltas {
position := selectIthOne(index.labelBitmap, index.ranks, index.selects, ordinal)
delta := position - int(index.selects[ordinal>>5])
if delta < 0 || delta >= int(domainMapSelectOverflow) {
index.selectDeltas[ordinal] = domainMapSelectOverflow
} else {
index.selectDeltas[ordinal] = uint8(delta)
}
}
}
func (index *domainMapIndex) childStart(ordinal int, delta uint8) int {
if delta == domainMapSelectOverflow {
return index.uncachedChildStart(ordinal)
}
return int(index.selects[ordinal>>5]) + int(delta) + 1
}
func (index *domainMapIndex) uncachedChildStart(ordinal int) int {
return selectIthOne(index.labelBitmap, index.ranks, index.selects, ordinal) + 1
}
// match consumes one domain label per recursive step, like DomainTrie.search.
// Each branch gets its own remaining prefix, so failed matches cannot consume it.
func (index *domainMapIndex) match(nodeID int, domain string) int {
if domain == "" {
if getBit(index.leaves, nodeID) != 0 {
return nodeID
}
return -1
}
bitmapIndex := 0
if nodeID > 0 {
bitmapIndex = index.childStart(nodeID-1, index.selectDeltas[nodeID-1])
for getBit(index.labelBitmap, bitmapIndex) == 0 && index.labels[bitmapIndex-nodeID] < domainStepByte {
bitmapIndex++
}
if getBit(index.labelBitmap, bitmapIndex) != 0 || index.labels[bitmapIndex-nodeID] != domainStepByte {
return -1
}
nodeID = bitmapIndex - nodeID + 1
bitmapIndex = index.childStart(nodeID-1, index.selectDeltas[nodeID-1])
}
separator := strings.LastIndexByte(domain, domainStepByte)
part := domain[separator+1:]
remaining := ""
if separator >= 0 {
remaining = domain[:separator]
}
for offset := 0; offset < len(part); offset++ {
if part[offset] >= utf8.RuneSelf {
part = byteReverse(strings.ToLower(utils.Reverse(part)))
break
}
}
staticNode, staticIndex := nodeID, bitmapIndex
for offset := 0; offset < len(part); offset++ {
label := revLowerAt(part, offset)
for getBit(index.labelBitmap, staticIndex) == 0 && index.labels[staticIndex-staticNode] < label {
staticIndex++
}
if getBit(index.labelBitmap, staticIndex) != 0 || index.labels[staticIndex-staticNode] != label || label == complexWildcardByte {
staticNode = -1
break
}
staticNode = staticIndex - staticNode + 1
if offset+1 < len(part) {
staticIndex = index.childStart(staticNode-1, index.selectDeltas[staticNode-1])
}
}
if staticNode >= 0 {
if terminal := index.match(staticNode, remaining); terminal >= 0 {
return terminal
}
}
for getBit(index.labelBitmap, bitmapIndex) == 0 {
label := index.labels[bitmapIndex-nodeID]
childID := bitmapIndex - nodeID + 1
switch label {
case wildcardByte:
if part != wildcard {
if terminal := index.match(childID, remaining); terminal >= 0 {
return terminal
}
}
case complexWildcardByte:
return childID
}
if label > complexWildcardByte {
break
}
bitmapIndex++
}
return -1
}
+87
View File
@@ -0,0 +1,87 @@
package trie
import (
"encoding/binary"
"errors"
"io"
)
func (mapping *DomainMap[T]) WriteBin(writer io.Writer, writeValue func(io.Writer, T) error) error {
if mapping.IsEmpty() {
return errors.New("empty domainMap")
}
// domainSet
if err := mapping.index.DomainSet.WriteBin(writer); err != nil {
return err
}
// separator
if _, err := writer.Write([]byte{0}); err != nil {
return err
}
// version
if _, err := writer.Write([]byte{1}); err != nil {
return err
}
// values
if err := binary.Write(writer, binary.BigEndian, int64(len(mapping.values))); err != nil {
return err
}
for _, value := range mapping.values {
if err := writeValue(writer, value); err != nil {
return err
}
}
return nil
}
func ReadDomainMapBin[T any](reader io.Reader, readValue func(io.Reader) (T, error)) (*DomainMap[T], error) {
// domainSet
set, err := ReadDomainSetBin(reader)
if err != nil {
return nil, err
}
// separator
separator := make([]byte, 1)
if _, err := io.ReadFull(reader, separator); err != nil {
return nil, err
}
if separator[0] != 0 {
return nil, errors.New("separator is invalid")
}
// version
version := make([]byte, 1)
if _, err := io.ReadFull(reader, version); err != nil {
return nil, err
}
if version[0] != 1 {
return nil, errors.New("version is invalid")
}
// values
var length int64
if err := binary.Read(reader, binary.BigEndian, &length); err != nil {
return nil, err
}
if length < 1 {
return nil, errors.New("length is invalid")
}
mapping := &DomainMap[T]{values: make([]T, length)}
mapping.index.DomainSet = set
for index := range mapping.values {
mapping.values[index], err = readValue(reader)
if err != nil {
return nil, err
}
}
// init
mapping.init()
return mapping, nil
}
+719
View File
@@ -0,0 +1,719 @@
package trie_test
import (
"bytes"
"encoding/gob"
"fmt"
"io"
"runtime"
"strconv"
"strings"
"testing"
"github.com/metacubex/mihomo/component/trie"
"github.com/stretchr/testify/assert"
)
func testDomainMapLookup[T any](test *testing.T, mapping *trie.DomainMap[T], query string) (T, bool) {
test.Helper()
value, found := mapping.Lookup(query)
assert.Equal(test, found, mapping.DomainSet().Has(query), query)
return value, found
}
func testDomainMapBin[T any](test *testing.T, mapping *trie.DomainMap[T]) *trie.DomainMap[T] {
test.Helper()
var buffer bytes.Buffer
assert.NoError(test, mapping.WriteBin(&buffer, func(writer io.Writer, value T) error {
return gob.NewEncoder(writer).Encode(value)
}))
restored, err := trie.ReadDomainMapBin(&buffer, func(reader io.Reader) (T, error) {
var value T
err := gob.NewDecoder(reader).Decode(&value)
return value, err
})
assert.NoError(test, err)
values := make(map[string]T)
mapping.Foreach(func(domain string, value T) bool {
values[domain] = value
return true
})
restoredValues := make(map[string]T)
restored.Foreach(func(domain string, value T) bool {
restoredValues[domain] = value
return true
})
assert.Equal(test, values, restoredValues)
return restored
}
func TestDomainMapLifecycle(test *testing.T) {
var nilBuilder *trie.DomainMapBuilder[int]
assert.True(test, nilBuilder.IsEmpty())
assert.Nil(test, nilBuilder.Build())
var emptyMap trie.DomainMap[int]
var nilMap *trie.DomainMap[int]
for _, mapping := range []*trie.DomainMap[int]{nilMap, &emptyMap} {
assert.True(test, mapping.IsEmpty())
assert.Nil(test, mapping.DomainSet())
value, found := testDomainMapLookup(test, mapping, "example.com")
assert.False(test, found)
assert.Zero(test, value)
calls := 0
mapping.Foreach(func(domain string, value int) bool {
calls++
return true
})
assert.Zero(test, calls)
var buffer bytes.Buffer
assert.Error(test, mapping.WriteBin(&buffer, func(writer io.Writer, value int) error {
test.Error("empty map must not call the value encoder")
return nil
}))
assert.Zero(test, buffer.Len())
}
var builder trie.DomainMapBuilder[int]
assert.True(test, builder.IsEmpty())
assert.Nil(test, builder.Build())
for _, domain := range []string{
"", ".", "..dev", "example.com.", " example.com", "example.com ",
"invalid..example", "stun.+", "a.+.b", "a.+", "+", "+.+.com",
"a+b.com", "a*b.com", "*a.com", "a*.com",
} {
assert.ErrorIs(test, builder.Insert(domain, 1), trie.ErrInvalidDomain, domain)
assert.True(test, builder.IsEmpty(), domain)
}
assert.NoError(test, builder.Insert("+.example.com", 1))
assert.NoError(test, builder.Insert("example.com", 2))
assert.NoError(test, builder.Insert(".example.com", 3))
assert.False(test, builder.IsEmpty())
mapping := builder.Build()
assert.False(test, mapping.IsEmpty())
assert.True(test, builder.IsEmpty())
assert.Nil(test, builder.Build())
for query, expected := range map[string]int{"example.com": 2, "www.example.com": 3, "a.b.example.com": 3} {
value, found := testDomainMapLookup(test, mapping, query)
assert.True(test, found, query)
assert.Equal(test, expected, value, query)
}
assert.NoError(test, builder.Insert("+.other.example", 0))
next := builder.Build()
assert.NoError(test, builder.Insert("reset.example", 4))
builder.Reset()
assert.True(test, builder.IsEmpty())
assert.Nil(test, builder.Build())
assert.NoError(test, builder.Insert("fresh.example", 5))
fresh := builder.Build()
value, found := testDomainMapLookup(test, fresh, "fresh.example")
assert.True(test, found)
assert.Equal(test, 5, value)
value, found = testDomainMapLookup(test, fresh, "reset.example")
assert.False(test, found)
assert.Zero(test, value)
value, found = testDomainMapLookup(test, mapping, "www.example.com")
assert.True(test, found)
assert.Equal(test, 3, value)
_, found = testDomainMapLookup(test, mapping, "www.other.example")
assert.False(test, found)
_, found = testDomainMapLookup(test, mapping, "fresh.example")
assert.False(test, found)
value, found = testDomainMapLookup(test, next, "www.example.com")
assert.False(test, found)
assert.Zero(test, value)
value, found = testDomainMapLookup(test, next, "www.other.example")
assert.True(test, found)
assert.Zero(test, value)
}
func TestDomainMapValues(test *testing.T) {
var builder trie.DomainMapBuilder[[]int]
assert.NoError(test, builder.Insert("+.example.com", []int{1}))
assert.NoError(test, builder.Insert("+.EXAMPLE.COM", []int{2}))
assert.NoError(test, builder.Insert("nil.example.com", nil))
mapping := builder.Build()
for _, mapping := range []*trie.DomainMap[[]int]{mapping, testDomainMapBin(test, mapping)} {
for _, query := range []string{"example.com", "www.example.com", "WwW.ExAmPlE.CoM"} {
value, found := testDomainMapLookup(test, mapping, query)
assert.True(test, found, query)
assert.Equal(test, []int{2}, value, query)
}
value, found := testDomainMapLookup(test, mapping, "nil.example.com")
assert.True(test, found)
assert.Nil(test, value)
value, found = testDomainMapLookup(test, mapping, "missing.example")
assert.False(test, found)
assert.Nil(test, value)
values := make(map[string][]int)
mapping.Foreach(func(domain string, value []int) bool {
values[domain] = value
return true
})
assert.Equal(test, map[string][]int{
"example.com": {2},
".example.com": {2},
"nil.example.com": nil,
}, values)
}
var emptyBuilder trie.DomainMapBuilder[struct{}]
assert.NoError(test, emptyBuilder.Insert("+.example.com", struct{}{}))
empty := emptyBuilder.Build()
for _, empty := range []*trie.DomainMap[struct{}]{empty, testDomainMapBin(test, empty)} {
for query, expected := range map[string]bool{"example.com": true, "www.example.com": true, "a.b.example.com": true, "example.net": false} {
_, found := testDomainMapLookup(test, empty, query)
assert.Equal(test, expected, found, query)
}
}
}
func TestDomainMapLookup(test *testing.T) {
rules := []struct {
domain string
value string
}{
{".example.com", "suffix"},
{"*.example.com", "single-label"},
{"api.example.com", "api"},
{"internal.*.example.com", "internal-service"},
{"dead.a.example.com", "dead"},
{"+.example.net", "net"},
{".example.org", "org"},
{"例子.测试", "unicode"},
{"xn--fsqu00a.xn--0zwm56d", "punycode"},
{"bücher.example", "books"},
{"+.测试.cn", "unicode-suffix"},
{"Mijia Cloud", "device"},
{"_acme-challenge.example.com", "acme"},
{"router", "local"},
}
var builder trie.DomainMapBuilder[string]
for _, rule := range rules {
assert.NoError(test, builder.Insert(rule.domain, rule.value))
}
mapping := builder.Build()
for _, mapping := range []*trie.DomainMap[string]{mapping, testDomainMapBin(test, mapping)} {
for query, expected := range map[string]string{
"": "",
"api.example.com": "api",
"API.EXAMPLE.COM": "api",
"www.example.com": "single-label",
"a.example.com": "single-label",
"dead.a.example.com": "dead",
"internal.service.example.com": "internal-service",
"other.service.example.com": "suffix",
"internal.other.service.example.com": "suffix",
"example.com": "",
"example.net": "net",
"www.example.net": "net",
"a.b.example.net": "net",
"example.org": "",
"www.example.org": "org",
"example.test": "",
"例子.测试": "unicode",
"XN--FSQU00A.XN--0ZWM56D": "punycode",
"BÜCHER.EXAMPLE": "books",
"测试.cn": "unicode-suffix",
"www.测试.cn": "unicode-suffix",
"日本語.测试": "",
"Mijia Cloud": "device",
"MIJIA CLOUD": "device",
"_acme-challenge.example.com": "acme",
"ROUTER": "local",
} {
test.Run(query, func(test *testing.T) {
value, found := testDomainMapLookup(test, mapping, query)
assert.Equal(test, expected != "", found)
assert.Equal(test, expected, value)
})
}
}
}
func TestDomainMapWildcard(test *testing.T) {
tests := []struct {
domains []string
queries map[string]int
}{
{
[]string{"*.*.*.baidu.com", "www.baidu.*", "stun.*.*", "*.*.qq.com", "test.*.baidu.com", "*.apple.com"},
map[string]int{
"a.b.c.baidu.com": 1,
"www.baidu.com": 2,
"www.baidu.net": 2,
"stun.ab.cd": 3,
"test.test.qq.com": 4,
"test.test.baidu.com": 5,
"www.apple.com": 6,
"test.baidu.com": 0,
"a.b.baidu.com": 0,
"d.a.b.c.baidu.com": 0,
"stun.l.google.com": 0,
"www.google.com": 0,
"a.www.google.com": 0,
"test.qq.com": 0,
"test.test.test.qq.com": 0,
"apple.com": 0,
"a.www.apple.com": 0,
},
},
{
[]string{"*.dev", ".org", ".apple.*"},
map[string]int{
"example.dev": 1,
"test.org": 2,
"a.b.org": 2,
"test.apple.com": 3,
"test.apple.net": 3,
"a.b.apple.com": 3,
"dev": 0,
"foo.example.dev": 0,
"org": 0,
"apple.com": 0,
"test.orange.com": 0,
},
},
{
[]string{"*"},
map[string]int{"router": 1, "com": 1, "example.com": 0, "": 0},
},
{
[]string{"a.*", "*.a"},
map[string]int{"a.com": 1, "b.a": 2, "a.a": 2, "a": 0, "com": 0, "www.a.com": 0},
},
}
for _, testCase := range tests {
test.Run(testCase.domains[0], func(test *testing.T) {
var builder trie.DomainMapBuilder[int]
for index, domain := range testCase.domains {
assert.NoError(test, builder.Insert(domain, index+1))
}
mapping := builder.Build()
for _, mapping := range []*trie.DomainMap[int]{mapping, testDomainMapBin(test, mapping)} {
for query, expected := range testCase.queries {
value, found := testDomainMapLookup(test, mapping, query)
assert.Equal(test, expected != 0, found, query)
assert.Equal(test, expected, value, query)
}
}
})
}
}
func TestDomainMapComplexWildcard(test *testing.T) {
tests := []struct {
domains []string
queries map[string]int
}{
{
[]string{"+.example.com", "example.com"},
map[string]int{
"example.com": 2,
"www.example.com": 1,
},
},
{
[]string{"+.baidu.com", "+.a.baidu.com", "www.baidu.com", "+.bb.baidu.com"},
map[string]int{
"baidu.com": 1,
"test.test.baidu.com": 1,
"a.baidu.com": 2,
"www.a.baidu.com": 2,
"www.baidu.com": 3,
"bb.baidu.com": 4,
"www.bb.baidu.com": 4,
"google.com": 0,
},
},
{
[]string{"+.stun.*.*", "+.stun.*.*.*", "+.stun.*.*.*.*", "stun.l.google.com"},
map[string]int{
"stun.website.com": 1,
"global.stun.website.com": 1,
"region.global.stun.website.com": 1,
"global.stun.l.google.com": 2,
"stun.a.b.example.com": 3,
"global.stun.a.b.example.com": 3,
"stun.l.google.com": 4,
"stun.com": 0,
"stun.a.b.c.example.com": 0,
"global.turn.website.com": 0,
},
},
{
[]string{"+.*", "stun.*.*.*"},
map[string]int{
"router": 1,
"example.com": 1,
"stun.l.google.com": 2,
"global.stun.l.google.com": 1,
"": 0,
},
},
}
for _, testCase := range tests {
test.Run(testCase.domains[0], func(test *testing.T) {
var builder trie.DomainMapBuilder[int]
for index, domain := range testCase.domains {
assert.NoError(test, builder.Insert(domain, index+1))
}
mapping := builder.Build()
for _, mapping := range []*trie.DomainMap[int]{mapping, testDomainMapBin(test, mapping)} {
for query, expected := range testCase.queries {
value, found := testDomainMapLookup(test, mapping, query)
assert.Equal(test, expected != 0, found, query)
assert.Equal(test, expected, value, query)
}
}
})
}
}
func TestDomainMapWildcardShadow(test *testing.T) {
tests := []struct {
domains []string
queries map[string]int
}{
{
[]string{"*.example.com", "dead.a.example.com"},
map[string]int{"a.example.com": 1, "b.a.example.com": 0, "dead.a.example.com": 2},
},
{
[]string{"*.*.example.com", "dead.*.a.example.com", "dead.b.a.example.com"},
map[string]int{
"b.a.example.com": 1,
"a.example.com": 0,
"dead.c.a.example.com": 2,
"dead.b.a.example.com": 3,
"other.c.a.example.com": 0,
},
},
{
[]string{"*.*.*.example.com", "*.a.example.com"},
map[string]int{"b.c.a.example.com": 1, "d.b.c.a.example.com": 0, "c.a.example.com": 2, "a.example.com": 0},
},
}
for _, testCase := range tests {
test.Run(testCase.domains[0], func(test *testing.T) {
var builder trie.DomainMapBuilder[int]
for index, domain := range testCase.domains {
assert.NoError(test, builder.Insert(domain, index+1))
}
mapping := builder.Build()
for _, mapping := range []*trie.DomainMap[int]{mapping, testDomainMapBin(test, mapping)} {
for query, expected := range testCase.queries {
value, found := testDomainMapLookup(test, mapping, query)
assert.Equal(test, expected != 0, found, query)
assert.Equal(test, expected, value, query)
}
}
})
}
}
func TestDomainMapLongDomain(test *testing.T) {
prefix := strings.Repeat("label.", 32)
var builder trie.DomainMapBuilder[int]
assert.NoError(test, builder.Insert("+.example.com", 1))
assert.NoError(test, builder.Insert(prefix+"example.com", 2))
mapping := builder.Build()
for _, mapping := range []*trie.DomainMap[int]{mapping, testDomainMapBin(test, mapping)} {
for query, expected := range map[string]int{
prefix + "example.com": 2,
"www." + prefix + "example.com": 1,
prefix + "example.net": 0,
} {
value, found := testDomainMapLookup(test, mapping, query)
assert.Equal(test, expected != 0, found, query)
assert.Equal(test, expected, value, query)
}
}
}
func TestDomainMapManyDomains(test *testing.T) {
domains := make([]string, 2000)
var builder trie.DomainMapBuilder[int]
for index := range domains {
domains[index] = fmt.Sprintf("host%d.example.com", index)
assert.NoError(test, builder.Insert(domains[index], index+1))
}
mapping := builder.Build()
for _, mapping := range []*trie.DomainMap[int]{mapping, testDomainMapBin(test, mapping)} {
for index, domain := range domains {
value, found := testDomainMapLookup(test, mapping, domain)
assert.True(test, found, domain)
assert.Equal(test, index+1, value, domain)
query := "www." + domain
value, found = testDomainMapLookup(test, mapping, query)
assert.False(test, found, query)
assert.Zero(test, value, query)
}
value, found := testDomainMapLookup(test, mapping, "missing.example.com")
assert.False(test, found)
assert.Zero(test, value)
}
}
func TestDomainMapForeach(test *testing.T) {
domains := []string{
"google.com",
"stun.*.*.*",
"test.*.google.com",
"+.baidu.com",
"*.baidu.com",
"*.*.baidu.com",
"BAIDU.COM",
".baidu.com",
".example.org",
"+.测试.cn",
"bücher.example",
"BÜCHER.EXAMPLE",
}
var builder trie.DomainMapBuilder[int]
for index, domain := range domains {
assert.NoError(test, builder.Insert(domain, index))
}
mapping := builder.Build()
for _, mapping := range []*trie.DomainMap[int]{mapping, testDomainMapBin(test, mapping)} {
for _, limit := range []int{1, 3} {
calls := 0
mapping.Foreach(func(domain string, value int) bool {
calls++
return calls < limit
})
assert.Equal(test, limit, calls)
}
var rebuilt trie.DomainMapBuilder[int]
var mapDomains []string
values := make(map[string]int)
mapping.Foreach(func(domain string, value int) bool {
assert.NotContains(test, values, domain)
mapDomains = append(mapDomains, domain)
values[domain] = value
assert.NoError(test, rebuilt.Insert(domain, value))
return true
})
assert.Equal(test, map[string]int{
"google.com": 0,
"stun.*.*.*": 1,
"test.*.google.com": 2,
"baidu.com": 6,
".baidu.com": 7,
"*.baidu.com": 4,
"*.*.baidu.com": 5,
".example.org": 8,
"测试.cn": 9,
".测试.cn": 9,
"bücher.example": 11,
}, values)
var setDomains []string
mapping.DomainSet().Foreach(func(domain string) bool {
setDomains = append(setDomains, domain)
return true
})
assert.ElementsMatch(test, mapDomains, setDomains)
for _, mapping := range []*trie.DomainMap[int]{mapping, rebuilt.Build()} {
for domain, expected := range map[string]int{"google.com": 0, "baidu.com": 6, "a.b.c.baidu.com": 7, "www.example.org": 8} {
value, found := testDomainMapLookup(test, mapping, domain)
assert.True(test, found, domain)
assert.Equal(test, expected, value, domain)
}
value, found := testDomainMapLookup(test, mapping, "example.org")
assert.False(test, found)
assert.Zero(test, value)
}
}
}
type domainMapBenchmarkQuery struct {
name string
keys []string
found bool
}
func domainMapLookupDomains(count int) []string {
domains := make([]string, count)
for index := range domains {
domain := "host" + strconv.Itoa(index) + ".example.com"
switch index % 5 {
case 0:
domains[index] = domain
case 1:
domains[index] = "+." + domain
case 2:
domains[index] = "." + domain
case 3:
domains[index] = "*." + domain
case 4:
domains[index] = "service.*." + domain
}
}
return domains
}
func BenchmarkDomainMapLookup(benchmark *testing.B) {
const deepDomain = "api.service.region.cluster.internal.prod.company.example.com"
domains := append(domainMapLookupDomains(10000),
"*.*.overlap.example.com",
"dead.*.a.overlap.example.com",
"dead.b.a.overlap.example.com",
deepDomain,
"例子.测试",
"bücher.example",
"xn--fsqu00a.xn--0zwm56d",
)
queries := []domainMapBenchmarkQuery{
{"exact", []string{"host0.example.com", "HOST9995.EXAMPLE.COM"}, true},
{"suffix", []string{"www.host1.example.com", "a.b.host2.example.com"}, true},
{"wildcard", []string{"www.host3.example.com", "service.eu.host4.example.com"}, true},
{"wildcard_fallback", []string{"b.a.overlap.example.com", "c.a.overlap.example.com"}, true},
{"miss", []string{"host0.example.net", "www.host0.example.com", "other.eu.host4.example.com"}, false},
{"deep", []string{deepDomain, "prod.eu-west-1.api.metrics.host1.example.com"}, true},
{"unicode", []string{"例子.测试", "BÜCHER.EXAMPLE"}, true},
{"punycode", []string{"xn--fsqu00a.xn--0zwm56d"}, true},
}
benchmark.Run("int", func(benchmark *testing.B) {
benchmarkDomainMapLookup(benchmark, domains, queries, 1)
})
benchmark.Run("empty", func(benchmark *testing.B) {
benchmarkDomainMapLookup(benchmark, domains, queries, struct{}{})
benchmark.Run("set", func(benchmark *testing.B) {
var builder trie.DomainSetBuilder
for _, domain := range domains {
assert.NoError(benchmark, builder.Insert(domain))
}
set := builder.Build()
for _, query := range queries {
benchmark.Run(query.name, func(benchmark *testing.B) {
for _, key := range query.keys {
assert.Equal(benchmark, query.found, set.Has(key), key)
}
benchmark.ReportAllocs()
benchmark.ResetTimer()
var found bool
for iteration := 0; iteration < benchmark.N; iteration++ {
found = set.Has(query.keys[iteration%len(query.keys)])
}
benchmark.StopTimer()
runtime.KeepAlive(found)
})
}
})
})
}
func benchmarkDomainMapLookup[T any](benchmark *testing.B, domains []string, queries []domainMapBenchmarkQuery, value T) {
benchmark.Run("map", func(benchmark *testing.B) {
var builder trie.DomainMapBuilder[T]
for _, domain := range domains {
assert.NoError(benchmark, builder.Insert(domain, value))
}
mapping := builder.Build()
for _, query := range queries {
benchmark.Run(query.name, func(benchmark *testing.B) {
for _, key := range query.keys {
_, found := mapping.Lookup(key)
assert.Equal(benchmark, query.found, found, key)
}
benchmark.ReportAllocs()
benchmark.ResetTimer()
var result T
var found bool
for iteration := 0; iteration < benchmark.N; iteration++ {
result, found = mapping.Lookup(query.keys[iteration%len(query.keys)])
}
benchmark.StopTimer()
runtime.KeepAlive(result)
runtime.KeepAlive(found)
})
}
})
benchmark.Run("trie", func(benchmark *testing.B) {
tree := trie.New[T]()
for _, domain := range domains {
assert.NoError(benchmark, tree.Insert(domain, value))
}
tree.Optimize()
for _, query := range queries {
benchmark.Run(query.name, func(benchmark *testing.B) {
for _, key := range query.keys {
assert.Equal(benchmark, query.found, tree.Search(key) != nil, key)
}
benchmark.ReportAllocs()
benchmark.ResetTimer()
var result T
var found bool
for iteration := 0; iteration < benchmark.N; iteration++ {
node := tree.Search(query.keys[iteration%len(query.keys)])
found = node != nil
if found {
result = node.Data()
} else {
var zero T
result = zero
}
}
benchmark.StopTimer()
runtime.KeepAlive(result)
runtime.KeepAlive(found)
})
}
})
}
func BenchmarkDomainMapBuild(benchmark *testing.B) {
for _, count := range []int{100, 10000} {
domains := domainBuildBenchmarkDomains(count)
benchmark.Run(fmt.Sprintf("%d/map", count), func(benchmark *testing.B) {
benchmark.ReportAllocs()
var before, after runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&before)
benchmark.ResetTimer()
var mapping *trie.DomainMap[int]
for iteration := 0; iteration < benchmark.N; iteration++ {
var builder trie.DomainMapBuilder[int]
for _, domain := range domains {
if err := builder.Insert(domain, 1); err != nil {
benchmark.Fatal(err)
}
}
mapping = builder.Build()
}
benchmark.StopTimer()
runtime.GC()
runtime.ReadMemStats(&after)
runtime.KeepAlive(domains)
runtime.KeepAlive(mapping)
benchmark.ReportMetric(float64(int64(after.HeapAlloc)-int64(before.HeapAlloc)), "retained-B")
})
benchmark.Run(fmt.Sprintf("%d/trie", count), func(benchmark *testing.B) {
benchmark.ReportAllocs()
var before, after runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&before)
benchmark.ResetTimer()
var tree *trie.DomainTrie[int]
for iteration := 0; iteration < benchmark.N; iteration++ {
tree = trie.New[int]()
for _, domain := range domains {
if err := tree.Insert(domain, 1); err != nil {
benchmark.Fatal(err)
}
}
tree.Optimize()
}
benchmark.StopTimer()
runtime.GC()
runtime.ReadMemStats(&after)
runtime.KeepAlive(domains)
runtime.KeepAlive(tree)
benchmark.ReportMetric(float64(int64(after.HeapAlloc)-int64(before.HeapAlloc)), "retained-B")
})
}
}
+132 -38
View File
@@ -10,6 +10,7 @@ import (
"github.com/metacubex/mihomo/common/utils"
"github.com/openacid/low/bitmap"
"golang.org/x/exp/slices"
)
const (
@@ -24,47 +25,117 @@ type DomainSet struct {
ranks, selects []int32
}
type qElt struct{ s, e, col int }
type qElt struct{ s, e int }
// DomainSetBuilder incrementally collects domain patterns for a DomainSet.
// Its zero value is ready to use.
type DomainSetBuilder struct {
keys []string
}
// Insert validates and adds a domain pattern to the builder. It accepts the
// same domain syntax as [DomainTrie.Insert].
func (b *DomainSetBuilder) Insert(domain string) error {
parts, err := ValidAndSplitDomain(domain)
if err != nil {
return err
}
if parts[0] == complexWildcard {
b.insert(parts[1:])
b.insert(parts)
} else {
b.insert(parts)
}
return nil
}
func (b *DomainSetBuilder) insert(parts []string) {
if parts[0] == dotWildcard {
parts[0] = complexWildcard
}
b.keys = append(b.keys, utils.Reverse(joinDomain(parts)))
}
// IsEmpty reports whether the builder contains any domain paths.
func (b *DomainSetBuilder) IsEmpty() bool {
return b == nil || len(b.keys) == 0
}
// Reset discards all domains accumulated by the builder.
func (b *DomainSetBuilder) Reset() {
b.keys = nil
}
// Build consumes the accumulated domains and creates an immutable DomainSet.
// The builder can be reused after Build returns.
func (b *DomainSetBuilder) Build() *DomainSet {
if b == nil {
return nil
}
keys := b.keys
b.keys = nil
return buildDomainSet(keys, nil)
}
// NewDomainSet creates a new *DomainSet struct, from a DomainTrie.
func (t *DomainTrie[T]) NewDomainSet() *DomainSet {
reserveDomains := make([]string, 0)
t.Foreach(func(domain string, data T) bool {
reserveDomains = append(reserveDomains, utils.Reverse(domain))
keys := make([]string, 0)
t.Foreach(func(domain string, _ T) bool {
if domain[0] == domainStepByte {
// Suffix-only patterns need an explicit '+' wildcard marker in
// the internal key; a leading dot alone is only a label separator.
domain = complexWildcard + domain
}
keys = append(keys, utils.Reverse(domain))
return true
})
// ensure that the same prefix is continuous
// and according to the ascending sequence of length
sort.Strings(reserveDomains)
keys := reserveDomains
return buildDomainSet(keys, nil)
}
func buildDomainSet(keys []string, onTerminal func(string)) *DomainSet {
if len(keys) == 0 {
return nil
}
// ensure that the same prefix is continuous
// and according to the ascending sequence of length
sort.Strings(keys)
// The construction loop below consumes only one terminal key per node, so a
// duplicate would be indexed past its end and panic.
keys = slices.Compact(keys)
ss := &DomainSet{}
lIdx := 0
queue := []qElt{{0, len(keys), 0}}
for i := 0; i < len(queue); i++ {
elt := queue[i]
if elt.col == len(keys[elt.s]) {
elt.s++
// a leaf node
setBit(&ss.leaves, i, 1)
}
for j := elt.s; j < elt.e; {
frm := j
for ; j < elt.e && keys[j][elt.col] == keys[frm][elt.col]; j++ {
nodeID := 0
queue := make([]qElt, 1, len(keys))
queue[0] = qElt{0, len(keys)}
next := make([]qElt, 0, len(keys))
for col := 0; len(queue) > 0; col++ {
for _, elt := range queue {
if col == len(keys[elt.s]) {
if onTerminal != nil {
onTerminal(keys[elt.s])
}
elt.s++
// a leaf node
setBit(&ss.leaves, nodeID, 1)
}
queue = append(queue, qElt{frm, j, elt.col + 1})
ss.labels = append(ss.labels, keys[frm][elt.col])
setBit(&ss.labelBitmap, lIdx, 0)
for j := elt.s; j < elt.e; {
frm := j
for ; j < elt.e && keys[j][col] == keys[frm][col]; j++ {
}
next = append(next, qElt{frm, j})
ss.labels = append(ss.labels, keys[frm][col])
setBit(&ss.labelBitmap, lIdx, 0)
lIdx++
}
setBit(&ss.labelBitmap, lIdx, 1)
lIdx++
nodeID++
}
setBit(&ss.labelBitmap, lIdx, 1)
lIdx++
queue, next = next, queue[:0]
}
ss.init()
@@ -98,23 +169,26 @@ func (ss *DomainSet) Has(key string) bool {
c := revLowerAt(key, i)
for ; ; bmIdx++ {
if getBit(ss.labelBitmap, bmIdx) != 0 {
if len(stack) > 0 {
for len(stack) > 0 {
cursor := stack[len(stack)-1]
stack = stack[0 : len(stack)-1]
// back wildcard and find next node
nextNodeId := countZeros(ss.labelBitmap, ss.ranks, cursor.bmIdx+1)
nextBmIdx := selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nextNodeId-1) + 1
j := cursor.index
for ; j < len(key) && revLowerAt(key, j) != domainStepByte; j++ {
}
if j == len(key) {
if getBit(ss.leaves, nextNodeId) != 0 {
// The wildcard consumed the rest of the key and reached a
// terminal node, so this branch matches.
return true
} else {
goto RESTART
}
// Otherwise, this node is not terminal and this wildcard branch
// has no input left for child edges. Try any remaining saved wildcards.
continue
}
for ; nextBmIdx-nextNodeId < len(ss.labels); nextBmIdx++ {
nextBmIdx := selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nextNodeId-1) + 1
for ; getBit(ss.labelBitmap, nextBmIdx) == 0; nextBmIdx++ {
if ss.labels[nextBmIdx-nextNodeId] == domainStepByte {
bmIdx = nextBmIdx
nodeId = nextNodeId
@@ -137,7 +211,20 @@ func (ss *DomainSet) Has(key string) bool {
break
}
}
nodeId = countZeros(ss.labelBitmap, ss.ranks, bmIdx+1)
nodeId = bmIdx - nodeId + 1 // countZeros(ss.labelBitmap, ss.ranks, bmIdx+1)
if i == len(key)-1 {
if getBit(ss.leaves, nodeId) != 0 {
// All input is consumed at a terminal node, so the key matches.
return true
}
if len(stack) == 0 {
// No input remains for this non-terminal node's child edges.
// With no saved wildcard branches left, the key cannot match.
return false
}
bmIdx = selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nodeId)
goto RESTART
}
bmIdx = selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nodeId-1) + 1
}
@@ -163,12 +250,12 @@ func byteReverse(s string) string {
return string(buf)
}
func (ss *DomainSet) keys(f func(key string) bool) {
func (ss *DomainSet) keys(f func(key string, nodeId int) bool) {
var currentKey []byte
var traverse func(int, int) bool
traverse = func(nodeId, bmIdx int) bool {
if getBit(ss.leaves, nodeId) != 0 {
if !f(string(currentKey)) {
if !f(string(currentKey), nodeId) {
return false
}
}
@@ -179,7 +266,7 @@ func (ss *DomainSet) keys(f func(key string) bool) {
}
nextLabel := ss.labels[bmIdx-nodeId]
currentKey = append(currentKey, nextLabel)
nextNodeId := countZeros(ss.labelBitmap, ss.ranks, bmIdx+1)
nextNodeId := bmIdx - nodeId + 1 // countZeros(ss.labelBitmap, ss.ranks, bmIdx+1)
nextBmIdx := selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nextNodeId-1) + 1
if !traverse(nextNodeId, nextBmIdx) {
return false
@@ -192,9 +279,16 @@ func (ss *DomainSet) keys(f func(key string) bool) {
return
}
// Foreach iterates over the stored domain patterns in unspecified order.
// Patterns use lowercase labels, "*" for a single-label wildcard, and a leading
// "." for subdomain-only matching. Exact and suffix-only patterns are separate
// entries; "+." shorthand is not emitted. Each pattern can be passed to
// DomainSetBuilder.Insert independently to reproduce the set.
func (ss *DomainSet) Foreach(f func(key string) bool) {
ss.keys(func(key string) bool {
return f(utils.Reverse(key))
ss.keys(func(key string, _ int) bool {
// Internal keys are reversed, with a trailing '+' for suffix wildcards.
// Removing that marker leaves the leading-dot syntax after reversal.
return f(utils.Reverse(strings.TrimSuffix(key, complexWildcard)))
})
}
+217 -19
View File
@@ -1,6 +1,8 @@
package trie_test
import (
"fmt"
"runtime"
"strconv"
"strings"
"testing"
@@ -29,6 +31,7 @@ func testDump(t *testing.T, tree *trie.DomainTrie[struct{}], set *trie.DomainSet
func TestDomainSet(t *testing.T) {
tree := trie.New[struct{}]()
var builder trie.DomainSetBuilder
domainSet := []string{
"baidu.com",
"google.com",
@@ -42,9 +45,11 @@ func TestDomainSet(t *testing.T) {
for _, domain := range domainSet {
assert.NoError(t, tree.Insert(domain, struct{}{}))
assert.NoError(t, builder.Insert(domain))
}
assert.False(t, tree.IsEmpty())
set := tree.NewDomainSet()
assert.False(t, builder.IsEmpty())
set := builder.Build()
assert.Equal(t, tree.NewDomainSet(), set)
assert.NotNil(t, set)
assert.True(t, set.Has("test.cn"))
assert.True(t, set.Has("cn"))
@@ -57,8 +62,70 @@ func TestDomainSet(t *testing.T) {
testDump(t, tree, set)
}
func TestDomainSetForeach(test *testing.T) {
var builder trie.DomainSetBuilder
for _, domain := range []string{".example.com", "+.example.org", "example.net"} {
assert.NoError(test, builder.Insert(domain))
}
set := builder.Build()
var keys []string
set.Foreach(func(key string) bool {
keys = append(keys, key)
assert.NoError(test, builder.Insert(key))
return true
})
assert.ElementsMatch(test, []string{".example.com", ".example.org", "example.org", "example.net"}, keys)
for _, set := range []*trie.DomainSet{set, builder.Build()} {
for domain, expected := range map[string]bool{
"example.com": false,
"www.example.com": true,
"example.org": true,
"www.example.org": true,
"example.net": true,
"www.example.net": false,
} {
assert.Equal(test, expected, set.Has(domain), domain)
}
}
}
func TestDomainSetBuilderLifecycle(t *testing.T) {
var builder trie.DomainSetBuilder
assert.True(t, builder.IsEmpty())
assert.ErrorIs(t, builder.Insert("invalid..example"), trie.ErrInvalidDomain)
assert.True(t, builder.IsEmpty())
assert.Nil(t, builder.Build())
for _, domain := range []string{"+.example.com", "example.com", "+.example.com"} {
assert.NoError(t, builder.Insert(domain))
}
set := builder.Build()
assert.True(t, builder.IsEmpty())
assert.True(t, set.Has("example.com"))
assert.True(t, set.Has("www.example.com"))
var keys []string
set.Foreach(func(key string) bool {
keys = append(keys, key)
return true
})
slices.Sort(keys)
assert.Equal(t, []string{".example.com", "example.com"}, keys)
assert.NoError(t, builder.Insert("other.example"))
set = builder.Build()
assert.True(t, set.Has("other.example"))
assert.False(t, set.Has("example.com"))
assert.NoError(t, builder.Insert("discard.example"))
builder.Reset()
assert.True(t, builder.IsEmpty())
assert.Nil(t, builder.Build())
}
func TestDomainSetComplexWildcard(t *testing.T) {
tree := trie.New[struct{}]()
var builder trie.DomainSetBuilder
domainSet := []string{
"+.baidu.com",
"+.a.baidu.com",
@@ -71,9 +138,11 @@ func TestDomainSetComplexWildcard(t *testing.T) {
for _, domain := range domainSet {
assert.NoError(t, tree.Insert(domain, struct{}{}))
assert.NoError(t, builder.Insert(domain))
}
assert.False(t, tree.IsEmpty())
set := tree.NewDomainSet()
assert.False(t, builder.IsEmpty())
set := builder.Build()
assert.Equal(t, tree.NewDomainSet(), set)
assert.NotNil(t, set)
assert.False(t, set.Has("google.com"))
assert.True(t, set.Has("www.baidu.com"))
@@ -83,6 +152,7 @@ func TestDomainSetComplexWildcard(t *testing.T) {
func TestDomainSetWildcard(t *testing.T) {
tree := trie.New[struct{}]()
var builder trie.DomainSetBuilder
domainSet := []string{
"*.*.*.baidu.com",
"www.baidu.*",
@@ -94,9 +164,11 @@ func TestDomainSetWildcard(t *testing.T) {
for _, domain := range domainSet {
assert.NoError(t, tree.Insert(domain, struct{}{}))
assert.NoError(t, builder.Insert(domain))
}
assert.False(t, tree.IsEmpty())
set := tree.NewDomainSet()
assert.False(t, builder.IsEmpty())
set := builder.Build()
assert.Equal(t, tree.NewDomainSet(), set)
assert.NotNil(t, set)
assert.True(t, set.Has("www.baidu.com"))
assert.True(t, set.Has("test.test.baidu.com"))
@@ -110,12 +182,41 @@ func TestDomainSetWildcard(t *testing.T) {
testDump(t, tree, set)
}
func TestDomainSetWildcardShadow(t *testing.T) {
tests := []struct {
domains []string
match string
notMatch string
}{
{[]string{"*.example.com", "dead.a.example.com"}, "a.example.com", "b.a.example.com"},
{[]string{"*.*.example.com", "dead.*.a.example.com", "dead.b.a.example.com"}, "b.a.example.com", "a.example.com"},
{[]string{"*.*.*.example.com", "*.a.example.com"}, "b.c.a.example.com", "d.b.c.a.example.com"},
}
for _, test := range tests {
tree := trie.New[struct{}]()
var builder trie.DomainSetBuilder
for _, domain := range test.domains {
assert.NoError(t, tree.Insert(domain, struct{}{}))
assert.NoError(t, builder.Insert(domain))
}
set := builder.Build()
assert.Equal(t, tree.NewDomainSet(), set)
assert.NotNil(t, set)
assert.True(t, set.Has(test.match), test.match)
assert.False(t, set.Has(test.notMatch), test.notMatch)
testDump(t, tree, set)
}
}
func TestDomainSetCase(t *testing.T) {
tree := trie.New[struct{}]()
for _, domain := range []string{"example.com", "+.mixed.example.org"} {
var builder trie.DomainSetBuilder
for _, domain := range []string{"example.com", "EXAMPLE.COM", "+.mixed.example.org"} {
assert.NoError(t, tree.Insert(domain, struct{}{}))
assert.NoError(t, builder.Insert(domain))
}
set := tree.NewDomainSet()
set := builder.Build()
assert.Equal(t, tree.NewDomainSet(), set)
assert.NotNil(t, set)
assert.True(t, set.Has("EXAMPLE.COM"))
assert.True(t, set.Has("ExAmPlE.cOm"))
@@ -127,10 +228,13 @@ func TestDomainSetCase(t *testing.T) {
// path than the byte-wise one because the set is built with rune-wise reversal.
func TestDomainSetUnicode(t *testing.T) {
tree := trie.New[struct{}]()
var builder trie.DomainSetBuilder
for _, domain := range []string{"中文.example", "+.测试.cn"} {
assert.NoError(t, tree.Insert(domain, struct{}{}))
assert.NoError(t, builder.Insert(domain))
}
set := tree.NewDomainSet()
set := builder.Build()
assert.Equal(t, tree.NewDomainSet(), set)
assert.NotNil(t, set)
assert.True(t, set.Has("中文.example"))
assert.True(t, set.Has("www.测试.cn"))
@@ -139,24 +243,29 @@ func TestDomainSetUnicode(t *testing.T) {
func TestDomainSetOversizedKey(t *testing.T) {
tree := trie.New[struct{}]()
assert.NoError(t, tree.Insert("+.example.com", struct{}{}))
set := tree.NewDomainSet()
var builder trie.DomainSetBuilder
for _, domain := range []string{"+.example.com"} {
assert.NoError(t, tree.Insert(domain, struct{}{}))
assert.NoError(t, builder.Insert(domain))
}
set := builder.Build()
assert.Equal(t, tree.NewDomainSet(), set)
assert.NotNil(t, set)
var builder strings.Builder
for builder.Len() < 300 {
builder.WriteString("label.")
var keyBuilder strings.Builder
for keyBuilder.Len() < 300 {
keyBuilder.WriteString("label.")
}
assert.True(t, set.Has(builder.String()+"example.com"))
assert.False(t, set.Has(builder.String()+"example.net"))
assert.True(t, set.Has(keyBuilder.String()+"example.com"))
assert.False(t, set.Has(keyBuilder.String()+"example.net"))
}
func BenchmarkDomainSetHas(b *testing.B) {
tree := trie.New[struct{}]()
var builder trie.DomainSetBuilder
for i := 0; i < 10000; i++ {
assert.NoError(b, tree.Insert("+."+strconv.Itoa(i)+".example.com", struct{}{}))
assert.NoError(b, builder.Insert("+."+strconv.Itoa(i)+".example.com"))
}
set := tree.NewDomainSet()
set := builder.Build()
// Keys are split by length because the Go compiler only keeps a
// non-constant sized allocation off the heap up to 32 bytes, so hostnames
@@ -188,3 +297,92 @@ func BenchmarkDomainSetHas(b *testing.B) {
})
}
}
func domainBenchmarkHash(value uint32) uint32 {
value ^= value >> 16
value *= 0x7feb352d
value ^= value >> 15
value *= 0x846ca68b
return value ^ (value >> 16)
}
func domainBuildBenchmarkDomains(count int) []string {
suffixes := [...]string{
"google.com",
"github.io",
"cloudflare.net",
"mozilla.org",
"amazonaws.com",
"apple.com",
"telegram.org",
"example.co.uk",
"example.com.au",
"example.com.tw",
"example.co.jp",
"example.de",
}
hosts := [...]string{
"api%d",
"cdn%d",
"img%d",
"static-%d",
"region-%d",
"production-download-%d",
"service%d.edge",
"download%d.assets.eu-west-1",
}
domains := make([]string, count)
for index := range domains {
hash := domainBenchmarkHash(uint32(index))
if index > 0 && hash%50 == 0 {
domains[index] = domains[int(uint64(hash>>8)%uint64(index))]
continue
}
domain := fmt.Sprintf(hosts[(hash>>8)%uint32(len(hosts))], index) + "." + suffixes[(hash>>12)%uint32(len(suffixes))]
switch (hash >> 24) % 20 {
case 0:
domains[index] = domain
case 1:
domains[index] = "." + domain
case 2:
domains[index] = "*." + domain
case 3:
domains[index] = "service.*." + domain
default:
domains[index] = "+." + domain
}
}
return domains
}
func BenchmarkDomainSetBuild(b *testing.B) {
domains := domainBuildBenchmarkDomains(10000)
b.Run("via_trie", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
tree := trie.New[struct{}]()
for _, domain := range domains {
if err := tree.Insert(domain, struct{}{}); err != nil {
b.Fatal(err)
}
}
set := tree.NewDomainSet()
runtime.KeepAlive(set)
}
})
b.Run("builder", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var builder trie.DomainSetBuilder
for _, domain := range domains {
if err := builder.Insert(domain); err != nil {
b.Fatal(err)
}
}
set := builder.Build()
runtime.KeepAlive(set)
}
})
}
+105 -33
View File
@@ -1,6 +1,7 @@
package trie_test
import (
"fmt"
"net/netip"
"testing"
@@ -113,33 +114,92 @@ func TestTrie_InvalidWildcardPlacement(t *testing.T) {
// DomainTrie.Search (treats a stray wildcard as a literal label) and
// DomainSet.Has (treats the wildcard byte as a wildcard) can never disagree.
valid := []string{"+.example.com", "*.example.com", "+.*", "stun.*.*.*", "*", "a.*", "*.a"}
for _, d := range valid {
tree := trie.New[netip.Addr]()
assert.NoErrorf(t, tree.Insert(d, localIP), "should accept %q", d)
}
t.Run("valid", func(t *testing.T) {
for _, d := range valid {
tree := trie.New[netip.Addr]()
assert.NoErrorf(t, tree.Insert(d, localIP), "should accept %q", d)
}
})
invalid := []string{"stun.+", "a.+.b", "a.+", "+", "+.+.com", "a*b.com", "*a.com", "a*.com"}
for _, d := range invalid {
tree := trie.New[netip.Addr]()
assert.ErrorIsf(t, tree.Insert(d, localIP), trie.ErrInvalidDomain, "should reject %q", d)
invalid := []struct {
domain string
reason string
}{
{domain: "stun.+", reason: `"+" wildcard is only allowed in the first label`},
{domain: "a.+.b", reason: `"+" wildcard is only allowed in the first label`},
{domain: "a.+", reason: `"+" wildcard is only allowed in the first label`},
{domain: "+", reason: `"+" wildcard must be followed by another label`},
{domain: "+.+.com", reason: `"+" wildcard is only allowed in the first label`},
{domain: "a+b.com", reason: `"+" wildcard must occupy the entire label 1`},
{domain: "a*b.com", reason: `"*" wildcard must occupy the entire label 1`},
{domain: "*a.com", reason: `"*" wildcard must occupy the entire label 1`},
{domain: "a*.com", reason: `"*" wildcard must occupy the entire label 1`},
}
t.Run("invalid", func(t *testing.T) {
for _, testCase := range invalid {
tree := trie.New[netip.Addr]()
err := tree.Insert(testCase.domain, localIP)
assert.ErrorIsf(t, err, trie.ErrInvalidDomain, "should reject %q", testCase.domain)
assert.ErrorContainsf(t, err, testCase.reason, "should explain why %q was rejected", testCase.domain)
}
})
// Accepted patterns must stay consistent between Search and DomainSet.Has.
queries := []string{"example.com", "a.example.com", "com", "x.com", "za.com", "anything.at.all"}
for _, d := range valid {
tree := trie.New[netip.Addr]()
assert.NoError(t, tree.Insert(d, localIP))
set := tree.NewDomainSet()
for _, q := range queries {
searchHit := tree.Search(q) != nil
setHit := set != nil && set.Has(q)
assert.Equalf(t, searchHit, setHit, "pattern %q query %q: Search=%v Has=%v", d, q, searchHit, setHit)
t.Run("consistency", func(t *testing.T) {
for _, d := range valid {
tree := trie.New[netip.Addr]()
assert.NoError(t, tree.Insert(d, localIP))
setFromTrie := tree.NewDomainSet()
var builder trie.DomainSetBuilder
assert.NoError(t, builder.Insert(d))
setFromBuilder := builder.Build()
assert.Equal(t, setFromTrie, setFromBuilder)
for _, q := range queries {
searchHit := tree.Search(q) != nil
trieSetHit := setFromTrie != nil && setFromTrie.Has(q)
builderSetHit := setFromBuilder != nil && setFromBuilder.Has(q)
assert.Equalf(t, searchHit, trieSetHit, "pattern %q query %q: Search=%v TrieSet=%v", d, q, searchHit, trieSetHit)
assert.Equalf(t, searchHit, builderSetHit, "pattern %q query %q: Search=%v BuilderSet=%v", d, q, searchHit, builderSetHit)
}
}
})
}
func TestTrie_ValidAndSplitDomain(t *testing.T) {
t.Run("valid", func(t *testing.T) {
assertValid := func(domain string, expected []string) {
parts, err := trie.ValidAndSplitDomain(domain)
assert.NoErrorf(t, err, "should accept %q", domain)
assert.Equal(t, expected, parts)
}
assertValid("GOOGLE.COM", []string{"google", "com"})
assertValid("Mijia Cloud", []string{"mijia cloud"})
})
invalid := []struct {
domain string
reason string
}{
{domain: "", reason: "domain is empty"},
{domain: "example.com.", reason: "trailing dot is not allowed"},
{domain: " example.com", reason: "leading whitespace is not allowed"},
{domain: "example.com ", reason: "trailing whitespace is not allowed"},
{domain: "A..COM", reason: "label 2 is empty"},
}
t.Run("invalid", func(t *testing.T) {
for _, testCase := range invalid {
parts, err := trie.ValidAndSplitDomain(testCase.domain)
assert.Nil(t, parts)
assert.ErrorIs(t, err, trie.ErrInvalidDomain)
assert.ErrorContains(t, err, testCase.reason)
assert.ErrorContains(t, err, fmt.Sprintf("%q", testCase.domain))
}
})
}
func TestTrie_Foreach(t *testing.T) {
tree := trie.New[netip.Addr]()
tree := trie.New[int]()
domainList := []string{
"google.com",
"stun.*.*.*",
@@ -147,25 +207,37 @@ func TestTrie_Foreach(t *testing.T) {
"+.baidu.com",
"*.baidu.com",
"*.*.baidu.com",
"baidu.com",
".example.org",
}
for _, domain := range domainList {
assert.NoError(t, tree.Insert(domain, localIP))
for index, domain := range domainList {
assert.NoError(t, tree.Insert(domain, index))
}
count := 0
tree.Foreach(func(domain string, data netip.Addr) bool {
count++
rebuilt := trie.New[int]()
values := make(map[string]int)
tree.Foreach(func(domain string, data int) bool {
assert.NotContains(t, values, domain)
values[domain] = data
assert.NoError(t, rebuilt.Insert(domain, data))
return true
})
assert.Equal(t, 7, count)
}
func TestTrie_Space(t *testing.T) {
validDomain := func(domain string) bool {
_, ok := trie.ValidAndSplitDomain(domain)
return ok
assert.Equal(t, map[string]int{
"google.com": 0,
"stun.*.*.*": 1,
"test.*.google.com": 2,
".baidu.com": 3,
"*.baidu.com": 4,
"*.*.baidu.com": 5,
"baidu.com": 6,
".example.org": 7,
}, values)
for _, tree := range []*trie.DomainTrie[int]{tree, rebuilt} {
for domain, expected := range map[string]int{"google.com": 0, "baidu.com": 6, "a.b.c.baidu.com": 3, "www.example.org": 7} {
node := tree.Search(domain)
if assert.NotNil(t, node, domain) {
assert.Equal(t, expected, node.Data(), domain)
}
}
assert.Nil(t, tree.Search("example.org"))
}
assert.True(t, validDomain("google.com"))
assert.False(t, validDomain(" google.com"))
assert.False(t, validDomain(" google.com "))
assert.True(t, validDomain("Mijia Cloud"))
}
+6 -3
View File
@@ -58,14 +58,17 @@ func (u *CoreUpdater) CoreBaseName() string {
if runtime.GOOS == "android" {
// mihomo-android-arm64-v8
return fmt.Sprintf("mihomo-%s-%s-v8", runtime.GOOS, runtime.GOARCH)
} else {
// mihomo-linux-arm64
return fmt.Sprintf("mihomo-%s-%s", runtime.GOOS, runtime.GOARCH)
}
// mihomo-linux-arm64
return fmt.Sprintf("mihomo-%s-%s", runtime.GOOS, runtime.GOARCH)
case "mips", "mipsle":
// mihomo-linux-mips-hardfloat
return fmt.Sprintf("mihomo-%s-%s-%s", runtime.GOOS, runtime.GOARCH, features.GOMIPS)
case "amd64":
if runtime.GOOS == "android" {
// mihomo-android-amd64
return fmt.Sprintf("mihomo-%s-%s", runtime.GOOS, runtime.GOARCH)
}
// mihomo-linux-amd64-v1
return fmt.Sprintf("mihomo-%s-%s-%s", runtime.GOOS, runtime.GOARCH, features.GOAMD64)
default:
+62 -39
View File
@@ -168,6 +168,7 @@ type DNS struct {
FakeIPPool6 *fakeip.Pool
FakeIPSkipper *fakeip.Skipper
FakeIPTTL int
FakeIPDisableMapping bool
NameServerPolicy []dns.Policy
ProxyServerNameserver []dns.NameServer
ProxyServerPolicy []dns.Policy
@@ -237,6 +238,7 @@ type RawDNS struct {
FakeIPRange6 string `yaml:"fake-ip-range6" json:"fake-ip-range6"`
FakeIPFilter []string `yaml:"fake-ip-filter" json:"fake-ip-filter"`
FakeIPFilterMode C.FilterMode `yaml:"fake-ip-filter-mode" json:"fake-ip-filter-mode"`
FakeIPDisableMapping bool `yaml:"fake-ip-disable-mapping" json:"fake-ip-disable-mapping"`
FakeIPTTL int `yaml:"fake-ip-ttl" json:"fake-ip-ttl"`
DefaultNameserver []string `yaml:"default-nameserver" json:"default-nameserver"`
CacheAlgorithm string `yaml:"cache-algorithm" json:"cache-algorithm"`
@@ -274,6 +276,7 @@ type RawTun struct {
Enable bool `yaml:"enable" json:"enable"`
Device string `yaml:"device" json:"device"`
Stack C.TUNStack `yaml:"stack" json:"stack"`
DNSMode string `yaml:"dns-mode" json:"dns-mode"`
DNSHijack []string `yaml:"dns-hijack" json:"dns-hijack"`
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
AutoDetectInterface bool `yaml:"auto-detect-interface" json:"auto-detect-interface"`
@@ -314,6 +317,7 @@ type RawTun struct {
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
ICMPTimeout int64 `yaml:"icmp-timeout" json:"icmp-timeout,omitempty"`
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
@@ -324,6 +328,9 @@ type RawTun struct {
// darwin special config
RecvMsgX bool `yaml:"recvmsgx" json:"recvmsgx,omitempty"`
SendMsgX bool `yaml:"sendmsgx" json:"sendmsgx,omitempty"`
// gvisor special config (Non-public option; do not include it in the document.)
ProcessorsPerChannel int `yaml:"processors-per-channel" json:"processors-per-channel,omitempty"`
}
type RawTuicServer struct {
@@ -524,8 +531,8 @@ func DefaultRawConfig() *RawConfig {
"tls://223.5.5.5:853",
},
FakeIPFilter: []string{
"dns.msftnsci.com",
"www.msftnsci.com",
"dns.msftncsi.com",
"www.msftncsi.com",
"www.msftconnecttest.com",
},
FakeIPFilterMode: C.FilterBlackList,
@@ -538,15 +545,16 @@ func DefaultRawConfig() *RawConfig {
Interval: 30,
},
Tun: RawTun{
Enable: false,
Device: "",
Stack: C.TunGvisor,
DNSHijack: []string{"0.0.0.0:53"}, // default hijack all dns query
AutoRoute: true,
AutoDetectInterface: true,
Inet6Address: []netip.Prefix{netip.MustParsePrefix("fdfe:dcba:9876::1/126")},
RecvMsgX: true,
SendMsgX: false, // In the current implementation, if enabled, the kernel may freeze during multi-thread downloads, so it is disabled by default.
Enable: false,
Device: "",
Stack: C.TunMips,
DNSHijack: []string{"0.0.0.0:53"}, // default hijack all dns query
AutoRoute: true,
AutoDetectInterface: true,
Inet6Address: []netip.Prefix{netip.MustParsePrefix("fdfe:dcba:9876::1/126")},
RecvMsgX: true,
SendMsgX: false, // In the current implementation, if enabled, the kernel may freeze during multi-thread downloads, so it is disabled by default.
ProcessorsPerChannel: 1, // For most users, memory usage is more important than peak performance. Setting this to 1 can significantly reduce memory consumption.
},
TuicServer: RawTuicServer{
Enable: false,
@@ -1169,7 +1177,9 @@ func parseHosts(cfg *RawConfig) (*trie.DomainTrie[resolver.HostValue], error) {
node = tree.Search(node.Data().Domain)
}
}
_ = tree.Insert(domain, value)
if err := tree.Insert(domain, value); err != nil {
log.Warnln("skip invalid hosts entry: %s", err)
}
}
}
tree.Optimize()
@@ -1246,6 +1256,12 @@ func parseNameServer(servers []string, respectRules bool, preferH3 bool) ([]dns.
if addr == "" {
err = errors.New("missing Tailscale proxy name")
}
case "et", "easytier":
addr = u.Host
dnsNetType = "easytier" // EasyTier overlay DNS via proxy name
if addr == "" {
err = errors.New("missing EasyTier proxy name")
}
case "dhcp":
addr = server[len("dhcp://"):] // some special notation cannot be parsed by url
dnsNetType = "dhcp" // UDP from DHCP
@@ -1323,7 +1339,7 @@ func parsePureDNSServer(server string) string {
}
}
func parseNameServerPolicy(nsPolicy *orderedmap.OrderedMap[string, any], ruleProviders map[string]P.RuleProvider, respectRules bool, preferH3 bool) ([]dns.Policy, error) {
func parseNameServerPolicy(nsPolicy *orderedmap.OrderedMap[string, any], adapterName string, ruleProviders map[string]P.RuleProvider, respectRules bool, preferH3 bool) ([]dns.Policy, error) {
var policy []dns.Policy
for pair := nsPolicy.Oldest(); pair != nil; pair = pair.Next() {
@@ -1376,21 +1392,21 @@ func parseNameServerPolicy(nsPolicy *orderedmap.OrderedMap[string, any], rulePro
if strings.HasPrefix(domain, "rule-set:") {
domainSetName := domain[9:]
matcher, err := parseDomainRuleSet(domainSetName, "dns.nameserver-policy", ruleProviders)
matcher, err := parseDomainRuleSet(domainSetName, adapterName, ruleProviders)
if err != nil {
return nil, err
}
policy[idx] = dns.Policy{Matcher: matcher, NameServers: nameservers}
} else if strings.HasPrefix(domain, "geosite:") {
country := domain[8:]
matcher, err := RC.NewGEOSITE(country, "dns.nameserver-policy")
matcher, err := RC.NewGEOSITE(country, adapterName)
if err != nil {
return nil, err
}
policy[idx] = dns.Policy{Matcher: matcher, NameServers: nameservers}
} else {
if _, valid := trie.ValidAndSplitDomain(domain); !valid {
return nil, fmt.Errorf("DNS ResoverRule invalid domain: %s", domain)
if _, err := trie.ValidAndSplitDomain(domain); err != nil {
return nil, fmt.Errorf("%s[%d]: %w", adapterName, idx, err)
}
}
}
@@ -1430,7 +1446,7 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
return nil, err
}
if dnsCfg.NameServerPolicy, err = parseNameServerPolicy(cfg.NameServerPolicy, ruleProviders, cfg.RespectRules, cfg.PreferH3); err != nil {
if dnsCfg.NameServerPolicy, err = parseNameServerPolicy(cfg.NameServerPolicy, "dns.nameserver-policy", ruleProviders, cfg.RespectRules, cfg.PreferH3); err != nil {
return nil, err
}
@@ -1438,7 +1454,7 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
return nil, err
}
if dnsCfg.ProxyServerPolicy, err = parseNameServerPolicy(cfg.ProxyServerNameserverPolicy, ruleProviders, false, cfg.PreferH3); err != nil {
if dnsCfg.ProxyServerPolicy, err = parseNameServerPolicy(cfg.ProxyServerNameserverPolicy, "dns.proxy-server-nameserver-policy", ruleProviders, false, cfg.PreferH3); err != nil {
return nil, err
}
if len(dnsCfg.ProxyServerPolicy) != 0 && len(dnsCfg.ProxyServerNameserver) == 0 {
@@ -1493,14 +1509,16 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
}
if cfg.EnhancedMode == C.DNSFakeIP {
var fakeIPTrie *trie.DomainTrie[struct{}]
if len(dnsCfg.Fallback) != 0 {
fakeIPTrie = trie.New[struct{}]()
var fakeIPDomainSetBuilder *trie.DomainSetBuilder
if cfg.FakeIPFilterMode != C.FilterRule && len(dnsCfg.Fallback) != 0 {
fakeIPDomainSetBuilder = &trie.DomainSetBuilder{}
for _, fb := range dnsCfg.Fallback {
if net.ParseIP(fb.Addr) != nil {
continue
}
_ = fakeIPTrie.Insert(fb.Addr, struct{}{})
if err := fakeIPDomainSetBuilder.Insert(fb.Addr); err != nil {
log.Warnln("skip fallback nameserver in fake-ip filter: %s", err)
}
}
}
@@ -1513,7 +1531,7 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
}
skipper.Rules = rules
} else {
host, err := parseDomain(cfg.FakeIPFilter, fakeIPTrie, "dns.fake-ip-filter", ruleProviders)
host, err := parseDomain(cfg.FakeIPFilter, fakeIPDomainSetBuilder, "dns.fake-ip-filter", ruleProviders)
if err != nil {
return nil, err
}
@@ -1522,6 +1540,7 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
dnsCfg.FakeIPSkipper = skipper
dnsCfg.FakeIPTTL = cfg.FakeIPTTL
dnsCfg.FakeIPDisableMapping = cfg.FakeIPDisableMapping
if dnsCfg.FakeIPRange.IsValid() {
pool, err := fakeip.New(fakeip.Options{
@@ -1576,14 +1595,14 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
dnsCfg.FallbackIPFilter = append(dnsCfg.FallbackIPFilter, matcher)
}
if len(cfg.FallbackFilter.Domain) > 0 {
domainTrie := trie.New[struct{}]()
var domainSetBuilder trie.DomainSetBuilder
for idx, domain := range cfg.FallbackFilter.Domain {
err = domainTrie.Insert(domain, struct{}{})
err = domainSetBuilder.Insert(domain)
if err != nil {
return nil, fmt.Errorf("DNS FallbackDomain[%d] format error: %w", idx, err)
}
}
matcher := domainTrie.NewDomainSet() // dns.fallback-filter.domain
matcher := domainSetBuilder.Build() // dns.fallback-filter.domain
dnsCfg.FallbackDomainFilter = append(dnsCfg.FallbackDomainFilter, matcher)
}
if len(cfg.FallbackFilter.GeoSite) > 0 {
@@ -1679,6 +1698,7 @@ func parseTun(rawTun RawTun, dns *DNS, general *General) error {
Enable: rawTun.Enable,
Device: rawTun.Device,
Stack: rawTun.Stack,
DNSMode: rawTun.DNSMode,
DNSHijack: rawTun.DNSHijack,
AutoRoute: rawTun.AutoRoute,
AutoDetectInterface: rawTun.AutoDetectInterface,
@@ -1719,6 +1739,7 @@ func parseTun(rawTun RawTun, dns *DNS, general *General) error {
UDPTimeout: rawTun.UDPTimeout,
ICMPTimeout: rawTun.ICMPTimeout,
DisableICMPForwarding: rawTun.DisableICMPForwarding,
CongestionController: rawTun.CongestionController,
FileDescriptor: rawTun.FileDescriptor,
Inet4RouteAddress: rawTun.Inet4RouteAddress,
@@ -1728,6 +1749,8 @@ func parseTun(rawTun RawTun, dns *DNS, general *General) error {
RecvMsgX: rawTun.RecvMsgX,
SendMsgX: rawTun.SendMsgX,
ProcessorsPerChannel: rawTun.ProcessorsPerChannel,
}
return nil
@@ -1816,7 +1839,7 @@ func parseSniffer(snifferRaw RawSniffer, ruleProviders map[string]P.RuleProvider
forceDomain, err := parseDomain(snifferRaw.ForceDomain, nil, "sniffer.force-domain", ruleProviders)
if err != nil {
return nil, fmt.Errorf("error in force-domain, error:%w", err)
return nil, err
}
snifferConfig.ForceDomain = forceDomain
@@ -1834,7 +1857,7 @@ func parseSniffer(snifferRaw RawSniffer, ruleProviders map[string]P.RuleProvider
skipDomain, err := parseDomain(snifferRaw.SkipDomain, nil, "sniffer.skip-domain", ruleProviders)
if err != nil {
return nil, fmt.Errorf("error in skip-domain, error:%w", err)
return nil, err
}
snifferConfig.SkipDomain = skipDomain
@@ -1888,9 +1911,9 @@ func parseIPCIDR(addresses []string, cidrSet *cidr.IpCidrSet, adapterName string
return
}
func parseDomain(domains []string, domainTrie *trie.DomainTrie[struct{}], adapterName string, ruleProviders map[string]P.RuleProvider) (matchers []C.DomainMatcher, err error) {
func parseDomain(domains []string, domainSetBuilder *trie.DomainSetBuilder, adapterName string, ruleProviders map[string]P.RuleProvider) (matchers []C.DomainMatcher, err error) {
var matcher C.DomainMatcher
for _, domain := range domains {
for idx, domain := range domains {
domainLower := strings.ToLower(domain)
if strings.HasPrefix(domainLower, "geosite:") {
subkeys := strings.Split(domain, ":")
@@ -1899,7 +1922,7 @@ func parseDomain(domains []string, domainTrie *trie.DomainTrie[struct{}], adapte
for _, country := range subkeys {
matcher, err = RC.NewGEOSITE(country, adapterName)
if err != nil {
return nil, err
return nil, fmt.Errorf("%s[%d] %q: %w", adapterName, idx, domain, err)
}
matchers = append(matchers, matcher)
}
@@ -1910,22 +1933,22 @@ func parseDomain(domains []string, domainTrie *trie.DomainTrie[struct{}], adapte
for _, domainSetName := range subkeys {
matcher, err = parseDomainRuleSet(domainSetName, adapterName, ruleProviders)
if err != nil {
return nil, err
return nil, fmt.Errorf("%s[%d] %q: %w", adapterName, idx, domain, err)
}
matchers = append(matchers, matcher)
}
} else {
if domainTrie == nil {
domainTrie = trie.New[struct{}]()
if domainSetBuilder == nil {
domainSetBuilder = &trie.DomainSetBuilder{}
}
err = domainTrie.Insert(domain, struct{}{})
err = domainSetBuilder.Insert(domain)
if err != nil {
return nil, err
return nil, fmt.Errorf("%s[%d]: %w", adapterName, idx, err)
}
}
}
if !domainTrie.IsEmpty() {
matcher = domainTrie.NewDomainSet()
if !domainSetBuilder.IsEmpty() {
matcher = domainSetBuilder.Build()
matchers = append(matchers, matcher)
}
return
+15 -32
View File
@@ -163,45 +163,28 @@ func validateDialerProxies(proxies map[string]C.Proxy) error {
}
}
// perform depth-first search to detect cycles for each proxy
// every proxy has at most one dialer-proxy, so walk each chain once: reaching a proxy
// of the current walk means a cycle, reaching one an earlier walk finished does not
const onPath, acyclic = 1, 2
state := make(map[string]uint8, len(graph))
var path []string
for name := range graph {
visited := make(map[string]bool, len(graph))
path := make([]string, 0, len(graph))
if validateDialerProxiesHasCycle(name, graph, visited, path) {
return fmt.Errorf("proxy [%s] has circular dialer-proxy dependency", name)
path = path[:0]
for current, ok := name, true; ok && state[current] != acyclic; current, ok = graph[current] {
if state[current] == onPath {
return fmt.Errorf("proxy [%s] has circular dialer-proxy dependency", name)
}
state[current] = onPath
path = append(path, current)
}
for _, p := range path {
state[p] = acyclic
}
}
return nil
}
// validateDialerProxiesHasCycle performs DFS to detect if there's a cycle starting from current proxy
func validateDialerProxiesHasCycle(current string, graph map[string]string, visited map[string]bool, path []string) bool {
// check if current is already in path (cycle detected)
for _, p := range path {
if p == current {
return true
}
}
// already visited and no cycle
if visited[current] {
return false
}
visited[current] = true
path = append(path, current)
// check dialer-proxy of current proxy
if dialerProxy, exists := graph[current]; exists {
if validateDialerProxiesHasCycle(dialerProxy, graph, visited, path) {
return true
}
}
return false
}
func verifyIP6() bool {
if skip, _ := strconv.ParseBool(os.Getenv("SKIP_SYSTEM_IPV6_CHECK")); skip {
return true
+89 -19
View File
@@ -8,9 +8,11 @@ import (
func TestValidateDialerProxies(t *testing.T) {
testCases := []struct {
testName string
proxy []map[string]any
errContains string
testName string
proxy []map[string]any
// the proxy named in a cycle error depends on map iteration order,
// so any of these errors is accepted; nil means no error
errs []string
}{
{
testName: "ValidReference",
@@ -18,61 +20,129 @@ func TestValidateDialerProxies(t *testing.T) {
{"name": "base-proxy", "type": "socks5", "server": "127.0.0.1", "port": 1080},
{"name": "proxy-with-dialer", "type": "socks5", "server": "127.0.0.1", "port": 1081, "dialer-proxy": "base-proxy"},
},
errContains: "",
},
{
testName: "NotFoundReference",
proxy: []map[string]any{ // create proxy with non-existent dialer-proxy reference
{"name": "base-proxy", "type": "socks5", "server": "127.0.0.1", "port": 1080},
{"name": "valid-proxy-with-dialer", "type": "socks5", "server": "127.0.0.1", "port": 1081, "dialer-proxy": "base-proxy"},
{"name": "proxy-with-dialer", "type": "socks5", "server": "127.0.0.1", "port": 1081, "dialer-proxy": "non-existent-proxy"},
},
errContains: "not found",
errs: []string{"proxy [proxy-with-dialer] dialer-proxy [non-existent-proxy] not found"},
},
{
testName: "CircularDependency",
proxy: []map[string]any{
// create proxy A that references B
proxy: []map[string]any{ // proxy-b -> proxy-a <-> proxy-c
{"name": "proxy-a", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "proxy-c"},
// create proxy B that references C
{"name": "proxy-b", "type": "socks5", "server": "127.0.0.1", "port": 1081, "dialer-proxy": "proxy-a"},
// create proxy C that references A (creates cycle)
{"name": "proxy-c", "type": "socks5", "server": "127.0.0.1", "port": 1082, "dialer-proxy": "proxy-a"},
},
errContains: "circular",
errs: []string{
"proxy [proxy-a] has circular dialer-proxy dependency",
"proxy [proxy-b] has circular dialer-proxy dependency",
"proxy [proxy-c] has circular dialer-proxy dependency",
},
},
{
testName: "ComplexChain",
proxy: []map[string]any{ // create a valid chain: proxy-d -> proxy-c -> proxy-b -> proxy-a
proxy: []map[string]any{ // proxy-d, proxy-e and proxy-f share the chain proxy-c -> proxy-b -> proxy-a
{"name": "proxy-a", "type": "socks5", "server": "127.0.0.1", "port": 1080},
{"name": "proxy-b", "type": "socks5", "server": "127.0.0.1", "port": 1081, "dialer-proxy": "proxy-a"},
{"name": "proxy-c", "type": "socks5", "server": "127.0.0.1", "port": 1082, "dialer-proxy": "proxy-b"},
{"name": "proxy-d", "type": "socks5", "server": "127.0.0.1", "port": 1083, "dialer-proxy": "proxy-c"},
{"name": "proxy-e", "type": "socks5", "server": "127.0.0.1", "port": 1084, "dialer-proxy": "proxy-c"},
{"name": "proxy-f", "type": "socks5", "server": "127.0.0.1", "port": 1085, "dialer-proxy": "proxy-c"},
},
errContains: "",
},
{
testName: "EmptyDialerProxy",
proxy: []map[string]any{ // create proxy without dialer-proxy
{"name": "simple-proxy", "type": "socks5", "server": "127.0.0.1", "port": 1080},
{"name": "another-simple-proxy", "type": "socks5", "server": "127.0.0.1", "port": 1081},
},
errContains: "",
},
{
testName: "SelfReference",
proxy: []map[string]any{ // create proxy that references itself
{"name": "base-proxy", "type": "socks5", "server": "127.0.0.1", "port": 1080},
{"name": "self-proxy", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "self-proxy"},
},
errContains: "circular",
errs: []string{"proxy [self-proxy] has circular dialer-proxy dependency"},
},
{
testName: "NotFoundBeforeCycle",
proxy: []map[string]any{
{"name": "a", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "b"},
{"name": "b", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "a"},
{"name": "c", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "missing"},
},
errs: []string{"proxy [c] dialer-proxy [missing] not found"},
},
{
testName: "TwoProxyCycle",
proxy: []map[string]any{
{"name": "a", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "b"},
{"name": "b", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "a"},
{"name": "c", "type": "socks5", "server": "127.0.0.1", "port": 1080},
},
errs: []string{
"proxy [a] has circular dialer-proxy dependency",
"proxy [b] has circular dialer-proxy dependency",
},
},
{
testName: "LongChainIntoCycle",
// x -> a -> b -> c -> d -> e -> c, beside an acyclic chain y -> z, w -> z
proxy: []map[string]any{
{"name": "x", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "a"},
{"name": "a", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "b"},
{"name": "b", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "c"},
{"name": "c", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "d"},
{"name": "d", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "e"},
{"name": "e", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "c"},
{"name": "y", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "z"},
{"name": "z", "type": "socks5", "server": "127.0.0.1", "port": 1080},
{"name": "w", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "z"},
},
errs: []string{
"proxy [x] has circular dialer-proxy dependency",
"proxy [a] has circular dialer-proxy dependency",
"proxy [b] has circular dialer-proxy dependency",
"proxy [c] has circular dialer-proxy dependency",
"proxy [d] has circular dialer-proxy dependency",
"proxy [e] has circular dialer-proxy dependency",
},
},
{
testName: "SharedRelayBesideCycle",
// p and q share an acyclic relay, t leads into the cycle r <-> s
proxy: []map[string]any{
{"name": "p", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "relay"},
{"name": "q", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "relay"},
{"name": "relay", "type": "socks5", "server": "127.0.0.1", "port": 1080},
{"name": "r", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "s"},
{"name": "s", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "r"},
{"name": "t", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "s"},
},
errs: []string{
"proxy [r] has circular dialer-proxy dependency",
"proxy [s] has circular dialer-proxy dependency",
"proxy [t] has circular dialer-proxy dependency",
},
},
}
for _, testCase := range testCases {
t.Run(testCase.testName, func(t *testing.T) {
config := RawConfig{Proxy: testCase.proxy}
_, _, err := parseProxies(&config)
if testCase.errContains == "" {
assert.NoError(t, err, testCase.testName)
} else {
assert.ErrorContains(t, err, testCase.errContains, testCase.testName)
// repeat so that different map iteration orders are covered
for i := 0; i < 20; i++ {
_, _, err := parseProxies(&config)
if testCase.errs == nil {
assert.NoError(t, err)
} else if assert.Error(t, err) {
assert.Contains(t, testCase.errs, err.Error())
}
}
})
}
+3
View File
@@ -53,6 +53,7 @@ const (
OpenVPN
Tailscale
ZeroTier
EasyTier
GostRelay
)
@@ -237,6 +238,8 @@ func (at AdapterType) String() string {
return "Tailscale"
case ZeroTier:
return "ZeroTier"
case EasyTier:
return "EasyTier"
case GostRelay:
return "GostRelay"
case Relay:
+5
View File
@@ -0,0 +1,5 @@
//go:build no_easytier
package features
const NoEasyTier = true
+5
View File
@@ -0,0 +1,5 @@
//go:build !no_easytier
package features
const NoEasyTier = false
+3
View File
@@ -16,6 +16,9 @@ func Tags() (tags []string) {
if NoZeroTier {
tags = append(tags, "no_zerotier")
}
if NoEasyTier {
tags = append(tags, "no_easytier")
}
if WithGVisor {
tags = append(tags, "with_gvisor")
}
+4
View File
@@ -9,12 +9,14 @@ var StackTypeMapping = map[string]TUNStack{
strings.ToLower(TunGvisor.String()): TunGvisor,
strings.ToLower(TunSystem.String()): TunSystem,
strings.ToLower(TunMixed.String()): TunMixed,
strings.ToLower(TunMips.String()): TunMips,
}
const (
TunGvisor TUNStack = iota
TunSystem
TunMixed
TunMips
)
type TUNStack int
@@ -42,6 +44,8 @@ func (e TUNStack) String() string {
return "System"
case TunMixed:
return "Mixed"
case TunMips:
return "Mips"
default:
return "unknown"
}
+9 -2
View File
@@ -383,10 +383,17 @@ func (doh *dnsOverHTTPS) createClient(ctx context.Context) (*http.Client, error)
// HTTP3 is enabled in the upstream options). If this attempt is successful,
// it returns an HTTP3 transport, otherwise it returns the H1/H2 transport.
func (doh *dnsOverHTTPS) createTransport(ctx context.Context) (t http.RoundTripper, err error) {
// http.Transport dials in a context detached from the request, so a dial
// that the query has given up on must still end on its own.
transport := &http.Transport{
DisableCompression: true,
DialContext: doh.dialer.DialContext,
IdleConnTimeout: transportDefaultIdleConnTimeout,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
ctx, cancel := context.WithTimeout(ctx, dialTimeout)
defer cancel()
return doh.dialer.DialContext(ctx, network, addr)
},
IdleConnTimeout: transportDefaultIdleConnTimeout,
TLSHandshakeTimeout: dialTimeout,
}
if doh.url.Scheme == "http" {
+2
View File
@@ -339,6 +339,7 @@ func (doq *dnsOverQUIC) openConnection(ctx context.Context) (quicConn *quic.Conn
host, _, err := net.SplitHostPort(doq.addr)
if err != nil {
_ = packetConn.Close()
return nil, err
}
@@ -354,6 +355,7 @@ func (doq *dnsOverQUIC) openConnection(ctx context.Context) (quicConn *quic.Conn
NameCertVerify: doq.nameCertVerify,
})
if err != nil {
_ = packetConn.Close()
return nil, err
}
+65
View File
@@ -0,0 +1,65 @@
package dns
import (
"context"
"fmt"
"sync"
"sync/atomic"
D "github.com/miekg/dns"
)
type easyTierDNSClient struct {
name string
}
type easyTierResolverEntry struct {
id uint64
client dnsClient
}
var (
easyTierResolverID atomic.Uint64
easyTierResolverMu sync.RWMutex
easyTierResolvers = map[string]easyTierResolverEntry{}
)
var _ dnsClient = (*easyTierDNSClient)(nil)
func RegisterEasyTierDnsClient(name string, client dnsClient) func() {
id := easyTierResolverID.Add(1)
easyTierResolverMu.Lock()
easyTierResolvers[name] = easyTierResolverEntry{
id: id,
client: client,
}
easyTierResolverMu.Unlock()
return func() {
easyTierResolverMu.Lock()
if entry, ok := easyTierResolvers[name]; ok && entry.id == id {
delete(easyTierResolvers, name)
}
easyTierResolverMu.Unlock()
}
}
func newEasyTierClient(name string) *easyTierDNSClient {
return &easyTierDNSClient{name: name}
}
func (c *easyTierDNSClient) Address() string {
return "easytier://" + c.name
}
func (c *easyTierDNSClient) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error) {
easyTierResolverMu.RLock()
entry, ok := easyTierResolvers[c.name]
easyTierResolverMu.RUnlock()
if !ok || entry.client == nil {
return nil, fmt.Errorf("proxy %q does not provide EasyTier DNS", c.name)
}
return entry.client.ExchangeContext(ctx, m)
}
func (c *easyTierDNSClient) ResetConnection() {}
+18 -15
View File
@@ -10,14 +10,15 @@ import (
)
type ResolverEnhancer struct {
ipv6 bool
mode C.DNSMode
fakeIPPool *fakeip.Pool
fakeIPPool6 *fakeip.Pool
fakeIPSkipper *fakeip.Skipper
fakeIPTTL int
mapping *lru.LruCache[netip.Addr, string]
useHosts bool
ipv6 bool
mode C.DNSMode
fakeIPPool *fakeip.Pool
fakeIPPool6 *fakeip.Pool
fakeIPSkipper *fakeip.Skipper
fakeIPTTL int
fakeIPDisableMapping bool
mapping *lru.LruCache[netip.Addr, string]
useHosts bool
}
func (h *ResolverEnhancer) FakeIPEnabled() bool {
@@ -159,13 +160,14 @@ func (h *ResolverEnhancer) StoreFakePoolState() {
}
type EnhancerConfig struct {
IPv6 bool
EnhancedMode C.DNSMode
FakeIPPool *fakeip.Pool
FakeIPPool6 *fakeip.Pool
FakeIPSkipper *fakeip.Skipper
FakeIPTTL int
UseHosts bool
IPv6 bool
EnhancedMode C.DNSMode
FakeIPPool *fakeip.Pool
FakeIPPool6 *fakeip.Pool
FakeIPSkipper *fakeip.Skipper
FakeIPTTL int
FakeIPDisableMapping bool
UseHosts bool
}
func NewEnhancer(cfg EnhancerConfig) *ResolverEnhancer {
@@ -182,6 +184,7 @@ func NewEnhancer(cfg EnhancerConfig) *ResolverEnhancer {
}
e.fakeIPSkipper = cfg.FakeIPSkipper
e.fakeIPTTL = cfg.FakeIPTTL
e.fakeIPDisableMapping = cfg.FakeIPDisableMapping
if e.fakeIPTTL < 1 {
e.fakeIPTTL = 1
}
+3 -1
View File
@@ -237,11 +237,13 @@ func newHandler(resolver resolver.Resolver, mapper *ResolverEnhancer) handler {
middlewares = append(middlewares, withHosts(mapper.mapping))
}
disableMapping := false
if mapper.mode == C.DNSFakeIP {
middlewares = append(middlewares, withFakeIP(mapper.fakeIPSkipper, mapper.fakeIPPool, mapper.fakeIPPool6, mapper.fakeIPTTL))
disableMapping = mapper.fakeIPDisableMapping
}
if mapper.mode != C.DNSNormal {
if mapper.mode != C.DNSNormal && !disableMapping {
middlewares = append(middlewares, withMapping(mapper.mapping))
}
+3 -1
View File
@@ -585,7 +585,9 @@ func NewResolver(config Config) (rs Resolvers) {
if triePolicy == nil {
triePolicy = trie.New[[]dnsClient]()
}
_ = triePolicy.Insert(policy.Domain, cacheTransform(policy.NameServers))
if err := triePolicy.Insert(policy.Domain, cacheTransform(policy.NameServers)); err != nil {
log.Warnln("[DNS] skip invalid nameserver policy: %s", err)
}
}
}
insertPolicy(nil)
+2
View File
@@ -128,6 +128,8 @@ func transform(servers []NameServer, resolver resolver.Resolver) []dnsClient {
c = newSystemClient()
case "tailscale":
c = newTailscaleClient(s.Addr)
case "easytier":
c = newEasyTierClient(s.Addr)
case "rcode":
c = newRCodeClient(s.Addr)
case "quic":
+93 -20
View File
@@ -133,7 +133,13 @@ profile: # 存储 select 选择记录
# Tun 配置
tun:
enable: false
stack: system # gvisor/mixed
stack: mips # gvisor/mixed/system
# 系统 DNS 配置方式
# - disabled,不设置系统 DNS
# - native,将 tun 地址设为系统 DNS
# - hijack,在 native 基础上额外拦截发往其他网卡的 53 端口流量(Windows 需 strict-route,Linux 需 auto-redirect)
# - 置空,和旧行为一致,Windows 和 Linux 在启用 auto-route 默认 hijack,否则 disabled;macOS 默认 disabled
# dns-mode: hijack
dns-hijack:
- 0.0.0.0:53 # 需要劫持的 DNS
# auto-detect-interface: true # 自动识别出口网卡
@@ -144,6 +150,7 @@ tun:
auto-redirect: false # 自动配置 iptables 以重定向 TCP 连接。仅支持 Linux。带有 auto-redirect 的 auto-route 现在可以在路由器上按预期工作,无需干预。
# strict-route: true # 将所有连接路由到 tun 来防止泄漏,但你的设备将无法其他设备被访问
# disable-icmp-forwarding: true # 禁用 ICMP 转发,防止某些情况下的 ICMP 环回问题,ping 将不会显示真实的延迟
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; only effective on mips
route-address-set: # 将指定规则集中的目标 IP CIDR 规则添加到防火墙, 不匹配的流量将绕过路由, 仅支持 Linux,且需要 nftables,`auto-route` 和 `auto-redirect` 已启用。
- ruleset-1
- ruleset-2
@@ -314,6 +321,7 @@ dns:
- dhcp://en0 # dns from dhcp
- quic://dns.adguard.com:784 # DNS over QUIC
# - ts://tailscale # 使用指定 Tailscale 出站的 DNS 配置查询
# - et://easytier # 仅解析 overlay A/PTR;建议放在 nameserver-policy
# - '8.8.8.8#RULES' # 效果同respect-rules,但仅对该服务器生效
# - '8.8.8.8#en0' # 兼容指定 DNS 出口网卡
@@ -406,20 +414,22 @@ proxies: # socks5
server: server
port: 44046
psk: yourpsk
# version: 4 # support 1/2/3/4/5
# udp: true # support UDP on version 3/4/5
# reuse: false # v4/5 only
# userkey: per-user-client-id # v6 only; sent as the Snell ClientID
# version: 4 # support 1/2/3/4/5/6
# udp: true # support UDP on version 3/4/5/6
# reuse: false # v4/5/6 only
# mode: default # v6 only, default / unshaped / unsafe-raw, must match the server
# obfs-opts:
# mode: http # or tls/shadow-tls/restls/jls
# mode: http # or tls/shadow-tls/restls/jls (http/tls are not available on v6)
- name: "snell-shadow-tls"
type: snell
server: server
port: 44046
psk: yourpsk
# version: 4 # support 1/2/3/4/5
# udp: true # support UDP on version 3/4/5
# reuse: false # v4/5 only
# version: 4 # support 1/2/3/4/5/6
# udp: true # support UDP on version 3/4/5/6
# reuse: false # v4/5/6 only
# client-fingerprint: chrome
obfs-opts:
mode: shadow-tls
@@ -433,7 +443,7 @@ proxies: # socks5
server: server
port: 44046
psk: yourpsk
# version: 4 # support 1/2/3/4/5
# version: 4 # support 1/2/3/4/5/6
# client-fingerprint: chrome
obfs-opts:
mode: restls
@@ -446,7 +456,7 @@ proxies: # socks5
server: server
port: 44046
psk: yourpsk
# version: 4 # support 1/2/3/4/5
# version: 4 # support 1/2/3/4/5/6
# client-fingerprint: chrome
obfs-opts:
mode: jls
@@ -1293,7 +1303,7 @@ proxies: # socks5
# reserved: [209,98,59]
# persistent-keepalive: 0
# ip-stack:
# mode: auto # options: auto, gvisor, mips; auto uses gVisor when compiled in and mihomo IP stack (MIPS) otherwise
# mode: auto # options: auto, mips, gvisor; auto uses mihomo IP stack (MIPS), gvisor needs compiled with -tags with_gvisor
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; ignored by gVisor
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
# dialer-proxy: "ss1"
@@ -1366,12 +1376,13 @@ proxies: # socks5
- name: "zerotier"
type: zerotier
network: "0123456789abcdef" # 16-digit ZeroTier network ID
# state-dir: ./zerotier-node # persistent node identity; defaults to an isolated directory derived from network and outbound name
# state-dir: ./zerotier-node # persistent node state and default identity; defaults to an isolated directory derived from network and outbound name
# identity-secret: "0123456789:0:public-key:private-key" # complete identity.secret contents; overrides the identity in state-dir and is not written there
# planet: ./planet # optional private planet file; replaces the built-in Earth planet
# mtu: 1400 # optional local MTU override; cannot exceed the controller MTU
# physical-mtu: 1432 # optional ZeroTier UDP payload MTU (510-10324; default 1432)
# ip-stack:
# mode: auto # options: auto, gvisor, mips; auto uses gVisor when compiled in and mihomo IP stack (MIPS) otherwise
# mode: auto # options: auto, mips, gvisor; auto uses mihomo IP stack (MIPS), gvisor needs compiled with -tags with_gvisor
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; ignored by gVisor
# primary-port: 0 # primary UDP port; 0 selects an available port
# secondary-port: 0 # second UDP port; 0 selects an available port, -1 disables it
@@ -1392,6 +1403,48 @@ proxies: # socks5
# routing-mark: 6666
# ip-version: ipv4-prefer
# easytier
# overlay 仅支持 IPv4;ip-version 只影响底层 peer 连接,不启用 overlay IPv6
- name: "easytier"
type: easytier
network-name: example
network-secret: secret
# hostname: mihomo
# ipv4: 10.144.0.1/24
# dhcp: true # ipv4 为空时默认开启,否则实例没有 overlay IPv4
peers: # 可配置多个入口;默认不隐式连接 public.easytier.top;无 listeners 时至少填一个
- tcp://192.0.2.10:11010
- udp://192.0.2.11:11010
# - "tcp://relay.example.com:11010?peer-public-key=base64-x25519-public-key" # 锁定共享节点公钥,防止中间人
# secure-mode: true # Noise E2EE;配置 local-*-key 或 peer URI 中的 peer-public-key 时会自动开启
# local-private-key: "base64-x25519-private-key" # 可选,固定本机身份,避免每次启动更换公钥
# local-public-key: "base64-x25519-public-key" # 可选,通常可由私钥派生
# listeners: ["tcp://0.0.0.0:11010"]
# no-listener: true # 默认 true,listeners 为空
# mapped-listeners: ["tcp://203.0.113.10:11010"]
# exit-nodes: ["10.144.0.1"]
# proxy-networks: ["10.0.0.0/24"]
# instance-name: mihomo-easytier
# state-dir: ./easytier # 默认 easytier/<name>,用于持久化 instance_id
udp: true
# accept-dns: false
# enable-exit-node: false
# enable-encryption: true
# encryption-algorithm: aes-gcm
# private-mode: false
# latency-first: false
# disable-p2p: false
# enable-kcp-proxy: false
# disable-kcp-input: false
# enable-quic-proxy: false
# disable-quic-input: false
# mtu: 1380
# tld-dns-zone: et.net.
# dialer-proxy: "ss1"
# interface-name: "WLAN"
# routing-mark: 6666
# ip-version: ipv4-prefer
# openvpn
- name: "openvpn"
type: openvpn
@@ -1450,7 +1503,7 @@ proxies: # socks5
# mtu: 1500
udp: true
# ip-stack:
# mode: auto # options: auto, gvisor, mips; auto uses gVisor when compiled in and mihomo IP stack (MIPS) otherwise
# mode: auto # options: auto, mips, gvisor; auto uses mihomo IP stack (MIPS), gvisor needs compiled with -tags with_gvisor
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; ignored by gVisor
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
# dialer-proxy: "ss1"
@@ -1469,7 +1522,7 @@ proxies: # socks5
mtu: 1280
udp: true
# ip-stack:
# mode: auto # options: auto, gvisor, mips; auto uses gVisor when compiled in and mihomo IP stack (MIPS) otherwise
# mode: auto # options: auto, mips, gvisor; auto uses mihomo IP stack (MIPS), gvisor needs compiled with -tags with_gvisor
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; ignored by gVisor
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
# dialer-proxy: "ss1"
@@ -1507,7 +1560,7 @@ proxies: # socks5
udp: true
network: h2
# ip-stack:
# mode: auto # options: auto, gvisor, mips; auto uses gVisor when compiled in and mihomo IP stack (MIPS) otherwise
# mode: auto # options: auto, mips, gvisor; auto uses mihomo IP stack (MIPS), gvisor needs compiled with -tags with_gvisor
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; ignored by gVisor
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
# dialer-proxy: "ss1"
@@ -1603,7 +1656,7 @@ proxies: # socks5
port: 22
username: root
password: password
privateKey: path
private-key: path
# mieru
- name: mieru
@@ -1746,6 +1799,15 @@ proxy-groups:
url: "https://cp.cloudflare.com/generate_204"
interval: 300
# strategy: consistent-hashing # 可选 round-robin 和 sticky-sessions
# hash-key: in-user # 可选,仅 consistent-hashing 和 sticky-sessions 支持;
# # round-robin 不做哈希,配置它会报错而不是被忽略。
# # 只改变「拿什么值去哈希」,不改变策略拿到哈希值之后如何选节点;
# # 不填时行为与旧版完全一致。
# # in-user 用 inbound 的认证用户名作 key(与 IN-USER 规则读取的是
# # 同一个字段),它不随目标地址变化,因此一件跨多个域名的任务不会
# # 中途换节点、换出口 IP。未认证的请求回退到该策略原本的 key。
# # 两种策略给出的一致性时长不同(前者永久、后者 10 分钟),
# # 取舍见 PR #3133。
# select 用户自行选择节点
- name: Proxy
@@ -2072,6 +2134,12 @@ listeners:
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
password: vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg=
cipher: 2022-blake3-aes-256-gcm
# users: # 多用户,匹配到的用户名可用于 IN-USER 规则,仅支持 AEAD 加密及 2022-blake3-aes-* 加密
# # 2022-blake3-aes-*: 上方 password 为服务端 PSK,此处为用户 PSK,客户端密码填写 "服务端PSK:用户PSK"
# # AEAD 加密: 上方 password 需留空,客户端密码直接填写此处的密码
# # 注意: AEAD 加密的数据包中不含用户标识,服务端需对每个包逐个尝试所有用户的密码,UDP 处理开销随用户数线性增长(且无效包会尝试全部用户),用户较多时请使用 2022-blake3-aes-*
# username1: 6NNH4wlU1Sg+r8uILmCzg9qogjbKGDh/RXT7SYwFx1g=
# username2: 9x0ZrXIZTB5+nwF4QzF+Rn4KfJ2kchNm74aOYhZ+8Sg=
# simple-obfs:
# enable: false # 设置为true时开启
# mode: http # Available: http, tls
@@ -2135,10 +2203,11 @@ listeners:
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
psk: your-password
version: 4 # 支持 1/2/3/4/5
version: 4 # 支持 1/2/3/4/5/6
udp: true # UDP over TCP tunnel,默认 true
# mode: default # 仅 v6:default / unshaped / unsafe-raw,需与客户端一致;v6 的 psk 长度须为 12 到 255 字节
# obfs-opts:
# mode: http # 可选:http / tls
# mode: http # 可选:http / tls(v6 不支持,配置时会报错)
# host: bing.com
# shadow-tls:
# enable: false # 设置为true时开启
@@ -2531,6 +2600,8 @@ listeners:
# traffic-pattern: ""
# 如果开启,且客户端不发送用户提示,代理服务器将拒绝连接
# user-hint-is-mandatory: false
# 在上行和下行同时空闲这个秒数后,关闭底层TCP连接。最小值为60。
# tcp-idle-timeout: 1800
- name: sudoku-in-1
type: sudoku
@@ -2744,7 +2815,8 @@ listeners:
type: tun
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
stack: system # gvisor / mixed
stack: mips # gvisor / mixed / system
# dns-mode: hijack # disabled / native / hijack,为空时采用旧行为
dns-hijack:
- 0.0.0.0:53 # 需要劫持的 DNS
# auto-detect-interface: false # 自动识别出口网卡
@@ -2786,6 +2858,7 @@ listeners:
# exclude-package: # 排除被路由的 Android 应用包名
# - com.android.captiveportallogin
# disable-icmp-forwarding: true # 禁用 ICMP 转发,防止某些情况下的 ICMP 环回问题,ping 将不会显示真实的延迟
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; only effective on mips
# 入口配置与 Listener 等价,传入流量将和 socks,mixed 等入口一样按照 mode 所指定的方式进行匹配处理
# shadowsocks,vmess 入口配置(传入流量将和 socks,mixed 等入口一样按照 mode 所指定的方式进行匹配处理)
# ss-config: ss://2022-blake3-aes-256-gcm:vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg=@:23456
+22 -22
View File
@@ -6,47 +6,48 @@ require (
github.com/bahlo/generic-list-go v0.2.0
github.com/coreos/go-iptables v0.8.0
github.com/dlclark/regexp2 v1.12.0
github.com/enfein/mieru/v3 v3.35.0
github.com/easytier/easytier/easytier-go v0.0.0-20261111015056-2abb1676b475
github.com/enfein/mieru/v3 v3.39.0
github.com/gobwas/ws v1.4.0
github.com/gofrs/uuid/v5 v5.4.0
github.com/golang/snappy v1.0.0
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78
github.com/metacubex/amneziawg-go v0.0.0-20260816073447-736a78668832
github.com/metacubex/amneziawg-go v0.0.0-20260908071407-0c1c6f40ecd7
github.com/metacubex/bart v0.29.0
github.com/metacubex/bbolt v0.0.0-20260706163408-d4ec34ad7c48
github.com/metacubex/blake3 v0.1.0
github.com/metacubex/chacha v0.1.5
github.com/metacubex/chi v0.1.1
github.com/metacubex/connect-ip-go v0.0.0-20260727083417-67ccdb0cf771
github.com/metacubex/cpu v0.1.1
github.com/metacubex/cpu v0.1.2
github.com/metacubex/edwards25519 v1.2.0
github.com/metacubex/fswatch v0.1.1
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759
github.com/metacubex/http v0.1.7
github.com/metacubex/http v0.1.8
github.com/metacubex/jls-quic-go v0.0.0-20260727080412-732f2fc9a34d
github.com/metacubex/jls-tls v0.0.0-20260723084315-67adc0e2f796
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604
github.com/metacubex/mhurl v0.1.0
github.com/metacubex/mipstack v0.0.0-20260816065001-b7038299fe13
github.com/metacubex/mipstack v0.0.0-20261019124225-9a80a07eaeb9
github.com/metacubex/mlkem v0.1.0
github.com/metacubex/quic-go v0.61.1-0.20260727080200-2548683b76f4
github.com/metacubex/randv2 v0.2.0
github.com/metacubex/restls-client-go v0.1.9
github.com/metacubex/sevenzip v1.6.4
github.com/metacubex/sing v0.5.7
github.com/metacubex/sing-mux v0.3.10
github.com/metacubex/sing-quic v0.0.0-20260726014900-38b0e9295f51
github.com/metacubex/sing-shadowsocks v0.2.12
github.com/metacubex/sing-shadowsocks2 v0.2.7
github.com/metacubex/sing-tun v0.4.22
github.com/metacubex/sing v0.5.9
github.com/metacubex/sing-mux v0.3.12
github.com/metacubex/sing-quic v0.0.0-20260904234848-1c242664697a
github.com/metacubex/sing-shadowsocks v0.2.14
github.com/metacubex/sing-shadowsocks2 v0.2.8
github.com/metacubex/sing-tun v0.4.29
github.com/metacubex/sing-vmess v0.2.5
github.com/metacubex/sing-wireguard v0.0.0-20260810013230-110eac03c3f0
github.com/metacubex/sing-wireguard v0.0.0-20261002050126-e5fa1a607406
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141
github.com/metacubex/ssh v0.1.0
github.com/metacubex/tailscale v0.0.0-20260807072706-a4fb5feabcbb
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c
github.com/metacubex/tls v0.1.8
github.com/metacubex/utls v1.8.7
github.com/metacubex/tailscale v0.0.0-20260821153257-ff0ecd818181
github.com/metacubex/tfo-go v0.0.0-20261026151606-08d83ec08c84
github.com/metacubex/tls v0.1.9
github.com/metacubex/utls v1.9.0-alpha.1
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f
github.com/metacubex/zerotier-go v0.0.0-20260813124750-13fa6f45da5f
github.com/mroth/weightedrand/v2 v2.1.0
@@ -54,13 +55,13 @@ require (
github.com/rasky/go-lzo v0.0.0-20200203143853-96a758eda86e
github.com/samber/lo v1.53.0
github.com/sirupsen/logrus v1.9.4
github.com/stretchr/testify v1.11.1
github.com/stretchr/testify v1.12.1
github.com/vmihailenco/msgpack/v5 v5.4.1
github.com/yosida95/uritemplate/v3 v3.0.2
gitlab.com/go-extension/aes-ccm v0.0.0-20230221065045-e58665ef23c7
go.uber.org/automaxprocs v1.6.0
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
gopkg.in/yaml.v3 v3.0.1
go.yaml.in/yaml/v3 v3.0.5
go4.org/netipx v0.0.0-20260823151212-3075585bcbeb
)
// lastest version compatible with golang1.20
@@ -87,7 +88,6 @@ require (
github.com/bodgit/plumbing v1.3.0 // indirect
github.com/bodgit/windows v1.0.1 // indirect
github.com/coder/websocket v1.8.12 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dunglas/httpsfv v1.0.2 // indirect
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 // indirect
github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 // indirect
@@ -110,19 +110,19 @@ require (
github.com/klauspost/reedsolomon v1.12.3 // indirect
github.com/mdlayher/socket v0.5.1 // indirect
github.com/metacubex/ascon v0.1.0 // indirect
github.com/metacubex/gvisor v0.0.0-20260810011720-3cc44cf9ac22 // indirect
github.com/metacubex/gvisor v0.0.0-20260922041103-e2cbcd6e7400 // indirect
github.com/metacubex/hkdf v0.1.0 // indirect
github.com/metacubex/hpke v0.1.0 // indirect
github.com/metacubex/jsonv2 v0.0.0-20260721082349-16b4998c8f89 // indirect
github.com/metacubex/nftables v0.0.0-20260426003805-208c2c1ba2cb // indirect
github.com/metacubex/qpack v0.6.0 // indirect
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260725073821-e61ab99cede2 // indirect
github.com/metacubex/wazero v0.0.0-20260628025728-9ae6bdcf2a7d // indirect
github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49 // indirect
github.com/mitchellh/go-ps v1.0.0 // indirect
github.com/oasisprotocol/deoxysii v0.0.0-20220228165953-2091330c22b7 // indirect
github.com/pierrec/lz4/v4 v4.1.27 // indirect
github.com/pires/go-proxyproto v0.8.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/safchain/ethtool v0.3.0 // indirect
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a // indirect
github.com/sina-ghaderi/poly1305 v0.0.0-20220724002748-c5926b03988b // indirect
+45 -43
View File
@@ -22,14 +22,15 @@ github.com/coder/websocket v1.8.12/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3C
github.com/coreos/go-iptables v0.8.0 h1:MPc2P89IhuVpLI7ETL/2tx3XZ61VeICZjYqDEgNsPRc=
github.com/coreos/go-iptables v0.8.0/go.mod h1:Qe8Bv2Xik5FyTXwgIbLAnv2sWSBmvWdFETJConOQ//Q=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8=
github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dunglas/httpsfv v1.0.2 h1:iERDp/YAfnojSDJ7PW3dj1AReJz4MrwbECSSE59JWL0=
github.com/dunglas/httpsfv v1.0.2/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg=
github.com/enfein/mieru/v3 v3.35.0 h1:AKQT6l9R6xcYaUocpfjqE/vWEvYMxpl+071bhfDXkMY=
github.com/enfein/mieru/v3 v3.35.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
github.com/easytier/easytier/easytier-go v0.0.0-20261111015056-2abb1676b475 h1:L5C1yfYJyzcX7lCWi6aEX8H/0gBKqnlGcVxaBfQVTY8=
github.com/easytier/easytier/easytier-go v0.0.0-20261111015056-2abb1676b475/go.mod h1:fCEi5+K2yt+sPDONSWO1uNpOifrwPgFGvm3J0YrFRvk=
github.com/enfein/mieru/v3 v3.39.0 h1:22WJN9i7I4FrY1cTAVp5KfKOFm4sWrXVOXhqf5fkdr8=
github.com/enfein/mieru/v3 v3.39.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 h1:kXYqH/sL8dS/FdoFjr12ePjnLPorPo2FsnrHNuXSDyo=
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358/go.mod h1:hkIFzoiIPZYxdFOOLyDho59b7SrDfo+w3h+yWdlg45I=
github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 h1:8j2RH289RJplhA6WfdaPqzg1MjH2K8wX5e0uhAxrw2g=
@@ -92,8 +93,8 @@ github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78 h1:LqWr0vb9zDNuQS+jJd4fnRYk/SEI7KJ7TDe/L4WFK48=
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78/go.mod h1:BTBG/iVY7rg3qq5WdVCg0GFk58CSvCDSbjy8I7kEx/c=
github.com/metacubex/amneziawg-go v0.0.0-20260816073447-736a78668832 h1:mAIVFc8Z9jziImzNl5bXUBVU2bTEmP2sXfosn/6YxPs=
github.com/metacubex/amneziawg-go v0.0.0-20260816073447-736a78668832/go.mod h1:MsM/5czONyXMJ3PRr5DbQ4O/BxzAnJWOIcJdLzW6qHY=
github.com/metacubex/amneziawg-go v0.0.0-20260908071407-0c1c6f40ecd7 h1:OJa/EzqUNScl8X4UCUfG5DDqRdEds89k2XwzBZrnqcE=
github.com/metacubex/amneziawg-go v0.0.0-20260908071407-0c1c6f40ecd7/go.mod h1:MsM/5czONyXMJ3PRr5DbQ4O/BxzAnJWOIcJdLzW6qHY=
github.com/metacubex/ascon v0.1.0 h1:6ZWxmXYszT1XXtwkf6nxfFhc/OTtQ9R3Vyj1jN32lGM=
github.com/metacubex/ascon v0.1.0/go.mod h1:eV5oim4cVPPdEL8/EYaTZ0iIKARH9pnhAK/fcT5Kacc=
github.com/metacubex/bart v0.29.0 h1:yVc/lLdDqn+7FShI0qUghStHl0/d3mn4EH/I5R5niKk=
@@ -108,22 +109,22 @@ github.com/metacubex/chi v0.1.1 h1:GajmCIXSIPAZNxqTTYpkCrkY9suBz9wjIdgPcoQ5K1A=
github.com/metacubex/chi v0.1.1/go.mod h1:/CvDXe8jZD/ecU8Y7fmS5XKLRR44UDmC6/IBkRIb6Z4=
github.com/metacubex/connect-ip-go v0.0.0-20260727083417-67ccdb0cf771 h1:nLGBvwQ2vmsD+gU/XWBQH3xaYCM3vQCJIqPfw3mc/L0=
github.com/metacubex/connect-ip-go v0.0.0-20260727083417-67ccdb0cf771/go.mod h1:9FjDcopUc+tgUva3dauAVzrYPHd0rant+zkvyECzkMg=
github.com/metacubex/cpu v0.1.1 h1:rRV5HGmeuGzjiKI3hYbL0dCd0qGwM7VUtk4ICXD06mI=
github.com/metacubex/cpu v0.1.1/go.mod h1:09VEt4dSRLR+bOA8l4w4NDuzGZ8n5dkMv7e8axgEeTU=
github.com/metacubex/cpu v0.1.2 h1:xJHPWLkGilSWm6vEvzz8Loe+UusODRkVnuXz96TWAZo=
github.com/metacubex/cpu v0.1.2/go.mod h1:09VEt4dSRLR+bOA8l4w4NDuzGZ8n5dkMv7e8axgEeTU=
github.com/metacubex/edwards25519 v1.2.0 h1:pIQZLBsjQgg3Nl/c86YYFEUAbL5qQRnPq4LrgIw0KK4=
github.com/metacubex/edwards25519 v1.2.0/go.mod h1:NCQF3J/Ki7382FJuokwsywEIIEI/gro/3smyXgQJsx0=
github.com/metacubex/fswatch v0.1.1 h1:jqU7C/v+g0qc2RUFgmAOPoVvfl2BXXUXEumn6oQuxhU=
github.com/metacubex/fswatch v0.1.1/go.mod h1:czrTT7Zlbz7vWft8RQu9Qqh+JoX+Nnb+UabuyN1YsgI=
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759 h1:cjd4biTvOzK9ubNCCkQ+ldc4YSH/rILn53l/xGBFHHI=
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759/go.mod h1:UHOv2xu+RIgLwpXca7TLrXleEd4oR3sPatW6IF8wU88=
github.com/metacubex/gvisor v0.0.0-20260810011720-3cc44cf9ac22 h1:C4d4/BA8WuQmJnSpjy0UN4vJvRMjU3133rxIYQgbPPs=
github.com/metacubex/gvisor v0.0.0-20260810011720-3cc44cf9ac22/go.mod h1:mBJW3UXUusd8ZYO5M6mig0uScIey9iIubgdIiQAk2ug=
github.com/metacubex/gvisor v0.0.0-20260922041103-e2cbcd6e7400 h1:r9YO+xZUWi+xQROzdYkKL2twoliSJh34vOHMVAqsaL8=
github.com/metacubex/gvisor v0.0.0-20260922041103-e2cbcd6e7400/go.mod h1:mBJW3UXUusd8ZYO5M6mig0uScIey9iIubgdIiQAk2ug=
github.com/metacubex/hkdf v0.1.0 h1:fPA6VzXK8cU1foc/TOmGCDmSa7pZbxlnqhl3RNsthaA=
github.com/metacubex/hkdf v0.1.0/go.mod h1:3seEfds3smgTAXqUGn+tgEJH3uXdsUjOiduG/2EtvZ4=
github.com/metacubex/hpke v0.1.0 h1:gu2jUNhraehWi0P/z5HX2md3d7L1FhPQE6/Q0E9r9xQ=
github.com/metacubex/hpke v0.1.0/go.mod h1:vfDm6gfgrwlXUxKDkWbcE44hXtmc1uxLDm2BcR11b3U=
github.com/metacubex/http v0.1.7 h1:dEaQmijUaR/2QKqgjBUmPZCRuh1zBfDqB6ZRNLwvbHg=
github.com/metacubex/http v0.1.7/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
github.com/metacubex/http v0.1.8 h1:d91onDan2ZXYE8W/uAy5oFmXHH2xi1L7LbGPV5EmCM0=
github.com/metacubex/http v0.1.8/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
github.com/metacubex/jls-quic-go v0.0.0-20260727080412-732f2fc9a34d h1:OF3TUGKdHRrRMp7nb0Pa72QYwKPol9NqSy2yTcP2Sog=
github.com/metacubex/jls-quic-go v0.0.0-20260727080412-732f2fc9a34d/go.mod h1:dH8StPlpZ7atSUuTnfTnRXvJK22nOtQVimNwQ9Gmk58=
github.com/metacubex/jls-tls v0.0.0-20260723084315-67adc0e2f796 h1:1iI4np/Dm1ztCfTW2LoN166O6n728HXMc11aIazYdps=
@@ -134,8 +135,8 @@ github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604 h1:hJwCVlE3ojViC3
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604/go.mod h1:lpmN3m269b3V5jFCWtffqBLS4U3QQoIid9ugtO+OhVc=
github.com/metacubex/mhurl v0.1.0 h1:ZdW4Zxe3j3uJ89gNytOazHu6kbHn5owutN/VfXOI8GE=
github.com/metacubex/mhurl v0.1.0/go.mod h1:2qpQImCbXoUs6GwJrjuEXKelPyoimsIXr07eNKZdS00=
github.com/metacubex/mipstack v0.0.0-20260816065001-b7038299fe13 h1:aOU4avd9u7uFivubzn+SjFmEDWAkGF+gvZ0ecEdeg64=
github.com/metacubex/mipstack v0.0.0-20260816065001-b7038299fe13/go.mod h1:+bbwALZI0pbi2auSG5A3ptdpV2DZ2eLObziXo+P7oj0=
github.com/metacubex/mipstack v0.0.0-20261019124225-9a80a07eaeb9 h1:/uFijgwBH3L7m/Ztfd+XpQjMmYgN74FjNTxperKhtdQ=
github.com/metacubex/mipstack v0.0.0-20261019124225-9a80a07eaeb9/go.mod h1:+bbwALZI0pbi2auSG5A3ptdpV2DZ2eLObziXo+P7oj0=
github.com/metacubex/mlkem v0.1.0 h1:wFClitonSFcmipzzQvax75beLQU+D7JuC+VK1RzSL8I=
github.com/metacubex/mlkem v0.1.0/go.mod h1:amhaXZVeYNShuy9BILcR7P0gbeo/QLZsnqCdL8U2PDQ=
github.com/metacubex/nftables v0.0.0-20260426003805-208c2c1ba2cb h1:wk6mHYPURSUvWcUv72gNP79oiylFsscBSDPJ6ieV6Iw=
@@ -152,36 +153,38 @@ github.com/metacubex/restls-client-go v0.1.9 h1:QmLKwVFuAjB6rL9lQNKj8CuwHqGMJjV3
github.com/metacubex/restls-client-go v0.1.9/go.mod h1:BN/U52vPw7j8VTSh2vleD/MnmVKCov84mS5VcjVHH4g=
github.com/metacubex/sevenzip v1.6.4 h1:OIL+DeOeSAbKNsjqxcYUMiarRmX6Kaxakb0GT7E9Oik=
github.com/metacubex/sevenzip v1.6.4/go.mod h1:FP3X9bzFKj9wPxifGN9B3w2fIEicMjzKYIGIhnu+1pw=
github.com/metacubex/sing v0.5.7 h1:8OC+fhKFSv/l9ehEhJRaZZAOuthfZo68SteBVLe8QqM=
github.com/metacubex/sing v0.5.7/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w=
github.com/metacubex/sing-mux v0.3.10 h1:r5CuZ/KuwFsEcRRwpLvzLncW4fDzNfmSEcBEWcy/+94=
github.com/metacubex/sing-mux v0.3.10/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
github.com/metacubex/sing-quic v0.0.0-20260726014900-38b0e9295f51 h1:FpQj1XfYBIm4LAml+LDjvnfjDs20cSDsFmgjThOqmks=
github.com/metacubex/sing-quic v0.0.0-20260726014900-38b0e9295f51/go.mod h1:6ayFGfzzBE85csgQkM3gf4neFq6s0losHlPRSxY+nuk=
github.com/metacubex/sing-shadowsocks v0.2.12 h1:Wqzo8bYXrK5aWqxu/TjlTnYZzAKtKsaFQBdr6IHFaBE=
github.com/metacubex/sing-shadowsocks v0.2.12/go.mod h1:2e5EIaw0rxKrm1YTRmiMnDulwbGxH9hAFlrwQLQMQkU=
github.com/metacubex/sing-shadowsocks2 v0.2.7 h1:hSuuc0YpsfiqYqt1o+fP4m34BQz4e6wVj3PPBVhor3A=
github.com/metacubex/sing-shadowsocks2 v0.2.7/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE=
github.com/metacubex/sing-tun v0.4.22 h1:6ARRJ2BIFD1u4r/DTMNcxaNuGyimfXEeUyD4iFJRaZs=
github.com/metacubex/sing-tun v0.4.22/go.mod h1:9T0SN+FHvzRrn7hgl2kmXy5v8xzzLKW1hITButIPAco=
github.com/metacubex/sing v0.5.9 h1:R4JVFIHnkbRsvvrZs/sYAdoZ9K/P6DqlD8ZoSQAejFs=
github.com/metacubex/sing v0.5.9/go.mod h1:ynXUNwUt4dfOFO805EWzw3ORmNWXoexziwn5XYCfsq8=
github.com/metacubex/sing-mux v0.3.12 h1:80jrJsGgRW7ZHpJCRpwJhG3yzT5muEHIWjaOsDJZ2wE=
github.com/metacubex/sing-mux v0.3.12/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
github.com/metacubex/sing-quic v0.0.0-20260904234848-1c242664697a h1:qZzQwtWDrPU1LXoMow0/iLHY3mb7uauS/mho8hYcenE=
github.com/metacubex/sing-quic v0.0.0-20260904234848-1c242664697a/go.mod h1:6ayFGfzzBE85csgQkM3gf4neFq6s0losHlPRSxY+nuk=
github.com/metacubex/sing-shadowsocks v0.2.14 h1:P9HUtAPRVa24sB0dHwwTUkaEu5V0A8FGXJ35zdNAbN4=
github.com/metacubex/sing-shadowsocks v0.2.14/go.mod h1:kUDOwF06u5/zSkwPQa0BSdYLa1a7XtGVFik1/VSTkN0=
github.com/metacubex/sing-shadowsocks2 v0.2.8 h1:6MoODu7BAcnwIC0w9muq+2LZVz01wWD07L5IRhOty9Q=
github.com/metacubex/sing-shadowsocks2 v0.2.8/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE=
github.com/metacubex/sing-tun v0.4.29 h1:KIULEuW0iFXxLegOgrW8orq5Sx4TCBBhwo6j8+CIFBs=
github.com/metacubex/sing-tun v0.4.29/go.mod h1:eCWMOzQLc804EJBORaOxUOHzqTjb8qbCnO2tbsQF1vA=
github.com/metacubex/sing-vmess v0.2.5 h1:m9Zt5I27lB9fmLMZfism9sH2LcnAfShZfwSkf6/KJoE=
github.com/metacubex/sing-vmess v0.2.5/go.mod h1:AwtlzUgf8COe9tRYAKqWZ+leDH7p5U98a0ZUpYehl8Q=
github.com/metacubex/sing-wireguard v0.0.0-20260810013230-110eac03c3f0 h1:4g/ObGTfHaY2zXcFjKOUO9aAFk+yFjxsZfUPQPG6J8c=
github.com/metacubex/sing-wireguard v0.0.0-20260810013230-110eac03c3f0/go.mod h1:H27NH3IgI4qk1Wj8kS9pneNMJYEuxFskcQfkfVW9vnw=
github.com/metacubex/sing-wireguard v0.0.0-20261002050126-e5fa1a607406 h1:sronRtbNXPCT9sOpcsISq87w4mLufxP7mQFUEg+zUCY=
github.com/metacubex/sing-wireguard v0.0.0-20261002050126-e5fa1a607406/go.mod h1:OiYj4hitKrN1YIrgGHXp6zKnc9asCspF+SrYlLN2hYQ=
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141 h1:DK2l6m2Fc85H2BhiAPgbJygiWhesPlfGmF+9Vw6ARdk=
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141/go.mod h1:/yI4OiGOSn0SURhZdJF3CbtPg3nwK700bG8TZLMBvAg=
github.com/metacubex/ssh v0.1.0 h1:iGfr99qk/eMHzUnQ/0bTxXT8+8SWqLSHBWDHoAhngzw=
github.com/metacubex/ssh v0.1.0/go.mod h1:NUtl0d+/f2cG9ECEpMM8iCVOpmggQlC13oLeDUONDlU=
github.com/metacubex/tailscale v0.0.0-20260807072706-a4fb5feabcbb h1:EE4+ehlygfki5qJvkIYs6zJXhv7WFAX+4cDQi/b6cY8=
github.com/metacubex/tailscale v0.0.0-20260807072706-a4fb5feabcbb/go.mod h1:fMMYScJPYt8Ss3D4VhontA2uV2N9NPZbbXsPP6LgQeo=
github.com/metacubex/tailscale v0.0.0-20260821153257-ff0ecd818181 h1:hWsSSzuCHe+WvPV1zhoJ8gXTXbp/5nhpPKxtpqgIXu0=
github.com/metacubex/tailscale v0.0.0-20260821153257-ff0ecd818181/go.mod h1:fMMYScJPYt8Ss3D4VhontA2uV2N9NPZbbXsPP6LgQeo=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260725073821-e61ab99cede2 h1:nKyLVJEU4jsLVx+rdqbDUbEKTX/Sdu161AeVoZC9tlY=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260725073821-e61ab99cede2/go.mod h1:W00EeoPdd2jbV3+ZUa0m2b7FdKx5B1LFsXvEpy7cToQ=
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c h1:+2C1UshSLzaogLY/IDz1XhOLxjhs3rkhVHB4eCN9Zto=
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c/go.mod h1:l9oLnLoEXyGZ5RVLsh7QCC5XsouTUyKk4F2nLm2DHLw=
github.com/metacubex/tls v0.1.8 h1:BHF2payjtxC7wdR3tnq8vl3FAgEQB6/pPjP2tJNTsP4=
github.com/metacubex/tls v0.1.8/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
github.com/metacubex/utls v1.8.7 h1:Cp+yWkNTFkSihETgGWq34hlVFds5HpYWVOR1xovUVTs=
github.com/metacubex/utls v1.8.7/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
github.com/metacubex/tfo-go v0.0.0-20261026151606-08d83ec08c84 h1:mWjqcMU28lJ1+J9lkk/INJ1TIJbYvtarrsYiLlmEo48=
github.com/metacubex/tfo-go v0.0.0-20261026151606-08d83ec08c84/go.mod h1:l9oLnLoEXyGZ5RVLsh7QCC5XsouTUyKk4F2nLm2DHLw=
github.com/metacubex/tls v0.1.9 h1:pcHJSwFeHNswF96Z5RQW+j5cmwI2AYPdsNumK6JJSls=
github.com/metacubex/tls v0.1.9/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
github.com/metacubex/utls v1.9.0-alpha.1 h1:0tE4Pi5eoGnhEvS+ZZvVhEpZh5Ugo2nDQM+69g4SFaM=
github.com/metacubex/utls v1.9.0-alpha.1/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
github.com/metacubex/wazero v0.0.0-20260628025728-9ae6bdcf2a7d h1:UMFI+kdp0jA8s9tC7oul0pWeTW6s8lnm0dD5PT+RY14=
github.com/metacubex/wazero v0.0.0-20260628025728-9ae6bdcf2a7d/go.mod h1:p48xp436h1oGfoXuEnVONeDhTW+E2UpY94GAVxA62oI=
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f h1:FGBPRb1zUabhPhDrlKEjQ9lgIwQ6cHL4x8M9lrERhbk=
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f/go.mod h1:oPGcV994OGJedmmxrcK9+ni7jUEMGhR+uVQAdaduIP4=
github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49 h1:lhlqpYHopuTLx9xQt22kSA9HtnyTDmk5XjjQVCGHe2E=
@@ -209,7 +212,6 @@ github.com/pierrec/lz4/v4 v4.1.27/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcR
github.com/pires/go-proxyproto v0.8.0 h1:5unRmEAPbHXHuLjDg01CxJWf91cw3lKHc/0xzKpXEe0=
github.com/pires/go-proxyproto v0.8.0/go.mod h1:iknsfgnH8EkjrMeMyvfKByp9TiBZCKZM0jx2xmKqnVY=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g=
github.com/rasky/go-lzo v0.0.0-20200203143853-96a758eda86e h1:dCWirM5F3wMY+cmRda/B1BiPsFtmzXqV9b0hLWtVBMs=
@@ -234,15 +236,15 @@ github.com/stangelandcl/ppmd v0.1.1/go.mod h1:Rrv7M+/2P5jYr/GMLhBl7Ug3uJ1bUiVzr5
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d h1:JcGKBZAL7ePLwOhUdN8qGQZlP5GueEiIZwY7R62pejE=
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d/go.mod h1:XrBNfAFN+pwoWuksbFS9Ccxnopa15zJGgXRFN90l3K4=
github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 h1:Gzfnfk2TWrk8Jj4P4c1a3CtQyMaTVCznlkLZI++hok4=
@@ -278,10 +280,12 @@ gitlab.com/yawning/bsaes.git v0.0.0-20190805113838-0a714cd429ec/go.mod h1:BZ1RAo
go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs=
go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8=
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
go4.org/mem v0.0.0-20240501181205-ae6ca9944745 h1:Tl++JLUCe4sxGu8cTpDzRLd3tN7US4hOxG5YpKCzkek=
go4.org/mem v0.0.0-20240501181205-ae6ca9944745/go.mod h1:reUoABIJ9ikfM5sgtSF3Wushcza7+WeD01VB9Lirh3g=
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M=
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
go4.org/netipx v0.0.0-20260823151212-3075585bcbeb h1:XBM4hvfwGAttkkiTIFfeigdfcL1xIfdKXqFdgiHGtDs=
go4.org/netipx v0.0.0-20260823151212-3075585bcbeb/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
@@ -322,8 +326,6 @@ golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24=
golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
software.sslmate.com/src/go-pkcs12 v0.4.0 h1:H2g08FrTvSFKUj+D309j1DPfk5APnIdAQAB8aEykJ5k=
+8 -7
View File
@@ -265,13 +265,14 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
CacheMaxSize: c.CacheMaxSize,
})
m := dns.NewEnhancer(dns.EnhancerConfig{
IPv6: ipv6,
EnhancedMode: c.EnhancedMode,
FakeIPPool: c.FakeIPPool,
FakeIPPool6: c.FakeIPPool6,
FakeIPSkipper: c.FakeIPSkipper,
FakeIPTTL: c.FakeIPTTL,
UseHosts: c.UseHosts,
IPv6: ipv6,
EnhancedMode: c.EnhancedMode,
FakeIPPool: c.FakeIPPool,
FakeIPPool6: c.FakeIPPool6,
FakeIPSkipper: c.FakeIPSkipper,
FakeIPTTL: c.FakeIPTTL,
UseHosts: c.UseHosts,
FakeIPDisableMapping: c.FakeIPDisableMapping,
})
// reuse cache of old host mapper
+14
View File
@@ -63,6 +63,7 @@ type tunSchema struct {
Enable bool `yaml:"enable" json:"enable"`
Device *string `yaml:"device" json:"device"`
Stack *C.TUNStack `yaml:"stack" json:"stack"`
DNSMode *string `yaml:"dns-mode" json:"dns-mode,omitempty"`
DNSHijack *[]string `yaml:"dns-hijack" json:"dns-hijack"`
AutoRoute *bool `yaml:"auto-route" json:"auto-route"`
AutoDetectInterface *bool `yaml:"auto-detect-interface" json:"auto-detect-interface"`
@@ -98,6 +99,7 @@ type tunSchema struct {
EndpointIndependentNat *bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
UDPTimeout *int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
ICMPTimeout *int64 `yaml:"icmp-timeout" json:"icmp-timeout,omitempty"`
CongestionController *string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
FileDescriptor *int `yaml:"file-descriptor" json:"file-descriptor"`
Inet4RouteAddress *[]netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
@@ -108,6 +110,9 @@ type tunSchema struct {
// darwin special config
RecvMsgX *bool `yaml:"recvmsgx" json:"recvmsgx,omitempty"`
SendMsgX *bool `yaml:"sendmsgx" json:"sendmsgx,omitempty"`
// gvisor special config (Non-public option; do not include it in the document.)
ProcessorsPerChannel *int `yaml:"processors-per-channel" json:"processors-per-channel,omitempty"`
}
type tuicServerSchema struct {
@@ -147,6 +152,9 @@ func pointerOrDefaultTun(p *tunSchema, def LC.Tun) LC.Tun {
if p.Stack != nil {
def.Stack = *p.Stack
}
if p.DNSMode != nil {
def.DNSMode = *p.DNSMode
}
if p.DNSHijack != nil {
def.DNSHijack = *p.DNSHijack
}
@@ -261,6 +269,9 @@ func pointerOrDefaultTun(p *tunSchema, def LC.Tun) LC.Tun {
if p.ICMPTimeout != nil {
def.ICMPTimeout = *p.ICMPTimeout
}
if p.CongestionController != nil {
def.CongestionController = *p.CongestionController
}
if p.FileDescriptor != nil {
def.FileDescriptor = *p.FileDescriptor
}
@@ -270,6 +281,9 @@ func pointerOrDefaultTun(p *tunSchema, def LC.Tun) LC.Tun {
if p.SendMsgX != nil {
def.SendMsgX = *p.SendMsgX
}
if p.ProcessorsPerChannel != nil {
def.ProcessorsPerChannel = *p.ProcessorsPerChannel
}
}
return def
}
+1
View File
@@ -10,6 +10,7 @@ type ShadowsocksServer struct {
Enable bool
Listen string
Password string
Users map[string]string `yaml:"users" json:"users,omitempty"`
Cipher string
Udp bool
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
+1
View File
@@ -6,6 +6,7 @@ type SnellServer struct {
Listen string
Psk string
Version int
Mode string // v6 only: default / unshaped / unsafe-raw
UDP bool
ObfsMode string
ObfsHost string
+15
View File
@@ -13,6 +13,7 @@ type Tun struct {
Enable bool `yaml:"enable" json:"enable"`
Device string `yaml:"device" json:"device"`
Stack C.TUNStack `yaml:"stack" json:"stack"`
DNSMode string `yaml:"dns-mode" json:"dns-mode"`
DNSHijack []string `yaml:"dns-hijack" json:"dns-hijack"`
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
AutoDetectInterface bool `yaml:"auto-detect-interface" json:"auto-detect-interface"`
@@ -53,6 +54,7 @@ type Tun struct {
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
ICMPTimeout int64 `yaml:"icmp-timeout" json:"icmp-timeout,omitempty"`
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
@@ -63,6 +65,9 @@ type Tun struct {
// darwin special config
RecvMsgX bool `yaml:"recvmsgx" json:"recvmsgx,omitempty"`
SendMsgX bool `yaml:"sendmsgx" json:"sendmsgx,omitempty"`
// gvisor special config (Non-public option; do not include it in the document.)
ProcessorsPerChannel int `yaml:"processors-per-channel" json:"processors-per-channel,omitempty"`
}
func (t *Tun) Sort() {
@@ -102,6 +107,9 @@ func (t *Tun) Equal(other Tun) bool {
if t.Stack != other.Stack {
return false
}
if t.DNSMode != other.DNSMode {
return false
}
if !slices.Equal(t.DNSHijack, other.DNSHijack) {
return false
}
@@ -208,6 +216,9 @@ func (t *Tun) Equal(other Tun) bool {
if t.DisableICMPForwarding != other.DisableICMPForwarding {
return false
}
if t.CongestionController != other.CongestionController {
return false
}
if t.FileDescriptor != other.FileDescriptor {
return false
}
@@ -232,5 +243,9 @@ func (t *Tun) Equal(other Tun) bool {
return false
}
if t.ProcessorsPerChannel != other.ProcessorsPerChannel {
return false
}
return true
}
+15 -8
View File
@@ -2,6 +2,7 @@ package inbound
import (
"fmt"
"strconv"
"sync"
"github.com/metacubex/mihomo/adapter/inbound"
@@ -25,10 +26,11 @@ type Mieru struct {
type MieruOption struct {
BaseOption
Transport string `inbound:"transport"`
Users map[string]string `inbound:"users"`
TrafficPattern string `inbound:"traffic-pattern,omitempty"`
UserHintIsMandatory bool `inbound:"user-hint-is-mandatory,omitempty"`
Transport string `inbound:"transport"`
Users map[string]string `inbound:"users"`
TrafficPattern string `inbound:"traffic-pattern,omitempty"`
UserHintIsMandatory bool `inbound:"user-hint-is-mandatory,omitempty"`
TCPIdleTimeoutSecond int `inbound:"tcp-idle-timeout,omitempty"`
}
func NewMieru(option *MieruOption) (*Mieru, error) {
@@ -147,15 +149,17 @@ func buildMieruServerConfig(option *MieruOption, ports utils.IntRanges[uint16])
}
var trafficPattern *mierupb.TrafficPattern
trafficPattern, _ = mierutp.Decode(option.TrafficPattern)
var advancedSettings *mierupb.ServerAdvancedSettings
advancedSettings := &mierupb.ServerAdvancedSettings{}
if option.UserHintIsMandatory {
advancedSettings = &mierupb.ServerAdvancedSettings{
UserHintIsMandatory: proto.Bool(true),
}
advancedSettings.UserHintIsMandatory = proto.Bool(true)
}
if option.TCPIdleTimeoutSecond != 0 {
advancedSettings.TcpIdleTimeout = proto.String(strconv.Itoa(option.TCPIdleTimeoutSecond) + "s")
}
lc := option.ListenConfig()
return &mieruserver.ServerConfig{
Config: &mierupb.ServerConfig{
ListenIPAddress: proto.String(option.Listen),
PortBindings: portBindings,
Users: users,
TrafficPattern: trafficPattern,
@@ -190,5 +194,8 @@ func validateMieruOption(option *MieruOption) error {
return fmt.Errorf("invalid traffic pattern %q: %w", option.TrafficPattern, err)
}
}
if option.TCPIdleTimeoutSecond != 0 && option.TCPIdleTimeoutSecond < 60 {
return fmt.Errorf("invalid TCP idle timeout: mininum supported value is 60")
}
return nil
}
+30
View File
@@ -74,6 +74,20 @@ func TestNewMieru(t *testing.T) {
},
wantErr: false,
},
{
name: "valid TCP idle timeout",
args: args{
option: &inbound.MieruOption{
BaseOption: inbound.BaseOption{
Port: "8080",
},
Transport: "TCP",
Users: map[string]string{"user": "pass"},
TCPIdleTimeoutSecond: 60,
},
},
wantErr: false,
},
{
name: "invalid - no port",
args: args{
@@ -162,6 +176,20 @@ func TestNewMieru(t *testing.T) {
},
wantErr: true,
},
{
name: "invalid TCP idle timeout",
args: args{
option: &inbound.MieruOption{
BaseOption: inbound.BaseOption{
Port: "8080",
},
Transport: "TCP",
Users: map[string]string{"user": "pass"},
TCPIdleTimeoutSecond: 10,
},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -203,6 +231,7 @@ func testInboundMieruTCP(t *testing.T, handshakeMode string) {
defer l.Close()
lc := mieruTestInboundListenConfig{
ListenFn: func(ctx context.Context, network, address string) (net.Listener, error) {
assert.Equal(t, l.Addr().String(), address)
return l, nil
},
ListenPacketFn: func(ctx context.Context, network, address string) (net.PacketConn, error) {
@@ -273,6 +302,7 @@ func testInboundMieruUDP(t *testing.T, handshakeMode string) {
panic("should not be called")
},
ListenPacketFn: func(ctx context.Context, network, address string) (net.PacketConn, error) {
assert.Equal(t, l.LocalAddr().String(), address)
return l, nil
},
}
+15 -9
View File
@@ -1,6 +1,7 @@
package inbound
import (
"errors"
"strings"
C "github.com/metacubex/mihomo/constant"
@@ -11,15 +12,16 @@ import (
type ShadowSocksOption struct {
BaseOption
Password string `inbound:"password"`
Cipher string `inbound:"cipher"`
UDP bool `inbound:"udp,omitempty"`
MuxOption MuxOption `inbound:"mux-option,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
ResTLS ResTLS `inbound:"res-tls,omitempty"`
JLSConfig JLSConfig `inbound:"jls-config,omitempty"`
KcpTun KcpTun `inbound:"kcp-tun,omitempty"`
SimpleObfs SimpleObfs `inbound:"simple-obfs,omitempty"`
Password string `inbound:"password,omitempty"`
Users map[string]string `inbound:"users,omitempty"`
Cipher string `inbound:"cipher"`
UDP bool `inbound:"udp,omitempty"`
MuxOption MuxOption `inbound:"mux-option,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
ResTLS ResTLS `inbound:"res-tls,omitempty"`
JLSConfig JLSConfig `inbound:"jls-config,omitempty"`
KcpTun KcpTun `inbound:"kcp-tun,omitempty"`
SimpleObfs SimpleObfs `inbound:"simple-obfs,omitempty"`
}
type SimpleObfs struct {
@@ -50,6 +52,9 @@ func NewShadowSocks(options *ShadowSocksOption) (*ShadowSocks, error) {
if err != nil {
return nil, err
}
if options.Password == "" && len(options.Users) == 0 {
return nil, errors.New("shadowsocks: missing password")
}
return &ShadowSocks{
Base: base,
config: options,
@@ -57,6 +62,7 @@ func NewShadowSocks(options *ShadowSocksOption) (*ShadowSocks, error) {
Enable: true,
Listen: base.RawAddress(),
Password: options.Password,
Users: options.Users,
Cipher: options.Cipher,
Udp: options.UDP,
MuxOption: options.MuxOption.Build(),
+184
View File
@@ -1,14 +1,19 @@
package inbound_test
import (
"context"
"crypto/rand"
"encoding/base64"
"net"
"net/netip"
"strings"
"sync"
"testing"
"time"
"github.com/metacubex/mihomo/adapter/outbound"
"github.com/metacubex/mihomo/component/generator"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/listener/inbound"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/kcptun"
@@ -249,6 +254,185 @@ func TestInboundShadowSocks_SimpleObfs_Tls(t *testing.T) {
testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherShortLists, false)
}
var shadowsocksMultiUserCipherList = append(append([]string{}, shadowaead.List...),
"2022-blake3-aes-128-gcm",
"2022-blake3-aes-256-gcm",
"2022-blake3-aes-128-ccm",
"2022-blake3-aes-256-ccm",
)
func TestInboundShadowSocks_MultiUsers(t *testing.T) {
t.Parallel()
t.Run("InvalidConfigs", func(t *testing.T) {
t.Parallel()
tests := []struct {
name string
cipher string
password string
users map[string]string
}{
{"None", shadowsocks.MethodNone, "", map[string]string{"user1": "password"}},
{"Stream", shadowstream.List[0], "", map[string]string{"user1": "password"}},
{"2022Chacha20", "2022-blake3-chacha20-poly1305", shadowsocksPassword32, map[string]string{"user1": shadowsocksPassword32}},
{"2022MissingServerPassword", "2022-blake3-aes-128-gcm", "", map[string]string{"user1": shadowsocksPassword16}},
{"2022ShortUserKey", "2022-blake3-aes-256-gcm", shadowsocksPassword32, map[string]string{"user1": shadowsocksPassword16}},
{"AEADWithPassword", "aes-128-gcm", "password", map[string]string{"user1": "password1"}},
{"AEADEmptyUserPassword", "aes-128-gcm", "", map[string]string{"user1": ""}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
in, err := inbound.NewShadowSocks(&inbound.ShadowSocksOption{
BaseOption: inbound.BaseOption{
NameStr: "shadowsocks_inbound",
Listen: "127.0.0.1",
Port: "0",
},
Password: test.password,
Users: test.users,
Cipher: test.cipher,
})
if !assert.NoError(t, err) {
return
}
err = in.Listen(nil)
if !assert.Error(t, err) {
_ = in.Close()
}
})
}
})
for _, cipher := range shadowsocksMultiUserCipherList {
cipher := cipher
t.Run(cipher, func(t *testing.T) {
t.Parallel()
newShadowSocksKey := func(cipher string) string {
bits := 256
if strings.Contains(cipher, "-128-") {
bits = 128
}
key, err := generator.GenShadowsocksPassword(bits)
if err != nil {
panic(err)
}
return key
}
is2022 := strings.HasPrefix(cipher, "2022-")
var serverPassword string
if is2022 {
serverPassword = newShadowSocksKey(cipher)
}
users := map[string]string{
"user1": newShadowSocksKey(cipher),
"user2": newShadowSocksKey(cipher),
}
inboundOptions := inbound.ShadowSocksOption{
BaseOption: inbound.BaseOption{
NameStr: "shadowsocks_inbound",
Listen: "127.0.0.1",
Port: "0",
},
Password: serverPassword,
Users: users,
Cipher: cipher,
}
in, err := inbound.NewShadowSocks(&inboundOptions)
if !assert.NoError(t, err) {
return
}
tunnel := NewHttpTestTunnel()
defer tunnel.Close()
var inUsers []string
var inUsersMu sync.Mutex
handleTCPConn := tunnel.HandleTCPConnFn
tunnel.HandleTCPConnFn = func(conn net.Conn, metadata *C.Metadata) {
inUsersMu.Lock()
inUsers = append(inUsers, metadata.InUser)
inUsersMu.Unlock()
handleTCPConn(conn, metadata)
}
takeInUsers := func() []string {
inUsersMu.Lock()
defer inUsersMu.Unlock()
users := inUsers
inUsers = nil
return users
}
err = in.Listen(tunnel)
if !assert.NoError(t, err) {
return
}
defer in.Close()
addrPort, err := netip.ParseAddrPort(in.Address())
if !assert.NoError(t, err) {
return
}
newOutbound := func(password string) (*outbound.ShadowSocks, error) {
if is2022 {
password = serverPassword + ":" + password
}
outboundOptions := outbound.ShadowSocksOption{
Name: "shadowsocks_outbound",
Server: addrPort.Addr().String(),
Port: int(addrPort.Port()),
Password: password,
Cipher: cipher,
}
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
return outbound.NewShadowSocks(outboundOptions)
}
for username, password := range users {
username, password := username, password
t.Run(username, func(t *testing.T) {
out, err := newOutbound(password)
if !assert.NoError(t, err) {
return
}
defer out.Close()
tunnel.DoTest(t, out)
inUsers := takeInUsers()
assert.NotEmpty(t, inUsers)
for _, inUser := range inUsers {
assert.Equal(t, username, inUser)
}
})
}
t.Run("UnknownUser", func(t *testing.T) {
out, err := newOutbound(newShadowSocksKey(cipher))
if !assert.NoError(t, err) {
return
}
defer out.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
conn, err := out.DialContext(ctx, &C.Metadata{NetWork: C.TCP, DstIP: remoteAddr, DstPort: 80})
if err == nil {
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
_, _ = conn.Write([]byte("GET / HTTP/1.1\r\nHost: 1.2.3.4\r\n\r\n"))
_, err = conn.Read(make([]byte, 1))
_ = conn.Close()
}
assert.Error(t, err)
assert.Empty(t, takeInUsers())
})
})
}
}
func TestInboundShadowSocks_KcpTun(t *testing.T) {
if winGo120 {
t.Skip("skip kcptun test on windows go1.20")
+3 -1
View File
@@ -14,6 +14,7 @@ type SnellOption struct {
BaseOption
Psk string `inbound:"psk"`
Version int `inbound:"version,omitempty"`
Mode string `inbound:"mode,omitempty"` // v6 only: default / unshaped / unsafe-raw
UDP bool `inbound:"udp,omitempty"`
ObfsOpts SnellObfsOption `inbound:"obfs-opts,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
@@ -45,7 +46,7 @@ func NewSnell(options *SnellOption) (*Snell, error) {
if options.Version == 0 {
options.Version = 4
}
if options.Version < 1 || options.Version > 5 {
if options.Version < 1 || options.Version > 6 {
return nil, fmt.Errorf("snell inbound version %d is not supported", options.Version)
}
@@ -56,6 +57,7 @@ func NewSnell(options *SnellOption) (*Snell, error) {
Listen: base.RawAddress(),
Psk: options.Psk,
Version: options.Version,
Mode: options.Mode,
UDP: options.UDP,
ObfsMode: options.ObfsOpts.Mode,
ObfsHost: options.ObfsOpts.Host,
+173
View File
@@ -1,11 +1,16 @@
package inbound_test
import (
"bytes"
"context"
"crypto/rand"
"net"
"net/netip"
"testing"
"time"
"github.com/metacubex/mihomo/adapter/outbound"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/listener/inbound"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/restls"
@@ -157,3 +162,171 @@ func TestInboundSnell_JLS(t *testing.T) {
}
testInboundSnellUTLS(t, inboundOptions, outboundOptions)
}
func TestInboundSnell_V6(t *testing.T) {
for _, mode := range []string{"default", "unshaped", "unsafe-raw"} {
mode := mode
t.Run(mode, func(t *testing.T) {
t.Parallel()
t.Run("TCP", func(t *testing.T) {
inboundOptions := inbound.SnellOption{Version: 6, Mode: mode}
outboundOptions := outbound.SnellOption{Version: 6, Mode: mode}
testInboundSnell(t, inboundOptions, outboundOptions)
})
t.Run("TCPReuse", func(t *testing.T) {
inboundOptions := inbound.SnellOption{Version: 6, Mode: mode}
outboundOptions := outbound.SnellOption{Version: 6, Mode: mode, Reuse: true}
testInboundSnell(t, inboundOptions, outboundOptions)
})
t.Run("UDP", func(t *testing.T) {
testInboundSnellV6UDP(t, mode)
})
})
}
}
func TestInboundSnell_V6_ShadowTlsv3(t *testing.T) {
inboundOptions := inbound.SnellOption{
Version: 6,
ShadowTLS: inbound.ShadowTLS{
Enable: true,
Version: 3,
Users: []inbound.ShadowTLSUser{{Name: "test", Password: shadowsocksPassword16}},
Handshake: inbound.ShadowTLSHandshakeOptions{Dest: net.JoinHostPort(realityDest, "443")},
},
}
outboundOptions := outbound.SnellOption{
Version: 6,
ObfsOpts: map[string]any{"mode": shadowtls.Mode, "host": realityDest, "password": shadowsocksPassword16, "fingerprint": tlsFingerprint, "version": 3},
}
testInboundSnellUTLS(t, inboundOptions, outboundOptions)
}
// testInboundSnellV6UDP runs a UDP-over-TCP echo through the v6 inbound: the
// test tunnel reflects every datagram back to the source it came from.
func testInboundSnellV6UDP(t *testing.T, mode string) {
t.Parallel()
inboundOptions := inbound.SnellOption{
BaseOption: inbound.BaseOption{
NameStr: "snell_inbound_udp",
Listen: "127.0.0.1",
Port: "0",
},
Psk: userUUID,
Version: 6,
Mode: mode,
UDP: true,
}
in, err := inbound.NewSnell(&inboundOptions)
if !assert.NoError(t, err) {
return
}
tunnel := NewHttpTestTunnel()
defer tunnel.Close()
tunnel.HandleUDPPacketFn = func(packet C.UDPPacket, metadata *C.Metadata) {
defer packet.Drop()
if !assert.Equal(t, C.SNELL, metadata.Type) {
return
}
_, err := packet.WriteBack(packet.Data(), metadata.UDPAddr())
assert.NoError(t, err)
}
err = in.Listen(tunnel)
if !assert.NoError(t, err) {
return
}
defer in.Close()
addrPort, err := netip.ParseAddrPort(in.Address())
if !assert.NoError(t, err) {
return
}
outboundOptions := outbound.SnellOption{
Name: "snell_outbound_udp",
Server: addrPort.Addr().String(),
Port: int(addrPort.Port()),
Psk: userUUID,
Version: 6,
Mode: mode,
UDP: true,
}
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewSnell(outboundOptions)
if !assert.NoError(t, err) {
return
}
defer out.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
target := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 53}
pc, err := out.ListenPacketContext(ctx, &C.Metadata{
NetWork: C.UDP,
DstIP: netip.MustParseAddr("127.0.0.1"),
DstPort: 53,
})
if !assert.NoError(t, err) {
return
}
defer pc.Close()
for round := 0; round < 5; round++ {
message := make([]byte, 1200)
_, err = rand.Read(message)
if !assert.NoError(t, err) {
return
}
_, err = pc.WriteTo(message, target)
if !assert.NoError(t, err) {
return
}
received := make([]byte, 2048)
if !assert.NoError(t, pc.SetReadDeadline(time.Now().Add(10*time.Second))) {
return
}
n, from, err := pc.ReadFrom(received)
if !assert.NoError(t, err, "round %d", round) {
return
}
assert.Equal(t, target.String(), from.String())
assert.True(t, bytes.Equal(message, received[:n]), "round %d payload mismatch", round)
}
}
func TestInboundSnell_V6_Validation(t *testing.T) {
t.Parallel()
newInbound := func(options inbound.SnellOption) error {
options.BaseOption = inbound.BaseOption{
NameStr: "snell_inbound_validation",
Listen: "127.0.0.1",
Port: "0",
}
if options.Psk == "" {
options.Psk = userUUID
}
in, err := inbound.NewSnell(&options)
if err != nil {
return err
}
tunnel := NewHttpTestTunnel()
defer tunnel.Close()
err = in.Listen(tunnel)
if err == nil {
_ = in.Close()
}
return err
}
assert.Error(t, newInbound(inbound.SnellOption{Version: 6, Psk: "short"}), "psk shorter than 12 bytes must be rejected")
assert.Error(t, newInbound(inbound.SnellOption{Version: 6, ObfsOpts: inbound.SnellObfsOption{Mode: "http"}}), "v6 has no simple-obfs layer")
assert.Error(t, newInbound(inbound.SnellOption{Version: 6, ObfsOpts: inbound.SnellObfsOption{Mode: "tls"}}), "v6 has no simple-obfs layer")
assert.Error(t, newInbound(inbound.SnellOption{Version: 6, Mode: "bogus"}), "unknown mode must be rejected")
assert.Error(t, newInbound(inbound.SnellOption{Version: 4, Mode: "unshaped"}), "mode is v6 only")
assert.Error(t, newInbound(inbound.SnellOption{Version: 7}), "unknown version must be rejected")
assert.NoError(t, newInbound(inbound.SnellOption{Version: 6, Mode: "unshaped"}))
}
+9
View File
@@ -14,6 +14,7 @@ type TunOption struct {
BaseOption
Device string `inbound:"device,omitempty"`
Stack C.TUNStack `inbound:"stack,omitempty"`
DNSMode string `inbound:"dns-mode,omitempty"`
DNSHijack []string `inbound:"dns-hijack,omitempty"`
AutoRoute bool `inbound:"auto-route,omitempty"`
AutoDetectInterface bool `inbound:"auto-detect-interface,omitempty"`
@@ -54,6 +55,7 @@ type TunOption struct {
UDPTimeout int64 `inbound:"udp-timeout,omitempty"`
ICMPTimeout int64 `inbound:"icmp-timeout,omitempty"`
DisableICMPForwarding bool `inbound:"disable-icmp-forwarding,omitempty"`
CongestionController string `inbound:"congestion-controller,omitempty"`
FileDescriptor int `inbound:"file-descriptor,omitempty"`
Inet4RouteAddress []netip.Prefix `inbound:"inet4-route-address,omitempty"`
@@ -64,6 +66,9 @@ type TunOption struct {
// darwin special config
RecvMsgX bool `inbound:"recvmsgx,omitempty"`
SendMsgX bool `inbound:"sendmsgx,omitempty"`
// gvisor special config (Non-public option; do not include it in the document.)
ProcessorsPerChannel int `inbound:"processors-per-channel,omitempty"`
}
var _ encoding.TextUnmarshaler = (*netip.Addr)(nil) // ensure netip.Addr can decode direct by structure package
@@ -93,6 +98,7 @@ func NewTun(options *TunOption) (*Tun, error) {
Enable: true,
Device: options.Device,
Stack: options.Stack,
DNSMode: options.DNSMode,
DNSHijack: options.DNSHijack,
AutoRoute: options.AutoRoute,
AutoDetectInterface: options.AutoDetectInterface,
@@ -132,6 +138,7 @@ func NewTun(options *TunOption) (*Tun, error) {
UDPTimeout: options.UDPTimeout,
ICMPTimeout: options.ICMPTimeout,
DisableICMPForwarding: options.DisableICMPForwarding,
CongestionController: options.CongestionController,
FileDescriptor: options.FileDescriptor,
Inet4RouteAddress: options.Inet4RouteAddress,
@@ -141,6 +148,8 @@ func NewTun(options *TunOption) (*Tun, error) {
RecvMsgX: options.RecvMsgX,
SendMsgX: options.SendMsgX,
ProcessorsPerChannel: options.ProcessorsPerChannel,
},
}, nil
}
+4 -2
View File
@@ -29,7 +29,7 @@ func Handle(conn net.Conn, tunnel C.Tunnel, request *mierumodel.Request, additio
conn.Close()
return
}
user := conn.(mierucommon.UserContext).UserName()
// Handle the connection with tunnel.
switch request.Command {
case mieruconstant.Socks5ConnectCmd: // TCP
@@ -46,15 +46,17 @@ func Handle(conn net.Conn, tunnel C.Tunnel, request *mierumodel.Request, additio
}
inbound.ApplyAdditions(
metadata,
inbound.WithInName(conn.(mierucommon.UserContext).UserName()),
inbound.WithInUser(user),
inbound.WithSrcAddr(conn.RemoteAddr()),
inbound.WithInAddr(conn.LocalAddr()),
)
inbound.ApplyAdditions(metadata, additions...)
tunnel.HandleTCPConn(conn, metadata)
case mieruconstant.Socks5UDPAssociateCmd: // UDP
additions = append(additions, inbound.WithInUser(user))
pc := mierucommon.NewPacketOverStreamTunnel(conn)
ep := N.NewEnhancePacketConn(pc)
defer ep.Close()
for {
data, put, addr, err := ep.WaitReadFrom()
if err != nil {
+1 -1
View File
@@ -64,7 +64,7 @@ func ParseListener(mapping map[string]any) (C.InboundListener, error) {
listener, err = IN.NewTunnel(tunnelOption)
case "tun":
tunOption := &IN.TunOption{
Stack: C.TunGvisor,
Stack: C.TunMips,
DNSHijack: []string{"0.0.0.0:53"}, // default hijack all dns query
}
err = decoder.Decode(mapping, tunOption)
+1
View File
@@ -140,6 +140,7 @@ func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel,
}
func (l *Listener) Close() error {
l.closed = true
var retErr error
for _, lis := range l.listeners {
err := lis.Close()
+53 -1
View File
@@ -2,8 +2,10 @@ package sing_shadowsocks
import (
"context"
"errors"
"fmt"
"net"
"os"
"strings"
"github.com/metacubex/mihomo/adapter/inbound"
@@ -36,10 +38,16 @@ type Listener struct {
config LC.ShadowsocksServer
listeners []net.Listener
udpListeners []net.PacketConn
service shadowsocks.Service
service service
simpleObfs func(net.Conn) net.Conn
}
// service is the common part of shadowsocks.Service and shadowsocks.MultiService
type service interface {
network.TCPConnectionHandler
network.UDPHandler
}
var _listener *Listener
func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel, additions ...inbound.Addition) (C.MultiAddrListener, error) {
@@ -71,6 +79,8 @@ func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel,
sl.config = config
switch {
case len(config.Users) > 0:
sl.service, err = newMultiService(config, udpTimeout, h)
case config.Cipher == shadowsocks.MethodNone:
sl.service = shadowsocks.NewNoneService(udpTimeout, h)
case common.Contains(shadowaead.List, config.Cipher):
@@ -233,6 +243,48 @@ func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel,
return sl, nil
}
// newMultiService creates a service that identifies the user by its password,
// the matched username is passed to the tunnel as metadata.InUser.
//
// For 2022-blake3-aes-* methods, config.Password is the server PSK (iPSK) and each user password is
// the user PSK (uPSK), so the client password is "iPSK:uPSK".
// For legacy AEAD methods, each user password is used directly and config.Password must be empty.
// Legacy AEAD has no user identity in the packet, so every user is tried for each packet, which makes
// the cost grow linearly with the number of users.
func newMultiService(config LC.ShadowsocksServer, udpTimeout int64, handler shadowsocks.Handler) (service, error) {
var multiService shadowsocks.MultiService[string]
var err error
switch {
case common.Contains(shadowaead.List, config.Cipher):
if config.Password != "" {
return nil, fmt.Errorf("shadowsocks: password must be empty when users is set for method: %s", config.Cipher)
}
multiService, err = shadowaead.NewMultiService[string](config.Cipher, udpTimeout, handler)
case common.Contains(shadowaead_2022.List, config.Cipher):
multiService, err = shadowaead_2022.NewMultiServiceWithPassword[string](config.Cipher, config.Password, udpTimeout, handler, ntp.Now)
if errors.Is(err, os.ErrInvalid) { // 2022-blake3-chacha*-poly1305 can't identify users
err = fmt.Errorf("shadowsocks: users is not supported for method: %s", config.Cipher)
}
default:
err = fmt.Errorf("shadowsocks: users is not supported for method: %s", config.Cipher)
}
if err != nil {
return nil, err
}
userNameList := make([]string, 0, len(config.Users))
userPasswordList := make([]string, 0, len(config.Users))
for name, password := range config.Users {
userNameList = append(userNameList, name)
userPasswordList = append(userPasswordList, password)
}
err = multiService.UpdateUsersWithPasswords(userNameList, userPasswordList)
if err != nil {
return nil, err
}
return multiService, nil
}
func (l *Listener) Close() error {
l.closed = true
var retErr error
+12 -2
View File
@@ -274,6 +274,13 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
excludeMACAddress = append(excludeMACAddress, addr)
}
switch options.DNSMode {
case "", tun.DNSModeDisabled, tun.DNSModeNative, tun.DNSModeHijack:
default:
log.Warnln("[TUN] ignored invalid dns-mode: %s", options.DNSMode)
options.DNSMode = ""
}
var dnsAdds []netip.AddrPort
for _, d := range options.DNSHijack {
@@ -390,6 +397,7 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
GSO: options.GSO,
Inet4Address: options.Inet4Address,
Inet6Address: options.Inet6Address,
DNSMode: options.DNSMode,
AutoRoute: options.AutoRoute,
IPRoute2TableIndex: tableIndex,
IPRoute2RuleIndex: ruleIndex,
@@ -418,6 +426,7 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
InterfaceMonitor: defaultInterfaceMonitor,
EXP_RecvMsgX: options.RecvMsgX,
EXP_SendMsgX: options.SendMsgX,
EXP_ProcessorsPerChannel: options.ProcessorsPerChannel,
}
if options.AutoRedirect {
@@ -496,6 +505,7 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
Logger: log.SingLogger,
ForwarderBindInterface: forwarderBindInterface,
InterfaceFinder: interfaceFinder,
TCPCongestionControl: options.CongestionController,
EnforceBindInterface: EnforceBindInterface,
}
l.tunIf = tunIf
@@ -541,8 +551,8 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
if options.FileDescriptor != 0 {
tunName = fmt.Sprintf("%s(fd=%d)", tunName, options.FileDescriptor)
}
l.addrStr = fmt.Sprintf("%s(%s,%s), mtu: %d, auto route: %v, auto redir: %v, ip stack: %s",
tunName, tunOptions.Inet4Address, tunOptions.Inet6Address, tunMTU, options.AutoRoute, options.AutoRedirect, options.Stack)
l.addrStr = fmt.Sprintf("%s(%s,%s), mtu: %d, auto route: %v, auto redir: %v, ip stack: %s, dns mode: %s",
tunName, tunOptions.Inet4Address, tunOptions.Inet6Address, tunMTU, options.AutoRoute, options.AutoRedirect, options.Stack, options.DNSMode)
return
}
+5 -4
View File
@@ -74,10 +74,10 @@ func New(config LC.VlessServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
return nil, err
}
if sl.decryption != nil {
decryption := sl.decryption
defer func() { // decryption must be closed to avoid the goroutine leak
if err != nil {
_ = sl.decryption.Close()
sl.decryption = nil
_ = decryption.Close()
}
}()
}
@@ -328,11 +328,12 @@ func (l *Listener) AddrList() (addrList []net.Addr) {
func (l *Listener) HandleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
ctx := sing.WithAdditions(context.TODO(), additions...)
if l.decryption != nil {
var err error
conn, err = l.decryption.Handshake(conn, nil)
c, err := l.decryption.Handshake(conn, nil)
if err != nil {
_ = conn.Close()
return
}
conn = c
}
err := l.service.NewConnection(ctx, conn, metadata.Metadata{
Protocol: "vless",
+25 -1
View File
@@ -31,6 +31,7 @@ type Listener struct {
closed bool
config LC.SnellServer
listeners []net.Listener
v6Mode snell.V6Mode // only used for version 6
}
func New(config LC.SnellServer, lc C.InboundListenConfig, tunnel C.Tunnel, additions ...inbound.Addition) (C.MultiAddrListener, error) {
@@ -39,6 +40,10 @@ func New(config LC.SnellServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
}
switch config.Version {
case snell.Version1, snell.Version2, snell.Version3, snell.Version4, snell.Version5:
if config.Mode != "" {
return nil, errors.New("snell inbound mode is only supported on version 6")
}
case snell.Version6:
default:
return nil, fmt.Errorf("snell inbound version %d is not supported", config.Version)
}
@@ -52,6 +57,20 @@ func New(config LC.SnellServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
}
l := &Listener{config: config}
if config.Version == snell.Version6 {
if err := snell.ValidateV6PSK([]byte(config.Psk)); err != nil {
return nil, fmt.Errorf("snell inbound %w", err)
}
if config.ObfsMode != "" {
// v6 replaced the simple-obfs layer with PSK-derived traffic shaping
return nil, fmt.Errorf("snell inbound version 6 does not support obfs mode %s", config.ObfsMode)
}
var err error
l.v6Mode, err = snell.ParseV6Mode(config.Mode)
if err != nil {
return nil, fmt.Errorf("snell inbound %w", err)
}
}
securityModes := make([]string, 0, 3)
if config.ShadowTLS.Enable {
@@ -162,7 +181,12 @@ func (l *Listener) HandleConn(rawConn net.Conn, tunnel C.Tunnel, additions ...in
default:
return
}
stream := snell.ServerStreamConn(conn, []byte(l.config.Psk), l.config.Version)
var stream *snell.Snell
if l.config.Version == snell.Version6 {
stream = snell.ServerStreamConnV6(conn, []byte(l.config.Psk), l.v6Mode)
} else {
stream = snell.ServerStreamConn(conn, []byte(l.config.Psk), l.config.Version)
}
for {
reuse, err := l.handleRequest(stream, tunnel, additions...)
if err != nil || !reuse {
+6 -8
View File
@@ -11,6 +11,7 @@ import (
"github.com/metacubex/mihomo/adapter/inbound"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/pool"
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
@@ -145,7 +146,8 @@ func (l *Listener) handleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbou
_ = stream.Close()
continue
}
go l.handler.HandleSocket(targetAddr, stream, additions...)
// mux streams ignore deadlines, so the 200ms sniff peek of a server-speaks-first target would never end
go l.handler.HandleSocket(targetAddr, N.NewDeadlineConn(stream), additions...)
}
default:
targetAddr := socks5.ParseAddr(session.Target)
@@ -167,11 +169,12 @@ func wrapSessionConn(conn net.Conn) net.Conn {
func (l *Listener) handleUoTSession(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
writer := sudoku.NewUoTPacketConn(conn)
reader := sudoku.NewUoTReader(conn)
remoteAddr := conn.RemoteAddr()
connID := utils.NewUUIDV4().String() // make a new SNAT key
for {
addrStr, payload, err := sudoku.ReadDatagram(conn)
target, payload, err := reader.ReadDatagram()
if err != nil {
if !errors.Is(err, io.EOF) {
log.Debugln("[Sudoku][UoT] session closed: %v", err)
@@ -180,12 +183,6 @@ func (l *Listener) handleUoTSession(conn net.Conn, tunnel C.Tunnel, additions ..
return
}
target := socks5.ParseAddr(addrStr)
if target == nil {
log.Debugln("[Sudoku][UoT] drop invalid target: %s", addrStr)
continue
}
cPacket := &uotPacket{
payload: payload,
writer: writer,
@@ -211,6 +208,7 @@ func (p *uotPacket) WriteBack(b []byte, addr net.Addr) (int, error) {
}
func (p *uotPacket) Drop() {
_ = pool.Put(p.payload)
p.payload = nil
}
+30 -12
View File
@@ -14,9 +14,9 @@ import (
)
type domainStrategy struct {
count int
domainTrie *trie.DomainTrie[struct{}]
domainSet *trie.DomainSet
count int
domainSetBuilder trie.DomainSetBuilder
domainSet *trie.DomainSet
}
func (d *domainStrategy) Behavior() P.RuleBehavior {
@@ -32,27 +32,26 @@ func (d *domainStrategy) Count() int {
}
func (d *domainStrategy) Reset() {
d.domainTrie = trie.New[struct{}]()
d.domainSetBuilder.Reset()
d.domainSet = nil
d.count = 0
}
func (d *domainStrategy) Insert(rule string) {
if strings.ContainsRune(rule, '/') {
log.Warnln("invalid domain:[%s]", rule)
log.Warnln("skip invalid domain from rule provider: invalid domain %q: slash is not allowed", rule)
return
}
err := d.domainTrie.Insert(rule, struct{}{})
err := d.domainSetBuilder.Insert(rule)
if err != nil {
log.Warnln("invalid domain:[%s]", rule)
log.Warnln("skip invalid domain from rule provider: %s", err)
} else {
d.count++
}
}
func (d *domainStrategy) FinishInsert() {
d.domainSet = d.domainTrie.NewDomainSet()
d.domainTrie = nil
d.domainSet = d.domainSetBuilder.Build()
}
func (d *domainStrategy) FromMrs(r io.Reader, count int) error {
@@ -72,6 +71,9 @@ func (d *domainStrategy) WriteMrs(w io.Writer) error {
return d.domainSet.WriteBin(w)
}
// DumpMrs emits a compact domain rule list in lexicographical order through f.
// A "domain" entry and a ".domain" entry are represented by one "+.domain" rule;
// either entry alone is emitted unchanged. Returning false from f stops iteration.
func (d *domainStrategy) DumpMrs(f func(key string) bool) {
if d.domainSet != nil {
var keys []string
@@ -79,12 +81,28 @@ func (d *domainStrategy) DumpMrs(f func(key string) bool) {
keys = append(keys, key)
return true
})
// Group exact and suffix-only entries for the same domain.
// Set entries are unique, so each group contains at most two entries.
slices.SortFunc(keys, func(left, right string) int {
left = strings.TrimPrefix(left, ".")
right = strings.TrimPrefix(right, ".")
return strings.Compare(left, right)
})
for index := 0; index+1 < len(keys); index++ {
domain := strings.TrimPrefix(keys[index], ".")
if domain == strings.TrimPrefix(keys[index+1], ".") {
// Both the domain itself and its subdomains are covered by one "+." rule.
keys[index] = "+." + domain
keys[index+1] = ""
index++
}
}
keys = slices.DeleteFunc(keys, func(key string) bool { return key == "" })
// Sort the compact rules by their full text, including wildcard prefixes.
slices.Sort(keys)
for _, key := range keys {
if _, ok := slices.BinarySearch(keys, "+."+key); ok {
continue // ignore the rules added by trie internal processing
}
if !f(key) {
return
}
+94
View File
@@ -0,0 +1,94 @@
package provider_test
import (
"testing"
"github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/rules/provider"
"github.com/stretchr/testify/assert"
)
func TestDomainStrategyDumpMrs(test *testing.T) {
tests := []struct {
name string
domains []string
expected []string
queries map[string]bool
}{
{
"suffix-only",
[]string{".example.com"},
[]string{".example.com"},
map[string]bool{"example.com": false, "www.example.com": true},
},
{
"exact-only",
[]string{"example.com"},
[]string{"example.com"},
map[string]bool{"example.com": true, "www.example.com": false},
},
{
"merge-terminals",
[]string{"example.com", ".example.com"},
[]string{"+.example.com"},
map[string]bool{"example.com": true, "www.example.com": true},
},
{
"deduplicate",
[]string{"+.example.com", "+.example.com", "example.com", ".example.com"},
[]string{"+.example.com"},
map[string]bool{"example.com": true, "www.example.com": true},
},
{
"mixed",
[]string{".example.com", "example.net", "example.org", ".example.org"},
[]string{"+.example.org", ".example.com", "example.net"},
map[string]bool{
"example.com": false,
"www.example.com": true,
"example.net": true,
"www.example.net": false,
"example.org": true,
"www.example.org": true,
},
},
{
"wildcards",
[]string{"*.example.com", "+.example.org", "test.*.google.com", ".test.*.google.com", ".example.net"},
[]string{"*.example.com", "+.example.org", "+.test.*.google.com", ".example.net"},
map[string]bool{
"example.com": false,
"www.example.com": true,
"example.org": true,
"www.example.org": true,
"test.www.google.com": true,
"www.test.www.google.com": true,
"example.net": false,
"www.example.net": true,
},
},
}
for _, testCase := range tests {
test.Run(testCase.name, func(test *testing.T) {
strategy := provider.NewDomainStrategy()
for _, domain := range testCase.domains {
strategy.Insert(domain)
}
strategy.FinishInsert()
rebuilt := provider.NewDomainStrategy()
var domains []string
strategy.DumpMrs(func(domain string) bool {
domains = append(domains, domain)
rebuilt.Insert(domain)
return true
})
rebuilt.FinishInsert()
assert.Equal(test, testCase.expected, domains)
for domain, expected := range testCase.queries {
metadata := &constant.Metadata{Host: domain}
assert.Equal(test, expected, strategy.Match(metadata, constant.RuleMatchHelper{}), domain)
assert.Equal(test, expected, rebuilt.Match(metadata, constant.RuleMatchHelper{}), domain)
}
})
}
}
+2 -1
View File
@@ -174,9 +174,10 @@ func (c *Client) idleCleanup() {
func (c *Client) idleCleanupExpTime(expTime time.Time) {
activeCount := 0
sessionToClose := make([]*Session, 0, c.idleSession.Len())
c.idleSessionLock.Lock()
sessionToClose := make([]*Session, 0, c.idleSession.Len())
it := c.idleSession.Iterate()
for it.IsNotEnd() {
session := it.Value()
+1 -1
View File
@@ -230,7 +230,7 @@ func (c *Client) DialUDP(dialer utils.PacketDialer) (UDPConn, error) {
}
// Send request
err = WriteClientRequest(stream, ClientRequest{
UDP: false,
UDP: true,
})
if err != nil {
_ = stream.Close()
+1 -1
View File
@@ -248,7 +248,7 @@ func (m udpMessage) Size() int {
}
func (m udpMessage) Pack() []byte {
data := make([]byte, m.Size())
data := make([]byte, 0, m.Size())
buffer := bytes.NewBuffer(data)
_ = binary.Write(buffer, binary.BigEndian, m.SessionID)
_ = binary.Write(buffer, binary.BigEndian, uint16(len(m.Host)))
+2
View File
@@ -62,6 +62,7 @@ func (c *Client) createConn(ctx context.Context, dial DialFn) (*smux.Session, er
convid := randv2.Uint32()
kcpconn, err := kcp.NewConn4(convid, addr, c.block, config.DataShard, config.ParityShard, true, conn)
if err != nil {
_ = conn.Close()
return nil, err
}
kcpconn.SetStreamMode(true)
@@ -86,6 +87,7 @@ func (c *Client) createConn(ctx context.Context, dial DialFn) (*smux.Session, er
}
if err := smux.VerifyConfig(smuxConfig); err != nil {
_ = kcpconn.Close()
return nil, err
}
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more