Compare commits

...
28 Commits
Author SHA1 Message Date
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
82 changed files with 5287 additions and 2484 deletions

No files matched your search

+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)
}
}
+12
View File
@@ -315,9 +315,21 @@ func (e *EasyTier) init() error {
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()
+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
+26 -1
View File
@@ -26,6 +26,7 @@ type Snell struct {
restlsConfig *restls.Config
jlsConfig *jls.ClientConfig
version int
v6Mode snell.V6Mode
reuse bool
}
@@ -38,6 +39,7 @@ type SnellOption struct {
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 +68,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
}
@@ -249,16 +254,35 @@ 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)
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{
@@ -280,6 +304,7 @@ func NewSnell(option SnellOption) (*Snell, error) {
restlsConfig: restlsConfig,
jlsConfig: jlsConfig,
version: option.Version,
v6Mode: v6Mode,
reuse: reuse,
}
s.dialer = option.NewDialer(s.DialOptions())
+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()
+63 -36
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
@@ -380,7 +383,8 @@ 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")
@@ -450,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 {
@@ -464,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
@@ -540,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
}
@@ -562,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
}
@@ -781,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
}
+18 -15
View File
@@ -45,7 +45,7 @@ func request(user, host string) *C.Metadata {
// 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 moves it as soon as the host changes.
// 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"}
@@ -58,26 +58,29 @@ func TestLoadBalanceHashKeyInUserSurvivesADestinationChange(t *testing.T) {
"hash-key: user must ignore the destination")
}
byDestination := strategyConsistentHashing(testUrl, getKey)
seen := map[int]bool{}
// 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 {
seen[indexOf(t, proxies, byDestination(proxies, request("job-1", host), false))] = true
seenKeys[getKey(request("job-1", host))] = struct{}{}
}
require.Greater(t, len(seen), 1,
"the default key is expected to move with the destination")
require.Len(t, seenKeys, len(hosts),
"the default key must change with the destination")
}
// Pinning must not become a single node: distinct users still spread.
func TestLoadBalanceHashKeyInUserSpreadsUsers(t *testing.T) {
proxies := balancedProxies(8)
strategy := strategyConsistentHashing(testUrl, getKeyWithInUser(getKey))
// 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"}
seen := map[int]bool{}
for _, user := range []string{"job-1", "job-2", "job-3", "job-4", "job-5", "job-6"} {
selected := strategy(proxies, request(user, "a.example.com"), false)
seen[indexOf(t, proxies, selected)] = true
seenKeys := map[string]struct{}{}
for _, user := range users {
seenKeys[keyed(request(user, "a.example.com"))] = struct{}{}
}
require.Greater(t, len(seen), 1)
require.Len(t, seenKeys, len(users))
}
// Sticky sessions keys on source and destination; a client behind one source
+9 -1
View File
@@ -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
}
+99
View File
@@ -329,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)
}
+4
View File
@@ -114,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)
+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
+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{
+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
}
+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)
+2
View File
@@ -274,6 +274,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"`
@@ -1694,6 +1695,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,
+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())
}
}
})
}
+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" {
+28 -11
View File
@@ -134,6 +134,12 @@ profile: # 存储 select 选择记录
tun:
enable: false
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 # 自动识别出口网卡
@@ -408,20 +414,21 @@ 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
# 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
@@ -435,7 +442,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
@@ -448,7 +455,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
@@ -2126,6 +2133,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
@@ -2189,10 +2202,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时开启
@@ -2585,6 +2599,8 @@ listeners:
# traffic-pattern: ""
# 如果开启,且客户端不发送用户提示,代理服务器将拒绝连接
# user-hint-is-mandatory: false
# 在上行和下行同时空闲这个秒数后,关闭底层TCP连接。最小值为60。
# tcp-idle-timeout: 1800
- name: sudoku-in-1
type: sudoku
@@ -2799,6 +2815,7 @@ listeners:
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
stack: mips # gvisor / mixed / system
# dns-mode: hijack # disabled / native / hijack,为空时采用旧行为
dns-hijack:
- 0.0.0.0:53 # 需要劫持的 DNS
# auto-detect-interface: false # 自动识别出口网卡
+9 -9
View File
@@ -6,8 +6,8 @@ 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/easytier/easytier/easytier-go v0.0.0-20260910071355-3d0c9c3ca5e2
github.com/enfein/mieru/v3 v3.38.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
@@ -28,26 +28,26 @@ require (
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-20260930071539-961d4b1c1983
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.8
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.13
github.com/metacubex/sing-shadowsocks2 v0.2.8
github.com/metacubex/sing-tun v0.4.27
github.com/metacubex/sing-tun v0.4.29
github.com/metacubex/sing-vmess v0.2.5
github.com/metacubex/sing-wireguard v0.0.0-20260826105301-c3ae17d19f9e
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-20260821153257-ff0ecd818181
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c
github.com/metacubex/tls v0.1.8
github.com/metacubex/utls v1.8.8
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
+18 -18
View File
@@ -27,10 +27,10 @@ github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz
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/easytier/easytier/easytier-go v0.0.0-20260910071355-3d0c9c3ca5e2 h1:2/9iRUcMR3QPrT2XFf/i7QV5YoSHPFjkgBM5tP8xbcc=
github.com/easytier/easytier/easytier-go v0.0.0-20260910071355-3d0c9c3ca5e2/go.mod h1:fCEi5+K2yt+sPDONSWO1uNpOifrwPgFGvm3J0YrFRvk=
github.com/enfein/mieru/v3 v3.38.0 h1:+DuixHFoCGEYEopoEg8fHmDJ5Ak30PuXuf1GIh2Xpu0=
github.com/enfein/mieru/v3 v3.38.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=
@@ -135,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-20260930071539-961d4b1c1983 h1:BGb9PDJrrZSsDnJyeFWFY9v6uTr6/LxokQgwuHVAsDI=
github.com/metacubex/mipstack v0.0.0-20260930071539-961d4b1c1983/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=
@@ -153,8 +153,8 @@ 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.8 h1:OwJDSPP+pza6Ywt7NMR4kEYq+UNrsIywSk/eAMlqxz8=
github.com/metacubex/sing v0.5.8/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w=
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=
@@ -163,12 +163,12 @@ github.com/metacubex/sing-shadowsocks v0.2.13 h1:PKmInHy9+4nY3FLhmKcWdASUBo9WZ/K
github.com/metacubex/sing-shadowsocks v0.2.13/go.mod h1:2e5EIaw0rxKrm1YTRmiMnDulwbGxH9hAFlrwQLQMQkU=
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.27 h1:dWCpFDlWelQrhH3y5KkMrJXEXYeJ0V2LROP8Cxv96MI=
github.com/metacubex/sing-tun v0.4.27/go.mod h1:5nlmrOy+FG0yhiLm+O/pzmirZVrpLuDQZuA+qI9x5kg=
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-20260826105301-c3ae17d19f9e h1:KGKZt//rrELT/dEwgYcHCqNYEGr3a7uVutlZrzrZZWY=
github.com/metacubex/sing-wireguard v0.0.0-20260826105301-c3ae17d19f9e/go.mod h1:OiYj4hitKrN1YIrgGHXp6zKnc9asCspF+SrYlLN2hYQ=
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=
@@ -177,12 +177,12 @@ github.com/metacubex/tailscale v0.0.0-20260821153257-ff0ecd818181 h1:hWsSSzuCHe+
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.8 h1:7fiMYahL+tT1I/vG1MWidv88r/3A5NnPrurjzApZGyQ=
github.com/metacubex/utls v1.8.8/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=
+4
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"`
@@ -151,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
}
+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
+4
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"`
@@ -106,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
}
+14 -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,11 +149,12 @@ 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{
@@ -191,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
}
+28
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) {
+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"}))
}
+2
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"`
@@ -97,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,
+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
+9 -2
View File
@@ -274,6 +274,12 @@ 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:
return nil, fmt.Errorf("invalid dns-mode: %s", options.DNSMode)
}
var dnsAdds []netip.AddrPort
for _, d := range options.DNSHijack {
@@ -390,6 +396,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,
@@ -543,8 +550,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
}
+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
}
+16
View File
@@ -20,6 +20,7 @@ const (
Version3 = 3
Version4 = 4
Version5 = 5
Version6 = 6
DefaultSnellVersion = Version1
// max packet length
@@ -154,6 +155,9 @@ func HalfClose(conn net.Conn) error {
}
func StreamConn(conn net.Conn, psk []byte, version int) *Snell {
if version >= Version6 {
return StreamConnV6(conn, psk, V6ModeDefault)
}
if version >= Version4 {
return &Snell{Conn: newV4Conn(conn, psk)}
}
@@ -173,6 +177,18 @@ func ServerStreamConn(conn net.Conn, psk []byte, version int) *Snell {
return stream
}
// StreamConnV6 wraps conn with the Snell v6 record layer in the given mode.
// The request/reply layer above it is shared with the other versions.
func StreamConnV6(conn net.Conn, psk []byte, mode V6Mode) *Snell {
return &Snell{Conn: newV6Conn(conn, psk, mode)}
}
func ServerStreamConnV6(conn net.Conn, psk []byte, mode V6Mode) *Snell {
stream := StreamConnV6(conn, psk, mode)
stream.reply = true
return stream
}
func PacketConn(conn net.Conn) net.PacketConn {
return &packetConn{
Conn: conn,
+663
View File
@@ -0,0 +1,663 @@
package snell
import (
"crypto/cipher"
cryptorand "crypto/rand"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"sync"
"time"
"github.com/metacubex/mihomo/transport/shadowsocks/shadowaead"
)
// Snell v6 keeps the v4 record layout (7-byte header sealed with AES-128-GCM,
// followed by the sealed payload) but wraps it in a PSK-derived "profile": the
// salt is scattered inside a padded block, every record carries an unencrypted
// prefix that doubles as the header's AAD, padding is interleaved with the
// payload ciphertext and record sizes follow a shaped schedule. The `unshaped`
// mode drops the profile layer and the `unsafe-raw` mode drops the crypto as
// well; both must match the server's configured mode.
type V6Mode int
const (
V6ModeDefault V6Mode = iota
V6ModeUnshaped
V6ModeUnsafeRaw
)
func ParseV6Mode(name string) (V6Mode, error) {
switch name {
case "", "default":
return V6ModeDefault, nil
case "unshaped":
return V6ModeUnshaped, nil
case "unsafe-raw":
return V6ModeUnsafeRaw, nil
default:
return 0, fmt.Errorf("snell v6 unknown mode: %s", name)
}
}
func (m V6Mode) String() string {
switch m {
case V6ModeDefault:
return "default"
case V6ModeUnshaped:
return "unshaped"
case V6ModeUnsafeRaw:
return "unsafe-raw"
default:
return fmt.Sprintf("mode(%d)", int(m))
}
}
const (
v6SaltSize = 16
v6NonceSize = 12
v6TagSize = 16
v6HeaderVersion = 4
v6HeaderPlainSize = 7
v6HeaderCipherSize = v6HeaderPlainSize + v6TagSize
v6MaxPayload = 0xffff
// the official server rejects PSKs outside this range
V6MinPSKLength = 12
V6MaxPSKLength = 255
)
var (
errV6BadHeader = errors.New("snell v6 invalid record header")
errV6RecordPadding = errors.New("snell v6 unexpected padding in record")
errV6PayloadTooLong = errors.New("snell v6 payload too large")
)
func ValidateV6PSK(psk []byte) error {
if len(psk) < V6MinPSKLength || len(psk) > V6MaxPSKLength {
return fmt.Errorf("snell v6 psk length must be between %d and %d bytes", V6MinPSKLength, V6MaxPSKLength)
}
return nil
}
type v6RecordReader interface {
// readRecord returns the payload of the next record, or
// shadowaead.ErrZeroChunk for an end-of-stream record.
readRecord() ([]byte, error)
}
type v6RecordWriter interface {
// write splits p into as many records as the mode requires
write(p []byte) error
// writePacket emits p as exactly one record
writePacket(p []byte) error
writeZeroChunk() error
}
type v6Conn struct {
net.Conn
psk []byte
mode V6Mode
profile *v6Profile
r v6RecordReader
rBuf []byte
rMux sync.Mutex
w v6RecordWriter
wMux sync.Mutex
}
func newV6Conn(conn net.Conn, psk []byte, mode V6Mode) *v6Conn {
c := &v6Conn{Conn: conn, psk: psk, mode: mode}
if mode == V6ModeDefault {
c.profile = newV6Profile(psk)
}
return c
}
func (c *v6Conn) initReader() {
switch c.mode {
case V6ModeUnsafeRaw:
c.r = &v6RawReader{Reader: c.Conn}
case V6ModeUnshaped:
c.r = &v6UnshapedReader{Reader: c.Conn, psk: c.psk}
default:
c.r = &v6ShapedReader{Reader: c.Conn, psk: c.psk, profile: c.profile}
}
}
func (c *v6Conn) initWriter() error {
switch c.mode {
case V6ModeUnsafeRaw:
c.w = &v6RawWriter{Writer: c.Conn}
return nil
case V6ModeUnshaped:
w, err := newV6UnshapedWriter(c.Conn, c.psk)
if err != nil {
return err
}
c.w = w
return nil
default:
w, err := newV6ShapedWriter(c.Conn, c.psk, c.profile)
if err != nil {
return err
}
c.w = w
return nil
}
}
func (c *v6Conn) Read(b []byte) (int, error) {
c.rMux.Lock()
defer c.rMux.Unlock()
if c.r == nil {
c.initReader()
}
if len(c.rBuf) == 0 {
payload, err := c.r.readRecord()
if err != nil {
return 0, err
}
c.rBuf = payload
}
n := copy(b, c.rBuf)
c.rBuf = c.rBuf[n:]
return n, nil
}
func (c *v6Conn) Write(b []byte) (int, error) {
c.wMux.Lock()
defer c.wMux.Unlock()
if c.w == nil {
if err := c.initWriter(); err != nil {
return 0, err
}
}
if len(b) == 0 {
return 0, c.w.writeZeroChunk()
}
if err := c.w.write(b); err != nil {
return 0, err
}
return len(b), nil
}
func (c *v6Conn) WritePacketFrame(b []byte) (int, error) {
if len(b) > v6MaxPayload {
return 0, errV6PayloadTooLong
}
c.wMux.Lock()
defer c.wMux.Unlock()
if c.w == nil {
if err := c.initWriter(); err != nil {
return 0, err
}
}
if err := c.w.writePacket(b); err != nil {
return 0, err
}
return len(b), nil
}
func (c *v6Conn) WriteTo(w io.Writer) (int64, error) {
var written int64
buf := make([]byte, v6MaxPayload)
for {
n, err := c.Read(buf)
if n > 0 {
nw, ew := w.Write(buf[:n])
written += int64(nw)
if ew != nil {
return written, ew
}
if nw != n {
return written, io.ErrShortWrite
}
}
if err != nil {
if err == io.EOF {
err = nil
}
return written, err
}
}
}
func (c *v6Conn) ReadFrom(r io.Reader) (int64, error) {
var read int64
buf := make([]byte, v6MaxPayload)
for {
n, err := r.Read(buf)
if n > 0 {
read += int64(n)
if _, ew := c.Write(buf[:n]); ew != nil {
return read, ew
}
}
if err != nil {
if err == io.EOF {
err = nil
}
return read, err
}
}
}
func v6AEAD(psk, salt []byte) (cipher.AEAD, error) {
return aesGCM(snellKDF(psk, salt, 16))
}
func v6RandomSalt() ([]byte, error) {
salt := make([]byte, v6SaltSize)
if _, err := io.ReadFull(cryptorand.Reader, salt); err != nil {
return nil, err
}
return salt, nil
}
func v6PutHeader(header []byte, paddingLength, payloadLength int) {
header[0] = v6HeaderVersion
header[1] = 0
header[2] = 0
binary.BigEndian.PutUint16(header[3:5], uint16(paddingLength))
binary.BigEndian.PutUint16(header[5:7], uint16(payloadLength))
}
// v6ParseHeader validates a plain header. strict additionally requires the two
// reserved bytes to be zero, which the official server only checks outside of
// the default mode.
func v6ParseHeader(header []byte, strict bool) (paddingLength, payloadLength int, err error) {
if header[0] != v6HeaderVersion {
return 0, 0, errV6BadHeader
}
if strict && (header[1] != 0 || header[2] != 0) {
return 0, 0, errV6BadHeader
}
return int(binary.BigEndian.Uint16(header[3:5])), int(binary.BigEndian.Uint16(header[5:7])), nil
}
// --- unsafe-raw ---------------------------------------------------------------
type v6RawReader struct {
io.Reader
}
func (r *v6RawReader) readRecord() ([]byte, error) {
var header [v6HeaderPlainSize]byte
if _, err := io.ReadFull(r.Reader, header[:]); err != nil {
return nil, err
}
paddingLength, payloadLength, err := v6ParseHeader(header[:], true)
if err != nil {
return nil, err
}
if paddingLength != 0 {
return nil, errV6RecordPadding
}
if payloadLength == 0 {
return nil, shadowaead.ErrZeroChunk
}
payload := make([]byte, payloadLength)
if _, err := io.ReadFull(r.Reader, payload); err != nil {
return nil, err
}
return payload, nil
}
type v6RawWriter struct {
io.Writer
}
func (w *v6RawWriter) writeRecord(payload []byte) error {
record := make([]byte, v6HeaderPlainSize+len(payload))
v6PutHeader(record, 0, len(payload))
copy(record[v6HeaderPlainSize:], payload)
_, err := w.Writer.Write(record)
return err
}
func (w *v6RawWriter) write(p []byte) error {
for len(p) > 0 {
n := minInt(len(p), v6MaxPayload)
if err := w.writeRecord(p[:n]); err != nil {
return err
}
p = p[n:]
}
return nil
}
func (w *v6RawWriter) writePacket(p []byte) error {
return w.writeRecord(p)
}
func (w *v6RawWriter) writeZeroChunk() error {
return w.writeRecord(nil)
}
// --- unshaped -------------------------------------------------------------------
type v6UnshapedReader struct {
io.Reader
psk []byte
aead cipher.AEAD
nonce [v6NonceSize]byte
}
func (r *v6UnshapedReader) readRecord() ([]byte, error) {
if r.aead == nil {
salt := make([]byte, v6SaltSize)
if _, err := io.ReadFull(r.Reader, salt); err != nil {
return nil, err
}
aead, err := v6AEAD(r.psk, salt)
if err != nil {
return nil, err
}
r.aead = aead
}
headerCipher := make([]byte, v6HeaderCipherSize)
if _, err := io.ReadFull(r.Reader, headerCipher); err != nil {
return nil, err
}
header, err := r.aead.Open(headerCipher[:0], r.nonce[:], headerCipher, nil)
incrementV4Nonce(r.nonce[:])
if err != nil {
return nil, err
}
paddingLength, payloadLength, err := v6ParseHeader(header, true)
if err != nil {
return nil, err
}
if paddingLength != 0 {
return nil, errV6RecordPadding
}
if payloadLength == 0 {
return nil, shadowaead.ErrZeroChunk
}
payloadCipher := make([]byte, payloadLength+v6TagSize)
if _, err := io.ReadFull(r.Reader, payloadCipher); err != nil {
return nil, err
}
payload, err := r.aead.Open(payloadCipher[:0], r.nonce[:], payloadCipher, nil)
incrementV4Nonce(r.nonce[:])
if err != nil {
return nil, err
}
return payload, nil
}
type v6UnshapedWriter struct {
io.Writer
aead cipher.AEAD
nonce [v6NonceSize]byte
salt []byte
saltSent bool
}
func newV6UnshapedWriter(w io.Writer, psk []byte) (*v6UnshapedWriter, error) {
salt, err := v6RandomSalt()
if err != nil {
return nil, err
}
aead, err := v6AEAD(psk, salt)
if err != nil {
return nil, err
}
return &v6UnshapedWriter{Writer: w, aead: aead, salt: salt}, nil
}
// appendRecord seals payload as one record and appends it to out.
func (w *v6UnshapedWriter) appendRecord(out []byte, payload []byte) []byte {
start := len(out)
out = append(out, make([]byte, v6HeaderPlainSize)...)
v6PutHeader(out[start:], 0, len(payload))
out = w.aead.Seal(out[:start], w.nonce[:], out[start:start+v6HeaderPlainSize], nil)
incrementV4Nonce(w.nonce[:])
if len(payload) > 0 {
out = w.aead.Seal(out, w.nonce[:], payload, nil)
incrementV4Nonce(w.nonce[:])
}
return out
}
func (w *v6UnshapedWriter) writeRecords(payloads [][]byte) error {
size := 0
if !w.saltSent {
size += v6SaltSize
}
for _, payload := range payloads {
size += v6HeaderCipherSize + len(payload)
if len(payload) > 0 {
size += v6TagSize
}
}
out := make([]byte, 0, size)
if !w.saltSent {
out = append(out, w.salt...)
w.saltSent = true
}
for _, payload := range payloads {
out = w.appendRecord(out, payload)
}
_, err := w.Writer.Write(out)
return err
}
func (w *v6UnshapedWriter) write(p []byte) error {
var payloads [][]byte
for len(p) > 0 {
n := minInt(len(p), v6MaxPayload)
payloads = append(payloads, p[:n])
p = p[n:]
}
return w.writeRecords(payloads)
}
func (w *v6UnshapedWriter) writePacket(p []byte) error {
return w.writeRecords([][]byte{p})
}
func (w *v6UnshapedWriter) writeZeroChunk() error {
return w.writeRecords([][]byte{nil})
}
// --- default (shaped) ------------------------------------------------------------
type v6ShapedReader struct {
io.Reader
psk []byte
profile *v6Profile
aead cipher.AEAD
nonce [v6NonceSize]byte
seq uint32
}
func (r *v6ShapedReader) readRecord() ([]byte, error) {
if r.aead == nil {
block := make([]byte, r.profile.saltBlockLen)
if _, err := io.ReadFull(r.Reader, block); err != nil {
return nil, err
}
salt := r.profile.extractSalt(block)
aead, err := v6AEAD(r.psk, salt[:])
if err != nil {
return nil, err
}
r.aead = aead
}
prefixLength := r.profile.recordPrefixLen(r.seq)
head := make([]byte, prefixLength+v6HeaderCipherSize)
if _, err := io.ReadFull(r.Reader, head); err != nil {
return nil, err
}
prefix := head[:prefixLength]
headerCipher := head[prefixLength:]
header, err := r.aead.Open(headerCipher[:0], r.nonce[:], headerCipher, prefix)
incrementV4Nonce(r.nonce[:])
if err != nil {
return nil, err
}
// the reserved header bytes are ignored in default mode
paddingLength, payloadLength, err := v6ParseHeader(header, false)
if err != nil {
return nil, err
}
seq := r.seq
r.seq++
if payloadLength == 0 {
if paddingLength > 0 {
if _, err := io.CopyN(io.Discard, r.Reader, int64(paddingLength)); err != nil {
return nil, err
}
}
return nil, shadowaead.ErrZeroChunk
}
body := make([]byte, paddingLength+payloadLength+v6TagSize)
if _, err := io.ReadFull(r.Reader, body); err != nil {
return nil, err
}
padding := body[:paddingLength]
payloadCipher := body[paddingLength:]
r.profile.mixPaddingPayload(seq, padding, payloadCipher)
payload, err := r.aead.Open(payloadCipher[:0], r.nonce[:], payloadCipher, padding)
incrementV4Nonce(r.nonce[:])
if err != nil {
return nil, err
}
return payload, nil
}
type v6ShapedWriter struct {
io.Writer
profile *v6Profile
aead cipher.AEAD
nonce [v6NonceSize]byte
salt []byte
saltSent bool
seq uint32
chunkSize int
lastWriteUnix int64
}
func newV6ShapedWriter(w io.Writer, psk []byte, profile *v6Profile) (*v6ShapedWriter, error) {
salt, err := v6RandomSalt()
if err != nil {
return nil, err
}
aead, err := v6AEAD(psk, salt)
if err != nil {
return nil, err
}
return &v6ShapedWriter{Writer: w, profile: profile, aead: aead, salt: salt}, nil
}
// payloadLimitFor advances the shaped chunk schedule and returns how much
// payload the next record may carry. The idle reset is second-granular.
func (w *v6ShapedWriter) payloadLimitFor(now time.Time) int {
nowUnix := now.Unix()
if w.lastWriteUnix == 0 || nowUnix-w.lastWriteUnix > int64(w.profile.idleResetSec) {
w.chunkSize = w.profile.chunkInitial
}
if w.chunkSize == 0 {
w.chunkSize = w.profile.chunkInitial
}
payloadLimit := w.profile.chunkPayloadLimit(w.seq, w.chunkSize)
if w.seq == 0 {
payloadLimit = minInt(payloadLimit, w.profile.firstRecordCap)
}
w.chunkSize = w.profile.nextChunkSize(w.chunkSize)
w.lastWriteUnix = nowUnix
return maxInt(1, minInt(payloadLimit, v6MaxPayload))
}
// appendRecord builds one shaped record for payload and appends it to out.
func (w *v6ShapedWriter) appendRecord(out []byte, payload []byte) []byte {
prefixLength := w.profile.recordPrefixLen(w.seq)
saltBlockLength := 0
saltPrefixLength := 0
if !w.saltSent {
saltBlockLength = w.profile.saltBlockLen
saltPrefixLength = saltBlockLength - v6SaltSize
}
paddingLength := w.profile.paddingLen(w.seq, len(payload), prefixLength, saltPrefixLength, saltBlockLength)
payloadCipherLength := 0
if len(payload) > 0 {
payloadCipherLength = len(payload) + v6TagSize
}
start := len(out)
out = append(out, make([]byte, saltBlockLength+prefixLength+v6HeaderCipherSize+paddingLength+payloadCipherLength)...)
record := out[start:]
if saltBlockLength > 0 {
block := record[:saltBlockLength]
// the salt block is shaped padding generated for the sentinel sequence 0xffffffff
// with the salt bytes scattered over it
w.profile.fillPadding(0xffffffff, block)
w.profile.writeSaltBlock(w.salt, block)
w.saltSent = true
}
offset := saltBlockLength
prefix := record[offset : offset+prefixLength]
w.profile.fillPadding(w.seq, prefix)
offset += prefixLength
header := record[offset : offset+v6HeaderCipherSize]
v6PutHeader(header, paddingLength, len(payload))
w.aead.Seal(header[:0], w.nonce[:], header[:v6HeaderPlainSize], prefix)
incrementV4Nonce(w.nonce[:])
offset += v6HeaderCipherSize
padding := record[offset : offset+paddingLength]
w.profile.fillPadding(w.seq, padding)
offset += paddingLength
if len(payload) > 0 {
region := record[offset : offset+payloadCipherLength]
copy(region, payload)
w.aead.Seal(region[:0], w.nonce[:], region[:len(payload)], padding)
incrementV4Nonce(w.nonce[:])
w.profile.mixPaddingPayload(w.seq, padding, region)
}
w.seq++
return out
}
func (w *v6ShapedWriter) write(p []byte) error {
now := time.Now()
var out []byte
for len(p) > 0 {
n := minInt(len(p), w.payloadLimitFor(now))
out = w.appendRecord(out, p[:n])
p = p[n:]
}
_, err := w.Writer.Write(out)
return err
}
func (w *v6ShapedWriter) writePacket(p []byte) error {
// packet mode still advances the chunk schedule but emits the whole
// datagram as a single record regardless of the current limit
w.payloadLimitFor(time.Now())
_, err := w.Writer.Write(w.appendRecord(nil, p))
return err
}
func (w *v6ShapedWriter) writeZeroChunk() error {
w.payloadLimitFor(time.Now())
_, err := w.Writer.Write(w.appendRecord(nil, nil))
return err
}
+650
View File
@@ -0,0 +1,650 @@
package snell
import (
"encoding/binary"
"math/bits"
"golang.org/x/crypto/blake2b"
)
// Snell v6 derives a deployment specific "profile" from the PSK. The profile
// decides how the salt is scattered inside the first block, how long the
// per-record prefix and padding are, how padding bytes look and how padding is
// interleaved with the ciphertext. Both peers derive the same profile, so every
// value below must be computed exactly the same way as the official
// implementation. The constants and the derivation order follow the protocol
// notes published by SagerNet/sing-snell (GPL-3.0-or-later), which reference
// the corresponding routines in Surge 6.7.0 (11520).
const (
v6GoldenGamma = 0x9e3779b97f4a7c15
v6LabelPadding = 0
v6LabelBitPercent = 1
v6LabelMotif = 2
v6LabelMixOffset = 3
v6LabelSalt = 3
v6LabelProfileID = 5
v6LabelGenerator = 6
v6LabelPadMin = 7
v6LabelPadMax = 8
v6LabelPadCount = 9
v6LabelPadInterval = 10
v6LabelSmallLimit = 11
v6LabelBitMin = 12
v6LabelBitMax = 13
v6LabelPrefixMin = 14
v6LabelPrefixMax = 15
v6LabelMixMode = 16
v6LabelMixRounds = 17
v6LabelMixStride = 18
v6LabelMixOffsetBase = 19
v6LabelMixBlock = 20
v6LabelChunkPolicy = 21
v6LabelChunkInitial = 22
v6LabelChunkFirstCap = 22
v6LabelChunkMax = 23
v6LabelChunkStep = 24
v6LabelChunkJitter = 25
v6LabelChunkBucket = 26
v6LabelIdleReset = 27
v6LabelWritePolicy = 28
v6LabelWriteFirst = 29
v6LabelWriteBucket = 30
v6LabelWriteSeq = 31
v6LabelWriteJitter = 32
v6LabelRecordPrefix = 33
v6LabelPayloadPad = 34
v6LabelWriteTarget = 35
v6LabelWriteJitterV = 36
v6LabelWriteNext = 37
v6LabelChunkSize = 38
v6LabelChunkJitterV = 39
// domain separators for handshake and chunk profile values
v6HandshakeDomain = 0x7053
v6MixHandshakeDomain = 0x51a7
v6ChunkInitialDomain = 0xf17c
// namespace seeds
v6NSSeedProfile = 0xb46c2e7d9a1538f1
v6NSSeedPrefix = 0x5d9217c083e64ab9
v6NSSeedMotif = 0xa71f0c54d8396e2b
v6NSSeedSalt = 0x3e8a91b52740f6cd
v6NSSeedMix = 0xc9f4260b7d1e835a
v6NSSeedChunk = 0x62d0b5e19c4a783f
v6NSSeedWrite = 0x917b3c48e6a205d4
// arithmetic constants of the profile PRFs
v6DomainMul = 0xd6e8feb86659fd93
v6NamespaceAdd = 0xa0761d6478bd642f
v6CoefB = 0x589965cc75374cc3
v6AddB = 0x33a213ec50ffe2e9
v6CoefA = 0xe7037ed1a0b428db
v6AddA = 0x8f3907f7b2b80c35
// salt shuffle/mask namespace xor
v6SaltNSXor = 0xdaa66d2c7ddf743f
v6MaxExtraPadding = 0x02da
)
// v6ProfileSeed is the BLAKE2b prefix mixed with the PSK to derive the profile secret.
var v6ProfileSeed = [...]byte{
0x8d, 0x41, 0xa7, 0x13, 0x5c, 0xe2, 0x09, 0xbb, 0x70, 0x2f, 0xd6, 0x94,
0x33, 0x18, 0xc0, 0x6e, 0x4a, 0x91, 0x25, 0xfd, 0xb8, 0x03, 0x77, 0xac,
}
// v6BitRotateTable maps low nibbles through bit rotations for padding generator 0.
var v6BitRotateTable = [...]byte{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
0x03, 0x05, 0x09, 0x11, 0x21, 0x41, 0x81, 0x06, 0x0a, 0x12, 0x22, 0x42, 0x82, 0x0c, 0x18, 0x24,
0x07, 0x0b, 0x13, 0x23, 0x43, 0x83, 0x0d, 0x19, 0x31, 0x61, 0xc1, 0x0e, 0x1c, 0x38, 0x70, 0xe0,
0x0f, 0x17, 0x27, 0x47, 0x87, 0x1b, 0x33, 0x63, 0xc3, 0x1d, 0x39, 0x71, 0xe1, 0x3c, 0x78, 0xf0,
0xf8, 0xf4, 0xec, 0xdc, 0xbc, 0x7c, 0xf2, 0xe6, 0xce, 0x9e, 0x3e, 0xf1, 0xe3, 0xc7, 0x8f, 0x1f,
0xfc, 0xfa, 0xf6, 0xee, 0xde, 0xbe, 0x7e, 0xf9, 0xf5, 0xed, 0xdd, 0xbd, 0x7d, 0xf3, 0xe7, 0xdb,
0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f, 0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f,
}
func minInt(a, b int) int {
if a < b {
return a
}
return b
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
func v6SplitMix64(x uint64) uint64 {
x ^= x >> 30
x *= 0xbf58476d1ce4e5b9
x ^= x >> 27
x *= 0x94d049bb133111eb
x ^= x >> 31
return x
}
func v6PRF32Fold(namespace uint64, label uint32, a uint64, b uint64) uint32 {
x := namespace ^ (b*v6CoefB + v6AddB) ^ (uint64(label) * v6GoldenGamma) ^ (a*v6CoefA + v6AddA)
y := v6SplitMix64(x)
return uint32(y ^ (y >> 32))
}
func v6Pick(raw uint32, lo int, hi int) int {
if hi < lo {
panic("snell v6: invalid profile range")
}
return lo + int(uint64(raw)%uint64(hi-lo+1))
}
func v6PickU32(raw uint32, lo uint32, hi uint32) uint32 {
if hi < lo {
panic("snell v6: invalid profile range")
}
return lo + raw%(hi-lo+1)
}
type v6Namespaces struct {
profile uint64
prefix uint64
motif uint64
salt uint64
mix uint64
chunk uint64
write uint64
}
func v6DeriveNamespace(secret []byte, label uint32, seedConst uint64) uint64 {
s0 := binary.LittleEndian.Uint64(secret[0:])
s1 := binary.LittleEndian.Uint64(secret[8:])
s2 := binary.LittleEndian.Uint64(secret[16:])
s3 := binary.LittleEndian.Uint64(secret[24:])
mixed := uint64(label)*v6DomainMul ^
(seedConst + v6NamespaceAdd) ^
s0 ^
(s1 + v6GoldenGamma) ^
bits.RotateLeft64(s2, 17) ^
bits.RotateLeft64(s3, -11)
return v6SplitMix64(mixed)
}
func newV6Namespaces(secret []byte) v6Namespaces {
return v6Namespaces{
profile: v6DeriveNamespace(secret, v6LabelProfileID, v6NSSeedProfile),
prefix: v6DeriveNamespace(secret, v6LabelPadding, v6NSSeedPrefix),
motif: v6DeriveNamespace(secret, v6LabelMotif, v6NSSeedMotif),
salt: v6DeriveNamespace(secret, v6LabelSalt, v6NSSeedSalt),
mix: v6DeriveNamespace(secret, v6LabelMixMode, v6NSSeedMix),
chunk: v6DeriveNamespace(secret, v6LabelChunkPolicy, v6NSSeedChunk),
write: v6DeriveNamespace(secret, v6LabelWritePolicy, v6NSSeedWrite),
}
}
func (n v6Namespaces) forLabel(label uint32) uint64 {
switch label {
case v6LabelPadding, v6LabelBitPercent, v6LabelPrefixMin, v6LabelPrefixMax, v6LabelRecordPrefix, v6LabelPayloadPad:
return n.prefix
case v6LabelMotif:
return n.motif
case v6LabelMixOffset, v6LabelMixMode, v6LabelMixRounds, v6LabelMixStride, v6LabelMixOffsetBase, v6LabelMixBlock:
return n.mix
case v6LabelChunkPolicy, v6LabelChunkInitial, v6LabelChunkMax, v6LabelChunkStep, v6LabelChunkJitter, v6LabelChunkBucket, v6LabelChunkSize, v6LabelChunkJitterV:
return n.chunk
case v6LabelWritePolicy, v6LabelWriteFirst, v6LabelWriteBucket, v6LabelWriteSeq, v6LabelWriteJitter, v6LabelWriteTarget, v6LabelWriteJitterV, v6LabelWriteNext:
return n.write
default:
return n.profile
}
}
func (n v6Namespaces) prf32(label uint32, a uint32, b uint32) uint32 {
return v6PRF32Fold(n.forLabel(label), label, uint64(a), uint64(b))
}
func (n v6Namespaces) prfBytes(label uint32, a uint32, output []byte) {
seed := n.forLabel(label) ^
(uint64(a)*v6DomainMul + 0xb57de1f3f82cb33f) ^
(uint64(label) * 0xa24baed4963ee407) ^
(uint64(len(output))*0x165667b19e3779f9 + 0x0d4cd3e7b14a36d7)
offset := 0
for offset < len(output) {
seed += v6GoldenGamma
block := v6SplitMix64(seed)
for shift := 0; shift < 64 && offset < len(output); shift += 8 {
output[offset] = byte(block >> shift)
offset++
}
}
}
func (n v6Namespaces) prfStatic(label uint32, domain uint32) uint32 {
return v6PRF32Fold(n.forLabel(label), label, 0, uint64(domain))
}
type v6Profile struct {
namespaces v6Namespaces
generator uint32
padMin int
padMax int
padCount uint32
padInterval uint32
smallLimit int
bitMin uint32
bitMax uint32
prefixMinRecord int
prefixMaxRecord int
mixMode uint32
mixRounds uint32
mixStride int
mixOffsetBase int
mixBlock int
chunkPolicy uint32
chunkInitial int
firstRecordCap int
chunkMax int
chunkStep int
chunkJitter int
idleResetSec int
writePolicy uint32
writeFirst uint32
chunkBuckets [8]int
writeBuckets [8]int
writeSeq [8]int
writeJitter int
writeJitterPct int
g1 int
g2 int
g3 int
g4 int
g5 int
g6 int
saltBlockLen int
mixStrideHandshake int
mixRoundsHandshake uint32
}
func v6ProfileSecret(psk []byte) [32]byte {
input := make([]byte, len(v6ProfileSeed)+len(psk))
copy(input, v6ProfileSeed[:])
copy(input[len(v6ProfileSeed):], psk)
return blake2b.Sum256(input)
}
func newV6Profile(psk []byte) *v6Profile {
secret := v6ProfileSecret(psk)
ns := newV6Namespaces(secret[:])
padMin := v6Pick(ns.prfStatic(v6LabelPadMin, 0), 0x18, 0xa0)
padMax := minInt(padMin+v6Pick(ns.prfStatic(v6LabelPadMax, 0), 0xa0, 0x3c0), v6MaxExtraPadding)
prefixMinHS := v6Pick(ns.prfStatic(v6LabelPrefixMin, v6HandshakeDomain), 0x10, 0x60)
prefixMaxHS := minInt(prefixMinHS+v6Pick(ns.prfStatic(v6LabelPrefixMax, v6HandshakeDomain), 0x10, 0xa0), 0x80)
prefixMinHS = minInt(prefixMinHS, prefixMaxHS)
saltPrefixLen := v6Pick(ns.prfStatic(v6LabelRecordPrefix, v6HandshakeDomain), prefixMinHS, prefixMaxHS)
saltBlockLen := v6SaltSize + saltPrefixLen
mixRoundsHS := v6PickU32(ns.prfStatic(v6LabelMixRounds, v6MixHandshakeDomain), 1, 4)
mixStrideHS := v6Pick(ns.prfStatic(v6LabelMixStride, v6MixHandshakeDomain), 0x11, 0xfb)
prefixMinRecord := v6Pick(ns.prfStatic(v6LabelPrefixMin, 0), 0x08, 0x50)
prefixMaxRecord := minInt(prefixMinRecord+v6Pick(ns.prfStatic(v6LabelPrefixMax, 0), 0x10, 0xa0), 0x80)
prefixMinRecord = minInt(prefixMinRecord, prefixMaxRecord)
chunkInitial := maxInt(0x60, minInt(v6Pick(ns.prfStatic(v6LabelChunkInitial, 0), 0x200, 0x05b4), 0x05b4))
firstRecordCap := maxInt(0x100, minInt(v6Pick(ns.prfStatic(v6LabelChunkFirstCap, v6ChunkInitialDomain), 0x100, 0x300), minInt(chunkInitial, 0x300)))
chunkMax := maxInt(v6Pick(ns.prfStatic(v6LabelChunkMax, 0), 0x2000, 0x3fff), chunkInitial)
profile := &v6Profile{
namespaces: ns,
generator: ns.prfStatic(v6LabelGenerator, 0) & 3,
padMin: padMin,
padMax: padMax,
padCount: v6PickU32(ns.prfStatic(v6LabelPadCount, 0), 2, 8),
padInterval: v6PickU32(ns.prfStatic(v6LabelPadInterval, 0), 2, 0x0b),
smallLimit: v6Pick(ns.prfStatic(v6LabelSmallLimit, 0), 0x60, 0x300),
bitMin: v6PickU32(ns.prfStatic(v6LabelBitMin, 0), 0x18, 0x29),
bitMax: v6PickU32(ns.prfStatic(v6LabelBitMax, 0), 0x3a, 0x4c),
prefixMinRecord: prefixMinRecord,
prefixMaxRecord: prefixMaxRecord,
mixMode: ns.prfStatic(v6LabelMixMode, 0) % 3,
mixRounds: v6PickU32(ns.prfStatic(v6LabelMixRounds, 0), 1, 3),
mixStride: v6Pick(ns.prfStatic(v6LabelMixStride, 0), 2, 13),
mixOffsetBase: v6Pick(ns.prfStatic(v6LabelMixOffsetBase, 0), 0, 15),
mixBlock: v6Pick(ns.prfStatic(v6LabelMixBlock, 0), 8, 0x40),
chunkPolicy: ns.prfStatic(v6LabelChunkPolicy, 0) % 3,
chunkInitial: chunkInitial,
firstRecordCap: firstRecordCap,
chunkMax: chunkMax,
chunkStep: minInt(v6Pick(ns.prfStatic(v6LabelChunkStep, 0), 0x400, 0x1000), 0x0b68),
chunkJitter: minInt(v6Pick(ns.prfStatic(v6LabelChunkJitter, 0), 0x10, 0xc0), 0x0b6),
idleResetSec: v6Pick(ns.prfStatic(v6LabelIdleReset, 0), 0x0c, 0x5a),
writePolicy: ns.prfStatic(v6LabelWritePolicy, 0) % 3,
writeFirst: v6PickU32(ns.prfStatic(v6LabelWriteFirst, 0), 4, 8),
writeJitter: v6Pick(ns.prfStatic(v6LabelWriteJitter, 0), 0x08, 0x60),
writeJitterPct: v6Pick(ns.prfStatic(v6LabelWritePolicy, 0x504c), 8, 0x30),
g1: v6Pick(ns.prfStatic(v6LabelGenerator, 1), 0x18, 0x80),
g2: v6Pick(ns.prfStatic(v6LabelGenerator, 2), 0x10, 0x60),
g3: v6Pick(ns.prfStatic(v6LabelGenerator, 3), 0x10, 0x60),
g4: v6Pick(ns.prfStatic(v6LabelGenerator, 4), 0x00, 0x09),
g5: v6Pick(ns.prfStatic(v6LabelGenerator, 5), 0x01, 0x08),
g6: v6Pick(ns.prfStatic(v6LabelGenerator, 6), 0x07, 0x17),
saltBlockLen: saltBlockLen,
mixStrideHandshake: mixStrideHS,
mixRoundsHandshake: mixRoundsHS,
}
for index := 0; index < 8; index++ {
profile.chunkBuckets[index] = v6Pick(ns.prfStatic(v6LabelChunkBucket, uint32(index)), 0x1000, chunkMax)
profile.writeBuckets[index] = v6Pick(ns.prfStatic(v6LabelWriteBucket, uint32(index)), 0x140, 0x05b4)
profile.writeSeq[index] = v6Pick(ns.prfStatic(v6LabelWriteSeq, uint32(index)), 0x168, 0x05b4)
}
return profile
}
// recordPrefixLen returns the length of the unencrypted prefix in front of the
// header of the record with the given sequence number.
func (p *v6Profile) recordPrefixLen(seq uint32) int {
return v6Pick(p.namespaces.prf32(v6LabelRecordPrefix, seq, 0), p.prefixMinRecord, p.prefixMaxRecord)
}
func (p *v6Profile) chunkPayloadLimit(seq uint32, chunkSize int) int {
if chunkSize == 0 {
chunkSize = p.chunkInitial
}
switch p.chunkPolicy {
case 1:
chunkSize = p.chunkBuckets[p.namespaces.prf32(v6LabelChunkSize, seq, uint32(chunkSize))%uint32(len(p.chunkBuckets))]
case 2:
rawJitter := p.namespaces.prf32(v6LabelChunkJitterV, seq, uint32(chunkSize))
chunkSize += int(rawJitter%uint32(p.chunkJitter*2+1)) - p.chunkJitter
}
return maxInt(0x40, minInt(chunkSize, p.chunkMax))
}
func (p *v6Profile) nextChunkSize(chunkSize int) int {
if chunkSize == 0 {
return p.chunkInitial
}
return minInt(chunkSize+p.chunkStep, p.chunkMax)
}
// paddingLen decides how much padding the record with sequence number seq
// carries. totalLen is the salt block length when this is the first record.
func (p *v6Profile) paddingLen(seq uint32, payloadLen int, prefixLen int, saltPrefixLen int, totalLen int) int {
paddingLen := 0
if seq < p.padCount || (payloadLen > 0 && payloadLen <= p.smallLimit) || (p.padInterval > 0 && seq%p.padInterval == 0) {
paddingLen = v6Pick(p.namespaces.prf32(v6LabelPayloadPad, seq, uint32(payloadLen)), p.padMin, p.padMax)
}
payloadTagLen := 0
if payloadLen > 0 {
payloadTagLen = v6TagSize
}
frameLen := totalLen + prefixLen + v6HeaderCipherSize + paddingLen + payloadLen + payloadTagLen
targetLen := p.writeTarget(seq, frameLen)
if targetLen > frameLen {
paddingLen += minInt(targetLen-frameLen, v6MaxExtraPadding)
}
if totalLen > 0 {
paddingLen = p.firstRecordPaddingLen(paddingLen, prefixLen, saltPrefixLen, payloadLen)
}
return minInt(paddingLen, 0xffff)
}
func (p *v6Profile) writeTarget(seq uint32, frameLen int) int {
if frameLen > 0x05b3 {
if frameLen <= 0xffff {
return frameLen
}
return 0xffff
}
var targetLen int
if seq < p.writeFirst {
targetLen = p.writeSeq[seq]
} else {
targetLen = p.writeBuckets[p.namespaces.prf32(v6LabelWriteTarget, seq, uint32(frameLen))%uint32(len(p.writeBuckets))]
}
if p.writePolicy == 2 {
rawJitter := p.namespaces.prf32(v6LabelWriteJitterV, seq, 0)
jitter := int(rawJitter%uint32(p.writeJitter*2+1)) - p.writeJitter
targetLen = maxInt(targetLen+jitter, 1)
}
spread := minInt(v6MaxExtraPadding, int(uint64(frameLen)*uint64(p.writeJitterPct)/100))
if p.namespaces.prf32(v6LabelWriteTarget, seq, uint32(spread))&1 == 0 {
if targetLen+spread <= 0xffff {
targetLen += spread
} else {
targetLen = 0xffff
}
} else {
halfSpread := spread >> 1
if targetLen > halfSpread {
targetLen -= halfSpread
}
}
for targetLen >= 0 && frameLen > targetLen {
nextLen := p.writeBuckets[p.namespaces.prf32(v6LabelWriteNext, seq, uint32(targetLen))%uint32(len(p.writeBuckets))]
if nextLen <= targetLen {
nextLen = targetLen + p.padMax
if nextLen > 0xffff {
return 0xffff
}
}
targetLen = nextLen
}
return targetLen
}
func (p *v6Profile) firstRecordPaddingLen(paddingLen int, prefixLen int, saltPrefixLen int, payloadLen int) int {
overheadLen := saltPrefixLen + prefixLen + paddingLen
thresholdInput := payloadLen + 0x37
if payloadLen == 0 {
thresholdInput = payloadLen + 0x27
}
threshold := maxInt((thresholdInput*25+0x4a)/75, 0xc0)
if overheadLen >= threshold {
return paddingLen
}
targetPaddingLen := threshold - saltPrefixLen - prefixLen
maxPaddingLen := p.padMax + v6MaxExtraPadding
if maxPaddingLen <= targetPaddingLen {
targetPaddingLen = maxPaddingLen
}
if targetPaddingLen > 0xfffe {
return paddingLen
}
return targetPaddingLen
}
// fillPadding generates the deterministic padding bytes of a record.
func (p *v6Profile) fillPadding(seq uint32, output []byte) {
if len(output) == 0 {
return
}
p.namespaces.prfBytes(v6LabelPadding, seq, output)
switch p.generator {
case 0:
bitCount := v6PickU32(p.namespaces.prf32(v6LabelBitPercent, seq, 0), p.bitMin, p.bitMax)
rotate := 1
scaled := int(bitCount) * 8
if scaled > 0x31 {
rotate = 7
if scaled <= 0x02ed {
rotate = (scaled + 0x32) / 100
}
}
for index, value := range output {
raw := byte(int(value) + index)
tableRow := maxInt(rotate, 1)
tableValue := v6BitRotateTable[tableRow*16+int((raw^value)&0x0f)]
output[index] = bits.RotateLeft8(tableValue, int((raw^(value>>4))&7))
}
case 1:
for index, value := range output {
bucket := int(value) % (p.g1 + p.g2 + p.g3)
switch {
case bucket < p.g1:
// the byte/index mix is truncated to a byte before being reduced into the printable range
output[index] = byte(v6Pick(uint32(byte(int(value)+index)), 0x20, 0x7e))
case bucket < p.g1+p.g2:
output[index] = byte(v6Pick(uint32(byte(int(value)^index)), 0x80, 0xbf))
default:
output[index] = byte(v6Pick(uint32(byte(int(value)+index*7)), 0xc0, 0xff))
}
}
case 2:
for index, value := range output {
low := (int(value&0x0f) + p.g4 + (index & 1)) % 10
high := (int(value) + ((index & 3) << 4) + 0x30) & 0xf0
output[index] = byte(high | low)
}
case 3:
motif := make([]byte, 32)
p.namespaces.prfBytes(v6LabelMotif, seq, motif)
motifLen := p.g5 * 4
if motifLen == 0 {
motifLen = 4
}
period := maxInt(p.g6, 5)
blockOffset := 0
motifOffset := 0
for index, value := range output {
switch {
case blockOffset < period-3:
output[index] = byte((p.g5+3)*index) ^ motif[motifOffset%len(motif)]
case blockOffset < period-1:
output[index] = byte(0x30 | (int(value) % 10))
}
blockOffset++
if blockOffset == period {
blockOffset = 0
}
motifOffset++
if motifOffset == motifLen {
motifOffset = 0
}
}
}
}
// --- salt block -------------------------------------------------------------
func v6SaltShufflePRF(nsSalt uint64, domain uint32, index uint32) uint32 {
rdx := uint64(index)*v6CoefB + v6AddB
rdi := nsSalt ^ v6SaltNSXor
rsi := uint64(domain)*v6CoefA + v6AddA
y := v6SplitMix64((rdx ^ rdi) ^ rsi)
return uint32(y ^ (y >> 32))
}
func v6ShufflePerm(nsSalt uint64, rounds uint8, length int) []byte {
out := make([]byte, length)
for index := range out {
out[index] = byte(index)
}
if length == 0 {
return out
}
if rounds == 0 {
rounds = 1
}
for round := uint32(0); round < uint32(rounds); round++ {
domain := uint32(v6MixHandshakeDomain) + round
for i := 0; i < length; i++ {
span := uint64(length - i)
raw := uint64(v6SaltShufflePRF(nsSalt, domain, uint32(i)))
j := i + int(raw%span)
out[i], out[j] = out[j], out[i]
}
}
return out
}
func v6SaltMask(nsSalt uint64, mixStride uint8, index uint32) byte {
prf := v6PRF32Fold(nsSalt, v6LabelMotif, uint64(v6MixHandshakeDomain), uint64(index))
return byte(index)*mixStride ^ byte(prf)
}
// extractSalt recovers the 16-byte salt scattered inside the first block.
func (p *v6Profile) extractSalt(block []byte) [v6SaltSize]byte {
perm := v6ShufflePerm(p.namespaces.salt, byte(p.mixRoundsHandshake), len(block))
var out [v6SaltSize]byte
for i := 0; i < v6SaltSize; i++ {
out[i] = v6SaltMask(p.namespaces.salt, byte(p.mixStrideHandshake), uint32(i)) ^ block[perm[i]]
}
return out
}
// writeSaltBlock scatters the salt into block, which must already hold the
// shaped padding generated for the sentinel sequence 0xffffffff.
func (p *v6Profile) writeSaltBlock(salt []byte, block []byte) {
perm := v6ShufflePerm(p.namespaces.salt, byte(p.mixRoundsHandshake), len(block))
for i := 0; i < v6SaltSize; i++ {
block[perm[i]] = v6SaltMask(p.namespaces.salt, byte(p.mixStrideHandshake), uint32(i)) ^ salt[i]
}
}
// --- padding / ciphertext interleave -----------------------------------------
// mixPaddingPayload swaps bytes between the padding and the payload ciphertext.
// The operation is its own inverse, so the reader applies it before decrypting.
func (p *v6Profile) mixPaddingPayload(seq uint32, padding []byte, payloadCipher []byte) {
n := minInt(len(padding), len(payloadCipher))
if n == 0 {
return
}
for round := uint32(0); round < p.mixRounds; round++ {
switch p.mixMode {
case 0:
p.mixFixedStride(round, padding, payloadCipher, n)
case 1:
p.mixAlternatingBlock(round, padding, payloadCipher, n)
case 2:
p.mixPRFStride(seq, round, padding, payloadCipher, n)
}
}
}
func (p *v6Profile) mixFixedStride(round uint32, padding []byte, payloadCipher []byte, n int) {
stride := maxInt(p.mixStride+int(round%3), 1)
if stride == 1 {
for i := 0; i < n; i++ {
padding[i], payloadCipher[i] = payloadCipher[i], padding[i]
}
return
}
for off := p.mixOffsetBase % stride; off < n; off += stride {
padding[off], payloadCipher[off] = payloadCipher[off], padding[off]
}
}
func (p *v6Profile) mixAlternatingBlock(round uint32, padding []byte, payloadCipher []byte, n int) {
block := p.mixBlock
for off := int(round&1) * block; off+block <= n; off += block * 2 {
for i := off; i < off+block; i++ {
padding[i], payloadCipher[i] = payloadCipher[i], padding[i]
}
}
}
func (p *v6Profile) mixPRFStride(seq uint32, round uint32, padding []byte, payloadCipher []byte, n int) {
stride := maxInt(p.mixStride+int(round%3), 1)
off := int((uint64(p.namespaces.prf32(v6LabelMixOffset, seq, round)) + uint64(p.mixOffsetBase)) % uint64(stride))
if stride == 1 {
for i := 0; i < n; i++ {
padding[i], payloadCipher[i] = payloadCipher[i], padding[i]
}
return
}
for ; off < n; off += stride {
padding[off], payloadCipher[off] = payloadCipher[off], padding[off]
}
}
+204
View File
@@ -0,0 +1,204 @@
package snell
import (
"bytes"
"crypto/rand"
"errors"
"io"
"net"
"reflect"
"testing"
"time"
"github.com/metacubex/mihomo/transport/shadowsocks/shadowaead"
"github.com/stretchr/testify/require"
)
var v6TestModes = map[string]V6Mode{
"default": V6ModeDefault,
"unshaped": V6ModeUnshaped,
"unsafe-raw": V6ModeUnsafeRaw,
}
const v6TestPSK = "snell-v6-test-psk-0123456789"
func TestV6ParseMode(t *testing.T) {
for _, name := range []string{"", "default", "unshaped", "unsafe-raw"} {
_, err := ParseV6Mode(name)
require.NoError(t, err, name)
}
_, err := ParseV6Mode("bogus")
require.Error(t, err)
require.Equal(t, "unshaped", V6ModeUnshaped.String())
}
func TestV6ProfileDeterministic(t *testing.T) {
a := newV6Profile([]byte(v6TestPSK))
b := newV6Profile([]byte(v6TestPSK))
require.True(t, reflect.DeepEqual(a, b), "same psk must derive the same profile")
c := newV6Profile([]byte(v6TestPSK + "x"))
require.False(t, reflect.DeepEqual(a.namespaces, c.namespaces), "different psk must derive a different profile")
}
func TestV6SaltBlockRoundTrip(t *testing.T) {
for i := 0; i < 32; i++ {
psk := make([]byte, 24)
_, err := rand.Read(psk)
require.NoError(t, err)
profile := newV6Profile(psk)
salt, err := v6RandomSalt()
require.NoError(t, err)
block := make([]byte, profile.saltBlockLen)
profile.fillPadding(0xffffffff, block)
profile.writeSaltBlock(salt, block)
extracted := profile.extractSalt(block)
require.Equal(t, salt, extracted[:])
}
}
func TestV6MixRoundTrip(t *testing.T) {
for i := 0; i < 32; i++ {
psk := make([]byte, 16)
_, err := rand.Read(psk)
require.NoError(t, err)
profile := newV6Profile(psk)
padding := make([]byte, 300)
payload := make([]byte, 700)
_, _ = rand.Read(padding)
_, _ = rand.Read(payload)
origPadding := append([]byte(nil), padding...)
origPayload := append([]byte(nil), payload...)
profile.mixPaddingPayload(uint32(i), padding, payload)
profile.mixPaddingPayload(uint32(i), padding, payload)
require.Equal(t, origPadding, padding)
require.Equal(t, origPayload, payload)
}
}
// v6Pair returns a client and a server side wrapped with the v6 record layer
// over a real loopback TCP connection.
func v6Pair(t *testing.T, mode V6Mode) (client, server *Snell) {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
defer listener.Close()
accepted := make(chan net.Conn, 1)
go func() {
conn, err := listener.Accept()
if err != nil {
close(accepted)
return
}
accepted <- conn
}()
clientConn, err := net.Dial("tcp", listener.Addr().String())
require.NoError(t, err)
serverConn, ok := <-accepted
require.True(t, ok)
t.Cleanup(func() {
clientConn.Close()
serverConn.Close()
})
return StreamConnV6(clientConn, []byte(v6TestPSK), mode), ServerStreamConnV6(serverConn, []byte(v6TestPSK), mode)
}
func TestV6ConnStream(t *testing.T) {
for name, mode := range v6TestModes {
t.Run(name, func(t *testing.T) {
client, server := v6Pair(t, mode)
payload := make([]byte, 300*1024)
_, err := rand.Read(payload)
require.NoError(t, err)
errCh := make(chan error, 1)
go func() {
_, err := client.Write(payload)
if err == nil {
err = HalfClose(client)
}
errCh <- err
}()
received := make([]byte, len(payload))
require.NoError(t, server.SetReadDeadline(time.Now().Add(10*time.Second)))
_, err = io.ReadFull(server.Conn, received)
require.NoError(t, err)
require.True(t, bytes.Equal(payload, received), "payload mismatch")
require.NoError(t, <-errCh)
// the zero chunk ends the stream
_, err = server.Conn.Read(received[:1])
require.True(t, errors.Is(err, shadowaead.ErrZeroChunk), "expected zero chunk, got %v", err)
// and the other direction works independently
reply := []byte("hello from server")
_, err = server.Write(reply)
require.NoError(t, err)
got := make([]byte, len(reply))
require.NoError(t, client.SetReadDeadline(time.Now().Add(10*time.Second)))
_, err = io.ReadFull(client.Conn, got)
require.NoError(t, err)
require.Equal(t, reply, got)
})
}
}
func TestV6ConnPacketFrames(t *testing.T) {
for name, mode := range v6TestModes {
t.Run(name, func(t *testing.T) {
client, server := v6Pair(t, mode)
for round := 0; round < 20; round++ {
// sizes above the shaped chunk limit must still arrive as one record
packet := make([]byte, 1400+round*97)
_, err := rand.Read(packet)
require.NoError(t, err)
_, err = client.WritePacketFrame(packet)
require.NoError(t, err)
buf := make([]byte, 64*1024)
require.NoError(t, server.SetReadDeadline(time.Now().Add(10*time.Second)))
n, err := server.Conn.Read(buf)
require.NoError(t, err)
require.Equal(t, len(packet), n, "a packet frame must be read back in one piece")
require.True(t, bytes.Equal(packet, buf[:n]))
}
})
}
}
func TestV6ConnWrongPSK(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
defer listener.Close()
go func() {
conn, err := listener.Accept()
if err != nil {
return
}
defer conn.Close()
server := ServerStreamConnV6(conn, []byte(v6TestPSK+"-other"), V6ModeDefault)
buf := make([]byte, 16)
_, _ = server.Conn.Read(buf)
}()
conn, err := net.Dial("tcp", listener.Addr().String())
require.NoError(t, err)
defer conn.Close()
client := StreamConnV6(conn, []byte(v6TestPSK), V6ModeDefault)
_, err = client.Write([]byte("hello"))
require.NoError(t, err)
require.NoError(t, client.SetReadDeadline(time.Now().Add(5*time.Second)))
_, err = client.Conn.Read(make([]byte, 16))
require.Error(t, err, "the server must not produce a readable reply with a different psk")
}
func TestValidateV6PSK(t *testing.T) {
require.Error(t, ValidateV6PSK([]byte("short")))
require.Error(t, ValidateV6PSK(make([]byte, 256)))
require.NoError(t, ValidateV6PSK([]byte(v6TestPSK)))
}
+46 -72
View File
@@ -1,100 +1,74 @@
package sudoku
import (
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"net/netip"
"strconv"
"strings"
"github.com/metacubex/mihomo/transport/socks5"
)
// EncodeAddress returns the SOCKS5 encoding of rawAddr ("host:port").
func EncodeAddress(rawAddr string) ([]byte, error) {
return AppendAddress(nil, rawAddr)
}
// AppendAddress appends the SOCKS5 encoding of rawAddr ("host:port") to dst; dst is returned
// unchanged on error. IPv4-mapped IPv6 literals are encoded as IPv4 and IPv6 zones are dropped.
func AppendAddress(dst []byte, rawAddr string) ([]byte, error) {
host, portStr, err := net.SplitHostPort(rawAddr)
if err != nil {
return nil, err
return dst, err
}
portInt, err := strconv.ParseUint(portStr, 10, 16)
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, err
return dst, err
}
var buf []byte
if i := strings.IndexByte(host, '%'); i >= 0 {
// Zone identifiers are not representable in SOCKS5 IPv6 address encoding.
host = host[:i]
}
if ip := net.ParseIP(host); ip != nil {
if ip4 := ip.To4(); ip4 != nil {
buf = append(buf, 0x01) // IPv4
buf = append(buf, ip4...)
} else {
buf = append(buf, 0x04) // IPv6
ip16 := ip.To16()
if ip16 == nil {
return nil, fmt.Errorf("invalid ipv6: %q", host)
}
buf = append(buf, ip16...)
}
if ip, err := netip.ParseAddr(host); err == nil {
return AppendAddrPort(dst, netip.AddrPortFrom(ip, uint16(port))), nil
}
if len(host) > 255 {
return dst, errors.New("domain too long")
}
dst = append(dst, socks5.AtypDomainName, byte(len(host)))
dst = append(dst, host...)
return append(dst, byte(port>>8), byte(port)), nil
}
// AppendAddrPort appends the SOCKS5 encoding of an IP destination to dst. IPv4-mapped IPv6
// addresses are encoded as IPv4 and zones are dropped.
func AppendAddrPort(dst []byte, ap netip.AddrPort) []byte {
if ip := ap.Addr().Unmap(); ip.Is4() {
v := ip.As4()
dst = append(dst, socks5.AtypIPv4)
dst = append(dst, v[:]...)
} else {
if len(host) > 255 {
return nil, fmt.Errorf("domain too long")
}
buf = append(buf, 0x03) // domain
buf = append(buf, byte(len(host)))
buf = append(buf, host...)
v := ip.As16()
dst = append(dst, socks5.AtypIPv6)
dst = append(dst, v[:]...)
}
var portBytes [2]byte
binary.BigEndian.PutUint16(portBytes[:], uint16(portInt))
buf = append(buf, portBytes[:]...)
return buf, nil
return append(dst, byte(ap.Port()>>8), byte(ap.Port()))
}
func DecodeAddress(r io.Reader) (string, error) {
var atyp [1]byte
if _, err := io.ReadFull(r, atyp[:]); err != nil {
return "", err
}
switch atyp[0] {
case 0x01: // IPv4
var ipBuf [net.IPv4len]byte
if _, err := io.ReadFull(r, ipBuf[:]); err != nil {
return "", err
}
var portBuf [2]byte
if _, err := io.ReadFull(r, portBuf[:]); err != nil {
return "", err
}
return net.JoinHostPort(net.IP(ipBuf[:]).String(), fmt.Sprint(binary.BigEndian.Uint16(portBuf[:]))), nil
case 0x04: // IPv6
var ipBuf [net.IPv6len]byte
if _, err := io.ReadFull(r, ipBuf[:]); err != nil {
return "", err
}
var portBuf [2]byte
if _, err := io.ReadFull(r, portBuf[:]); err != nil {
return "", err
}
return net.JoinHostPort(net.IP(ipBuf[:]).String(), fmt.Sprint(binary.BigEndian.Uint16(portBuf[:]))), nil
case 0x03: // domain
var lengthBuf [1]byte
if _, err := io.ReadFull(r, lengthBuf[:]); err != nil {
return "", err
}
l := int(lengthBuf[0])
hostBuf := make([]byte, l)
if _, err := io.ReadFull(r, hostBuf); err != nil {
return "", err
}
var portBuf [2]byte
if _, err := io.ReadFull(r, portBuf[:]); err != nil {
return "", err
}
return net.JoinHostPort(string(hostBuf), fmt.Sprint(binary.BigEndian.Uint16(portBuf[:]))), nil
default:
return "", fmt.Errorf("unknown address type: %d", atyp[0])
// DecodeAddress parses the SOCKS5 address at the start of b and returns it as "host:port";
// bytes after the address are ignored.
func DecodeAddress(b []byte) (string, error) {
addr := socks5.SplitAddr(b)
if addr == nil {
if len(b) == 0 {
return "", io.EOF
}
return "", fmt.Errorf("invalid address: type %d, %d bytes", b[0], len(b))
}
return addr.String(), nil
}
-150
View File
@@ -1,150 +0,0 @@
package crypto
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"golang.org/x/crypto/chacha20poly1305"
)
type AEADConn struct {
net.Conn
aead cipher.AEAD
readBuf bytes.Buffer
nonceSize int
}
func (cc *AEADConn) CloseWrite() error {
if cc == nil || cc.Conn == nil {
return nil
}
if cw, ok := cc.Conn.(interface{ CloseWrite() error }); ok {
return cw.CloseWrite()
}
return nil
}
func (cc *AEADConn) CloseRead() error {
if cc == nil || cc.Conn == nil {
return nil
}
if cr, ok := cc.Conn.(interface{ CloseRead() error }); ok {
return cr.CloseRead()
}
return nil
}
func NewAEADConn(c net.Conn, key string, method string) (*AEADConn, error) {
if method == "none" {
return &AEADConn{Conn: c, aead: nil}, nil
}
h := sha256.New()
h.Write([]byte(key))
keyBytes := h.Sum(nil)
var aead cipher.AEAD
var err error
switch method {
case "aes-128-gcm":
block, _ := aes.NewCipher(keyBytes[:16])
aead, err = cipher.NewGCM(block)
case "chacha20-poly1305":
aead, err = chacha20poly1305.New(keyBytes)
default:
return nil, fmt.Errorf("unsupported cipher: %s", method)
}
if err != nil {
return nil, err
}
return &AEADConn{
Conn: c,
aead: aead,
nonceSize: aead.NonceSize(),
}, nil
}
func (cc *AEADConn) Write(p []byte) (int, error) {
if cc.aead == nil {
return cc.Conn.Write(p)
}
maxPayload := 65535 - cc.nonceSize - cc.aead.Overhead()
totalWritten := 0
var frameBuf bytes.Buffer
header := make([]byte, 2)
nonce := make([]byte, cc.nonceSize)
for len(p) > 0 {
chunkSize := len(p)
if chunkSize > maxPayload {
chunkSize = maxPayload
}
chunk := p[:chunkSize]
p = p[chunkSize:]
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return totalWritten, err
}
ciphertext := cc.aead.Seal(nil, nonce, chunk, nil)
frameLen := len(nonce) + len(ciphertext)
binary.BigEndian.PutUint16(header, uint16(frameLen))
frameBuf.Reset()
frameBuf.Write(header)
frameBuf.Write(nonce)
frameBuf.Write(ciphertext)
if _, err := cc.Conn.Write(frameBuf.Bytes()); err != nil {
return totalWritten, err
}
totalWritten += chunkSize
}
return totalWritten, nil
}
func (cc *AEADConn) Read(p []byte) (int, error) {
if cc.aead == nil {
return cc.Conn.Read(p)
}
if cc.readBuf.Len() > 0 {
return cc.readBuf.Read(p)
}
header := make([]byte, 2)
if _, err := io.ReadFull(cc.Conn, header); err != nil {
return 0, err
}
frameLen := int(binary.BigEndian.Uint16(header))
body := make([]byte, frameLen)
if _, err := io.ReadFull(cc.Conn, body); err != nil {
return 0, err
}
if len(body) < cc.nonceSize {
return 0, errors.New("frame too short")
}
nonce := body[:cc.nonceSize]
ciphertext := body[cc.nonceSize:]
plaintext, err := cc.aead.Open(nil, nonce, ciphertext, nil)
if err != nil {
return 0, errors.New("decryption failed")
}
cc.readBuf.Write(plaintext)
return cc.readBuf.Read(p)
}
+61 -21
View File
@@ -1,7 +1,6 @@
package crypto
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
@@ -15,6 +14,8 @@ import (
"sync"
"sync/atomic"
"github.com/metacubex/mihomo/common/pool"
"golang.org/x/crypto/chacha20poly1305"
)
@@ -67,11 +68,12 @@ type RecordConn struct {
recvSeq uint64
recvInitialized bool
readBuf bytes.Buffer
// writeFrame is a reusable buffer for [len||header||ciphertext] on the wire.
// Guarded by writeMu.
writeFrame []byte
// readFrame is the pooled record whose decrypted plaintext (readPlain) the
// caller has not fully read yet; it is nil whenever the connection is idle.
// Guarded by readMu.
readFrame []byte
readPlain []byte
readOff int
}
func (c *RecordConn) CloseWrite() error {
@@ -137,7 +139,7 @@ func (c *RecordConn) Rekey(baseSend, baseRecv []byte) error {
if err := c.resetTrafficState(); err != nil {
return err
}
c.readBuf.Reset()
c.releaseReadFrame()
c.sendAEAD = nil
c.recvAEAD = nil
@@ -357,17 +359,16 @@ func (c *RecordConn) Write(p []byte) (int, error) {
if bodyLen > maxFrameBodySize {
return total, errors.New("frame too large")
}
if cap(c.writeFrame) < frameLen {
c.writeFrame = make([]byte, frameLen)
}
frame := c.writeFrame[:frameLen]
frame := pool.Get(frameLen)
binary.BigEndian.PutUint16(frame[:2], uint16(bodyLen))
copy(frame[2:2+recordHeaderSize], header[:])
dst := frame[2+recordHeaderSize : 2+recordHeaderSize : frameLen]
_ = aead.Seal(dst[:0], header[:], chunk, header[:])
if _, err := c.Conn.Write(frame); err != nil {
_, err := c.Conn.Write(frame)
_ = pool.Put(frame)
if err != nil {
return total, err
}
@@ -390,8 +391,8 @@ func (c *RecordConn) Read(p []byte) (int, error) {
c.readMu.Lock()
defer c.readMu.Unlock()
if c.readBuf.Len() > 0 {
return c.readBuf.Read(p)
if c.readOff < len(c.readPlain) {
return c.drainPlain(p), nil
}
var lenBuf [2]byte
@@ -406,10 +407,25 @@ func (c *RecordConn) Read(p []byte) (int, error) {
return 0, errors.New("frame too large")
}
body := make([]byte, bodyLen)
body := pool.Get(bodyLen)
if _, err := io.ReadFull(c.Conn, body); err != nil {
_ = pool.Put(body)
return 0, err
}
n, plain, err := c.open(body, p)
if plain == nil {
_ = pool.Put(body)
return n, err
}
// p was too small for the record: keep the frame until it is drained.
c.readFrame, c.readPlain, c.readOff = body, plain, 0
return c.drainPlain(p), nil
}
// open authenticates one record body. The plaintext goes straight into p when it
// fits (n bytes, plain == nil); otherwise it is decrypted in place and returned as
// plain for drainPlain to hand out.
func (c *RecordConn) open(body, p []byte) (n int, plain []byte, err error) {
header := body[:recordHeaderSize]
ciphertext := body[recordHeaderSize:]
@@ -417,25 +433,49 @@ func (c *RecordConn) Read(p []byte) (int, error) {
seq := binary.BigEndian.Uint64(header[4:])
if err := c.validateRecvPosition(epoch, seq); err != nil {
return 0, err
return 0, nil, err
}
if c.recvAEAD == nil || c.recvAEADEpoch != epoch {
a, err := c.newAEADFor(c.keys.baseRecv, epoch)
if err != nil {
return 0, err
return 0, nil, err
}
c.recvAEAD = a
c.recvAEADEpoch = epoch
}
aead := c.recvAEAD
plaintext, err := aead.Open(nil, header, ciphertext, header)
plainSize := len(ciphertext) - aead.Overhead()
direct := plainSize >= 0 && len(p) >= plainSize
dst := ciphertext[:0]
if direct {
dst = p[:0]
}
plaintext, err := aead.Open(dst, header, ciphertext, header)
if err != nil {
return 0, fmt.Errorf("decryption failed: epoch=%d seq=%d: %w", epoch, seq, err)
return 0, nil, fmt.Errorf("decryption failed: epoch=%d seq=%d: %w", epoch, seq, err)
}
c.markRecvPosition(epoch, seq)
c.readBuf.Write(plaintext)
return c.readBuf.Read(p)
if direct {
return len(plaintext), nil, nil
}
return 0, plaintext, nil
}
func (c *RecordConn) drainPlain(dst []byte) int {
n := copy(dst, c.readPlain[c.readOff:])
c.readOff += n
if c.readOff >= len(c.readPlain) {
c.releaseReadFrame()
}
return n
}
func (c *RecordConn) releaseReadFrame() {
if c.readFrame != nil {
_ = pool.Put(c.readFrame)
}
c.readFrame, c.readPlain, c.readOff = nil, nil, 0
}
@@ -84,3 +84,41 @@ func TestRecordConn_FirstFrameUsesRandomizedCounters(t *testing.T) {
t.Fatalf("plaintext mismatch: got %q want %q", got, want)
}
}
func TestRecordConn_SmallReadsReleaseFrame(t *testing.T) {
pskSend := sha256.Sum256([]byte("record-send"))
pskRecv := sha256.Sum256([]byte("record-recv"))
raw := &captureConn{}
writer, err := NewRecordConn(raw, "chacha20-poly1305", pskSend[:], pskRecv[:])
if err != nil {
t.Fatalf("new writer: %v", err)
}
want := bytes.Repeat([]byte("0123456789abcdef"), 1024)
if _, err := writer.Write(want); err != nil {
t.Fatalf("write: %v", err)
}
reader, err := NewRecordConn(&replayConn{reader: bytes.NewReader(raw.Bytes())}, "chacha20-poly1305", pskRecv[:], pskSend[:])
if err != nil {
t.Fatalf("new reader: %v", err)
}
got := make([]byte, len(want))
buf := make([]byte, 100)
for off := 0; off < len(got); {
n, err := reader.Read(buf)
if err != nil {
t.Fatalf("read: %v", err)
}
if reader.readFrame != nil && reader.readOff >= len(reader.readPlain) {
t.Fatal("drained record still holds its frame")
}
off += copy(got[off:], buf[:n])
}
if !bytes.Equal(got, want) {
t.Fatal("plaintext mismatch")
}
if reader.readFrame != nil {
t.Fatal("idle reader holds a frame")
}
}
+1 -1
View File
@@ -526,7 +526,7 @@ func ReadServerSession(conn net.Conn, meta *HandshakeMeta) (*ServerSession, erro
case KIPTypeStartMux:
return &ServerSession{Conn: conn, Type: SessionTypeMultiplex, UserHash: userHash}, nil
case KIPTypeOpenTCP:
target, err := DecodeAddress(bytes.NewReader(first.Payload))
target, err := DecodeAddress(first.Payload)
if err != nil {
return nil, fmt.Errorf("decode target address failed: %w", err)
}
+128 -3
View File
@@ -2,6 +2,8 @@ package sudoku
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
@@ -66,6 +68,38 @@ func TestPackedConnRoundTrip_WithPadding(t *testing.T) {
}
}
// newSocketPair returns two connected loopback conns. The packed tests use it instead of net.Pipe: a pipe
// has no buffer, so a Write returns only once the peer has read every byte, including the padding byte that
// may close it. A decoder that already has the whole message never reads that byte, and a server that
// answers at that point leaves both ends blocked in Write.
func newSocketPair() (server, client net.Conn, err error) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, nil, err
}
defer ln.Close()
accepted := make(chan net.Conn, 1)
go func() {
c, err := ln.Accept()
if err != nil {
c = nil
}
accepted <- c
}()
client, err = net.Dial("tcp", ln.Addr().String())
if err != nil {
return nil, nil, err
}
server = <-accepted
if server == nil {
_ = client.Close()
return nil, nil, errors.New("accept loopback conn failed")
}
return server, client, nil
}
func newPackedConfig(table *sudokuobfs.Table) *ProtocolConfig {
cfg := DefaultConfig()
cfg.Key = "sudoku-test-key"
@@ -118,12 +152,17 @@ func TestPackedDownlinkSoak(t *testing.T) {
}
func runPackedTCPSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
serverConn, clientConn := net.Pipe()
serverConn, clientConn, err := newSocketPair()
if err != nil {
errCh <- err
return
}
target := fmt.Sprintf("1.1.1.%d:80", (id%200)+1)
payload := []byte{0x42, byte(id)}
serverErr := make(chan error, 1)
go func() {
defer serverConn.Close()
c, meta, err := ServerHandshake(serverConn, cfg)
if err != nil {
serverErr <- fmt.Errorf("server handshake tcp: %w", err)
@@ -183,12 +222,17 @@ func runPackedTCPSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
}
func runPackedUoTSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
serverConn, clientConn := net.Pipe()
serverConn, clientConn, err := newSocketPair()
if err != nil {
errCh <- err
return
}
target := "8.8.8.8:53"
payload := []byte{0xaa, byte(id)}
serverErr := make(chan error, 1)
go func() {
defer serverConn.Close()
c, meta, err := ServerHandshake(serverConn, cfg)
if err != nil {
serverErr <- fmt.Errorf("server handshake uot: %w", err)
@@ -226,7 +270,7 @@ func runPackedUoTSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
return
}
addr, data, err := ReadDatagram(cConn)
addr, data, err := readTestDatagram(cConn)
if err != nil {
errCh <- fmt.Errorf("client read datagram: %w", err)
return
@@ -270,3 +314,84 @@ func TestCustomTableHandshake(t *testing.T) {
}
}
}
func readTestDatagram(r io.Reader) (string, []byte, error) {
addr, payload, err := NewUoTReader(r).ReadDatagram()
if err != nil {
return "", nil, err
}
return addr.String(), payload, nil
}
type countingWriter struct {
writes int
bytes.Buffer
}
func (w *countingWriter) Write(p []byte) (int, error) {
w.writes++
return w.Buffer.Write(p)
}
func TestUoTDatagramIsOneWrite(t *testing.T) {
for _, target := range []string{"8.8.8.8:53", "[2001:db8::1]:443", "example.com:80"} {
var w countingWriter
payload := bytes.Repeat([]byte{0x5a}, 1200)
if err := WriteDatagram(&w, target, payload); err != nil {
t.Fatalf("%s: write datagram: %v", target, err)
}
if w.writes != 1 {
t.Fatalf("%s: datagram took %d writes, want 1", target, w.writes)
}
addr, got, err := readTestDatagram(&w.Buffer)
if err != nil || addr != target || !bytes.Equal(got, payload) {
t.Fatalf("%s: round trip got %q %d bytes, %v", target, addr, len(got), err)
}
}
var w countingWriter
if err := WriteDatagram(&w, "8.8.8.8:53", make([]byte, 65535)); err != nil {
t.Fatalf("largest payload: %v", err)
}
if err := WriteDatagram(&w, "8.8.8.8:53", make([]byte, 65536)); err == nil {
t.Fatal("payload over 65535 bytes must be rejected")
}
}
func TestUoTPacketConnReadFrom(t *testing.T) {
frame := func(addr string, padding int, payload string) []byte {
enc, err := EncodeAddress(addr)
if err != nil {
t.Fatal(err)
}
b := binary.BigEndian.AppendUint16(nil, uint16(len(enc)+padding))
b = binary.BigEndian.AppendUint16(b, uint16(len(payload)))
b = append(b, enc...)
b = append(b, make([]byte, padding)...)
return append(b, payload...)
}
var stream []byte
stream = append(stream, frame("example.com:53", 0, "dns")...) // domain peers are dropped
stream = append(stream, frame("8.8.8.8:53", 0, "too long for p")...) // consumed, reported as short
stream = append(stream, frame("[::ffff:1.2.3.4]:5353", 300, "ok")...) // padded address, mapped IPv6
client, server := net.Pipe()
defer client.Close()
go func() {
_, _ = server.Write(stream)
_ = server.Close()
}()
pc := NewUoTPacketConn(client)
p := make([]byte, 8)
if _, _, err := pc.ReadFrom(p); !errors.Is(err, io.ErrShortBuffer) {
t.Fatalf("oversized datagram: err = %v, want io.ErrShortBuffer", err)
}
n, from, err := pc.ReadFrom(p)
if err != nil || string(p[:n]) != "ok" {
t.Fatalf("read after short buffer: %q, %v", p[:n], err)
}
if udp := from.(*net.UDPAddr); udp.String() != "1.2.3.4:5353" || len(udp.IP) != net.IPv4len {
t.Fatalf("peer = %v (%d-byte IP), want 1.2.3.4:5353 as IPv4", from, len(udp.IP))
}
}
+2 -2
View File
@@ -207,7 +207,7 @@ func TestHTTPMaskTunnel_Poll_UoTRoundTrip(t *testing.T) {
if s.Type != SessionTypeUoT {
return fmt.Errorf("unexpected session type: %v", s.Type)
}
gotAddr, gotPayload, err := ReadDatagram(s.Conn)
gotAddr, gotPayload, err := readTestDatagram(s.Conn)
if err != nil {
return fmt.Errorf("server read datagram: %w", err)
}
@@ -250,7 +250,7 @@ func TestHTTPMaskTunnel_Poll_UoTRoundTrip(t *testing.T) {
if err := WriteDatagram(cConn, target, payload); err != nil {
t.Fatalf("write datagram: %v", err)
}
gotAddr, gotPayload, err := ReadDatagram(cConn)
gotAddr, gotPayload, err := readTestDatagram(cConn)
if err != nil {
t.Fatalf("read datagram: %v", err)
}
+15 -6
View File
@@ -11,6 +11,7 @@ import (
"strings"
"time"
"github.com/metacubex/mihomo/common/pool"
sudokuobfs "github.com/metacubex/mihomo/transport/sudoku/obfs/sudoku"
)
@@ -53,6 +54,11 @@ type KIPMessage struct {
Payload []byte
}
// kipHeaderSize is magic | type | u16 payload length.
const kipHeaderSize = len(kipMagic) + 1 + 2
// WriteKIPMessage sends header and payload with a single write, so the transport frames
// them as one record instead of two.
func WriteKIPMessage(w io.Writer, typ byte, payload []byte) error {
if w == nil {
return fmt.Errorf("%w: nil writer", errKIP)
@@ -61,19 +67,22 @@ func WriteKIPMessage(w io.Writer, typ byte, payload []byte) error {
return fmt.Errorf("%w: payload too large: %d", errKIP, len(payload))
}
var hdr [3 + 1 + 2]byte
copy(hdr[:3], []byte(kipMagic))
hdr[3] = typ
binary.BigEndian.PutUint16(hdr[4:], uint16(len(payload)))
buf := pool.Get(kipHeaderSize + len(payload))
defer pool.Put(buf)
copy(buf, kipMagic)
buf[3] = typ
binary.BigEndian.PutUint16(buf[4:], uint16(len(payload)))
copy(buf[kipHeaderSize:], payload)
return writeAllChunks(w, hdr[:], payload)
_, err := w.Write(buf)
return err
}
func ReadKIPMessage(r io.Reader) (*KIPMessage, error) {
if r == nil {
return nil, fmt.Errorf("%w: nil reader", errKIP)
}
var hdr [3 + 1 + 2]byte
var hdr [kipHeaderSize]byte
if _, err := io.ReadFull(r, hdr[:]); err != nil {
return nil, err
}
+15
View File
@@ -1,6 +1,7 @@
package sudoku
import (
"bytes"
"testing"
sudokuobfs "github.com/metacubex/mihomo/transport/sudoku/obfs/sudoku"
@@ -62,3 +63,17 @@ func TestResolveClientHelloTableRejectsEntropyMismatch(t *testing.T) {
t.Fatalf("expected entropy-table mismatch to fail")
}
}
func TestWriteKIPMessageIsOneWrite(t *testing.T) {
var w countingWriter
if err := WriteKIPMessage(&w, KIPTypeOpenTCP, []byte{1, 2, 3}); err != nil {
t.Fatalf("write: %v", err)
}
if w.writes != 1 {
t.Fatalf("KIP message took %d writes, want 1", w.writes)
}
msg, err := ReadKIPMessage(bytes.NewReader(w.Bytes()))
if err != nil || msg.Type != KIPTypeOpenTCP || !bytes.Equal(msg.Payload, []byte{1, 2, 3}) {
t.Fatalf("round trip: %+v, %v", msg, err)
}
}
+1 -2
View File
@@ -1,7 +1,6 @@
package sudoku
import (
"bytes"
"context"
"fmt"
"net"
@@ -119,7 +118,7 @@ func (s *MultiplexServer) AcceptTCP() (net.Conn, string, error) {
return nil, "", err
}
target, err := DecodeAddress(bytes.NewReader(payload))
target, err := DecodeAddress(payload)
if err != nil {
_ = stream.Close()
return nil, "", err
+172 -30
View File
@@ -1,6 +1,7 @@
package multiplex
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
@@ -9,6 +10,8 @@ import (
"sync"
"sync/atomic"
"time"
"github.com/metacubex/mihomo/common/pool"
)
const (
@@ -16,6 +19,8 @@ const (
frameData byte = 0x02
frameClose byte = 0x03
frameReset byte = 0x04
framePing byte = 0x05
framePong byte = 0x06
)
const (
@@ -26,6 +31,12 @@ const (
maxFrameSize = 256 * 1024
maxDataPayload = 128 * 1024
keepaliveInterval = 15 * time.Second
// Frames of at most coalesceMaxPayload bytes are queued and written together with the
// frames of other streams; larger ones are written directly behind the queue. A sender
// that finds coalesceMaxPending bytes queued waits for its turn to write.
coalesceMaxPayload = 4 * 1024
coalesceMaxPending = 64 * 1024
)
var errMuxReceiveQueueFull = errors.New("mux receive queue full")
@@ -38,7 +49,11 @@ type acceptEvent struct {
type Session struct {
conn net.Conn
// writeMu is held by whichever goroutine is writing to conn. Small frames wait in
// pending (guarded by pendMu) so that one write can carry the frames of several streams.
writeMu sync.Mutex
pendMu sync.Mutex
pending *bytes.Buffer
streamsMu sync.Mutex
streams map[uint32]*stream
@@ -50,8 +65,10 @@ type Session struct {
closeOnce sync.Once
closeErr error
lastWrite atomic.Int64
keepaliveOnce sync.Once
// wroteSinceTick is set by sendFrame and consumed by the idle keepalive tick.
wroteSinceTick atomic.Bool
keepaliveOnce sync.Once
pongPending atomic.Bool
}
func NewClientSession(conn net.Conn) (*Session, error) {
@@ -63,7 +80,6 @@ func NewClientSession(conn net.Conn) (*Session, error) {
streams: make(map[uint32]*stream),
closed: make(chan struct{}),
}
s.lastWrite.Store(time.Now().UnixNano())
go s.readLoop()
s.startKeepalive(keepaliveInterval)
return s, nil
@@ -79,7 +95,6 @@ func NewServerSession(conn net.Conn) (*Session, error) {
acceptCh: make(chan acceptEvent, 256),
closed: make(chan struct{}),
}
s.lastWrite.Store(time.Now().UnixNano())
go s.readLoop()
s.startKeepalive(keepaliveInterval)
return s, nil
@@ -138,6 +153,13 @@ func (s *Session) closeWithError(err error) {
close(s.closed)
_ = s.conn.Close()
s.pendMu.Lock()
if s.pending != nil {
pool.PutBuffer(s.pending)
s.pending = nil
}
s.pendMu.Unlock()
})
}
@@ -188,22 +210,132 @@ func (s *Session) sendFrame(frameType byte, streamID uint32, payload []byte) err
return fmt.Errorf("mux payload too large: %d", len(payload))
}
var header [headerSize]byte
header[0] = frameType
binary.BigEndian.PutUint32(header[1:5], streamID)
binary.BigEndian.PutUint32(header[5:9], uint32(len(payload)))
s.writeMu.Lock()
defer s.writeMu.Unlock()
if err := writeAllChunks(s.conn, header[:], payload); err != nil {
s.closeWithError(err)
var err error
if len(payload) <= coalesceMaxPayload {
err = s.sendQueued(frameType, streamID, payload)
} else {
err = s.sendDirect(frameType, streamID, payload)
}
if err != nil {
return err
}
s.lastWrite.Store(time.Now().UnixNano())
// Load first: the store only happens once per keepalive interval, so the hot path
// never writes the shared cache line.
if !s.wroteSinceTick.Load() {
s.wroteSinceTick.Store(true)
}
return nil
}
func putHeader(header []byte, frameType byte, streamID uint32, payloadLen int) {
header[0] = frameType
binary.BigEndian.PutUint32(header[1:5], streamID)
binary.BigEndian.PutUint32(header[5:9], uint32(payloadLen))
}
// sendQueued appends the frame to the pending batch, then writes the batch unless another
// goroutine is already writing, which picks the frame up when it finishes its current write.
func (s *Session) sendQueued(frameType byte, streamID uint32, payload []byte) error {
var header [headerSize]byte
putHeader(header[:], frameType, streamID, len(payload))
s.pendMu.Lock()
if s.pending == nil {
s.pending = pool.GetBuffer()
}
s.pending.Write(header[:])
s.pending.Write(payload)
full := s.pending.Len() >= coalesceMaxPending
s.pendMu.Unlock()
return s.flushPending(full)
}
// flushPending writes the pending batch. Unless wait is set it gives up when another
// goroutine holds the write role; that goroutine rechecks the batch after each write, so
// no frame is stranded.
func (s *Session) flushPending(wait bool) error {
for {
if wait {
s.writeMu.Lock()
} else if !s.writeMu.TryLock() {
return nil
}
err := s.writeBatch(nil)
s.writeMu.Unlock()
if err != nil {
return err
}
wait = false
s.pendMu.Lock()
empty := s.pending == nil
s.pendMu.Unlock()
if empty {
return nil
}
}
}
// writeBatch writes the pending batch, followed by header when it is not nil, with one
// write. writeMu must be held.
func (s *Session) writeBatch(header []byte) error {
s.pendMu.Lock()
batch := s.pending
s.pending = nil
s.pendMu.Unlock()
var err error
switch {
case batch == nil && header == nil:
return nil
case batch == nil:
_, err = s.conn.Write(header)
default:
batch.Write(header)
_, err = s.conn.Write(batch.Bytes())
pool.PutBuffer(batch)
}
if err != nil {
s.closeWithError(err)
}
return err
}
// sendDirect writes a large frame behind any batch that is already pending, which keeps the
// frames of a stream in order. The header travels with the batch; nothing can be queued in
// front of the payload because writeMu is held until it is written.
func (s *Session) sendDirect(frameType byte, streamID uint32, payload []byte) error {
var header [headerSize]byte
putHeader(header[:], frameType, streamID, len(payload))
s.writeMu.Lock()
err := s.writeBatch(header[:])
if err == nil {
if _, err = s.conn.Write(payload); err != nil {
s.closeWithError(err)
}
}
s.writeMu.Unlock()
if err != nil {
return err
}
// Frames queued while this one was being written still need a writer.
_ = s.flushPending(false)
return nil
}
// requestPong answers a ping off the read loop, which must not block on a write. Pings that
// arrive while a pong is still waiting to be sent share it.
func (s *Session) requestPong() {
if s.pongPending.Swap(true) {
return
}
go func() {
s.pongPending.Store(false)
_ = s.sendFrame(framePong, 0, nil)
}()
}
func (s *Session) startKeepalive(interval time.Duration) {
if s == nil || interval <= 0 {
return
@@ -215,8 +347,7 @@ func (s *Session) startKeepalive(interval time.Duration) {
for {
select {
case <-ticker.C:
lastWrite := time.Unix(0, s.lastWrite.Load())
if time.Since(lastWrite) < interval {
if s.wroteSinceTick.Swap(false) {
continue
}
// Stream zero is never allocated. v0.4.7 peers ignore DATA
@@ -224,6 +355,8 @@ func (s *Session) startKeepalive(interval time.Duration) {
if err := s.sendFrame(frameData, 0, nil); err != nil {
return
}
// The keepalive itself is not traffic.
s.wroteSinceTick.Store(false)
case <-s.closed:
return
}
@@ -299,6 +432,19 @@ func (s *Session) readLoop() {
}
}
switch frameType {
case framePing:
if streamID != 0 || len(payload) != 0 {
s.closeWithError(errors.New("invalid mux ping frame"))
return
}
s.requestPong()
case framePong:
if streamID != 0 || len(payload) != 0 {
s.closeWithError(errors.New("invalid mux pong frame"))
return
}
case frameOpen:
if s.acceptCh == nil {
s.sendReset(streamID, "unexpected open")
@@ -397,7 +543,7 @@ type stream struct {
writeMu sync.Mutex
mu sync.Mutex
cond *sync.Cond
cond sync.Cond // cond.L is &mu.
closed bool
localReadClosed bool
localWriteClosed bool
@@ -407,19 +553,15 @@ type stream struct {
queue [][]byte
// queuedBytes includes unread bytes in readBuf and queue.
queuedBytes int
localAddr net.Addr
remoteAddr net.Addr
}
// streamAddr is the placeholder address every stream reports; streams have no network
// address of their own, and sharing one value saves two allocations per stream.
var streamAddr net.Addr = &net.TCPAddr{}
func newStream(session *Session, id uint32) *stream {
st := &stream{
session: session,
id: id,
localAddr: &net.TCPAddr{},
remoteAddr: &net.TCPAddr{},
}
st.cond = sync.NewCond(&st.mu)
st := &stream{session: session, id: id}
st.cond.L = &st.mu
return st
}
@@ -623,8 +765,8 @@ func (c *stream) CloseRead() error {
return nil
}
func (c *stream) LocalAddr() net.Addr { return c.localAddr }
func (c *stream) RemoteAddr() net.Addr { return c.remoteAddr }
func (c *stream) LocalAddr() net.Addr { return streamAddr }
func (c *stream) RemoteAddr() net.Addr { return streamAddr }
func (c *stream) SetDeadline(t time.Time) error {
_ = c.SetReadDeadline(t)
+115 -1
View File
@@ -18,7 +18,6 @@ func TestSessionKeepaliveUsesV047CompatibleFrame(t *testing.T) {
streams: make(map[uint32]*stream),
closed: make(chan struct{}),
}
session.lastWrite.Store(time.Now().UnixNano())
t.Cleanup(func() {
session.closeWithError(net.ErrClosed)
_ = peerConn.Close()
@@ -266,3 +265,118 @@ func TestStreamConcurrentWritesRemainContiguous(t *testing.T) {
}
}
}
func TestSessionMixedFrameSizesKeepStreamOrder(t *testing.T) {
clientConn, serverConn := net.Pipe()
clientSession, err := NewClientSession(clientConn)
if err != nil {
t.Fatalf("new client session: %v", err)
}
serverSession, err := NewServerSession(serverConn)
if err != nil {
t.Fatalf("new server session: %v", err)
}
t.Cleanup(func() {
_ = clientSession.Close()
_ = serverSession.Close()
})
// Small writes are batched, large ones are written directly behind the batch; each
// stream must still see its own bytes in order.
const streams = 6
sizes := []int{1, 700, coalesceMaxPayload + 1, 40, maxDataPayload + 5, 3, coalesceMaxPayload, 9000}
expected := func(marker byte) []byte {
var out []byte
for i := 0; i < 20; i++ {
out = append(out, bytes.Repeat([]byte{marker + byte(i)}, sizes[i%len(sizes)])...)
}
return out
}
type result struct {
marker byte
data []byte
err error
}
results := make(chan result, streams)
go func() {
for i := 0; i < streams; i++ {
st, _, err := serverSession.AcceptStream()
if err != nil {
results <- result{err: err}
continue
}
go func() {
data, err := io.ReadAll(st)
r := result{data: data, err: err}
if len(data) > 0 {
r.marker = data[0]
}
results <- r
}()
}
}()
var wg sync.WaitGroup
for i := 0; i < streams; i++ {
st, err := clientSession.OpenStream(nil)
if err != nil {
t.Fatalf("open stream: %v", err)
}
wg.Add(1)
go func(st net.Conn, marker byte) {
defer wg.Done()
offset := 0
data := expected(marker)
for i := 0; offset < len(data); i++ {
n := sizes[i%len(sizes)]
if _, err := st.Write(data[offset : offset+n]); err != nil {
t.Errorf("write: %v", err)
return
}
offset += n
}
_ = st.(interface{ CloseWrite() error }).CloseWrite()
}(st, byte(i*40))
}
wg.Wait()
for i := 0; i < streams; i++ {
r := <-results
if r.err != nil {
t.Fatalf("read stream: %v", r.err)
}
if !bytes.Equal(r.data, expected(r.marker)) {
t.Fatalf("stream with marker %d received reordered or corrupted data", r.marker)
}
}
}
func TestSessionAnswersPingWithPong(t *testing.T) {
sessionConn, peerConn := net.Pipe()
session, err := NewServerSession(sessionConn)
if err != nil {
t.Fatalf("new server session: %v", err)
}
t.Cleanup(func() {
_ = session.Close()
_ = peerConn.Close()
})
_ = peerConn.SetDeadline(time.Now().Add(2 * time.Second))
var ping [headerSize]byte
ping[0] = framePing
if _, err := peerConn.Write(ping[:]); err != nil {
t.Fatalf("write ping: %v", err)
}
var pong [headerSize]byte
if _, err := io.ReadFull(peerConn, pong[:]); err != nil {
t.Fatalf("read pong: %v", err)
}
if pong[0] != framePong || binary.BigEndian.Uint32(pong[1:5]) != 0 || binary.BigEndian.Uint32(pong[5:9]) != 0 {
t.Fatalf("reply = %v, want an empty PONG on stream 0", pong)
}
if session.IsClosed() {
t.Fatal("session closed by ping")
}
}
@@ -1,12 +0,0 @@
package multiplex
import "io"
func writeAllChunks(w io.Writer, chunks ...[]byte) error {
for _, chunk := range chunks {
if _, err := w.Write(chunk); err != nil {
return err
}
}
return nil
}
+22 -7
View File
@@ -9,8 +9,10 @@ import (
)
type pipeDeadline struct {
mu sync.Mutex
mu sync.Mutex
// timer is reused across set calls; armed says it may still fire.
timer *time.Timer
armed bool
cancel chan struct{}
}
@@ -22,10 +24,10 @@ func (d *pipeDeadline) set(t time.Time) {
d.mu.Lock()
defer d.mu.Unlock()
if d.timer != nil && !d.timer.Stop() {
if d.armed && !d.timer.Stop() {
<-d.cancel
}
d.timer = nil
d.armed = false
closed := isClosedPipeChan(d.cancel)
if t.IsZero() {
@@ -39,9 +41,12 @@ func (d *pipeDeadline) set(t time.Time) {
if closed {
d.cancel = make(chan struct{})
}
d.timer = time.AfterFunc(dur, func() {
close(d.cancel)
})
if d.timer == nil {
d.timer = time.AfterFunc(dur, d.expire)
} else {
d.timer.Reset(dur)
}
d.armed = true
return
}
@@ -50,6 +55,8 @@ func (d *pipeDeadline) set(t time.Time) {
}
}
func (d *pipeDeadline) expire() { close(d.cancel) }
func (d *pipeDeadline) wait() <-chan struct{} {
d.mu.Lock()
ch := d.cancel
@@ -93,7 +100,7 @@ type halfPipeConn struct {
writeDeadline pipeDeadline
}
func newHalfPipe() (net.Conn, net.Conn) {
func newHalfPipe() (*halfPipeConn, *halfPipeConn) {
cb1 := make(chan []byte)
cb2 := make(chan []byte)
cn1 := make(chan int)
@@ -162,6 +169,14 @@ func (c *halfPipeConn) Read(p []byte) (int, error) {
}
}
// awaitReadable blocks until the peer is writing (or the pipe ends or the read deadline fires) without taking any
// bytes: a zero-length Read consumes a writer turn with n=0 and the writer re-offers the rest. It lets an idle
// reader wait without holding a buffer.
func (c *halfPipeConn) awaitReadable() error {
_, err := c.Read(nil)
return err
}
func (c *halfPipeConn) Write(p []byte) (int, error) {
switch {
case isClosedPipeChan(c.localWriteDone):
+35 -17
View File
@@ -3,12 +3,12 @@ package httpmask
import (
"context"
"fmt"
mrand "math/rand"
"net"
"strings"
"time"
"github.com/metacubex/http"
"github.com/metacubex/randv2"
)
type TunnelMode string
@@ -179,21 +179,39 @@ var (
dialPollFn = dialPoll
)
func applyTunnelHeaders(h http.Header, host string, mode TunnelMode) {
if h == nil {
return
// Header values are prebuilt and shared by every request: the transport only reads them, and a fresh []string per
// header would be most of what applying the profile costs.
var (
userAgentValues = singleValues(userAgents)
acceptValues = singleValues(accepts)
acceptLanguageValues = singleValues(acceptLanguages)
noCacheValue = []string{"no-cache"}
keepAliveValue = []string{"keep-alive"}
tunnelModeValues = map[TunnelMode][]string{
TunnelModeStream: {string(TunnelModeStream)},
TunnelModePoll: {string(TunnelModePoll)},
}
r := rngPool.Get().(*mrand.Rand)
ua := userAgents[r.Intn(len(userAgents))]
accept := accepts[r.Intn(len(accepts))]
lang := acceptLanguages[r.Intn(len(acceptLanguages))]
rngPool.Put(r)
h.Set("User-Agent", ua)
h.Set("Accept", accept)
h.Set("Accept-Language", lang)
h.Set("Cache-Control", "no-cache")
h.Set("Pragma", "no-cache")
h.Set("Connection", "keep-alive")
h.Set("Host", host)
h.Set("X-Sudoku-Tunnel", string(mode))
)
func singleValues(vs []string) [][]string {
out := make([][]string, len(vs))
for i, v := range vs {
out[i] = []string{v}
}
return out
}
func applyTunnelHeaders(h http.Header, host string, mode TunnelMode) {
h["User-Agent"] = userAgentValues[randv2.IntN(len(userAgentValues))]
h["Accept"] = acceptValues[randv2.IntN(len(acceptValues))]
h["Accept-Language"] = acceptLanguageValues[randv2.IntN(len(acceptLanguageValues))]
h["Cache-Control"] = noCacheValue
h["Pragma"] = noCacheValue
h["Connection"] = keepAliveValue
h["Host"] = []string{host}
modeValue, ok := tunnelModeValues[mode]
if !ok {
modeValue = []string{string(mode)}
}
h["X-Sudoku-Tunnel"] = modeValue
}
@@ -1,363 +0,0 @@
package httpmask
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"fmt"
"github.com/metacubex/http"
"io"
"net"
"sync/atomic"
"time"
)
type pollConn struct {
queuedConn
readiness *tunnelReadiness
ctx context.Context
cancel context.CancelFunc
client *http.Client
owner *tunnelHTTPTransport
pushURL string
pullURL string
finURL string
closeURL string
headerHost string
uploadSeq atomic.Uint64
}
func (c *pollConn) closeWithError(err error) error {
_ = c.queuedConn.closeWithError(err)
if c.cancel != nil {
c.cancel()
}
bestEffortCloseSession(c.client, c.closeURL, c.headerHost, TunnelModePoll)
if c.owner != nil {
c.owner.close()
}
return nil
}
func (c *pollConn) Close() error {
return c.closeWithError(io.ErrClosedPipe)
}
func dialPoll(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) {
info, err := dialSession(ctx, serverAddress, opts, TunnelModePoll)
if err != nil {
return nil, err
}
return newPollConn(info, opts)
}
func dialPollWithClient(ctx context.Context, client *http.Client, dialer *preconnectDialer, target httpClientTarget, opts TunnelDialOptions) (net.Conn, error) {
info, err := dialSessionWithClient(ctx, client, dialer, target, TunnelModePoll, opts, sessionPreconnectCount())
if err != nil {
return nil, err
}
return newPollConn(info, opts)
}
func newPollConn(info *sessionDialInfo, opts TunnelDialOptions) (net.Conn, error) {
if info == nil {
return nil, fmt.Errorf("httpmask: nil session")
}
connCtx, cancel := context.WithCancel(context.Background())
c := &pollConn{
ctx: connCtx,
cancel: cancel,
readiness: newTunnelReadiness(),
client: info.client,
owner: info.owner,
pushURL: info.pushURL,
pullURL: info.pullURL,
finURL: info.finURL,
closeURL: info.closeURL,
headerHost: info.headerHost,
queuedConn: newQueuedConn(),
}
go c.pullLoop()
go c.pushLoop()
outConn := net.Conn(c)
if opts.EarlyHandshake != nil && opts.EarlyHandshake.WrapConn != nil && (opts.EarlyHandshake.Ready == nil || opts.EarlyHandshake.Ready()) {
upgraded, err := opts.EarlyHandshake.WrapConn(c)
if err != nil {
_ = c.Close()
return nil, err
}
if upgraded != nil {
outConn = upgraded
}
return wrapReadyTunnelConn(outConn, c.waitReady), nil
}
if opts.Upgrade != nil {
upgraded, err := opts.Upgrade(c)
if err != nil {
_ = c.Close()
return nil, err
}
if upgraded != nil {
outConn = upgraded
}
}
return wrapReadyTunnelConn(outConn, c.waitReady), nil
}
func (c *pollConn) waitReady(ctx context.Context) error {
if err := c.readiness.wait(ctx, c.closed, c.closedErr); err != nil {
return err
}
return nil
}
func (c *pollConn) pullLoop() {
const (
minBackoff = 10 * time.Millisecond
maxBackoff = 250 * time.Millisecond
)
backoff := minBackoff
for {
select {
case <-c.closed:
return
default:
}
req, err := http.NewRequestWithContext(c.ctx, http.MethodGet, c.pullURL, nil)
if err != nil {
_ = c.closeWithError(err)
return
}
req.Host = c.headerHost
applyTunnelHeaders(req.Header, c.headerHost, TunnelModePoll)
resp, err := c.client.Do(req)
if err != nil {
if isDialError(err) || isRetryableHTTPTransportError(err) {
closeIdleConnections(c.client)
if err := waitRetry(c.closed, c.closedErr, backoff); err != nil {
return
}
backoff = nextBackoff(backoff, minBackoff, maxBackoff)
continue
}
_ = c.closeWithError(fmt.Errorf("poll pull request failed: %w", err))
return
}
if resp.StatusCode != http.StatusOK {
if isRetryableStatusCode(resp.StatusCode) {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024))
_ = resp.Body.Close()
closeIdleConnections(c.client)
if err := waitRetry(c.closed, c.closedErr, backoff); err != nil {
return
}
backoff = nextBackoff(backoff, minBackoff, maxBackoff)
continue
}
_ = resp.Body.Close()
_ = c.closeWithError(fmt.Errorf("poll pull bad status: %s", resp.Status))
return
}
c.readiness.markPullReady()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Bytes()
if len(line) == 0 {
continue
}
payload := make([]byte, base64.StdEncoding.DecodedLen(len(line)))
n, err := base64.StdEncoding.Decode(payload, line)
if err != nil {
_ = resp.Body.Close()
_ = c.closeWithError(fmt.Errorf("poll pull decode failed: %w", err))
return
}
select {
case c.rxc <- payload[:n]:
case <-c.closed:
_ = resp.Body.Close()
return
}
}
_ = resp.Body.Close()
if err := scanner.Err(); err != nil {
if isRetryableHTTPTransportError(err) {
closeIdleConnections(c.client)
if err := waitRetry(c.closed, c.closedErr, backoff); err != nil {
return
}
backoff = nextBackoff(backoff, minBackoff, maxBackoff)
continue
}
_ = c.closeWithError(fmt.Errorf("poll pull scan failed: %w", err))
return
}
if resp.Trailer.Get(tunnelStreamEOFHeader) == "1" {
c.markReadEOF()
return
}
backoff = minBackoff
}
}
func (c *pollConn) pushLoop() {
const (
maxBatchBytes = 64 * 1024
flushInterval = 5 * time.Millisecond
maxLineRawBytes = 16 * 1024
minBackoff = 10 * time.Millisecond
maxBackoff = 250 * time.Millisecond
)
var (
buf bytes.Buffer
encoded = make([]byte, base64.StdEncoding.EncodedLen(maxLineRawBytes)+1)
pendingRaw int
timer = time.NewTimer(flushInterval)
writeErr error
)
defer timer.Stop()
defer func() { c.completeWrite(writeErr) }()
fail := func(err error) {
writeErr = err
_ = c.closeWithError(err)
}
flush := func() error {
if buf.Len() == 0 {
return nil
}
sequence := c.uploadSeq.Add(1)
requestURL, err := uploadURL(c.pushURL, sequence)
if err != nil {
return err
}
payload := append([]byte(nil), buf.Bytes()...)
if err := retryPersistent(c.closed, c.closedErr, minBackoff, maxBackoff, func() error {
reqCtx, cancel := context.WithTimeout(c.ctx, 20*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, requestURL, bytes.NewReader(payload))
if err != nil {
return err
}
req.Host = c.headerHost
applyTunnelHeaders(req.Header, c.headerHost, TunnelModePoll)
req.Header.Set("Content-Type", "text/plain")
resp, err := c.client.Do(req)
if err != nil {
closeIdleConnections(c.client)
return err
}
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024))
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = statusError(resp)
if isRetryableHTTPTransportError(err) {
closeIdleConnections(c.client)
}
return err
}
return nil
}); err != nil {
return err
}
buf.Reset()
pendingRaw = 0
c.readiness.markPushReady()
return nil
}
resetTimer(timer, flushInterval)
enqueue := func(b []byte) error {
for len(b) > 0 {
chunk := b
if len(chunk) > maxLineRawBytes {
chunk = b[:maxLineRawBytes]
}
b = b[len(chunk):]
encLen := base64.StdEncoding.EncodedLen(len(chunk))
if pendingRaw+len(chunk) > maxBatchBytes || buf.Len()+encLen+1 > maxBatchBytes*2 {
if err := flush(); err != nil {
return err
}
}
tmp := encoded[:encLen]
base64.StdEncoding.Encode(tmp, chunk)
encoded[encLen] = '\n'
_, _ = buf.Write(encoded[:encLen+1])
pendingRaw += len(chunk)
}
return nil
}
for {
select {
case b := <-c.writeCh:
if len(b) == 0 {
continue
}
if err := enqueue(b); err != nil {
fail(fmt.Errorf("poll push flush failed: %w", err))
return
}
if pendingRaw >= maxBatchBytes {
if err := flush(); err != nil {
fail(fmt.Errorf("poll push flush failed: %w", err))
return
}
resetTimer(timer, flushInterval)
}
case <-timer.C:
if err := flush(); err != nil {
fail(fmt.Errorf("poll push flush failed: %w", err))
return
}
resetTimer(timer, flushInterval)
case <-c.writeClosed:
// Drain any already-accepted writes so CloseWrite does not lose data.
for {
select {
case b := <-c.writeCh:
if len(b) == 0 {
continue
}
if err := enqueue(b); err != nil {
fail(fmt.Errorf("poll push flush failed: %w", err))
return
}
default:
if err := flush(); err != nil {
fail(fmt.Errorf("poll push flush failed: %w", err))
return
}
if err := sendSessionControl(c.client, c.finURL, c.headerHost, TunnelModePoll); err != nil {
fail(fmt.Errorf("poll FIN failed: %w", err))
return
}
return
}
}
case <-c.closed:
writeErr = c.closedErr()
return
}
}
}
@@ -5,6 +5,8 @@ import (
"net"
"sync"
"time"
"github.com/metacubex/mihomo/common/pool"
)
// queuedConn provides a net.Conn-like interface backed by internal channels.
@@ -27,11 +29,12 @@ type queuedConn struct {
readEOFOnce sync.Once
readMu sync.Mutex
mu sync.Mutex
readBuf []byte
closeErr error
localAddr net.Addr
remoteAddr net.Addr
mu sync.Mutex
readBuf []byte // unread tail of readPayload
readPayload []byte
closeErr error
localAddr net.Addr
remoteAddr net.Addr
}
const queuedConnPayloadQueueDepth = 64
@@ -138,16 +141,19 @@ func (c *queuedConn) Read(b []byte) (n int, err error) {
if len(c.readBuf) == 0 {
select {
case c.readBuf = <-c.rxc:
case p := <-c.rxc:
c.startPayload(p)
default:
}
}
if len(c.readBuf) == 0 {
select {
case c.readBuf = <-c.rxc:
case p := <-c.rxc:
c.startPayload(p)
case <-c.readEOF:
select {
case c.readBuf = <-c.rxc:
case p := <-c.rxc:
c.startPayload(p)
default:
return 0, io.EOF
}
@@ -157,9 +163,28 @@ func (c *queuedConn) Read(b []byte) (n int, err error) {
}
n = copy(b, c.readBuf)
c.readBuf = c.readBuf[n:]
if len(c.readBuf) == 0 {
recyclePayload(c.readPayload)
c.readPayload = nil
}
return n, nil
}
// startPayload makes p the payload being read, recycling the previous one.
func (c *queuedConn) startPayload(p []byte) {
recyclePayload(c.readPayload)
c.readPayload = p
c.readBuf = p
}
// recyclePayload returns a fully read payload to the pool when it is a whole pull chunk; the receiving conn is the
// only reference to it by then.
func recyclePayload(p []byte) {
if cap(p) == streamPullChunkBytes {
_ = pool.Put(p)
}
}
func (c *queuedConn) Write(b []byte) (n int, err error) {
if len(b) == 0 {
return 0, nil
@@ -0,0 +1,493 @@
package httpmask
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"math"
"net"
"sync/atomic"
"time"
"github.com/metacubex/http"
"github.com/metacubex/mihomo/common/pool"
)
const (
splitRequestTimeout = 20 * time.Second
splitFlushInterval = 5 * time.Millisecond
splitMinBackoff = 10 * time.Millisecond
splitMaxBackoff = 250 * time.Millisecond
streamMaxBatchBytes = 256 * 1024
streamPullChunkBytes = 32 * 1024
// A chunk at least this full is queued as the pooled buffer it was read into; smaller ones are copied out so a
// full queue of tiny payloads does not pin 32KiB each.
streamPullHandoverMinBytes = streamPullChunkBytes / 2
streamPullIdleBackoff = 25 * time.Millisecond
pollMaxBatchBytes = 64 * 1024
pollMaxLineBytes = 16 * 1024
)
var errSplitClosed = errors.New("split tunnel closed")
// splitCodec holds what differs between stream (raw octet bodies) and poll (base64 text lines).
type splitCodec struct {
mode TunnelMode
uploadContentType string
maxBatchBytes int // raw payload bytes per upload request
maxLineBytes int // raw payload bytes per encoded upload line
pullIdleBackoff time.Duration // pause before pulling again after a response without data
encodedLen func(rawLen int) int
appendEncoded func(dst, raw []byte) []byte
// readPull hands every decoded downlink payload to deliver until the body ends; a false deliver aborts with errSplitClosed.
readPull func(body io.Reader, deliver func([]byte) bool) (readAny bool, err error)
}
var splitStreamCodec = splitCodec{
mode: TunnelModeStream,
uploadContentType: "application/octet-stream",
maxBatchBytes: streamMaxBatchBytes,
maxLineBytes: math.MaxInt,
pullIdleBackoff: streamPullIdleBackoff,
encodedLen: func(rawLen int) int { return rawLen },
appendEncoded: func(dst, raw []byte) []byte { return append(dst, raw...) },
readPull: readStreamPull,
}
var splitPollCodec = splitCodec{
mode: TunnelModePoll,
uploadContentType: "text/plain",
maxBatchBytes: pollMaxBatchBytes,
maxLineBytes: pollMaxLineBytes,
encodedLen: func(rawLen int) int { return base64.StdEncoding.EncodedLen(rawLen) + 1 },
appendEncoded: appendBase64Line,
readPull: readPollPull,
}
func appendBase64Line(dst, raw []byte) []byte {
start := len(dst)
dst = append(dst, make([]byte, base64.StdEncoding.EncodedLen(len(raw)))...)
base64.StdEncoding.Encode(dst[start:], raw)
return append(dst, '\n')
}
func readStreamPull(body io.Reader, deliver func([]byte) bool) (readAny bool, err error) {
buf := pool.Get(streamPullChunkBytes)
defer func() { _ = pool.Put(buf) }()
for {
n, rerr := body.Read(buf)
if n > 0 {
readAny = true
var payload []byte
if n >= streamPullHandoverMinBytes {
// Mostly full: the reader takes the buffer itself, which saves a copy; queuedConn returns it to the pool.
payload = buf[:n]
buf = pool.Get(streamPullChunkBytes)
} else {
payload = append([]byte(nil), buf[:n]...)
}
if !deliver(payload) {
return readAny, errSplitClosed
}
}
if errors.Is(rerr, io.EOF) {
return readAny, nil
}
if rerr != nil {
return readAny, rerr
}
}
}
func readPollPull(body io.Reader, deliver func([]byte) bool) (readAny bool, err error) {
scanner := bufio.NewScanner(body)
for scanner.Scan() {
line := scanner.Bytes()
if len(line) == 0 {
continue
}
payload := make([]byte, base64.StdEncoding.DecodedLen(len(line)))
n, derr := base64.StdEncoding.Decode(payload, line)
if derr != nil {
return readAny, fmt.Errorf("decode: %w", derr)
}
readAny = true
if !deliver(payload[:n]) {
return readAny, errSplitClosed
}
}
return readAny, scanner.Err()
}
// splitConn is the client end of a stream or poll session: uploads leave as POST batches, the downlink
// arrives on a long-running GET, and queuedConn bridges both to a net.Conn.
type splitConn struct {
queuedConn
codec *splitCodec
readiness *tunnelReadiness
ctx context.Context
cancel context.CancelFunc
client *http.Client
owner *tunnelHTTPTransport
pushURL string
pullURL string
finURL string
closeURL string
headerHost string
uploadSeq atomic.Uint64
}
func dialStream(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) {
// "stream" mode uses split-stream to stay CDN-friendly by default.
return dialSplit(ctx, serverAddress, opts, &splitStreamCodec)
}
func dialPoll(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) {
return dialSplit(ctx, serverAddress, opts, &splitPollCodec)
}
func dialSplit(ctx context.Context, serverAddress string, opts TunnelDialOptions, codec *splitCodec) (net.Conn, error) {
info, err := dialSession(ctx, serverAddress, opts, codec.mode)
if err != nil {
return nil, err
}
return newSplitConn(info, opts, codec)
}
func dialStreamWithClient(ctx context.Context, client *http.Client, dialer *preconnectDialer, target httpClientTarget, opts TunnelDialOptions) (net.Conn, error) {
return dialSplitWithClient(ctx, client, dialer, target, opts, &splitStreamCodec)
}
func dialPollWithClient(ctx context.Context, client *http.Client, dialer *preconnectDialer, target httpClientTarget, opts TunnelDialOptions) (net.Conn, error) {
return dialSplitWithClient(ctx, client, dialer, target, opts, &splitPollCodec)
}
func dialSplitWithClient(ctx context.Context, client *http.Client, dialer *preconnectDialer, target httpClientTarget, opts TunnelDialOptions, codec *splitCodec) (net.Conn, error) {
info, err := dialSessionWithClient(ctx, client, dialer, target, codec.mode, opts, sessionPreconnectCount())
if err != nil {
return nil, err
}
return newSplitConn(info, opts, codec)
}
func newSplitConn(info *sessionDialInfo, opts TunnelDialOptions, codec *splitCodec) (net.Conn, error) {
connCtx, cancel := context.WithCancel(context.Background())
c := &splitConn{
queuedConn: newQueuedConn(),
codec: codec,
readiness: newTunnelReadiness(),
ctx: connCtx,
cancel: cancel,
client: info.client,
owner: info.owner,
pushURL: info.pushURL,
pullURL: info.pullURL,
finURL: info.finURL,
closeURL: info.closeURL,
headerHost: info.headerHost,
}
go c.pullLoop()
go c.pushLoop()
outConn := net.Conn(c)
if opts.EarlyHandshake != nil && opts.EarlyHandshake.WrapConn != nil && (opts.EarlyHandshake.Ready == nil || opts.EarlyHandshake.Ready()) {
upgraded, err := opts.EarlyHandshake.WrapConn(c)
if err != nil {
_ = c.Close()
return nil, err
}
if upgraded != nil {
outConn = upgraded
}
return wrapReadyTunnelConn(outConn, c.waitReady), nil
}
if opts.Upgrade != nil {
upgraded, err := opts.Upgrade(c)
if err != nil {
_ = c.Close()
return nil, err
}
if upgraded != nil {
outConn = upgraded
}
}
return wrapReadyTunnelConn(outConn, c.waitReady), nil
}
func (c *splitConn) Close() error {
return c.closeWithError(io.ErrClosedPipe)
}
func (c *splitConn) closeWithError(err error) error {
_ = c.queuedConn.closeWithError(err)
c.cancel()
bestEffortCloseSession(c.client, c.closeURL, c.headerHost, c.codec.mode)
c.owner.close()
return nil
}
func (c *splitConn) waitReady(ctx context.Context) error {
return c.readiness.wait(ctx, c.closed, c.closedErr)
}
func (c *splitConn) deliver(payload []byte) bool {
select {
case c.rxc <- payload:
return true
case <-c.closed:
return false
}
}
type pullOutcome int
const (
pullAgain pullOutcome = iota // the long-poll ended healthily
pullRetry // transient failure: back off, then pull again
pullStop // conn closed or downlink finished
)
func (c *splitConn) pullLoop() {
backoff := splitMinBackoff
for {
select {
case <-c.closed:
return
default:
}
outcome, readAny := c.pullOnce()
switch outcome {
case pullStop:
return
case pullRetry:
if err := waitRetry(c.closed, c.closedErr, backoff); err != nil {
return
}
backoff = nextBackoff(backoff, splitMinBackoff, splitMaxBackoff)
case pullAgain:
backoff = splitMinBackoff
if !readAny && c.codec.pullIdleBackoff > 0 {
// Avoid a tight loop when the server answered immediately with an empty body.
select {
case <-time.After(c.codec.pullIdleBackoff):
case <-c.closed:
return
}
}
}
}
}
// pullOnce runs one downlink GET. Fatal failures close the conn before returning pullStop.
func (c *splitConn) pullOnce() (outcome pullOutcome, readAny bool) {
mode := c.codec.mode
// The server ends an idle pull after PullReadTimeout. A fixed client
// lifetime would instead cancel healthy continuous downloads mid-stream.
reqCtx, cancel := context.WithCancel(c.ctx)
defer cancel()
req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, c.pullURL, nil)
if err != nil {
_ = c.closeWithError(err)
return pullStop, false
}
req.Host = c.headerHost
applyTunnelHeaders(req.Header, c.headerHost, mode)
resp, err := c.client.Do(req)
if err != nil {
if isDialError(err) || isRetryableHTTPTransportError(err) {
closeIdleConnections(c.client)
return pullRetry, false
}
_ = c.closeWithError(fmt.Errorf("%s pull request failed: %w", mode, err))
return pullStop, false
}
if resp.StatusCode != http.StatusOK {
if isRetryableStatusCode(resp.StatusCode) {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024))
_ = resp.Body.Close()
closeIdleConnections(c.client)
return pullRetry, false
}
_ = resp.Body.Close()
_ = c.closeWithError(fmt.Errorf("%s pull bad status: %s", mode, resp.Status))
return pullStop, false
}
c.readiness.markPullReady()
readAny, err = c.codec.readPull(resp.Body, c.deliver)
_ = resp.Body.Close()
switch {
case errors.Is(err, errSplitClosed):
return pullStop, readAny
case err == nil:
if resp.Trailer.Get(tunnelStreamEOFHeader) == "1" {
c.markReadEOF()
return pullStop, readAny
}
return pullAgain, readAny
case isRetryableHTTPTransportError(err):
closeIdleConnections(c.client)
return pullRetry, readAny
default:
_ = c.closeWithError(fmt.Errorf("%s pull failed: %w", mode, err))
return pullStop, readAny
}
}
// postUpload sends one encoded batch; the caller retries it until it succeeds or the conn closes.
func (c *splitConn) postUpload(requestURL string, payload []byte) error {
reqCtx, cancel := context.WithTimeout(c.ctx, splitRequestTimeout)
defer cancel()
req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, requestURL, bytes.NewReader(payload))
if err != nil {
return err
}
req.Host = c.headerHost
applyTunnelHeaders(req.Header, c.headerHost, c.codec.mode)
req.Header.Set("Content-Type", c.codec.uploadContentType)
resp, err := c.client.Do(req)
if err != nil {
closeIdleConnections(c.client)
return err
}
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024))
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = statusError(resp)
if isRetryableHTTPTransportError(err) {
closeIdleConnections(c.client)
}
return err
}
return nil
}
func (c *splitConn) pushLoop() {
codec := c.codec
var (
buf []byte
pendingRaw int
timer = time.NewTimer(splitFlushInterval)
timerArmed bool
writeErr error
)
// The timer runs only while a batch is buffered, so idle sessions never wake up.
timer.Stop()
defer timer.Stop()
defer func() { c.completeWrite(writeErr) }()
fail := func(err error) {
writeErr = err
_ = c.closeWithError(err)
}
failFlush := func(err error) { fail(fmt.Errorf("%s push flush failed: %w", codec.mode, err)) }
flush := func() error {
if len(buf) == 0 {
return nil
}
requestURL := uploadURL(c.pushURL, c.uploadSeq.Add(1))
attempts := 0
if err := retryPersistent(c.closed, c.closedErr, splitMinBackoff, splitMaxBackoff, func() error {
attempts++
return c.postUpload(requestURL, buf)
}); err != nil {
return err
}
if attempts == 1 {
buf = buf[:0]
} else {
// A failed attempt's transport goroutine may still be reading the old batch.
buf = nil
}
pendingRaw = 0
timer.Stop()
timerArmed = false
c.readiness.markPushReady()
return nil
}
enqueue := func(b []byte) error {
for len(b) > 0 {
line := b
if len(line) > codec.maxLineBytes {
line = b[:codec.maxLineBytes]
}
b = b[len(line):]
if pendingRaw+len(line) > codec.maxBatchBytes || len(buf)+codec.encodedLen(len(line)) > 2*codec.maxBatchBytes {
if err := flush(); err != nil {
return err
}
}
buf = codec.appendEncoded(buf, line)
pendingRaw += len(line)
}
return nil
}
for {
select {
case b := <-c.writeCh:
if len(b) == 0 {
continue
}
if err := enqueue(b); err != nil {
failFlush(err)
return
}
if pendingRaw >= codec.maxBatchBytes {
if err := flush(); err != nil {
failFlush(err)
return
}
} else if !timerArmed {
resetTimer(timer, splitFlushInterval)
timerArmed = true
}
case <-timer.C:
timerArmed = false
if err := flush(); err != nil {
failFlush(err)
return
}
case <-c.writeClosed:
// Drain any already-accepted writes so CloseWrite does not lose data.
for drained := false; !drained; {
select {
case b := <-c.writeCh:
if err := enqueue(b); err != nil {
failFlush(err)
return
}
default:
drained = true
}
}
if err := flush(); err != nil {
failFlush(err)
return
}
if err := sendSessionControl(c.client, c.finURL, c.headerHost, codec.mode); err != nil {
fail(fmt.Errorf("%s FIN failed: %w", codec.mode, err))
}
return
case <-c.closed:
writeErr = c.closedErr()
return
}
}
}
@@ -1,375 +0,0 @@
package httpmask
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/metacubex/http"
"io"
"net"
"sync/atomic"
"time"
)
func dialStream(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) {
// "stream" mode uses split-stream to stay CDN-friendly by default.
return dialStreamSplit(ctx, serverAddress, opts)
}
type streamSplitConn struct {
queuedConn
readiness *tunnelReadiness
ctx context.Context
cancel context.CancelFunc
client *http.Client
owner *tunnelHTTPTransport
pushURL string
pullURL string
finURL string
closeURL string
headerHost string
uploadSeq atomic.Uint64
}
func (c *streamSplitConn) Close() error {
return c.closeWithError(io.ErrClosedPipe)
}
func (c *streamSplitConn) closeWithError(err error) error {
_ = c.queuedConn.closeWithError(err)
if c.cancel != nil {
c.cancel()
}
bestEffortCloseSession(c.client, c.closeURL, c.headerHost, TunnelModeStream)
if c.owner != nil {
c.owner.close()
}
return nil
}
func dialStreamSplit(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) {
info, err := dialSession(ctx, serverAddress, opts, TunnelModeStream)
if err != nil {
return nil, err
}
return newStreamSplitConn(info, opts)
}
func dialStreamWithClient(ctx context.Context, client *http.Client, dialer *preconnectDialer, target httpClientTarget, opts TunnelDialOptions) (net.Conn, error) {
info, err := dialSessionWithClient(ctx, client, dialer, target, TunnelModeStream, opts, sessionPreconnectCount())
if err != nil {
return nil, err
}
return newStreamSplitConn(info, opts)
}
func newStreamSplitConn(info *sessionDialInfo, opts TunnelDialOptions) (net.Conn, error) {
if info == nil {
return nil, errors.New("httpmask: nil session")
}
connCtx, cancel := context.WithCancel(context.Background())
c := &streamSplitConn{
ctx: connCtx,
cancel: cancel,
readiness: newTunnelReadiness(),
client: info.client,
owner: info.owner,
pushURL: info.pushURL,
pullURL: info.pullURL,
finURL: info.finURL,
closeURL: info.closeURL,
headerHost: info.headerHost,
queuedConn: newQueuedConn(),
}
go c.pullLoop()
go c.pushLoop()
outConn := net.Conn(c)
if opts.EarlyHandshake != nil && opts.EarlyHandshake.WrapConn != nil && (opts.EarlyHandshake.Ready == nil || opts.EarlyHandshake.Ready()) {
upgraded, err := opts.EarlyHandshake.WrapConn(c)
if err != nil {
_ = c.Close()
return nil, err
}
if upgraded != nil {
outConn = upgraded
}
return wrapReadyTunnelConn(outConn, c.waitReady), nil
}
if opts.Upgrade != nil {
upgraded, err := opts.Upgrade(c)
if err != nil {
_ = c.Close()
return nil, err
}
if upgraded != nil {
outConn = upgraded
}
}
return wrapReadyTunnelConn(outConn, c.waitReady), nil
}
func (c *streamSplitConn) waitReady(ctx context.Context) error {
if err := c.readiness.wait(ctx, c.closed, c.closedErr); err != nil {
return err
}
return nil
}
func (c *streamSplitConn) pullLoop() {
const (
readChunkSize = 32 * 1024
idleBackoff = 25 * time.Millisecond
minBackoff = 10 * time.Millisecond
maxBackoff = 250 * time.Millisecond
)
var (
backoff = minBackoff
)
buf := make([]byte, readChunkSize)
for {
select {
case <-c.closed:
return
default:
}
// The server ends an idle pull after PullReadTimeout. A fixed client
// lifetime would instead cancel healthy continuous downloads mid-stream.
reqCtx, cancel := context.WithCancel(c.ctx)
req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, c.pullURL, nil)
if err != nil {
cancel()
_ = c.Close()
return
}
req.Host = c.headerHost
applyTunnelHeaders(req.Header, c.headerHost, TunnelModeStream)
resp, err := c.client.Do(req)
if err != nil {
cancel()
if isDialError(err) || isRetryableHTTPTransportError(err) {
closeIdleConnections(c.client)
if err := waitRetry(c.closed, c.closedErr, backoff); err != nil {
return
}
backoff = nextBackoff(backoff, minBackoff, maxBackoff)
continue
}
_ = c.Close()
return
}
backoff = minBackoff
if resp.StatusCode != http.StatusOK {
if isRetryableStatusCode(resp.StatusCode) {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024))
_ = resp.Body.Close()
cancel()
closeIdleConnections(c.client)
if err := waitRetry(c.closed, c.closedErr, backoff); err != nil {
return
}
backoff = nextBackoff(backoff, minBackoff, maxBackoff)
continue
}
_ = resp.Body.Close()
cancel()
_ = c.Close()
return
}
c.readiness.markPullReady()
readAny := false
bodyRetry := false
for {
n, rerr := resp.Body.Read(buf)
if n > 0 {
readAny = true
payload := make([]byte, n)
copy(payload, buf[:n])
select {
case c.rxc <- payload:
case <-c.closed:
_ = resp.Body.Close()
cancel()
return
}
}
if rerr != nil {
_ = resp.Body.Close()
cancel()
if errors.Is(rerr, io.EOF) {
if resp.Trailer.Get(tunnelStreamEOFHeader) == "1" {
c.markReadEOF()
return
}
// Long-poll ended; retry.
break
}
if isRetryableHTTPTransportError(rerr) {
closeIdleConnections(c.client)
bodyRetry = true
break
}
_ = c.Close()
return
}
}
cancel()
if bodyRetry {
if err := waitRetry(c.closed, c.closedErr, backoff); err != nil {
return
}
backoff = nextBackoff(backoff, minBackoff, maxBackoff)
continue
}
backoff = minBackoff
if !readAny {
// Avoid tight loop if the server replied quickly with an empty body.
select {
case <-time.After(idleBackoff):
case <-c.closed:
return
}
}
}
}
func (c *streamSplitConn) pushLoop() {
const (
maxBatchBytes = 256 * 1024
flushInterval = 5 * time.Millisecond
requestTimeout = 20 * time.Second
minBackoff = 10 * time.Millisecond
maxBackoff = 250 * time.Millisecond
)
var (
buf bytes.Buffer
timer = time.NewTimer(flushInterval)
writeErr error
)
defer timer.Stop()
defer func() { c.completeWrite(writeErr) }()
fail := func(err error) {
writeErr = err
_ = c.closeWithError(err)
}
flush := func() error {
if buf.Len() == 0 {
return nil
}
sequence := c.uploadSeq.Add(1)
requestURL, err := uploadURL(c.pushURL, sequence)
if err != nil {
return err
}
payload := append([]byte(nil), buf.Bytes()...)
if err := retryPersistent(c.closed, c.closedErr, minBackoff, maxBackoff, func() error {
reqCtx, cancel := context.WithTimeout(c.ctx, requestTimeout)
defer cancel()
req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, requestURL, bytes.NewReader(payload))
if err != nil {
return err
}
req.Host = c.headerHost
applyTunnelHeaders(req.Header, c.headerHost, TunnelModeStream)
req.Header.Set("Content-Type", "application/octet-stream")
resp, err := c.client.Do(req)
if err != nil {
closeIdleConnections(c.client)
return err
}
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024))
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = statusError(resp)
if isRetryableHTTPTransportError(err) {
closeIdleConnections(c.client)
}
return err
}
return nil
}); err != nil {
return err
}
buf.Reset()
c.readiness.markPushReady()
return nil
}
resetTimer(timer, flushInterval)
for {
select {
case b := <-c.writeCh:
if len(b) == 0 {
continue
}
if buf.Len()+len(b) > maxBatchBytes {
if err := flush(); err != nil {
fail(fmt.Errorf("stream push flush failed: %w", err))
return
}
resetTimer(timer, flushInterval)
}
_, _ = buf.Write(b)
if buf.Len() >= maxBatchBytes {
if err := flush(); err != nil {
fail(fmt.Errorf("stream push flush failed: %w", err))
return
}
resetTimer(timer, flushInterval)
}
case <-timer.C:
if err := flush(); err != nil {
fail(fmt.Errorf("stream push flush failed: %w", err))
return
}
resetTimer(timer, flushInterval)
case <-c.writeClosed:
// Drain any already-accepted writes so CloseWrite does not lose data.
for {
select {
case b := <-c.writeCh:
if len(b) == 0 {
continue
}
if buf.Len()+len(b) > maxBatchBytes {
if err := flush(); err != nil {
fail(fmt.Errorf("stream push flush failed: %w", err))
return
}
}
_, _ = buf.Write(b)
default:
if err := flush(); err != nil {
fail(fmt.Errorf("stream push flush failed: %w", err))
return
}
if err := sendSessionControl(c.client, c.finURL, c.headerHost, TunnelModeStream); err != nil {
fail(fmt.Errorf("stream FIN failed: %w", err))
return
}
return
}
}
case <-c.closed:
writeErr = c.closedErr()
return
}
}
}
+6 -14
View File
@@ -124,11 +124,8 @@ func setEarlyDataQuery(rawURL string, payload []byte) (string, error) {
return u.String(), nil
}
func parseEarlyDataQuery(u *url.URL) ([]byte, error) {
if u == nil {
return nil, nil
}
val := strings.TrimSpace(u.Query().Get(tunnelEarlyDataQueryKey))
func parseEarlyDataQuery(query url.Values) ([]byte, error) {
val := strings.TrimSpace(query.Get(tunnelEarlyDataQueryKey))
if val == "" {
return nil, nil
}
@@ -145,15 +142,10 @@ type sessionDialInfo struct {
headerHost string
}
func uploadURL(rawURL string, sequence uint64) (string, error) {
u, err := url.Parse(rawURL)
if err != nil {
return "", err
}
q := u.Query()
q.Set(tunnelUploadSequenceQuery, strconv.FormatUint(sequence, 10))
u.RawQuery = q.Encode()
return u.String(), nil
// uploadURL puts the sequence ahead of pushURL's query, where encoding the sorted keys has always placed it.
func uploadURL(pushURL string, sequence uint64) string {
base, query, _ := strings.Cut(pushURL, "?")
return base + "?" + tunnelUploadSequenceQuery + "=" + strconv.FormatUint(sequence, 10) + "&" + query
}
type tunnelHTTPTransport struct {
File diff suppressed because it is too large. Load diff
+159 -12
View File
@@ -10,12 +10,15 @@ import (
"io"
"net"
"net/http"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
mhttp "github.com/metacubex/http"
"github.com/metacubex/http/httputil"
"github.com/metacubex/mihomo/common/pool"
)
type roundTripFunc func(*mhttp.Request) (*mhttp.Response, error)
@@ -138,6 +141,44 @@ func TestQueuedConnReadEOFDrainsBufferedPayload(t *testing.T) {
}
}
func TestUploadURLMatchesQueryEncoding(t *testing.T) {
for _, token := range []string{"T-k_9", "a+b/c=", "sp ace&x=y", "é"} {
pushURL := "https://h.test/root/api/v1/upload?token=" + url.QueryEscape(token)
u, err := url.Parse(pushURL)
if err != nil {
t.Fatal(err)
}
q := u.Query()
q.Set(tunnelUploadSequenceQuery, "7")
u.RawQuery = q.Encode()
if got := uploadURL(pushURL, 7); got != u.String() {
t.Fatalf("token %q: uploadURL = %q, want %q", token, got, u.String())
}
}
}
func TestQueuedConnRecyclesDrainedPooledPayload(t *testing.T) {
conn := &queuedConn{
rxc: make(chan []byte, 1),
closed: make(chan struct{}),
}
conn.rxc <- pool.Get(streamPullChunkBytes)[:100]
var buf [60]byte
if _, err := conn.Read(buf[:]); err != nil {
t.Fatal(err)
}
if conn.readPayload == nil {
t.Fatal("payload released with 40 bytes still unread")
}
if n, err := conn.Read(buf[:]); n != 40 || err != nil {
t.Fatalf("second read = (%d, %v), want 40 bytes", n, err)
}
if conn.readPayload != nil {
t.Fatal("drained payload still held by the conn")
}
}
func TestSendSessionControlRetriesTransportEOF(t *testing.T) {
var calls atomic.Int32
client := &mhttp.Client{Transport: roundTripFunc(func(req *mhttp.Request) (*mhttp.Response, error) {
@@ -229,8 +270,7 @@ func TestTunnelServerPullTakeoverSerializesReaders(t *testing.T) {
defer sessionConn.Close()
server := NewTunnelServer(TunnelServerOptions{})
sess := &tunnelSession{conn: sessionConn, closed: make(chan struct{})}
server.sessions[token] = sess
sess := server.sessionAdd(token, sessionConn)
firstClient, firstServer := net.Pipe()
defer firstClient.Close()
@@ -269,6 +309,116 @@ func TestTunnelServerPullTakeoverSerializesReaders(t *testing.T) {
}
}
func TestPullFrameMatchesChunkedWriter(t *testing.T) {
payload := bytes.Repeat([]byte("sudoku"), 1000)
for _, n := range []int{1, 2, 3, 255, 4096, len(payload)} {
p := payload[:n]
var want bytes.Buffer
cw := httputil.NewChunkedWriter(&want)
_, _ = cw.Write(p)
if got := streamCodec.appendPullFrame(nil, p); !bytes.Equal(got, want.Bytes()) {
t.Fatalf("stream frame for %d bytes = %q, want %q", n, got, want.Bytes())
}
want.Reset()
_, _ = cw.Write([]byte(base64.StdEncoding.EncodeToString(p)))
_, _ = cw.Write([]byte("\n"))
got := pollCodec.appendPullFrame(make([]byte, 0, pollCodec.pullFrameSize(n)), p)
if !bytes.Equal(got, want.Bytes()) {
t.Fatalf("poll frame for %d bytes = %q, want %q", n, got, want.Bytes())
}
if len(got) > pollCodec.pullFrameSize(n) {
t.Fatalf("poll frame for %d bytes is %d, over its size bound %d", n, len(got), pollCodec.pullFrameSize(n))
}
}
}
func TestReadUploadGrowsPastPresize(t *testing.T) {
want := bytes.Repeat([]byte("0123456789abcdef"), 20000) // 320 KB: more than the pooled classes and the presize
for _, length := range []int64{-1, 0, 100, int64(len(want))} {
got, err := readUpload(bytes.NewReader(want), length, maxUploadBytes+1)
if err != nil || !bytes.Equal(got, want) {
t.Fatalf("declared length %d: read %d bytes, err %v, want %d bytes", length, len(got), err, len(want))
}
_ = pool.Put(got)
}
got, err := readUpload(bytes.NewReader(want), -1, 1000)
if err != nil || len(got) != 1000 {
t.Fatalf("limit: read %d bytes, err %v, want 1000", len(got), err)
}
_ = pool.Put(got)
}
func TestDecodeUploadLines(t *testing.T) {
enc := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) }
got, err := decodeUploadLines([]byte(enc("hello") + "\n\n \r\n" + enc("w") + "\r\n" + enc("orld")))
if err != nil || string(got) != "helloworld" {
t.Fatalf("decode = %q, %v", got, err)
}
_ = pool.Put(got)
if _, err := decodeUploadLines([]byte(enc("ok") + "\n!!!!\n")); err == nil {
t.Fatal("invalid base64 line was accepted")
}
}
func TestReadHTTPRequestKeepsReplayAndBody(t *testing.T) {
raw := "POST /api/v1/upload?token=t HTTP/1.1\r\nHost: x\r\nX-SUDOKU-Tunnel: poll \r\n" +
"Content-Length: 5\r\ncontent-length: 9\r\nConnection: keep-alive, Upgrade\r\nUpgrade: WebSocket\r\n\r\nhello"
client, server := net.Pipe()
defer client.Close()
defer server.Close()
go func() { _, _ = client.Write([]byte(raw)) }()
br := bufio.NewReader(server)
req, _, err := readHTTPRequest(server, br, []byte(raw[:4]))
if err != nil {
t.Fatalf("readHTTPRequest: %v", err)
}
if req.method != "POST" || req.target != "/api/v1/upload?token=t" || req.tunnel != "poll" || req.contentLength != "5" {
t.Fatalf("parsed request = %+v", req)
}
if !req.isWebSocketUpgrade() {
t.Fatal("upgrade headers were not recognised")
}
if got := req.replayPrefix(); !bytes.HasPrefix([]byte(raw), got) || !bytes.HasPrefix(got, []byte(raw[:len(raw)-5])) {
t.Fatalf("replay prefix = %q", got)
}
body, length, err := req.body()
if err != nil || length != 5 {
t.Fatalf("body: length %d, err %v", length, err)
}
if got, err := io.ReadAll(body); err != nil || string(got) != "hello" {
t.Fatalf("body = %q, %v", got, err)
}
}
func TestTunnelServerReapsIdleSession(t *testing.T) {
const token = "idle-session"
appConn, sessionConn := newHalfPipe()
defer appConn.Close()
defer sessionConn.Close()
server := NewTunnelServer(TunnelServerOptions{SessionTTL: 20 * time.Millisecond})
server.sessionAdd(token, sessionConn)
// The tunnel read ends once the reaper closes the session pipe.
readDone := make(chan error, 1)
go func() {
_, err := appConn.Read(make([]byte, 1))
readDone <- err
}()
select {
case <-readDone:
case <-time.After(5 * time.Second):
t.Fatal("idle session was not reaped")
}
if server.sessionHas(token) {
t.Fatal("reaped session is still registered")
}
}
func startTestTunnelServer(t testing.TB, server *TunnelServer) (string, func(), <-chan net.Conn) {
t.Helper()
@@ -308,20 +458,17 @@ func startTestTunnelServer(t testing.TB, server *TunnelServer) (string, func(),
func TestTunnelServerDownlinkHalfCloseKeepsUplink(t *testing.T) {
tests := []struct {
name string
pull func(*TunnelServer, net.Conn, string) (HandleResult, net.Conn, error)
push func(*TunnelServer, net.Conn, string, uint64, io.Reader) (HandleResult, net.Conn, error)
codec sessionCodec
pushBody string
}{
{
name: "stream",
pull: (*TunnelServer).streamPull,
push: (*TunnelServer).streamPush,
codec: streamCodec,
pushBody: "tail",
},
{
name: "poll",
pull: (*TunnelServer).pollPull,
push: (*TunnelServer).pollPush,
codec: pollCodec,
pushBody: base64.StdEncoding.EncodeToString([]byte("tail")) + "\n",
},
}
@@ -332,7 +479,7 @@ func TestTunnelServerDownlinkHalfCloseKeepsUplink(t *testing.T) {
appConn, sessionConn := newHalfPipe()
server := NewTunnelServer(TunnelServerOptions{PullReadTimeout: 20 * time.Millisecond})
server.sessions[token] = &tunnelSession{conn: sessionConn, nextUploadSeq: 1}
server.sessionAdd(token, sessionConn)
t.Cleanup(func() {
_ = appConn.Close()
server.sessionClose(token)
@@ -344,7 +491,7 @@ func TestTunnelServerDownlinkHalfCloseKeepsUplink(t *testing.T) {
appDone <- err
return
}
if err := appConn.(interface{ CloseWrite() error }).CloseWrite(); err != nil {
if err := appConn.CloseWrite(); err != nil {
appDone <- err
return
}
@@ -358,7 +505,7 @@ func TestTunnelServerDownlinkHalfCloseKeepsUplink(t *testing.T) {
clientConn, serverConn := net.Pipe()
done := make(chan error, 1)
go func() {
_, _, err := tt.pull(server, serverConn, token)
_, _, err := server.pull(serverConn, token, tt.codec)
done <- err
}()
@@ -385,7 +532,7 @@ func TestTunnelServerDownlinkHalfCloseKeepsUplink(t *testing.T) {
clientConn, serverConn = net.Pipe()
done = make(chan error, 1)
go func() {
_, _, err := tt.push(server, serverConn, token, 1, strings.NewReader(tt.pushBody))
_, _, err := server.push(serverConn, token, 1, strings.NewReader(tt.pushBody), -1, tt.codec)
done <- err
}()
resp, err = http.ReadResponse(bufio.NewReader(clientConn), &http.Request{Method: http.MethodPost})
@@ -11,33 +11,10 @@ import (
"github.com/gobwas/ws"
)
func looksLikeWebSocketUpgrade(headers map[string]string) bool {
if headers == nil {
return false
}
if !strings.EqualFold(strings.TrimSpace(headers["upgrade"]), "websocket") {
return false
}
conn := headers["connection"]
for _, part := range strings.Split(conn, ",") {
if strings.EqualFold(strings.TrimSpace(part), "upgrade") {
return true
}
}
return false
}
func (s *TunnelServer) handleWS(rawConn net.Conn, req *httpRequestHeader, headerBytes []byte, buffered []byte) (HandleResult, net.Conn, error) {
func (s *TunnelServer) handleWS(req *tunnelRequest) (HandleResult, net.Conn, error) {
rawConn := req.conn
rejectOrReply := func(code int, body string) (HandleResult, net.Conn, error) {
if s.passThroughOnReject {
prefix := make([]byte, 0, len(headerBytes)+len(buffered))
prefix = append(prefix, headerBytes...)
prefix = append(prefix, buffered...)
return HandlePassThrough, newRejectedPreBufferedConn(rawConn, prefix), nil
}
_ = writeSimpleHTTPResponse(rawConn, code, body)
_ = rawConn.Close()
return HandleDone, nil, nil
return s.rejectOrRespond(req, code, body)
}
u, err := url.ParseRequestURI(req.target)
@@ -52,11 +29,11 @@ func (s *TunnelServer) handleWS(rawConn net.Conn, req *httpRequestHeader, header
if strings.ToUpper(strings.TrimSpace(req.method)) != http.MethodGet {
return rejectOrReply(http.StatusBadRequest, "bad request")
}
if !looksLikeWebSocketUpgrade(req.headers) {
if !req.isWebSocketUpgrade() {
return rejectOrReply(http.StatusBadRequest, "bad request")
}
authVal := req.headers["authorization"]
authVal := req.authorization
if authVal == "" {
authVal = u.Query().Get(tunnelAuthQueryKey)
}
@@ -64,7 +41,7 @@ func (s *TunnelServer) handleWS(rawConn net.Conn, req *httpRequestHeader, header
return rejectOrReply(http.StatusNotFound, "not found")
}
earlyPayload, err := parseEarlyDataQuery(u)
earlyPayload, err := parseEarlyDataQuery(u.Query())
if err != nil {
return rejectOrReply(http.StatusBadRequest, "bad request")
}
@@ -76,10 +53,7 @@ func (s *TunnelServer) handleWS(rawConn net.Conn, req *httpRequestHeader, header
}
}
prefix := make([]byte, 0, len(headerBytes)+len(buffered))
prefix = append(prefix, headerBytes...)
prefix = append(prefix, buffered...)
wsConnRaw := newPreBufferedConn(rawConn, prefix)
wsConnRaw := newPreBufferedConn(rawConn, req.replayPrefix())
upgrader := ws.Upgrader{}
if prepared != nil && len(prepared.ResponsePayload) > 0 {
+59 -129
View File
@@ -1,7 +1,6 @@
package sudoku
import (
"bufio"
"bytes"
"io"
"net"
@@ -9,51 +8,21 @@ import (
"sync/atomic"
)
const IOBufferSize = 32 * 1024
const minDecodeReadSize = 64
var perm4 = [24][4]byte{
{0, 1, 2, 3},
{0, 1, 3, 2},
{0, 2, 1, 3},
{0, 2, 3, 1},
{0, 3, 1, 2},
{0, 3, 2, 1},
{1, 0, 2, 3},
{1, 0, 3, 2},
{1, 2, 0, 3},
{1, 2, 3, 0},
{1, 3, 0, 2},
{1, 3, 2, 0},
{2, 0, 1, 3},
{2, 0, 3, 1},
{2, 1, 0, 3},
{2, 1, 3, 0},
{2, 3, 0, 1},
{2, 3, 1, 0},
{3, 0, 1, 2},
{3, 0, 2, 1},
{3, 1, 0, 2},
{3, 1, 2, 0},
{3, 2, 0, 1},
{3, 2, 1, 0},
}
// decodeWindow bounds how many wire bytes decode compacts at a time.
const decodeWindow = 256
type Conn struct {
net.Conn
table *Table
reader *bufio.Reader
reader *wireReader
recorder *bytes.Buffer
recording atomic.Bool
recordLock sync.Mutex
rawBuf []byte
pendingData pendingBuffer
hintBuf [4]byte
hintCount int
writeMu sync.Mutex
writeBuf []byte
hintBuf [3]uint8 // hint indexes of a group still being read
hintCount int
writeMu sync.Mutex
writeBuf []byte
rng *sudokuRand
paddingThreshold uint64
@@ -85,10 +54,6 @@ func NewConn(c net.Conn, table *Table, pMin, pMax int, record bool) *Conn {
sc := &Conn{
Conn: c,
table: table,
reader: bufio.NewReaderSize(c, IOBufferSize),
rawBuf: make([]byte, IOBufferSize),
pendingData: newPendingBuffer(4096),
writeBuf: make([]byte, 0, 4096),
rng: localRng,
paddingThreshold: pickPaddingThreshold(localRng, pMin, pMax),
}
@@ -109,6 +74,8 @@ func (sc *Conn) StopRecording() {
sc.recordLock.Unlock()
}
// GetBufferedAndRecorded returns every wire byte read so far that has not been
// stopped from recording, plus bytes buffered but not yet decoded.
func (sc *Conn) GetBufferedAndRecorded() []byte {
if sc == nil {
return nil
@@ -121,19 +88,14 @@ func (sc *Conn) GetBufferedAndRecorded() []byte {
if sc.recorder != nil {
recorded = sc.recorder.Bytes()
}
if sc.reader == nil {
pending := sc.reader.pending()
if len(pending) == 0 {
return recorded
}
buffered := sc.reader.Buffered()
if buffered > 0 {
peeked, _ := sc.reader.Peek(buffered)
full := make([]byte, len(recorded)+len(peeked))
copy(full, recorded)
copy(full[len(recorded):], peeked)
return full
}
return recorded
full := make([]byte, len(recorded)+len(pending))
copy(full, recorded)
copy(full[len(recorded):], pending)
return full
}
func (sc *Conn) Write(p []byte) (n int, err error) {
@@ -147,83 +109,38 @@ func (sc *Conn) Write(p []byte) (n int, err error) {
sc.writeMu.Lock()
defer sc.writeMu.Unlock()
sc.writeBuf = encodeSudokuPayload(sc.writeBuf[:0], sc.table, sc.rng, sc.paddingThreshold, p)
if _, err := sc.Conn.Write(sc.writeBuf); err != nil {
return len(p), err
}
return len(p), nil
sc.writeBuf, n, err = writeSudokuPayload(sc.Conn, sc.writeBuf, sc.table, sc.rng, sc.paddingThreshold, p)
return n, err
}
func (sc *Conn) Read(p []byte) (n int, err error) {
if len(p) == 0 {
return 0, nil
}
if sc == nil || sc.Conn == nil || sc.reader == nil || len(sc.rawBuf) == 0 || sc.table == nil || sc.table.layout == nil {
if sc == nil || sc.Conn == nil || sc.table == nil || sc.table.layout == nil {
return 0, io.ErrClosedPipe
}
if n, ok := drainPending(p, &sc.pendingData); ok {
return n, nil
if sc.reader == nil {
// Write-only codecs never pay for a read buffer.
sc.reader = &wireReader{src: sc.Conn}
}
outN := 0
for {
nr, rErr := readRawLimited(sc.Conn, sc.reader, sc.rawBuf[:sudokuReadSize(len(p)-outN, len(sc.rawBuf))])
if nr > 0 {
chunk := sc.rawBuf[:nr]
chunk, rErr := sc.reader.peek()
if len(chunk) > 0 {
var consumed int
outN, consumed, rErr = sc.decode(p, chunk)
if sc.recording.Load() {
sc.recordLock.Lock()
if sc.recording.Load() && sc.recorder != nil {
sc.recorder.Write(chunk)
sc.recorder.Write(chunk[:consumed])
}
sc.recordLock.Unlock()
}
table := sc.table
layout := table.layout
for i := 0; i < len(chunk); {
if sc.hintCount == 0 && outN < len(p) && i+3 < len(chunk) &&
layout.hintTable[chunk[i]] &&
layout.hintTable[chunk[i+1]] &&
layout.hintTable[chunk[i+2]] &&
layout.hintTable[chunk[i+3]] {
val, ok := table.DecodeMap[packHintBytes(chunk[i], chunk[i+1], chunk[i+2], chunk[i+3])]
if !ok {
return 0, ErrInvalidSudokuMapMiss
}
p[outN] = val
outN++
i += 4
continue
}
b := chunk[i]
i++
if !layout.hintTable[b] {
continue
}
sc.hintBuf[sc.hintCount] = b
sc.hintCount++
if sc.hintCount != len(sc.hintBuf) {
continue
}
val, ok := table.DecodeMap[packHintBytes(sc.hintBuf[0], sc.hintBuf[1], sc.hintBuf[2], sc.hintBuf[3])]
if !ok {
return 0, ErrInvalidSudokuMapMiss
}
outN = appendDecodedByte(p, outN, &sc.pendingData, val)
sc.hintCount = 0
}
sc.reader.discard(consumed)
}
if rErr != nil {
if outN > 0 {
return outN, nil
}
if n, ok := drainPending(p, &sc.pendingData); ok {
return n, nil
}
return 0, rErr
}
if outN > 0 {
@@ -232,26 +149,39 @@ func (sc *Conn) Read(p []byte) (n int, err error) {
}
}
func sudokuReadSize(decodedRemaining, maxRaw int) int {
if maxRaw <= minDecodeReadSize || decodedRemaining <= 0 {
return maxRaw
}
if decodedRemaining > (maxRaw-minDecodeReadSize)/9 {
return maxRaw
}
// decode writes only as much plaintext as fits in p, so the wire bytes it
// consumed can be dropped and the rest stay in the reader. It consumes whole
// windows of wire bytes, keeping the hints of an unfinished group in hintBuf,
// but never more than can complete into the space left in p. Compacting a
// window through hintIdx with a branchless store skips padding without a
// per-byte branch.
func (sc *Conn) decode(p, chunk []byte) (outN, consumed int, err error) {
table := sc.table
hintIdx := &table.layout.hintIdx
var hints [512]uint8
return decodedRemaining*9 + minDecodeReadSize
}
for consumed < len(chunk) && outN < len(p) {
window := minInt(minInt(len(chunk)-consumed, decodeWindow), 4*(len(p)-outN)+3-sc.hintCount)
k := copy(hints[:], sc.hintBuf[:sc.hintCount])
for _, b := range chunk[consumed : consumed+window] {
idx := hintIdx[b]
hints[k&511] = idx
k += int(idx>>7) ^ 1
}
consumed += window
func readRawLimited(conn net.Conn, reader *bufio.Reader, dst []byte) (int, error) {
if len(dst) == 0 {
return 0, nil
groups := k / 4
for i := 0; i < groups; i++ {
h := (*[4]uint8)(hints[4*i:])
val, ok := table.decodeHints(h[0], h[1], h[2], h[3])
if !ok {
sc.hintCount = 0
return outN, consumed, ErrInvalidSudokuMapMiss
}
p[outN] = val
outN++
}
sc.hintCount = copy(sc.hintBuf[:], hints[4*groups:k])
}
if reader != nil && reader.Buffered() > 0 {
return reader.Read(dst)
}
if conn == nil {
return 0, io.ErrClosedPipe
}
return conn.Read(dst)
return outN, consumed, nil
}
+23 -50
View File
@@ -6,50 +6,25 @@ import (
"sync"
)
// DownlinkWriter encodes payload bytes with the selected downlink codec.
type DownlinkWriter struct {
dataWriter io.Writer
writeMu sync.Mutex
}
func NewDownlinkWriter(raw io.Writer, table *Table, pMin, pMax int) *DownlinkWriter {
localRng := newSeededRand()
return newDownlinkWriter(newSudokuDataWriter(raw, table, localRng, pMin, pMax))
}
func NewPackedDownlinkWriter(raw net.Conn, table *Table, pMin, pMax int) (*PackedConn, *DownlinkWriter) {
packed := NewPackedConn(raw, table, pMin, pMax)
return packed, newDownlinkWriter(packed)
}
// NewServerDownlinkWriter returns the server-to-client writer for a connection
// whose uplink is already wrapped. The packed codec buffers residual bits, so
// its Flush is returned as a closer to run before the connection is closed.
func NewServerDownlinkWriter(raw net.Conn, table *Table, pMin, pMax int, pure bool) (io.Writer, []func() error) {
if pure {
return NewDownlinkWriter(raw, table, pMin, pMax), nil
return newPureWriter(raw, table, newSeededRand(), pMin, pMax), nil
}
packed, writer := NewPackedDownlinkWriter(raw, table, pMin, pMax)
return writer, []func() error{packed.Flush}
packed := NewPackedConn(raw, table, pMin, pMax)
return writerOnly{packed}, []func() error{packed.Flush}
}
func newDownlinkWriter(dataWriter io.Writer) *DownlinkWriter {
return &DownlinkWriter{dataWriter: dataWriter}
}
// writerOnly hides every method but Write, so wrapping it in a directional
// conn does not half-close the shared socket twice.
type writerOnly struct{ io.Writer }
func (w *DownlinkWriter) Write(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
if w == nil || w.dataWriter == nil {
return 0, io.ErrClosedPipe
}
w.writeMu.Lock()
defer w.writeMu.Unlock()
return w.dataWriter.Write(p)
}
type sudokuDataWriter struct {
// pureWriter is the write half of Conn, safe for concurrent callers.
type pureWriter struct {
mu sync.Mutex
writer io.Writer
table *Table
rng *sudokuRand
@@ -57,30 +32,28 @@ type sudokuDataWriter struct {
writeBuf []byte
}
func newSudokuDataWriter(writer io.Writer, table *Table, rng *sudokuRand, pMin, pMax int) *sudokuDataWriter {
return &sudokuDataWriter{
func newPureWriter(writer io.Writer, table *Table, rng *sudokuRand, pMin, pMax int) *pureWriter {
return &pureWriter{
writer: writer,
table: table,
rng: rng,
paddingThreshold: pickPaddingThreshold(rng, pMin, pMax),
writeBuf: make([]byte, 0, 4096),
}
}
func (w *sudokuDataWriter) Write(p []byte) (int, error) {
func (w *pureWriter) Write(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
if w == nil || w.writer == nil {
return 0, io.ErrClosedPipe
}
if w.table == nil || w.table.layout == nil || w.rng == nil {
if w == nil || w.writer == nil || w.table == nil || w.table.layout == nil || w.rng == nil {
return 0, io.ErrClosedPipe
}
w.writeBuf = encodeSudokuPayload(w.writeBuf[:0], w.table, w.rng, w.paddingThreshold, p)
if _, err := w.writer.Write(w.writeBuf); err != nil {
return len(p), err
}
return len(p), nil
w.mu.Lock()
defer w.mu.Unlock()
var n int
var err error
w.writeBuf, n, err = writeSudokuPayload(w.writer, w.writeBuf, w.table, w.rng, w.paddingThreshold, p)
return n, err
}
+104 -58
View File
@@ -1,72 +1,118 @@
package sudoku
func encodeSudokuPayload(dst []byte, table *Table, rng *sudokuRand, paddingThreshold uint64, p []byte) []byte {
import (
"encoding/binary"
"math"
)
const (
// maxPaddedExpansion is the worst case per plaintext byte: five padding
// slots and four hints.
maxPaddedExpansion = 9
// encodeSlack is the headroom the encoder needs past the last byte it keeps,
// so each plaintext byte can be stored as one fixed-size array write.
encodeSlack = 16
)
// permShifts[i][j] is the bit offset, inside a packed puzzle, of the hint that
// the i-th hint order places in slot j. The orders are the 24 permutations of
// 0..3 in lexicographic order.
var permShifts = buildPermShifts()
func buildPermShifts() (shifts [24][4]uint8) {
n := 0
for a := uint8(0); a < 4; a++ {
for b := uint8(0); b < 4; b++ {
for c := uint8(0); c < 4; c++ {
for d := uint8(0); d < 4; d++ {
if a == b || a == c || a == d || b == c || b == d || c == d {
continue
}
shifts[n] = [4]uint8{8 * a, 8 * b, 8 * c, 8 * d}
n++
}
}
}
}
return shifts
}
// permute reorders the four hint bytes of a packed puzzle.
func permute(puzzle uint32, s *[4]uint8) uint32 {
return puzzle>>(s[0]&31)&0xff |
puzzle>>(s[1]&31)&0xff<<8 |
puzzle>>(s[2]&31)&0xff<<16 |
puzzle>>(s[3]&31)<<24
}
// pickPuzzle draws one puzzle of plaintext byte b and one hint order from a
// single 64-bit random value.
func (t *Table) pickPuzzle(b byte, draw uint64) uint32 {
puzzles := t.EncodeTable[b]
puzzle := puzzles[(draw>>32)*uint64(len(puzzles))>>32]
return permute(binary.LittleEndian.Uint32(puzzle[:]), &permShifts[(draw&math.MaxUint32)*uint64(len(permShifts))>>32])
}
// padSlot writes a candidate padding byte at w[k] and keeps it only when the
// slot's draw falls under threshold. A slot that draws no padding leaves k
// alone, so the next write overwrites the candidate.
func padSlot(state, threshold uint64, pool []byte, w *[16]byte, k int) (uint64, int) {
state, draw := wyNext(state)
w[k&15] = pool[(draw>>32)*uint64(len(pool))>>32]
return state, k + int((draw&math.MaxUint32-threshold)>>63)
}
// appendSudokuPayload encodes p after dst. Each plaintext byte becomes one
// puzzle's four hints in a random order, with a padding byte possible before
// each hint and one more before the group. threshold is the per-slot padding
// probability scaled to 1<<32, so a value of 1<<32 pads every slot.
func appendSudokuPayload(dst []byte, table *Table, rng *sudokuRand, threshold uint64, p []byte) []byte {
if len(p) == 0 {
return dst[:0]
return dst
}
if paddingThreshold == 0 {
return encodeSudokuPayloadNoPadding(dst, table, rng, p)
n := len(dst)
expansion := maxPaddedExpansion
if threshold == 0 {
expansion = 4
}
out := dst
if need := n + len(p)*expansion + encodeSlack; cap(out) < need {
out = make([]byte, n, need)
copy(out, dst)
}
out = out[:cap(out)]
state := rng.state
outCapacity := len(p)*6 + 1
if cap(dst) < outCapacity {
dst = make([]byte, 0, outCapacity)
}
out := dst[:0]
pads := table.PaddingPool
padLen := len(pads)
if paddingThreshold >= probOne {
if threshold == 0 {
for _, b := range p {
out = append(out, pads[rng.Intn(padLen)])
puzzles := table.EncodeTable[b]
puzzle := puzzles[rng.Intn(len(puzzles))]
perm := perm4[rng.Intn(len(perm4))]
for _, idx := range perm {
out = append(out, pads[rng.Intn(padLen)], puzzle[idx])
}
var draw uint64
state, draw = wyNext(state)
binary.LittleEndian.PutUint32(out[n:], table.pickPuzzle(b, draw))
n += 4
}
out = append(out, pads[rng.Intn(padLen)])
return out
rng.state = state
return out[:n]
}
pool := table.PaddingPool
for _, b := range p {
if uint64(rng.Uint32()) < paddingThreshold {
out = append(out, pads[rng.Intn(padLen)])
}
var draw uint64
state, draw = wyNext(state)
hints := table.pickPuzzle(b, draw)
puzzles := table.EncodeTable[b]
puzzle := puzzles[rng.Intn(len(puzzles))]
perm := perm4[rng.Intn(len(perm4))]
for _, idx := range perm {
if uint64(rng.Uint32()) < paddingThreshold {
out = append(out, pads[rng.Intn(padLen)])
}
out = append(out, puzzle[idx])
}
w := (*[16]byte)(out[n:])
var k int
state, k = padSlot(state, threshold, pool, w, 0)
state, k = padSlot(state, threshold, pool, w, k)
w[k&15] = byte(hints)
state, k = padSlot(state, threshold, pool, w, k+1)
w[k&15] = byte(hints >> 8)
state, k = padSlot(state, threshold, pool, w, k+1)
w[k&15] = byte(hints >> 16)
state, k = padSlot(state, threshold, pool, w, k+1)
w[k&15] = byte(hints >> 24)
n += k + 1
}
if uint64(rng.Uint32()) < paddingThreshold {
out = append(out, pads[rng.Intn(padLen)])
}
return out
}
func encodeSudokuPayloadNoPadding(dst []byte, table *Table, rng *sudokuRand, p []byte) []byte {
outCapacity := len(p) * 4
if cap(dst) < outCapacity {
dst = make([]byte, 0, outCapacity)
}
out := dst[:0]
for _, b := range p {
puzzles := table.EncodeTable[b]
puzzle := puzzles[rng.Intn(len(puzzles))]
perm := perm4[rng.Intn(len(perm4))]
out = append(out, puzzle[perm[0]], puzzle[perm[1]], puzzle[perm[2]], puzzle[perm[3]])
}
return out
rng.state = state
return out[:n]
}
+36 -23
View File
@@ -14,32 +14,43 @@ type byteLayout struct {
padMarker byte
paddingPool []byte
hintTable [256]bool
hintIdx [256]uint8 // pos<<2|val for a hint byte, poisonHint for a hint-class byte no encoder emits, notHint otherwise
encodeHint [4][16]byte
encodeGroup [64]byte
decodeGroup [256]byte
groupValid [256]bool
decodeGroup [256]byte // 0..63 for hints, 0xff for padding/invalid bytes
}
const (
// poisonHint indexes an all-zero set: a hint-class byte no encoder emits,
// which keeps the stream from ever decoding.
poisonHint = 64
notHint = 0x80
)
// indexHints derives hintIdx from encodeHint; aliases lists hint-class wire
// bytes that encodeHint never produces.
func (l *byteLayout) indexHints(aliases ...byte) {
for i := range l.hintIdx {
l.hintIdx[i] = notHint
}
for _, b := range aliases {
l.hintIdx[b] = poisonHint
}
for val := range l.encodeHint {
for pos, b := range l.encodeHint[val] {
l.hintIdx[b] = uint8(pos<<2 | val)
}
}
}
func (l *byteLayout) isHint(b byte) bool {
return l != nil && l.hintTable[b]
return l != nil && l.hintIdx[b] != notHint
}
func (l *byteLayout) hintByte(val, pos byte) byte {
return l.encodeHint[val&0x03][pos&0x0F]
}
func (l *byteLayout) groupByte(group byte) byte {
return l.encodeGroup[group&0x3F]
}
func (l *byteLayout) decodePackedGroup(b byte) (byte, bool) {
if l == nil {
return 0, false
}
return l.decodeGroup[b], l.groupValid[b]
}
// resolveLayout picks the byte layout for a single traffic direction.
// ASCII always wins if requested. Custom patterns are ignored when ASCII is preferred.
func resolveLayout(mode string, customPattern string) (*byteLayout, error) {
@@ -88,17 +99,19 @@ func newASCIILayout() *byteLayout {
}
layout.encodeGroup[group] = b
}
// Every byte with bit 6 set is hint-class on the wire, though only the 63
// below 0x7F and '\n' are ever emitted as hints.
var aliases []byte
for b := 0; b < 256; b++ {
layout.decodeGroup[b] = 0xff
wire := byte(b)
if (wire & 0x40) == 0x40 {
layout.hintTable[wire] = true
layout.decodeGroup[wire] = wire & 0x3F
layout.groupValid[wire] = true
aliases = append(aliases, wire)
}
}
layout.hintTable['\n'] = true
layout.decodeGroup['\n'] = 0x3F
layout.groupValid['\n'] = true
layout.indexHints(aliases...)
return layout
}
@@ -128,14 +141,14 @@ func newEntropyLayout() *byteLayout {
layout.encodeGroup[group] = ((v & 0x30) << 1) | (v & 0x0F)
}
for b := 0; b < 256; b++ {
layout.decodeGroup[b] = 0xff
wire := byte(b)
if (wire & 0x90) != 0 {
continue
}
layout.hintTable[wire] = true
layout.decodeGroup[wire] = ((wire >> 1) & 0x30) | (wire & 0x0F)
layout.groupValid[wire] = true
}
layout.indexHints()
return layout
}
@@ -229,11 +242,11 @@ func newCustomLayout(pattern string) (*byteLayout, error) {
layout.encodeGroup[group] = encodeBits(val, pos, -1)
}
for b := 0; b < 256; b++ {
layout.decodeGroup[b] = 0xff
wire := byte(b)
if (wire & xMask) != xMask {
continue
}
layout.hintTable[wire] = true
var val, pos byte
if wire&(1<<pBits[0]) != 0 {
@@ -248,8 +261,8 @@ func newCustomLayout(pattern string) (*byteLayout, error) {
}
}
layout.decodeGroup[wire] = (val << 4) | pos
layout.groupValid[wire] = true
}
layout.indexHints()
return layout, nil
}
+135 -179
View File
@@ -1,28 +1,19 @@
package sudoku
import (
"bufio"
"io"
"net"
"sync"
)
const (
packedProtectedPrefixBytes = 14
packedIOBufferSize = 32 * 1024
packedDecodeBufferSize = 32 * 1024
)
const packedProtectedPrefixBytes = 14
// PackedConn encodes traffic with the packed Sudoku layout while preserving
// the same padding model as the regular connection.
type PackedConn struct {
net.Conn
table *Table
reader *bufio.Reader
// Read-side buffers.
rawBuf []byte
pendingData pendingBuffer
reader *wireReader
// Write-side state.
writeMu sync.Mutex
@@ -67,10 +58,6 @@ func NewPackedConn(c net.Conn, table *Table, pMin, pMax int) *PackedConn {
pc := &PackedConn{
Conn: c,
table: table,
reader: bufio.NewReaderSize(c, packedIOBufferSize),
rawBuf: make([]byte, packedDecodeBufferSize),
pendingData: newPendingBuffer(4096),
writeBuf: make([]byte, 0, 4096),
rng: localRng,
paddingThreshold: pickPaddingThreshold(localRng, pMin, pMax),
}
@@ -89,6 +76,20 @@ func NewPackedConn(c net.Conn, table *Table, pMin, pMax int) *PackedConn {
return pc
}
// appendByte feeds one plaintext byte into the 6-bit accumulator and emits every
// group it completes.
func (pc *PackedConn) appendByte(out []byte, b byte) []byte {
pc.bitBuf = pc.bitBuf<<8 | uint64(b)
pc.bitCount += 8
for pc.bitCount >= 6 {
pc.bitCount -= 6
group := byte(pc.bitBuf >> pc.bitCount)
pc.bitBuf &= 1<<pc.bitCount - 1
out = appendPackedGroup(out, pc.table.layout, pc.rng, pc.paddingThreshold, pc.padPool, group)
}
return out
}
func (pc *PackedConn) appendForcedPadding(out []byte) []byte {
return append(out, pc.getPaddingByte())
}
@@ -114,18 +115,7 @@ func (pc *PackedConn) writeProtectedPrefix(out []byte, p []byte) ([]byte, int) {
gap := pc.nextProtectedPrefixGap()
effective := 0
for i := 0; i < limit; i++ {
pc.bitBuf = (pc.bitBuf << 8) | uint64(p[i])
pc.bitCount += 8
for pc.bitCount >= 6 {
pc.bitCount -= 6
group := byte(pc.bitBuf >> pc.bitCount)
if pc.bitCount == 0 {
pc.bitBuf = 0
} else {
pc.bitBuf &= (1 << pc.bitCount) - 1
}
out = appendPackedGroup(out, pc.table.layout, pc.rng, pc.paddingThreshold, pc.padPool, group)
}
out = pc.appendByte(out, p[i])
effective++
if effective >= gap {
@@ -148,6 +138,32 @@ func appendPackedGroup(out []byte, layout *byteLayout, rng *sudokuRand, paddingT
return append(out, layout.encodeGroup[group&0x3F])
}
// appendPackedBlocks encodes complete three-byte blocks. Keeping the no-padding
// loop separate removes the random draws and per-group append calls from it.
func appendPackedBlocks(out, p []byte, layout *byteLayout, rng *sudokuRand, threshold uint64, padPool []byte) []byte {
encode := &layout.encodeGroup
if threshold == 0 {
for ; len(p) >= 3; p = p[3:] {
b0, b1, b2 := p[0], p[1], p[2]
out = append(out,
encode[b0>>2],
encode[(b0&3)<<4|b1>>4],
encode[(b1&15)<<2|b2>>6],
encode[b2&63])
}
return out
}
for ; len(p) >= 3; p = p[3:] {
b0, b1, b2 := p[0], p[1], p[2]
groups := [4]byte{b0 >> 2, (b0&3)<<4 | b1>>4, (b1&15)<<2 | b2>>6, b2 & 63}
for _, group := range groups {
out = maybeAppendPackedPadding(out, rng, threshold, padPool)
out = append(out, encode[group])
}
}
return out
}
func maybeAppendPackedPadding(out []byte, rng *sudokuRand, paddingThreshold uint64, padPool []byte) []byte {
if paddingThreshold != 0 {
u := rng.Uint32()
@@ -169,88 +185,47 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
pc.writeMu.Lock()
defer pc.writeMu.Unlock()
needed := len(p)*3/2 + 32
if pc.paddingThreshold == 0 {
needed = ((len(p)+2)/3)*4 + 32
}
if cap(pc.writeBuf) < needed {
pc.writeBuf = make([]byte, 0, needed)
}
out := pc.writeBuf[:0]
// Bound storage independently of the caller's Write size, including padding.
out := growWriteBuf(pc.writeBuf, minInt(minInt(len(p), maxEncodedWriteSize)*3+64, maxEncodedWriteSize))
defer func() { pc.writeBuf = releaseWriteBuf(out) }()
layout := pc.table.layout
rng := pc.rng
paddingThreshold := pc.paddingThreshold
padPool := pc.padPool
var prefixN int
out, prefixN = pc.writeProtectedPrefix(out, p)
i := prefixN
out, i := pc.writeProtectedPrefix(out, p)
n := len(p)
// Align to a complete group boundary.
for pc.bitCount > 0 && i < n {
b := p[i]
out = pc.appendByte(out, p[i])
i++
pc.bitBuf = (pc.bitBuf << 8) | uint64(b)
pc.bitCount += 8
for pc.bitCount >= 6 {
pc.bitCount -= 6
group := byte(pc.bitBuf >> pc.bitCount)
if pc.bitCount == 0 {
pc.bitBuf = 0
} else {
pc.bitBuf &= (1 << pc.bitCount) - 1
}
end := i + (n-i)/3*3
blockSize := 4
if paddingThreshold != 0 {
blockSize = 8
}
written := 0
for i < end {
// Reserve room for the final two bytes, residual marker and trailing pad.
count := minInt((cap(out)-len(out)-8)/blockSize*3, end-i)
if count == 0 {
if _, err := pc.Conn.Write(out); err != nil {
return written, err
}
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, group)
written = i
out = out[:0]
continue
}
out = appendPackedBlocks(out, p[i:i+count], layout, rng, paddingThreshold, padPool)
i += count
}
for i+11 < n {
for batch := 0; batch < 4; batch++ {
b1, b2, b3 := p[i], p[i+1], p[i+2]
i += 3
g1 := (b1 >> 2) & 0x3F
g2 := ((b1 & 0x03) << 4) | ((b2 >> 4) & 0x0F)
g3 := ((b2 & 0x0F) << 2) | ((b3 >> 6) & 0x03)
g4 := b3 & 0x3F
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g1)
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g2)
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g3)
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g4)
}
}
for i+2 < n {
b1, b2, b3 := p[i], p[i+1], p[i+2]
i += 3
g1 := (b1 >> 2) & 0x3F
g2 := ((b1 & 0x03) << 4) | ((b2 >> 4) & 0x0F)
g3 := ((b2 & 0x0F) << 2) | ((b3 >> 6) & 0x03)
g4 := b3 & 0x3F
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g1)
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g2)
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g3)
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g4)
}
// The remaining one or two bytes stay in the accumulator.
for ; i < n; i++ {
b := p[i]
pc.bitBuf = (pc.bitBuf << 8) | uint64(b)
pc.bitCount += 8
for pc.bitCount >= 6 {
pc.bitCount -= 6
group := byte(pc.bitBuf >> pc.bitCount)
if pc.bitCount == 0 {
pc.bitBuf = 0
} else {
pc.bitBuf &= (1 << pc.bitCount) - 1
}
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, group)
}
out = pc.appendByte(out, p[i])
}
if pc.bitCount > 0 {
@@ -263,14 +238,9 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
out = maybeAppendPackedPadding(out, rng, paddingThreshold, padPool)
if len(out) > 0 {
pc.writeBuf = out[:0]
if _, err := pc.Conn.Write(out); err != nil {
return len(p), err
}
return len(p), nil
if _, err := pc.Conn.Write(out); err != nil {
return written, err
}
pc.writeBuf = out[:0]
return len(p), nil
}
@@ -288,7 +258,7 @@ func (pc *PackedConn) Flush() error {
pc.bitBuf = 0
pc.bitCount = 0
out = append(out, pc.table.layout.groupByte(group&0x3F))
out = append(out, pc.table.layout.encodeGroup[group&0x3F])
out = append(out, pc.padMarker)
}
@@ -306,71 +276,21 @@ func (pc *PackedConn) Read(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
if pc == nil || pc.Conn == nil || pc.reader == nil || len(pc.rawBuf) == 0 || pc.table == nil || pc.table.layout == nil {
if pc == nil || pc.Conn == nil || pc.table == nil || pc.table.layout == nil {
return 0, io.ErrClosedPipe
}
if n, ok := drainPending(p, &pc.pendingData); ok {
return n, nil
if pc.reader == nil {
// Write-only codecs never pay for a read buffer.
pc.reader = &wireReader{src: pc.Conn}
}
outN := 0
for {
nr, rErr := readRawLimited(pc.Conn, pc.reader, pc.rawBuf[:packedReadSize(len(p)-outN, len(pc.rawBuf))])
if nr > 0 {
rBuf := pc.readBitBuf
rBits := pc.readBits
padMarker := pc.padMarker
layout := pc.table.layout
chunk := pc.rawBuf[:nr]
for i := 0; i < len(chunk); {
if rBits == 0 && outN+3 <= len(p) && i+3 < len(chunk) &&
layout.hintTable[chunk[i]] && layout.hintTable[chunk[i+1]] &&
layout.hintTable[chunk[i+2]] && layout.hintTable[chunk[i+3]] {
g1 := layout.decodeGroup[chunk[i]]
g2 := layout.decodeGroup[chunk[i+1]]
g3 := layout.decodeGroup[chunk[i+2]]
g4 := layout.decodeGroup[chunk[i+3]]
p[outN] = (g1 << 2) | (g2 >> 4)
p[outN+1] = (g2 << 4) | (g3 >> 2)
p[outN+2] = (g3 << 6) | g4
outN += 3
i += 4
continue
}
b := chunk[i]
i++
if !layout.hintTable[b] {
if b == padMarker {
rBuf = 0
rBits = 0
}
continue
}
group, ok := layout.decodePackedGroup(b)
if !ok {
return 0, ErrInvalidSudokuMapMiss
}
rBuf = (rBuf << 6) | uint64(group)
rBits += 6
if rBits >= 8 {
rBits -= 8
val := byte(rBuf >> rBits)
outN = appendDecodedByte(p, outN, &pc.pendingData, val)
if rBits == 0 {
rBuf = 0
} else {
rBuf &= (uint64(1) << rBits) - 1
}
}
}
pc.readBitBuf = rBuf
pc.readBits = rBits
chunk, rErr := pc.reader.peek()
if len(chunk) > 0 {
var consumed int
outN, consumed, rErr = pc.decode(p, chunk)
pc.reader.discard(consumed)
}
if rErr != nil {
@@ -378,12 +298,6 @@ func (pc *PackedConn) Read(p []byte) (int, error) {
pc.readBitBuf = 0
pc.readBits = 0
}
if outN > 0 {
return outN, nil
}
if n, ok := drainPending(p, &pc.pendingData); ok {
return n, nil
}
return 0, rErr
}
@@ -393,17 +307,59 @@ func (pc *PackedConn) Read(p []byte) (int, error) {
}
}
// decode writes only as much plaintext as fits in p; the wire bytes it
// consumed can then be dropped and the rest stay in the reader.
func (pc *PackedConn) decode(p, chunk []byte) (outN, consumed int, err error) {
rBuf := pc.readBitBuf
rBits := pc.readBits
padMarker := pc.padMarker
layout := pc.table.layout
for consumed < len(chunk) && outN < len(p) {
i := consumed
if rBits == 0 && outN+3 <= len(p) && i+3 < len(chunk) {
g1 := layout.decodeGroup[chunk[i]]
g2 := layout.decodeGroup[chunk[i+1]]
g3 := layout.decodeGroup[chunk[i+2]]
g4 := layout.decodeGroup[chunk[i+3]]
// The invalid sentinel combines validation and decoding in one lookup.
if (g1 | g2 | g3 | g4) < 64 {
p[outN] = (g1 << 2) | (g2 >> 4)
p[outN+1] = (g2 << 4) | (g3 >> 2)
p[outN+2] = (g3 << 6) | g4
outN += 3
consumed += 4
continue
}
}
b := chunk[i]
consumed++
group := layout.decodeGroup[b]
if group >= 64 {
if b == padMarker {
rBuf = 0
rBits = 0
}
continue
}
rBuf = (rBuf << 6) | uint64(group)
rBits += 6
if rBits >= 8 {
rBits -= 8
p[outN] = byte(rBuf >> rBits)
outN++
rBuf &= (uint64(1) << rBits) - 1
}
}
pc.readBitBuf = rBuf
pc.readBits = rBits
return outN, consumed, nil
}
func (pc *PackedConn) getPaddingByte() byte {
return pc.padPool[pc.rng.Intn(len(pc.padPool))]
}
func packedReadSize(decodedRemaining, maxRaw int) int {
if maxRaw <= minDecodeReadSize || decodedRemaining <= 0 {
return maxRaw
}
if decodedRemaining > (maxRaw-minDecodeReadSize)/2 {
return maxRaw
}
return decodedRemaining*2 + minDecodeReadSize
}
@@ -3,6 +3,7 @@ package sudoku
import (
"bytes"
"io"
"math/rand"
"net"
"testing"
"time"
@@ -88,3 +89,105 @@ func TestPackedConn_ProtectedPrefixPadding(t *testing.T) {
t.Fatalf("roundtrip mismatch")
}
}
func TestCodecRoundTrip(t *testing.T) {
tables := map[string]*Table{
"entropy": NewTable("roundtrip-seed", "prefer_entropy"),
"ascii": NewTable("roundtrip-seed", "prefer_ascii"),
}
custom, err := NewTableWithCustom("roundtrip-seed", "up_ascii_down_entropy", "xpxvvpvv")
if err != nil {
t.Fatal(err)
}
tables["custom"] = custom.OppositeDirection()
for name, table := range tables {
for _, packed := range []bool{false, true} {
for _, pad := range [][2]int{{0, 0}, {5, 15}, {100, 100}} {
for _, size := range []int{1, 2, 14, 15, 100, 70000} {
payload := make([]byte, size)
rand.New(rand.NewSource(int64(size))).Read(payload)
mock := &mockConn{}
var w io.Writer = NewConn(mock, table, pad[0], pad[1], false)
if packed {
w = NewPackedConn(mock, table, pad[0], pad[1])
}
// Split the payload so partial packed groups carry over between writes.
if _, err := w.Write(payload[:size/2]); err != nil {
t.Fatal(err)
}
if _, err := w.Write(payload[size/2:]); err != nil {
t.Fatal(err)
}
if f, ok := w.(*PackedConn); ok {
if err := f.Flush(); err != nil {
t.Fatal(err)
}
}
for _, readSize := range []int{1, 7, 4096} {
src := &mockConn{readBuf: append([]byte(nil), mock.writeBuf...)}
var r io.Reader = NewConn(src, table, pad[0], pad[1], false)
if packed {
r = NewPackedConn(src, table, pad[0], pad[1])
}
got := make([]byte, 0, size)
buf := make([]byte, readSize)
for {
n, err := r.Read(buf)
got = append(got, buf[:n]...)
if err == io.EOF {
break
}
if err != nil {
t.Fatal(err)
}
}
if !bytes.Equal(got, payload) {
t.Fatalf("%s packed=%v pad=%v size=%d read=%d: round trip mismatch", name, packed, pad, size, readSize)
}
}
}
}
}
}
}
func TestConnRecordsEverythingRead(t *testing.T) {
table := NewTable("record-seed", "prefer_entropy")
writer := &mockConn{}
payload := bytes.Repeat([]byte("sudoku"), 3000)
if _, err := NewConn(writer, table, 5, 15, false).Write(payload); err != nil {
t.Fatal(err)
}
wire := writer.writeBuf
src := &mockConn{readBuf: append([]byte(nil), wire...)}
sc := NewConn(src, table, 5, 15, true)
buf := make([]byte, 200)
for step := 0; step < 3; step++ {
if _, err := io.ReadFull(sc, buf); err != nil {
t.Fatal(err)
}
// Recorded plus buffered must be every byte taken from the socket, whatever
// the reader has or has not decoded yet.
if got, want := sc.GetBufferedAndRecorded(), wire[:len(wire)-len(src.readBuf)]; !bytes.Equal(got, want) {
t.Fatalf("step %d: recorded %d bytes, want %d", step, len(got), len(want))
}
}
if !sc.reader.pooled {
t.Fatalf("a busy connection should have switched to a pooled read buffer")
}
sc.StopRecording()
if _, err := io.Copy(io.Discard, sc); err != nil {
t.Fatal(err)
}
if sc.reader.pooled || len(sc.reader.pending()) != 0 {
t.Fatalf("a drained connection should hold no pooled buffer")
}
if got := sc.GetBufferedAndRecorded(); len(got) != 0 {
t.Fatalf("recording was stopped, got %d bytes", len(got))
}
}
-69
View File
@@ -1,69 +0,0 @@
package sudoku
type pendingBuffer struct {
data []byte
off int
}
func newPendingBuffer(capacity int) pendingBuffer {
return pendingBuffer{data: make([]byte, 0, capacity)}
}
func (p *pendingBuffer) available() int {
if p == nil {
return 0
}
return len(p.data) - p.off
}
func (p *pendingBuffer) reset() {
if p == nil {
return
}
p.data = p.data[:0]
p.off = 0
}
func (p *pendingBuffer) ensureAppendCapacity(extra int) {
if p == nil || extra <= 0 {
return
}
if p.off == 0 {
return
}
if cap(p.data)-len(p.data) >= extra {
return
}
unread := len(p.data) - p.off
copy(p.data[:unread], p.data[p.off:])
p.data = p.data[:unread]
p.off = 0
}
func (p *pendingBuffer) appendByte(b byte) {
p.ensureAppendCapacity(1)
p.data = append(p.data, b)
}
func appendDecodedByte(dst []byte, n int, pending *pendingBuffer, b byte) int {
if n < len(dst) {
dst[n] = b
return n + 1
}
pending.appendByte(b)
return n
}
func drainPending(dst []byte, pending *pendingBuffer) (int, bool) {
if pending == nil || pending.available() == 0 {
return 0, false
}
n := copy(dst, pending.data[pending.off:])
pending.off += n
if pending.off == len(pending.data) {
pending.reset()
}
return n, true
}
+17 -29
View File
@@ -3,13 +3,14 @@ package sudoku
import (
crypto_rand "crypto/rand"
"encoding/binary"
"math/bits"
"time"
)
// sudokuRand is a wyrand generator. Its state advances by a constant, so draws
// do not depend on each other's results and the encoder can overlap them.
type sudokuRand struct {
state uint64
cached uint32
haveCached bool
state uint64
}
func newSeededRand() *sudokuRand {
@@ -22,38 +23,25 @@ func newSeededRand() *sudokuRand {
}
func newSudokuRand(seed int64) *sudokuRand {
state := uint64(seed)
if state == 0 {
state = 0x9e3779b97f4a7c15
}
return &sudokuRand{state: state}
return &sudokuRand{state: uint64(seed)}
}
// wyNext is the generator step as a pure function so hot loops can keep the
// state in a register.
func wyNext(state uint64) (next, out uint64) {
state += 0xa0761d6478bd642f
hi, lo := bits.Mul64(state, state^0xe7037ed1a0b428db)
return state, hi ^ lo
}
func (r *sudokuRand) Uint64() uint64 {
if r == nil {
return 0
}
r.haveCached = false
x := r.state
x ^= x >> 12
x ^= x << 25
x ^= x >> 27
r.state = x
return x * 0x2545f4914f6cdd1d
var out uint64
r.state, out = wyNext(r.state)
return out
}
func (r *sudokuRand) Uint32() uint32 {
if r == nil {
return 0
}
if r.haveCached {
r.haveCached = false
return r.cached
}
v := r.Uint64()
r.cached = uint32(v)
r.haveCached = true
return uint32(v >> 32)
return uint32(r.Uint64() >> 32)
}
func (r *sudokuRand) Intn(n int) int {
@@ -0,0 +1,80 @@
package sudoku
import (
"io"
"github.com/metacubex/mihomo/common/pool"
)
const (
// smallReadSize is what a connection reads into while it may block for a
// long time. Idle connections hold at most this much.
smallReadSize = 512
// readBufferSize is the wire read size of a busy connection, borrowed from
// the shared pool only while it has data.
readBufferSize = 32 * 1024
)
// wireReader hands the codecs the raw bytes already received, without a second
// copy. It reads small while a connection is quiet, switches to a pooled buffer
// once a read fills its buffer (more is queued, so the next read will not
// block), and returns that buffer when drained.
type wireReader struct {
src io.Reader
buf []byte
pooled bool
r, w int
wasFull bool
smallBuf [smallReadSize]byte
}
// peek borrows every unread wire byte, reading first when there are none. It
// waits for at least one byte, never for a full buffer. The slice is valid
// until the next peek or discard.
func (wr *wireReader) peek() ([]byte, error) {
if wr.r == wr.w {
if err := wr.fill(); err != nil {
return nil, err
}
}
return wr.buf[wr.r:wr.w], nil
}
func (wr *wireReader) fill() error {
switch {
case wr.wasFull && !wr.pooled:
wr.buf, wr.pooled = pool.Get(readBufferSize), true
case wr.buf == nil:
wr.buf = wr.smallBuf[:]
}
for {
n, err := wr.src.Read(wr.buf)
if n > 0 {
wr.r, wr.w = 0, n
wr.wasFull = n == len(wr.buf)
return nil
}
if err != nil {
return err
}
}
}
// discard drops n bytes peek returned. A pooled buffer goes back once it is
// drained by a read that did not fill it, since the next read may block.
func (wr *wireReader) discard(n int) {
wr.r += n
if wr.r == wr.w && wr.pooled && !wr.wasFull {
pool.Put(wr.buf)
wr.buf, wr.pooled = wr.smallBuf[:], false
wr.r, wr.w = 0, 0
}
}
// pending returns the received but undecoded bytes.
func (wr *wireReader) pending() []byte {
if wr == nil {
return nil
}
return wr.buf[wr.r:wr.w]
}
+49 -57
View File
@@ -4,6 +4,7 @@ import (
"crypto/sha256"
"encoding/binary"
"errors"
"math/bits"
"math/rand"
"strings"
)
@@ -14,12 +15,16 @@ var (
type Table struct {
EncodeTable [256][][4]byte
DecodeMap map[uint32]byte
PaddingPool []byte
IsASCII bool // 标记当前模式
layout *byteLayout
opposite *Table
hint uint32
// hintSets[pos<<2|val] holds bit k when the k-th shuffled grid has val at
// pos. Four hints identify a plaintext byte exactly when their sets share a
// single grid, and that grid's rank is the byte.
hintSets [128][5]uint64
}
// NewTable initializes the obfuscation tables with built-in layouts.
@@ -73,9 +78,8 @@ func newSingleDirectionTable(key string, mode string, customPattern string) (*Ta
}
t := &Table{
DecodeMap: make(map[uint32]byte),
IsASCII: layout.name == "ascii",
layout: layout,
IsASCII: layout.name == "ascii",
layout: layout,
}
t.PaddingPool = append(t.PaddingPool, layout.paddingPool...)
@@ -110,50 +114,31 @@ func newSingleDirectionTable(key string, mode string, customPattern string) (*Ta
}
combine(0, 4, []int{})
for k, g := range shuffledGrids {
for pos, val := range g {
t.hintSets[pos<<2|int(val-1)][k>>6] |= 1 << (k & 63)
}
}
// 构建映射表
for byteVal := 0; byteVal < 256; byteVal++ {
targetGrid := shuffledGrids[byteVal]
for _, positions := range combinations {
var currentHints [4]byte
// 1. 计算抽象提示 (Abstract Hints)
// 我们先计算出 val 和 pos,后面再根据模式编码成 byte
var rawParts [4]struct{ val, pos byte }
var hints [4]uint8
for i, pos := range positions {
val := targetGrid[pos] // 1..4
rawParts[i] = struct{ val, pos byte }{val, uint8(pos)}
hints[i] = uint8(pos)<<2 | (targetGrid[pos] - 1)
}
// 检查唯一性 (数独逻辑)
matchCount := 0
for _, g := range allGrids {
match := true
for _, p := range rawParts {
if g[p.pos] != p.val {
match = false
break
}
}
if match {
matchCount++
if matchCount > 1 {
break
}
}
// 唯一确定才可作为 puzzle
if _, ok := t.decodeHints(hints[0], hints[1], hints[2], hints[3]); !ok {
continue
}
if matchCount == 1 {
// 唯一确定,生成最终编码字节
for i, p := range rawParts {
currentHints[i] = t.layout.hintByte(p.val-1, p.pos)
}
t.EncodeTable[byteVal] = append(t.EncodeTable[byteVal], currentHints)
// 生成解码键 (需要对 Hints 进行排序以忽略传输顺序)
key := packHintsToKey(currentHints)
t.DecodeMap[key] = byte(byteVal)
var currentHints [4]byte
for i, pos := range positions {
currentHints[i] = t.layout.hintByte(targetGrid[pos]-1, uint8(pos))
}
t.EncodeTable[byteVal] = append(t.EncodeTable[byteVal], currentHints)
}
}
return t, nil
@@ -191,28 +176,35 @@ func tableHintFingerprint(key string, mode string, uplinkPattern string, downlin
return binary.BigEndian.Uint32(sum[:4])
}
func packHintsToKey(hints [4]byte) uint32 {
return packHintBytes(hints[0], hints[1], hints[2], hints[3])
}
// decodeHints returns the plaintext byte whose puzzle is exactly these four
// hint indexes (pos<<2|val, or poisonHint).
func (t *Table) decodeHints(a, b, c, d uint8) (byte, bool) {
sa, sb, sc, sd := &t.hintSets[a&127], &t.hintSets[b&127], &t.hintSets[c&127], &t.hintSets[d&127]
r0 := sa[0] & sb[0] & sc[0] & sd[0]
r1 := sa[1] & sb[1] & sc[1] & sd[1]
r2 := sa[2] & sb[2] & sc[2] & sd[2]
r3 := sa[3] & sb[3] & sc[3] & sd[3]
r4 := sa[4] & sb[4] & sc[4] & sd[4]
func packHintBytes(h0, h1, h2, h3 byte) uint32 {
// Sorting network for 4 elements (Bubble sort unrolled)
// Swap if a > b
if h0 > h1 {
h0, h1 = h1, h0
// Exactly one shared grid, and it must be one of the 256 that carry a byte.
multi := r0&(r0-1) | r1&(r1-1) | r2&(r2-1) | r3&(r3-1) | r4
var nonEmpty uint64
word := 0
if r1 != 0 {
nonEmpty++
word = 64
}
if h2 > h3 {
h2, h3 = h3, h2
if r2 != 0 {
nonEmpty++
word = 128
}
if h0 > h2 {
h0, h2 = h2, h0
if r3 != 0 {
nonEmpty++
word = 192
}
if h1 > h3 {
h1, h3 = h3, h1
if r0 != 0 {
nonEmpty++
}
if h1 > h2 {
h1, h2 = h2, h1
}
return uint32(h0)<<24 | uint32(h1)<<16 | uint32(h2)<<8 | uint32(h3)
rank := word + bits.TrailingZeros64(r0|r1|r2|r3)
return byte(rank), multi|(nonEmpty^1) == 0
}
@@ -0,0 +1,88 @@
package sudoku
import (
"io"
"math"
"github.com/metacubex/mihomo/common/pool"
)
const (
// maxEncodedWriteSize bounds one Write to the underlying connection and the
// encode buffer, matching readBufferSize.
maxEncodedWriteSize = 32 * 1024
// retainedWriteBytes is the encode buffer a connection keeps between writes.
// Larger encodes borrow a pooled buffer for the duration of one Write.
retainedWriteBytes = 2048
)
// minInt exists because the module still targets Go 1.20, which has no min.
func minInt(a, b int) int {
if a < b {
return a
}
return b
}
// writeSudokuPayload encodes p and writes it to w, keeping the encode buffer
// bounded however large p is. It fills the remaining space with complete
// payload bytes, then sends that buffer. The padding slot that closes a Write
// belongs to the whole Write, never to an internal batch.
func writeSudokuPayload(w io.Writer, buf []byte, table *Table, rng *sudokuRand, threshold uint64, p []byte) ([]byte, int, error) {
expansion := maxPaddedExpansion
if threshold == 0 {
expansion = 4
}
buf = growWriteBuf(buf, minInt(minInt(len(p), maxEncodedWriteSize)*expansion+encodeSlack, maxEncodedWriteSize))
out := buf[:0]
total, buffered := 0, 0
for len(p) > 0 {
n := minInt(len(p), (cap(out)-len(out)-encodeSlack)/expansion)
if n == 0 {
if _, err := w.Write(out); err != nil {
return releaseWriteBuf(out), total, err
}
total += buffered
buffered = 0
out = out[:0]
continue
}
out = appendSudokuPayload(out, table, rng, threshold, p[:n])
buffered += n
p = p[n:]
}
if threshold != 0 {
draw := rng.Uint64()
if draw&math.MaxUint32 < threshold {
pad := table.PaddingPool
out = append(out, pad[(draw>>32)*uint64(len(pad))>>32])
}
}
if _, err := w.Write(out); err != nil {
return releaseWriteBuf(out), total, err
}
return releaseWriteBuf(out), total + buffered, nil
}
// growWriteBuf returns an empty buffer with room for need bytes, borrowed from
// the pool when need exceeds what a connection may retain.
func growWriteBuf(buf []byte, need int) []byte {
if cap(buf) >= need {
return buf[:0]
}
if need <= retainedWriteBytes {
return make([]byte, 0, need)
}
return pool.Get(maxEncodedWriteSize)[:0]
}
// releaseWriteBuf keeps a small buffer for the next Write and returns a pooled
// one.
func releaseWriteBuf(buf []byte) []byte {
if cap(buf) <= retainedWriteBytes {
return buf[:0]
}
pool.Put(buf)
return nil
}
+10 -3
View File
@@ -10,6 +10,7 @@ import (
"net"
"time"
"github.com/metacubex/mihomo/common/pool"
"github.com/metacubex/mihomo/transport/sudoku/crypto"
"github.com/metacubex/mihomo/transport/sudoku/obfs/sudoku"
)
@@ -115,7 +116,10 @@ func selectTableByProbe(r *bufio.Reader, cfg *ProtocolConfig, tables []*sudoku.T
return nil, nil, fmt.Errorf("drain buffered bytes failed: %w", err)
}
tmp := make([]byte, readChunk)
// Most handshakes are decided by the bytes bufio already holds, so the read chunk is
// only taken once another read is needed.
var chunk []byte
defer func() { _ = pool.Put(chunk) }()
for {
if len(candidates) == 1 {
tail, err := drainBuffered(r)
@@ -153,9 +157,12 @@ func selectTableByProbe(r *bufio.Reader, cfg *ProtocolConfig, tables []*sudoku.T
return nil, probe, fmt.Errorf("handshake probe exceeded %d bytes", maxProbeBytes)
}
n, err := r.Read(tmp)
if chunk == nil {
chunk = pool.Get(readChunk)
}
n, err := r.Read(chunk)
if n > 0 {
probe = append(probe, tmp[:n]...)
probe = append(probe, chunk[:n]...)
}
if err != nil {
return nil, probe, fmt.Errorf("handshake probe read failed: %w", err)
+98 -63
View File
@@ -1,76 +1,121 @@
package sudoku
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"net"
"net/netip"
"sync"
"time"
"github.com/metacubex/mihomo/common/pool"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/transport/socks5"
)
const (
maxUoTPayload = 64 * 1024
)
// uotHeaderSize is u16 address length | u16 payload length.
const uotHeaderSize = 4
// WriteDatagram sends a single UDP datagram frame over a reliable stream.
func WriteDatagram(w io.Writer, addr string, payload []byte) error {
addrBuf, err := EncodeAddress(addr)
return writeDatagram(w, payload, func(b []byte) ([]byte, error) { return AppendAddress(b, addr) })
}
// writeDatagram sends the whole frame with one write, so it is sealed as one record.
func writeDatagram(w io.Writer, payload []byte, appendAddr func([]byte) ([]byte, error)) error {
if len(payload) > math.MaxUint16 {
return fmt.Errorf("payload too large: %d", len(payload))
}
buf := pool.Get(uotHeaderSize + socks5.MaxAddrLen + len(payload))
defer pool.Put(buf)
frame, err := appendAddr(buf[:uotHeaderSize])
if err != nil {
return fmt.Errorf("encode address: %w", err)
}
if addrLen := len(addrBuf); addrLen == 0 || addrLen > maxUoTPayload {
return fmt.Errorf("address too long: %d", len(addrBuf))
}
if payloadLen := len(payload); payloadLen > maxUoTPayload {
return fmt.Errorf("payload too large: %d", payloadLen)
}
var header [4]byte
binary.BigEndian.PutUint16(header[:2], uint16(len(addrBuf)))
binary.BigEndian.PutUint16(header[2:], uint16(len(payload)))
return writeAllChunks(w, header[:], addrBuf, payload)
binary.BigEndian.PutUint16(frame, uint16(len(frame)-uotHeaderSize))
binary.BigEndian.PutUint16(frame[2:], uint16(len(payload)))
_, err = w.Write(append(frame, payload...))
return err
}
// ReadDatagram parses a single UDP datagram frame from the reliable stream.
func ReadDatagram(r io.Reader) (string, []byte, error) {
addr, payloadLen, err := readDatagramHeaderAndAddress(r)
if err != nil {
return "", nil, err
// UoTReader reads datagram frames from a UoT stream. The header and address are read into
// scratch space owned by the reader, so a frame costs no allocation besides its payload.
type UoTReader struct {
r io.Reader
buf [uotHeaderSize + socks5.MaxAddrLen]byte
}
func NewUoTReader(r io.Reader) *UoTReader {
return &UoTReader{r: r}
}
// readHeader reads the next frame's header and address and leaves its payload (payloadLen bytes)
// unread. addr is only valid until the next call.
func (u *UoTReader) readHeader() (addr socks5.Addr, payloadLen int, err error) {
if _, err = io.ReadFull(u.r, u.buf[:uotHeaderSize]); err != nil {
return nil, 0, err
}
payload := make([]byte, payloadLen)
if _, err := io.ReadFull(r, payload); err != nil {
return "", nil, err
addrLen := int(binary.BigEndian.Uint16(u.buf[:2]))
payloadLen = int(binary.BigEndian.Uint16(u.buf[2:]))
if addrLen == 0 {
return nil, 0, fmt.Errorf("invalid address length: %d", addrLen)
}
// An encoded address is at most socks5.MaxAddrLen bytes; anything after it is padding.
n := addrLen
if n > socks5.MaxAddrLen {
n = socks5.MaxAddrLen
}
if _, err = io.ReadFull(u.r, u.buf[uotHeaderSize:uotHeaderSize+n]); err != nil {
return nil, 0, err
}
if err = discardBytes(u.r, addrLen-n); err != nil {
return nil, 0, err
}
if addr = socks5.SplitAddr(u.buf[uotHeaderSize : uotHeaderSize+n]); addr == nil {
return nil, 0, errors.New("decode address: invalid address")
}
return addr, payloadLen, nil
}
// ReadDatagram reads the next frame. addr is only valid until the next call; payload comes from
// common/pool and must be released with pool.Put.
func (u *UoTReader) ReadDatagram() (socks5.Addr, []byte, error) {
addr, payloadLen, err := u.readHeader()
if err != nil {
return nil, nil, err
}
payload := pool.Get(payloadLen)
if _, err := io.ReadFull(u.r, payload); err != nil {
_ = pool.Put(payload)
return nil, nil, err
}
return addr, payload, nil
}
// UoTPacketConn adapts a net.Conn with the Sudoku UoT framing to net.PacketConn.
type UoTPacketConn struct {
conn net.Conn
reader *UoTReader
writeMu sync.Mutex
}
func NewUoTPacketConn(conn net.Conn) *UoTPacketConn {
return &UoTPacketConn{conn: conn}
return &UoTPacketConn{conn: conn, reader: NewUoTReader(conn)}
}
func (c *UoTPacketConn) ReadFrom(p []byte) (int, net.Addr, error) {
for {
addrStr, payloadLen, err := readDatagramHeaderAndAddress(c.conn)
addr, payloadLen, err := c.reader.readHeader()
if err != nil {
return 0, nil, err
}
udpAddr, err := parseDatagramUDPAddr(addrStr)
udpAddr, err := uotUDPAddr(addr)
if payloadLen > len(p) {
if discardErr := discardBytes(c.conn, payloadLen); discardErr != nil {
return 0, nil, discardErr
@@ -81,7 +126,7 @@ func (c *UoTPacketConn) ReadFrom(p []byte) (int, net.Addr, error) {
if discardErr := discardBytes(c.conn, payloadLen); discardErr != nil {
return 0, nil, discardErr
}
log.Debugln("[Sudoku][UoT] discard datagram with invalid address %s: %v", addrStr, err)
log.Debugln("[Sudoku][UoT] discard datagram with invalid address %s: %v", addr, err)
continue
}
if _, err := io.ReadFull(c.conn, p[:payloadLen]); err != nil {
@@ -95,9 +140,16 @@ func (c *UoTPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) {
if addr == nil {
return 0, errors.New("address is nil")
}
appendAddr := func(b []byte) ([]byte, error) { return AppendAddress(b, addr.String()) }
if udpAddr, ok := addr.(*net.UDPAddr); ok {
if ap := udpAddr.AddrPort(); ap.Addr().IsValid() {
appendAddr = func(b []byte) ([]byte, error) { return AppendAddrPort(b, ap), nil }
}
}
c.writeMu.Lock()
defer c.writeMu.Unlock()
if err := WriteDatagram(c.conn, addr.String(), p); err != nil {
if err := writeDatagram(c.conn, p, appendAddr); err != nil {
return 0, err
}
return len(p), nil
@@ -123,39 +175,22 @@ func (c *UoTPacketConn) SetWriteDeadline(t time.Time) error {
return c.conn.SetWriteDeadline(t)
}
func readDatagramHeaderAndAddress(r io.Reader) (string, int, error) {
var header [4]byte
if _, err := io.ReadFull(r, header[:]); err != nil {
return "", 0, err
// uotUDPAddr converts a datagram's peer to a *net.UDPAddr. Domain names are not resolved: only
// the IP literals they may spell are accepted.
func uotUDPAddr(addr socks5.Addr) (*net.UDPAddr, error) {
var ap netip.AddrPort
switch addr[0] {
case socks5.AtypIPv4:
ap = netip.AddrPortFrom(netip.AddrFrom4([4]byte(addr[1:5])), binary.BigEndian.Uint16(addr[5:]))
case socks5.AtypIPv6:
ap = netip.AddrPortFrom(netip.AddrFrom16([16]byte(addr[1:17])), binary.BigEndian.Uint16(addr[17:]))
default:
var err error
if ap, err = netip.ParseAddrPort(addr.String()); err != nil {
return nil, err
}
}
addrLen := int(binary.BigEndian.Uint16(header[:2]))
payloadLen := int(binary.BigEndian.Uint16(header[2:]))
if addrLen <= 0 || addrLen > maxUoTPayload {
return "", 0, fmt.Errorf("invalid address length: %d", addrLen)
}
if payloadLen < 0 || payloadLen > maxUoTPayload {
return "", 0, fmt.Errorf("invalid payload length: %d", payloadLen)
}
addrBuf := make([]byte, addrLen)
if _, err := io.ReadFull(r, addrBuf); err != nil {
return "", 0, err
}
addr, err := DecodeAddress(bytes.NewReader(addrBuf))
if err != nil {
return "", 0, fmt.Errorf("decode address: %w", err)
}
return addr, payloadLen, nil
}
func parseDatagramUDPAddr(addr string) (*net.UDPAddr, error) {
addrPort, err := netip.ParseAddrPort(addr)
if err != nil {
return nil, err
}
return net.UDPAddrFromAddrPort(netip.AddrPortFrom(addrPort.Addr().Unmap(), addrPort.Port())), nil
return net.UDPAddrFromAddrPort(netip.AddrPortFrom(ap.Addr().Unmap(), ap.Port())), nil
}
func discardBytes(r io.Reader, n int) error {
-12
View File
@@ -1,12 +0,0 @@
package sudoku
import "io"
func writeAllChunks(w io.Writer, chunks ...[]byte) error {
for _, chunk := range chunks {
if _, err := w.Write(chunk); err != nil {
return err
}
}
return nil
}