Compare commits

...
27 Commits
Author SHA1 Message Date
saba-futai 3f27ef39f8 chore: refactored and fixed issues for sudoku while also improving performance (#3333) 2026-10-21 23:51:58 +08:00
Chenx Dust 2df147b906 feat: support dns-mode for tun (#3288) 2026-10-21 23:44:35 +08:00
wwqgtxx c4e818694c fix: CVE-2026-97031 for crypto/tls 2026-10-21 23:24:35 +08:00
Token 94b13aed49 fix: dialer-proxy cycle check takes quadratic time and memory (#3315) 2026-10-13 20:38:16 +08:00
Token df1b07af2c fix: a sub-millisecond URL test is reported as a failure (#3316) 2026-10-13 20:10:59 +08:00
Token 349af19116 fix: the embedded shadowsocks listener can't be closed (#3314) 2026-10-13 20:02:16 +08:00
enfein bc76c1398c chore: update mieru version (#3304)
Mainly fixes an issue of infinite TCP read retry when using QUIC like Hy2
as mieru's dialer proxy. The issue was reported by a user of mihomo 1.19.32.

Also includes other improvements.
2026-10-11 09:38:59 +08:00
Younes Beriane e4dd968de9 fix: keep fake-ip allocation state when cloning the pool on reload (#3283) 2026-10-08 15:57:16 +08:00
Cassian433 80101933c0 fix: bound doh dials so ones the query gave up on cannot pile up (#3274) 2026-10-08 15:04:41 +08:00
wwqgtxx 1354e52e6f fix: unpassed loadbalance test 2026-10-06 21:27:20 +08:00
wwqgtxx 9f053c4907 chore: lazy init wireguard device and stack 2026-10-02 13:06:43 +08:00
Jiawen Geng 88dcbf7f16 fix: default listener tun to mips stack (#3264) 2026-09-30 22:35:49 +08:00
BESTRUI ac652970fe fix: nil pconn deref when ctx is canceled during h2 ClientConn setup 2026-09-30 21:40:50 +08:00
artbred 409ee57ef2 fix: populate HWCap from auxv on linux 2026-09-30 21:37:59 +08:00
proxi 8fa048d376 fix: half-close in sing-mux 2026-09-30 21:22:40 +08:00
wwqgtxx 134176994f chore: support RX checksum offload for mipstack 2026-09-30 15:47:24 +08:00
wwqgtxx 60f70cec63 fix: align unconnected UDP and raw IP ICMP errors with Linux for mipstack 2026-09-30 00:08:22 +08:00
wwqgtxx 63bd52ec79 chore: change default IP stack mode to mips and support congestion-controller option for tun 2026-09-27 09:11:59 +08:00
enfein f103639c80 chore: update mieru version (#3242)
v3.38.0 reduces CPU usage when UDP session is idle.
2026-09-25 08:10:26 +08:00
FlyingSB 8d57a8c57c fix: exclude opcode from P_DATA_V1 AEAD additional data for OpenVPN (#3237)
OpenVPN authenticates the opcode/peer-id header as AEAD additional data
only for P_DATA_V2. For P_DATA_V1 the additional data is the packet ID
alone. We included the opcode for both, so every data packet exchanged
with a server that does not push peer-id (e.g. SoftEther) failed
authentication and was silently dropped after a successful handshake.
2026-09-25 00:24:38 +08:00
wwqgtxx 41b8a05915 fix: account for TCP options in effective MSS 2026-09-24 21:36:47 +08:00
简直蠢丶 3025efad06 feat: add load-balance hash-key to pin a session on the inbound user (#3133) 2026-09-24 20:32:42 +08:00
Peter Solomon 3c947c76d4 chore: convert support xhttp extra.headers (#3230) 2026-09-22 21:25:29 +08:00
Ryoma Dev afe94dafef fix: set udp InUser metadata for mieru inbound (#3236) 2026-09-22 20:46:47 +08:00
wwqgtxx 91dd03a9e5 chore: support lazy receive buffer reads for mipstack and gvisor 2026-09-22 17:07:49 +08:00
Chenx Dust 5019cc090e fix: potential race condition in c.idleSession.Len() in idleCleanupExpTime() for anytls (#3225) 2026-09-19 22:02:11 +08:00
MiaM1ku fbb674227d fix: restart EasyTier outbound after silent overlay failure (#3215) 2026-09-16 00:51:29 +08:00
66 changed files with 3637 additions and 2482 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
}
+19 -2
View File
@@ -274,8 +274,20 @@ func (c *conn) AddRef(ref any) {
c.ExtendedConn = N.NewRefConn(c.ExtendedConn, ref) // add ref for autoCloseProxyAdapter
}
// ipstackConn is a common experimental API interface implemented by:
// *mipstack.TCPConn, *mipstack.UDPConn, *mipstack.IPConn
// it's also implemented by our gVisor fork
type ipstackConn interface {
ReadWithBuffer(getBuffer func(sizeHint int) []byte) (int, error)
}
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
if _, ok := c.(syscall.Conn); !ok { // exclusion system conn like *net.TCPConn
switch c.(type) {
case syscall.Conn: // exclusion system conn like *net.TCPConn
break
case ipstackConn: // exclusion *mipstack.TCPConn
break
default:
c = N.NewDeadlineConn(c) // most conn from outbound can't handle readDeadline correctly
}
cc := &conn{N.NewExtendedConn(c), nil, nil, a.Addr()}
@@ -341,7 +353,12 @@ func (c *packetConn) AddRef(ref any) {
func NewPacketConn(pc net.PacketConn, a ProxyAdapter) C.PacketConn {
epc := N.NewEnhancePacketConn(pc)
if _, ok := pc.(syscall.Conn); !ok { // exclusion system conn like *net.UDPConn
switch pc.(type) {
case syscall.Conn: // exclusion system conn like *net.UDPConn
break
case ipstackConn: // exclusion *mipstack.UDPConn
break
default:
epc = N.NewDeadlineEnhancePacketConn(epc) // most conn from outbound can't handle readDeadline correctly
}
cpc := &packetConn{epc, nil, nil, a.Name(), utils.NewUUIDV4().String(), a.Addr(), a.ResolveUDP}
+155 -22
View File
@@ -12,6 +12,7 @@ import (
"path/filepath"
"strings"
"sync"
"time"
"github.com/metacubex/mihomo/component/easytier"
"github.com/metacubex/mihomo/component/resolver"
@@ -27,6 +28,8 @@ const (
easyTierDefaultStateDir = "easytier"
easyTierInstanceIDFile = "instance_id"
easyTierDNSTTL = 60
easyTierMinBackoff = time.Second
easyTierMaxBackoff = 30 * time.Second
)
var errEasyTierClosed = errors.New("easytier outbound closed")
@@ -40,8 +43,10 @@ type EasyTier struct {
zone string
ctx context.Context
cancel context.CancelFunc
startOnce sync.Once
startErr error
loopOnce sync.Once
startMu sync.Mutex
closed bool
readyCh chan struct{}
mu sync.Mutex
host *corehost.Host
instance *corehost.Instance
@@ -164,26 +169,115 @@ func NewEasyTier(option EasyTierOption) (*EasyTier, error) {
return outbound, nil
}
func (e *EasyTier) start() error {
e.startOnce.Do(func() {
if err := e.init(); err != nil {
e.startErr = err
_ = e.shutdown()
}
func (e *EasyTier) ensureStarted(ctx context.Context) error {
e.loopOnce.Do(func() {
go e.loop()
})
return e.startErr
for {
if err := e.ctx.Err(); err != nil {
return errEasyTierClosed
}
e.startMu.Lock()
closed := e.closed
readyCh := e.readyCh
e.startMu.Unlock()
if closed {
return errEasyTierClosed
}
e.mu.Lock()
instance := e.instance
e.mu.Unlock()
if instance != nil && instance.State() == corehost.StateRunning {
return nil
}
if readyCh == nil {
e.startMu.Lock()
if e.readyCh == nil {
e.readyCh = make(chan struct{})
}
readyCh = e.readyCh
e.startMu.Unlock()
}
select {
case <-ctx.Done():
return ctx.Err()
case <-e.ctx.Done():
return errEasyTierClosed
case <-readyCh:
}
}
}
func (e *EasyTier) ensureStarted(ctx context.Context) error {
done := make(chan error, 1)
go func() {
done <- e.start()
}()
select {
case err := <-done:
return err
case <-ctx.Done():
return ctx.Err()
func (e *EasyTier) signalReady() {
e.startMu.Lock()
if e.readyCh != nil {
close(e.readyCh)
e.readyCh = nil
}
e.startMu.Unlock()
}
func (e *EasyTier) loop() {
backoff := easyTierMinBackoff
for {
if e.ctx.Err() != nil {
return
}
e.startMu.Lock()
closed := e.closed
e.startMu.Unlock()
if closed {
return
}
err := e.init()
if err != nil {
log.Warnln("[EasyTier](%s) start failed: %v; retry in %s", e.Name(), err, backoff)
_ = e.shutdown()
timer := time.NewTimer(backoff)
select {
case <-e.ctx.Done():
timer.Stop()
return
case <-timer.C:
}
if backoff < easyTierMaxBackoff {
backoff *= 2
if backoff > easyTierMaxBackoff {
backoff = easyTierMaxBackoff
}
}
continue
}
backoff = easyTierMinBackoff
e.signalReady()
reason := e.serve()
_ = e.shutdown()
if e.ctx.Err() != nil {
return
}
e.startMu.Lock()
closed = e.closed
e.startMu.Unlock()
if closed {
return
}
if reason == "" {
reason = "instance stopped"
}
log.Warnln("[EasyTier](%s) %s; restarting in %s", e.Name(), reason, backoff)
timer := time.NewTimer(backoff)
select {
case <-e.ctx.Done():
timer.Stop()
return
case <-timer.C:
}
if backoff < easyTierMaxBackoff {
backoff *= 2
if backoff > easyTierMaxBackoff {
backoff = easyTierMaxBackoff
}
}
}
}
@@ -233,6 +327,41 @@ func (e *EasyTier) currentInstance() (*corehost.Instance, error) {
return e.instance, nil
}
func (e *EasyTier) serve() string {
e.mu.Lock()
instance := e.instance
e.mu.Unlock()
if instance == nil {
return "instance is not ready"
}
// Manual connectors retry inside core (reconnect_interval, default 1s).
// Events() is best-effort: a full host queue drops the event and does not
// stall the guest. Drain it for logs; recreate only when the stream closes.
events := instance.Events()
if events == nil {
if err := instance.Wait(e.ctx); err != nil && e.ctx.Err() == nil {
return err.Error()
}
return "instance stopped"
}
for {
select {
case <-e.ctx.Done():
return ""
case event, ok := <-events:
if !ok {
return "instance stopped"
}
switch event.Kind {
case "peer_added", "peer_removed":
log.Infoln("[EasyTier](%s) %s: %s", e.Name(), event.Kind, event.Message)
default:
log.Debugln("[EasyTier](%s) %s: %s", e.Name(), event.Kind, event.Message)
}
}
}
}
func (e *EasyTier) overlayNodes(ctx context.Context) ([]easytier.Node, error) {
instance, err := e.currentInstance()
if err != nil {
@@ -378,9 +507,13 @@ func (e *EasyTier) Close() error {
if e.unregister != nil {
e.unregister()
}
e.startOnce.Do(func() {
e.startErr = errEasyTierClosed
})
e.startMu.Lock()
e.closed = true
if e.readyCh != nil {
close(e.readyCh)
e.readyCh = nil
}
e.startMu.Unlock()
return e.shutdown()
}
+64 -41
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
@@ -193,11 +196,7 @@ type ipStack interface {
func newIPStack(option IPStackOption, localAddresses []netip.Prefix, mtu uint32) (ipStack, error) {
mode := option.Mode
if mode == ipStackAuto {
if features.WithGVisor {
mode = ipStackGVisor
} else {
mode = ipStackMips
}
mode = ipStackMips
}
switch mode {
case ipStackGVisor:
@@ -384,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")
@@ -454,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 {
@@ -468,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
@@ -544,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
}
@@ -566,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
}
@@ -785,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
}
+53 -6
View File
@@ -21,6 +21,7 @@ import (
type LoadBalanceOption struct {
Strategy string `group:"strategy,omitempty"`
HashKey string `group:"hash-key,omitempty"`
}
type LoadBalance struct {
@@ -34,6 +35,10 @@ type LoadBalance struct {
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy
var errStrategy = errors.New("unsupported strategy")
var errHashKey = errors.New("unsupported hash-key")
// keyFn derives the value a hashing strategy pins a request on.
type keyFn = func(metadata *C.Metadata) string
func getKey(metadata *C.Metadata) string {
if metadata == nil {
@@ -68,6 +73,39 @@ func getKeyWithSrcAndDst(metadata *C.Metadata) string {
return fmt.Sprintf("%s%s", src, dst)
}
// getKeyWithInUser pins on the authenticated inbound user instead of on an
// address. Both address-derived keys assume one client's traffic to one
// destination is one unit of work, which is false for a client whose single
// unit of work walks several destinations: the hash moves with the host, and
// the egress IP changes underneath a session the destination is tracking.
// The inbound user is the only identity the client itself controls, and
// `IN-USER` rules already match on it -- hence the option value `in-user`,
// which names the same thing those rules do. An unauthenticated request keeps
// the strategy's own key rather than collapsing every such request onto one
// node.
func getKeyWithInUser(fallback keyFn) keyFn {
return func(metadata *C.Metadata) string {
if metadata != nil && metadata.InUser != "" {
return metadata.InUser
}
return fallback(metadata)
}
}
// hashKey resolves the `hash-key` option into a decorator over whichever key
// the chosen strategy derives by default.
func hashKey(name string) (func(keyFn) keyFn, error) {
switch name {
case "":
return func(fn keyFn) keyFn { return fn }, nil
case "in-user":
return getKeyWithInUser, nil
}
return nil, fmt.Errorf("%w: %s", errHashKey, name)
}
func jumpHash(key uint64, buckets int32) int32 {
var b, j int64
@@ -155,10 +193,10 @@ func strategyRoundRobin(url string) strategyFn {
}
}
func strategyConsistentHashing(url string) strategyFn {
func strategyConsistentHashing(url string, keyOf keyFn) strategyFn {
maxRetry := 5
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
key := utils.MapHash(getKey(metadata))
key := utils.MapHash(keyOf(metadata))
buckets := int32(len(proxies))
for i := 0; i < maxRetry; i, key = i+1, key+1 {
idx := jumpHash(key, buckets)
@@ -179,14 +217,14 @@ func strategyConsistentHashing(url string) strategyFn {
}
}
func strategyStickySessions(url string) strategyFn {
func strategyStickySessions(url string, keyOf keyFn) strategyFn {
ttl := time.Minute * 10
maxRetry := 5
lruCache := lru.New[uint64, int](
lru.WithAge[uint64, int](int64(ttl.Seconds())),
lru.WithSize[uint64, int](1000))
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
key := utils.MapHash(getKeyWithSrcAndDst(metadata))
key := utils.MapHash(keyOf(metadata))
length := len(proxies)
idx, has := lruCache.Get(key)
if !has || idx >= length {
@@ -249,13 +287,22 @@ func (lb *LoadBalance) Now() string {
func NewLoadBalance(option GroupCommonOption, loadBalanceOption LoadBalanceOption, emptyFallback C.Proxy, providers []P.ProxyProvider) (lb *LoadBalance, err error) {
var strategyFn strategyFn
withKey, err := hashKey(loadBalanceOption.HashKey)
if err != nil {
return nil, err
}
switch loadBalanceOption.Strategy {
case "", "consistent-hashing":
strategyFn = strategyConsistentHashing(option.URL)
strategyFn = strategyConsistentHashing(option.URL, withKey(getKey))
case "round-robin":
// Rejected rather than ignored: round-robin hashes nothing, so a
// hash-key here means the config expects stickiness it will not get.
if loadBalanceOption.HashKey != "" {
return nil, fmt.Errorf("%w: round-robin does not hash", errHashKey)
}
strategyFn = strategyRoundRobin(option.URL)
case "sticky-sessions":
strategyFn = strategyStickySessions(option.URL)
strategyFn = strategyStickySessions(option.URL, withKey(getKeyWithSrcAndDst))
default:
return nil, fmt.Errorf("%w: %s", errStrategy, loadBalanceOption.Strategy)
}
+143
View File
@@ -0,0 +1,143 @@
package outboundgroup
import (
"net/netip"
"testing"
"github.com/metacubex/mihomo/adapter"
"github.com/metacubex/mihomo/adapter/outbound"
C "github.com/metacubex/mihomo/constant"
"github.com/stretchr/testify/require"
)
const testUrl = "https://www.gstatic.com/generate_204"
func balancedProxies(count int) []C.Proxy {
proxies := make([]C.Proxy, 0, count)
for i := 0; i < count; i++ {
proxies = append(proxies, adapter.NewProxy(outbound.NewDirect()))
}
return proxies
}
// The proxies are indistinguishable by name, so identity is the pointer.
func indexOf(t *testing.T, proxies []C.Proxy, selected C.Proxy) int {
t.Helper()
for i, proxy := range proxies {
if proxy == selected {
return i
}
}
require.Fail(t, "selected proxy is not a member of the group")
return -1
}
func request(user, host string) *C.Metadata {
return &C.Metadata{
NetWork: C.TCP,
Host: host,
DstPort: 443,
SrcIP: netip.MustParseAddr("127.0.0.1"),
InUser: user,
}
}
// One unit of work walking several destinations is the case both address-derived
// keys get wrong: the group is meant to hold that work on one egress, and the
// default key changes as soon as the host changes.
func TestLoadBalanceHashKeyInUserSurvivesADestinationChange(t *testing.T) {
proxies := balancedProxies(8)
hosts := []string{"a.example.com", "b.example.org", "c.example.net", "d.example.io"}
byUser := strategyConsistentHashing(testUrl, getKeyWithInUser(getKey))
pinned := indexOf(t, proxies, byUser(proxies, request("job-1", hosts[0]), false))
for _, host := range hosts {
selected := byUser(proxies, request("job-1", host), false)
require.Equal(t, pinned, indexOf(t, proxies, selected),
"hash-key: user must ignore the destination")
}
// Distinct destination keys are the deterministic contract of the fallback
// key. Distinct keys may still legally land in the same consistent-hash
// bucket, so asserting on selected proxy indexes would make this test flaky.
seenKeys := map[string]struct{}{}
for _, host := range hosts {
seenKeys[getKey(request("job-1", host))] = struct{}{}
}
require.Len(t, seenKeys, len(hosts),
"the default key must change with the destination")
}
// Pinning must preserve distinct inbound identities. Consistent hashing may
// legally put several distinct keys in one bucket, so this test checks the
// identity key before hashing instead of asserting a random bucket spread.
func TestLoadBalanceHashKeyInUserKeepsUsersDistinct(t *testing.T) {
keyed := getKeyWithInUser(getKey)
users := []string{"job-1", "job-2", "job-3", "job-4", "job-5", "job-6"}
seenKeys := map[string]struct{}{}
for _, user := range users {
seenKeys[keyed(request(user, "a.example.com"))] = struct{}{}
}
require.Len(t, seenKeys, len(users))
}
// Sticky sessions keys on source and destination; a client behind one source
// address cannot separate its own concurrent jobs without a supplied identity.
func TestLoadBalanceHashKeyInUserSeparatesJobsSharingASourceAddress(t *testing.T) {
proxies := balancedProxies(8)
strategy := strategyStickySessions(testUrl, getKeyWithInUser(getKeyWithSrcAndDst))
first := indexOf(t, proxies, strategy(proxies, request("job-1", "a.example.com"), false))
require.Equal(t, first,
indexOf(t, proxies, strategy(proxies, request("job-1", "b.example.org"), false)))
shared := strategyStickySessions(testUrl, getKeyWithSrcAndDst)
require.Equal(t,
indexOf(t, proxies, shared(proxies, request("job-1", "a.example.com"), false)),
indexOf(t, proxies, shared(proxies, request("job-2", "a.example.com"), false)),
"without a supplied key the two jobs are one session")
}
// An unauthenticated request keeps the strategy's own key. Returning a constant
// instead would herd every anonymous request onto one member.
func TestLoadBalanceHashKeyInUserFallsBackWhenUnauthenticated(t *testing.T) {
keyed := getKeyWithInUser(getKey)
require.Equal(t, "example.com", keyed(request("", "a.example.com")))
require.Equal(t, "job-1", keyed(request("job-1", "a.example.com")))
require.Equal(t, getKey(nil), keyed(nil))
}
// The option name is the contract with the config file, and nothing else here
// exercises it: every other test reaches the decorator directly, so renaming
// the case would leave them all green while `hash-key: in-user` stopped working.
func TestLoadBalanceHashKeyResolvesTheOptionName(t *testing.T) {
withInUser, err := hashKey("in-user")
require.NoError(t, err)
require.Equal(t, "job-1", withInUser(getKey)(request("job-1", "a.example.com")))
identity, err := hashKey("")
require.NoError(t, err)
require.Equal(t, getKey(request("job-1", "a.example.com")),
identity(getKey)(request("job-1", "a.example.com")))
}
func TestLoadBalanceHashKeyRejectsUnusableConfigs(t *testing.T) {
_, err := hashKey("session")
require.ErrorIs(t, err, errHashKey)
// `user` was the name this option carried before review. Rejecting it keeps
// the rename honest: without this the case above could still read `user`
// and every test here would stay green.
_, err = hashKey("user")
require.ErrorIs(t, err, errHashKey)
_, err = NewLoadBalance(GroupCommonOption{Name: "lb"},
LoadBalanceOption{Strategy: "round-robin", HashKey: "in-user"}, nil, nil)
require.ErrorIs(t, err, errHashKey)
_, err = NewLoadBalance(GroupCommonOption{Name: "lb"},
LoadBalanceOption{Strategy: "consistent-hashing", HashKey: "nonsense"}, nil, nil)
require.ErrorIs(t, err, errHashKey)
}
+4
View File
@@ -196,6 +196,10 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
return reuse
}
if headers, ok := extra["headers"].(map[string]any); ok && len(headers) > 0 {
opts["headers"] = headers
}
if v, ok := extra["noGRPCHeader"].(bool); ok && v {
opts["no-grpc-header"] = true
}
+3
View File
@@ -25,6 +25,9 @@ func NewEnhancePacketConn(pc net.PacketConn) EnhancePacketConn {
if singPC, isSingPC := pc.(SingPacketConn); isSingPC {
return newEnhanceSingPacketConn(singPC)
}
if withBufferPC, isWithBufferPC := pc.(withBufferPacketConn); isWithBufferPC {
return &enhanceWithBufferPacketConn{withBufferPacketConn: withBufferPC}
}
return &enhancePacketConn{PacketConn: pc}
}
+48
View File
@@ -0,0 +1,48 @@
package packet
import (
"net"
"github.com/metacubex/mihomo/common/pool"
)
type withBufferPacketConn interface {
net.PacketConn
ReadFromWithBuffer(func(sizeHint int) []byte) (int, net.Addr, error)
}
type enhanceWithBufferPacketConn struct {
withBufferPacketConn
}
func (c *enhanceWithBufferPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
var readBuf []byte
getBuffer := func(sizeHint int) []byte {
readBuf = pool.Get(sizeHint)
put = func() {
_ = pool.Put(readBuf)
}
return readBuf
}
var readN int
readN, addr, err = c.ReadFromWithBuffer(getBuffer)
if readN > 0 && readBuf != nil {
data = readBuf[:readN]
} else if put != nil {
put()
put = nil
}
return
}
func (c *enhanceWithBufferPacketConn) Upstream() any {
return c.withBufferPacketConn
}
func (c *enhanceWithBufferPacketConn) WriterReplaceable() bool {
return true
}
func (c *enhanceWithBufferPacketConn) ReaderReplaceable() bool {
return true
}
+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{
+5 -1
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"`
@@ -314,6 +315,7 @@ type RawTun struct {
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
ICMPTimeout int64 `yaml:"icmp-timeout" json:"icmp-timeout,omitempty"`
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
@@ -543,7 +545,7 @@ func DefaultRawConfig() *RawConfig {
Tun: RawTun{
Enable: false,
Device: "",
Stack: C.TunGvisor,
Stack: C.TunMips,
DNSHijack: []string{"0.0.0.0:53"}, // default hijack all dns query
AutoRoute: true,
AutoDetectInterface: true,
@@ -1693,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,
@@ -1733,6 +1736,7 @@ func parseTun(rawTun RawTun, dns *DNS, general *General) error {
UDPTimeout: rawTun.UDPTimeout,
ICMPTimeout: rawTun.ICMPTimeout,
DisableICMPForwarding: rawTun.DisableICMPForwarding,
CongestionController: rawTun.CongestionController,
FileDescriptor: rawTun.FileDescriptor,
Inet4RouteAddress: rawTun.Inet4RouteAddress,
+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" {
+25 -7
View File
@@ -133,7 +133,13 @@ profile: # 存储 select 选择记录
# Tun 配置
tun:
enable: false
stack: system # gvisor/mixed/mips
stack: mips # gvisor/mixed/system
# 系统 DNS 配置方式
# - disabled,不设置系统 DNS
# - native,将 tun 地址设为系统 DNS
# - hijack,在 native 基础上额外拦截发往其他网卡的 53 端口流量(Windows 需 strict-route,Linux 需 auto-redirect)
# - 置空,和旧行为一致,Windows 和 Linux 在启用 auto-route 默认 hijack,否则 disabled;macOS 默认 disabled
# dns-mode: hijack
dns-hijack:
- 0.0.0.0:53 # 需要劫持的 DNS
# auto-detect-interface: true # 自动识别出口网卡
@@ -144,6 +150,7 @@ tun:
auto-redirect: false # 自动配置 iptables 以重定向 TCP 连接。仅支持 Linux。带有 auto-redirect 的 auto-route 现在可以在路由器上按预期工作,无需干预。
# strict-route: true # 将所有连接路由到 tun 来防止泄漏,但你的设备将无法其他设备被访问
# disable-icmp-forwarding: true # 禁用 ICMP 转发,防止某些情况下的 ICMP 环回问题,ping 将不会显示真实的延迟
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; only effective on mips
route-address-set: # 将指定规则集中的目标 IP CIDR 规则添加到防火墙, 不匹配的流量将绕过路由, 仅支持 Linux,且需要 nftables,`auto-route` 和 `auto-redirect` 已启用。
- ruleset-1
- ruleset-2
@@ -1294,7 +1301,7 @@ proxies: # socks5
# reserved: [209,98,59]
# persistent-keepalive: 0
# ip-stack:
# mode: auto # options: auto, gvisor, mips; auto uses gVisor when compiled in and mihomo IP stack (MIPS) otherwise
# mode: auto # options: auto, mips, gvisor; auto uses mihomo IP stack (MIPS), gvisor needs compiled with -tags with_gvisor
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; ignored by gVisor
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
# dialer-proxy: "ss1"
@@ -1373,7 +1380,7 @@ proxies: # socks5
# mtu: 1400 # optional local MTU override; cannot exceed the controller MTU
# physical-mtu: 1432 # optional ZeroTier UDP payload MTU (510-10324; default 1432)
# ip-stack:
# mode: auto # options: auto, gvisor, mips; auto uses gVisor when compiled in and mihomo IP stack (MIPS) otherwise
# mode: auto # options: auto, mips, gvisor; auto uses mihomo IP stack (MIPS), gvisor needs compiled with -tags with_gvisor
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; ignored by gVisor
# primary-port: 0 # primary UDP port; 0 selects an available port
# secondary-port: 0 # second UDP port; 0 selects an available port, -1 disables it
@@ -1494,7 +1501,7 @@ proxies: # socks5
# mtu: 1500
udp: true
# ip-stack:
# mode: auto # options: auto, gvisor, mips; auto uses gVisor when compiled in and mihomo IP stack (MIPS) otherwise
# mode: auto # options: auto, mips, gvisor; auto uses mihomo IP stack (MIPS), gvisor needs compiled with -tags with_gvisor
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; ignored by gVisor
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
# dialer-proxy: "ss1"
@@ -1513,7 +1520,7 @@ proxies: # socks5
mtu: 1280
udp: true
# ip-stack:
# mode: auto # options: auto, gvisor, mips; auto uses gVisor when compiled in and mihomo IP stack (MIPS) otherwise
# mode: auto # options: auto, mips, gvisor; auto uses mihomo IP stack (MIPS), gvisor needs compiled with -tags with_gvisor
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; ignored by gVisor
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
# dialer-proxy: "ss1"
@@ -1551,7 +1558,7 @@ proxies: # socks5
udp: true
network: h2
# ip-stack:
# mode: auto # options: auto, gvisor, mips; auto uses gVisor when compiled in and mihomo IP stack (MIPS) otherwise
# mode: auto # options: auto, mips, gvisor; auto uses mihomo IP stack (MIPS), gvisor needs compiled with -tags with_gvisor
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; ignored by gVisor
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
# dialer-proxy: "ss1"
@@ -1790,6 +1797,15 @@ proxy-groups:
url: "https://cp.cloudflare.com/generate_204"
interval: 300
# strategy: consistent-hashing # 可选 round-robin 和 sticky-sessions
# hash-key: in-user # 可选,仅 consistent-hashing 和 sticky-sessions 支持;
# # round-robin 不做哈希,配置它会报错而不是被忽略。
# # 只改变「拿什么值去哈希」,不改变策略拿到哈希值之后如何选节点;
# # 不填时行为与旧版完全一致。
# # in-user 用 inbound 的认证用户名作 key(与 IN-USER 规则读取的是
# # 同一个字段),它不随目标地址变化,因此一件跨多个域名的任务不会
# # 中途换节点、换出口 IP。未认证的请求回退到该策略原本的 key。
# # 两种策略给出的一致性时长不同(前者永久、后者 10 分钟),
# # 取舍见 PR #3133。
# select 用户自行选择节点
- name: Proxy
@@ -2788,7 +2804,8 @@ listeners:
type: tun
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
stack: system # gvisor / mixed / mips
stack: mips # gvisor / mixed / system
# dns-mode: hijack # disabled / native / hijack,为空时采用旧行为
dns-hijack:
- 0.0.0.0:53 # 需要劫持的 DNS
# auto-detect-interface: false # 自动识别出口网卡
@@ -2830,6 +2847,7 @@ listeners:
# exclude-package: # 排除被路由的 Android 应用包名
# - com.android.captiveportallogin
# disable-icmp-forwarding: true # 禁用 ICMP 转发,防止某些情况下的 ICMP 环回问题,ping 将不会显示真实的延迟
# congestion-controller: cubic # TCP congestion controller: cubic, reno, bbr, or bbr3; only effective on mips
# 入口配置与 Listener 等价,传入流量将和 socks,mixed 等入口一样按照 mode 所指定的方式进行匹配处理
# shadowsocks,vmess 入口配置(传入流量将和 socks,mixed 等入口一样按照 mode 所指定的方式进行匹配处理)
# ss-config: ss://2022-blake3-aes-256-gcm:vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg=@:23456
+12 -12
View File
@@ -7,7 +7,7 @@ require (
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.37.0
github.com/enfein/mieru/v3 v3.38.1
github.com/gobwas/ws v1.4.0
github.com/gofrs/uuid/v5 v5.4.0
github.com/golang/snappy v1.0.0
@@ -19,35 +19,35 @@ require (
github.com/metacubex/chacha v0.1.5
github.com/metacubex/chi v0.1.1
github.com/metacubex/connect-ip-go v0.0.0-20260727083417-67ccdb0cf771
github.com/metacubex/cpu v0.1.1
github.com/metacubex/cpu v0.1.2
github.com/metacubex/edwards25519 v1.2.0
github.com/metacubex/fswatch v0.1.1
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759
github.com/metacubex/http v0.1.7
github.com/metacubex/http v0.1.8
github.com/metacubex/jls-quic-go v0.0.0-20260727080412-732f2fc9a34d
github.com/metacubex/jls-tls v0.0.0-20260723084315-67adc0e2f796
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604
github.com/metacubex/mhurl v0.1.0
github.com/metacubex/mipstack v0.0.0-20260910230046-ba762df4c91d
github.com/metacubex/mipstack v0.0.0-20261019124225-9a80a07eaeb9
github.com/metacubex/mlkem v0.1.0
github.com/metacubex/quic-go v0.61.1-0.20260727080200-2548683b76f4
github.com/metacubex/randv2 v0.2.0
github.com/metacubex/restls-client-go v0.1.9
github.com/metacubex/sevenzip v1.6.4
github.com/metacubex/sing v0.5.7
github.com/metacubex/sing-mux v0.3.10
github.com/metacubex/sing v0.5.8
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.24
github.com/metacubex/sing-tun v0.4.28
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.7
github.com/metacubex/tls v0.1.9
github.com/metacubex/utls v1.8.8
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
@@ -61,7 +61,7 @@ require (
gitlab.com/go-extension/aes-ccm v0.0.0-20230221065045-e58665ef23c7
go.uber.org/automaxprocs v1.6.0
go.yaml.in/yaml/v3 v3.0.5
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
go4.org/netipx v0.0.0-20260823151212-3075585bcbeb
)
// lastest version compatible with golang1.20
@@ -110,7 +110,7 @@ require (
github.com/klauspost/reedsolomon v1.12.3 // indirect
github.com/mdlayher/socket v0.5.1 // indirect
github.com/metacubex/ascon v0.1.0 // indirect
github.com/metacubex/gvisor v0.0.0-20260826100401-79317d808312 // indirect
github.com/metacubex/gvisor v0.0.0-20260922041103-e2cbcd6e7400 // indirect
github.com/metacubex/hkdf v0.1.0 // indirect
github.com/metacubex/hpke v0.1.0 // indirect
github.com/metacubex/jsonv2 v0.0.0-20260721082349-16b4998c8f89 // indirect
+24 -24
View File
@@ -29,8 +29,8 @@ 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.37.0 h1:DKBDeBmlbpNKiOXtKXqxJo/BF+KvJKnbChn6fryeyHg=
github.com/enfein/mieru/v3 v3.37.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
github.com/enfein/mieru/v3 v3.38.1 h1:UZ5zAJi0caSmaOniVy33pyY7ANxyf4PmPeLSuYZpDro=
github.com/enfein/mieru/v3 v3.38.1/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=
@@ -109,22 +109,22 @@ github.com/metacubex/chi v0.1.1 h1:GajmCIXSIPAZNxqTTYpkCrkY9suBz9wjIdgPcoQ5K1A=
github.com/metacubex/chi v0.1.1/go.mod h1:/CvDXe8jZD/ecU8Y7fmS5XKLRR44UDmC6/IBkRIb6Z4=
github.com/metacubex/connect-ip-go v0.0.0-20260727083417-67ccdb0cf771 h1:nLGBvwQ2vmsD+gU/XWBQH3xaYCM3vQCJIqPfw3mc/L0=
github.com/metacubex/connect-ip-go v0.0.0-20260727083417-67ccdb0cf771/go.mod h1:9FjDcopUc+tgUva3dauAVzrYPHd0rant+zkvyECzkMg=
github.com/metacubex/cpu v0.1.1 h1:rRV5HGmeuGzjiKI3hYbL0dCd0qGwM7VUtk4ICXD06mI=
github.com/metacubex/cpu v0.1.1/go.mod h1:09VEt4dSRLR+bOA8l4w4NDuzGZ8n5dkMv7e8axgEeTU=
github.com/metacubex/cpu v0.1.2 h1:xJHPWLkGilSWm6vEvzz8Loe+UusODRkVnuXz96TWAZo=
github.com/metacubex/cpu v0.1.2/go.mod h1:09VEt4dSRLR+bOA8l4w4NDuzGZ8n5dkMv7e8axgEeTU=
github.com/metacubex/edwards25519 v1.2.0 h1:pIQZLBsjQgg3Nl/c86YYFEUAbL5qQRnPq4LrgIw0KK4=
github.com/metacubex/edwards25519 v1.2.0/go.mod h1:NCQF3J/Ki7382FJuokwsywEIIEI/gro/3smyXgQJsx0=
github.com/metacubex/fswatch v0.1.1 h1:jqU7C/v+g0qc2RUFgmAOPoVvfl2BXXUXEumn6oQuxhU=
github.com/metacubex/fswatch v0.1.1/go.mod h1:czrTT7Zlbz7vWft8RQu9Qqh+JoX+Nnb+UabuyN1YsgI=
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759 h1:cjd4biTvOzK9ubNCCkQ+ldc4YSH/rILn53l/xGBFHHI=
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759/go.mod h1:UHOv2xu+RIgLwpXca7TLrXleEd4oR3sPatW6IF8wU88=
github.com/metacubex/gvisor v0.0.0-20260826100401-79317d808312 h1:GDSN5oSkugLGImDSM0W4UCovF5FLpTa6vL1g2f2+1do=
github.com/metacubex/gvisor v0.0.0-20260826100401-79317d808312/go.mod h1:mBJW3UXUusd8ZYO5M6mig0uScIey9iIubgdIiQAk2ug=
github.com/metacubex/gvisor v0.0.0-20260922041103-e2cbcd6e7400 h1:r9YO+xZUWi+xQROzdYkKL2twoliSJh34vOHMVAqsaL8=
github.com/metacubex/gvisor v0.0.0-20260922041103-e2cbcd6e7400/go.mod h1:mBJW3UXUusd8ZYO5M6mig0uScIey9iIubgdIiQAk2ug=
github.com/metacubex/hkdf v0.1.0 h1:fPA6VzXK8cU1foc/TOmGCDmSa7pZbxlnqhl3RNsthaA=
github.com/metacubex/hkdf v0.1.0/go.mod h1:3seEfds3smgTAXqUGn+tgEJH3uXdsUjOiduG/2EtvZ4=
github.com/metacubex/hpke v0.1.0 h1:gu2jUNhraehWi0P/z5HX2md3d7L1FhPQE6/Q0E9r9xQ=
github.com/metacubex/hpke v0.1.0/go.mod h1:vfDm6gfgrwlXUxKDkWbcE44hXtmc1uxLDm2BcR11b3U=
github.com/metacubex/http v0.1.7 h1:dEaQmijUaR/2QKqgjBUmPZCRuh1zBfDqB6ZRNLwvbHg=
github.com/metacubex/http v0.1.7/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
github.com/metacubex/http v0.1.8 h1:d91onDan2ZXYE8W/uAy5oFmXHH2xi1L7LbGPV5EmCM0=
github.com/metacubex/http v0.1.8/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
github.com/metacubex/jls-quic-go v0.0.0-20260727080412-732f2fc9a34d h1:OF3TUGKdHRrRMp7nb0Pa72QYwKPol9NqSy2yTcP2Sog=
github.com/metacubex/jls-quic-go v0.0.0-20260727080412-732f2fc9a34d/go.mod h1:dH8StPlpZ7atSUuTnfTnRXvJK22nOtQVimNwQ9Gmk58=
github.com/metacubex/jls-tls v0.0.0-20260723084315-67adc0e2f796 h1:1iI4np/Dm1ztCfTW2LoN166O6n728HXMc11aIazYdps=
@@ -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-20260910230046-ba762df4c91d h1:hc1OeKdo7YIcmTrzwlJLjNZ4EZDKRHi/Ntv7GdYs2YI=
github.com/metacubex/mipstack v0.0.0-20260910230046-ba762df4c91d/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,22 +153,22 @@ github.com/metacubex/restls-client-go v0.1.9 h1:QmLKwVFuAjB6rL9lQNKj8CuwHqGMJjV3
github.com/metacubex/restls-client-go v0.1.9/go.mod h1:BN/U52vPw7j8VTSh2vleD/MnmVKCov84mS5VcjVHH4g=
github.com/metacubex/sevenzip v1.6.4 h1:OIL+DeOeSAbKNsjqxcYUMiarRmX6Kaxakb0GT7E9Oik=
github.com/metacubex/sevenzip v1.6.4/go.mod h1:FP3X9bzFKj9wPxifGN9B3w2fIEicMjzKYIGIhnu+1pw=
github.com/metacubex/sing v0.5.7 h1:8OC+fhKFSv/l9ehEhJRaZZAOuthfZo68SteBVLe8QqM=
github.com/metacubex/sing v0.5.7/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w=
github.com/metacubex/sing-mux v0.3.10 h1:r5CuZ/KuwFsEcRRwpLvzLncW4fDzNfmSEcBEWcy/+94=
github.com/metacubex/sing-mux v0.3.10/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
github.com/metacubex/sing 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-mux v0.3.12 h1:80jrJsGgRW7ZHpJCRpwJhG3yzT5muEHIWjaOsDJZ2wE=
github.com/metacubex/sing-mux v0.3.12/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
github.com/metacubex/sing-quic v0.0.0-20260904234848-1c242664697a h1:qZzQwtWDrPU1LXoMow0/iLHY3mb7uauS/mho8hYcenE=
github.com/metacubex/sing-quic v0.0.0-20260904234848-1c242664697a/go.mod h1:6ayFGfzzBE85csgQkM3gf4neFq6s0losHlPRSxY+nuk=
github.com/metacubex/sing-shadowsocks v0.2.13 h1:PKmInHy9+4nY3FLhmKcWdASUBo9WZ/KrSPWjNpGaUTQ=
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.24 h1:2H/RhlwQxUgc1K8h46giwV5uTUovx+DhQGpVPlUB4Yo=
github.com/metacubex/sing-tun v0.4.24/go.mod h1:YLk0jq8ITecb0LlNKAXC+NTkYTYmvihQxFAR495LN8c=
github.com/metacubex/sing-tun v0.4.28 h1:IWcH13jEbsxzM5SZrRat3IeJG31WiF9fOj3r18yGHw4=
github.com/metacubex/sing-tun v0.4.28/go.mod h1:t2cK1AjogLda3/XxesmG0l7r1HzagLaUPBdNovhsb4Q=
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=
@@ -179,10 +179,10 @@ github.com/metacubex/tailscale-wireguard-go v0.0.0-20260725073821-e61ab99cede2 h
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260725073821-e61ab99cede2/go.mod h1:W00EeoPdd2jbV3+ZUa0m2b7FdKx5B1LFsXvEpy7cToQ=
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c h1:+2C1UshSLzaogLY/IDz1XhOLxjhs3rkhVHB4eCN9Zto=
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c/go.mod h1:l9oLnLoEXyGZ5RVLsh7QCC5XsouTUyKk4F2nLm2DHLw=
github.com/metacubex/tls v0.1.8 h1:BHF2payjtxC7wdR3tnq8vl3FAgEQB6/pPjP2tJNTsP4=
github.com/metacubex/tls v0.1.8/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
github.com/metacubex/utls v1.8.7 h1:Cp+yWkNTFkSihETgGWq34hlVFds5HpYWVOR1xovUVTs=
github.com/metacubex/utls v1.8.7/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
github.com/metacubex/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.8.8 h1:7fiMYahL+tT1I/vG1MWidv88r/3A5NnPrurjzApZGyQ=
github.com/metacubex/utls v1.8.8/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=
@@ -284,8 +284,8 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
go4.org/mem v0.0.0-20240501181205-ae6ca9944745 h1:Tl++JLUCe4sxGu8cTpDzRLd3tN7US4hOxG5YpKCzkek=
go4.org/mem v0.0.0-20240501181205-ae6ca9944745/go.mod h1:reUoABIJ9ikfM5sgtSF3Wushcza7+WeD01VB9Lirh3g=
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M=
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
go4.org/netipx v0.0.0-20260823151212-3075585bcbeb h1:XBM4hvfwGAttkkiTIFfeigdfcL1xIfdKXqFdgiHGtDs=
go4.org/netipx v0.0.0-20260823151212-3075585bcbeb/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
+8
View File
@@ -63,6 +63,7 @@ type tunSchema struct {
Enable bool `yaml:"enable" json:"enable"`
Device *string `yaml:"device" json:"device"`
Stack *C.TUNStack `yaml:"stack" json:"stack"`
DNSMode *string `yaml:"dns-mode" json:"dns-mode,omitempty"`
DNSHijack *[]string `yaml:"dns-hijack" json:"dns-hijack"`
AutoRoute *bool `yaml:"auto-route" json:"auto-route"`
AutoDetectInterface *bool `yaml:"auto-detect-interface" json:"auto-detect-interface"`
@@ -98,6 +99,7 @@ type tunSchema struct {
EndpointIndependentNat *bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
UDPTimeout *int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
ICMPTimeout *int64 `yaml:"icmp-timeout" json:"icmp-timeout,omitempty"`
CongestionController *string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
FileDescriptor *int `yaml:"file-descriptor" json:"file-descriptor"`
Inet4RouteAddress *[]netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
@@ -150,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
}
@@ -264,6 +269,9 @@ func pointerOrDefaultTun(p *tunSchema, def LC.Tun) LC.Tun {
if p.ICMPTimeout != nil {
def.ICMPTimeout = *p.ICMPTimeout
}
if p.CongestionController != nil {
def.CongestionController = *p.CongestionController
}
if p.FileDescriptor != nil {
def.FileDescriptor = *p.FileDescriptor
}
+8
View File
@@ -13,6 +13,7 @@ type Tun struct {
Enable bool `yaml:"enable" json:"enable"`
Device string `yaml:"device" json:"device"`
Stack C.TUNStack `yaml:"stack" json:"stack"`
DNSMode string `yaml:"dns-mode" json:"dns-mode"`
DNSHijack []string `yaml:"dns-hijack" json:"dns-hijack"`
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
AutoDetectInterface bool `yaml:"auto-detect-interface" json:"auto-detect-interface"`
@@ -53,6 +54,7 @@ type Tun struct {
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
ICMPTimeout int64 `yaml:"icmp-timeout" json:"icmp-timeout,omitempty"`
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
@@ -105,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
}
@@ -211,6 +216,9 @@ func (t *Tun) Equal(other Tun) bool {
if t.DisableICMPForwarding != other.DisableICMPForwarding {
return false
}
if t.CongestionController != other.CongestionController {
return false
}
if t.FileDescriptor != other.FileDescriptor {
return false
}
+4
View File
@@ -14,6 +14,7 @@ type TunOption struct {
BaseOption
Device string `inbound:"device,omitempty"`
Stack C.TUNStack `inbound:"stack,omitempty"`
DNSMode string `inbound:"dns-mode,omitempty"`
DNSHijack []string `inbound:"dns-hijack,omitempty"`
AutoRoute bool `inbound:"auto-route,omitempty"`
AutoDetectInterface bool `inbound:"auto-detect-interface,omitempty"`
@@ -54,6 +55,7 @@ type TunOption struct {
UDPTimeout int64 `inbound:"udp-timeout,omitempty"`
ICMPTimeout int64 `inbound:"icmp-timeout,omitempty"`
DisableICMPForwarding bool `inbound:"disable-icmp-forwarding,omitempty"`
CongestionController string `inbound:"congestion-controller,omitempty"`
FileDescriptor int `inbound:"file-descriptor,omitempty"`
Inet4RouteAddress []netip.Prefix `inbound:"inet4-route-address,omitempty"`
@@ -96,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,
@@ -135,6 +138,7 @@ func NewTun(options *TunOption) (*Tun, error) {
UDPTimeout: options.UDPTimeout,
ICMPTimeout: options.ICMPTimeout,
DisableICMPForwarding: options.DisableICMPForwarding,
CongestionController: options.CongestionController,
FileDescriptor: options.FileDescriptor,
Inet4RouteAddress: options.Inet4RouteAddress,
+3 -2
View File
@@ -29,7 +29,7 @@ func Handle(conn net.Conn, tunnel C.Tunnel, request *mierumodel.Request, additio
conn.Close()
return
}
user := conn.(mierucommon.UserContext).UserName()
// Handle the connection with tunnel.
switch request.Command {
case mieruconstant.Socks5ConnectCmd: // TCP
@@ -46,13 +46,14 @@ func Handle(conn net.Conn, tunnel C.Tunnel, request *mierumodel.Request, additio
}
inbound.ApplyAdditions(
metadata,
inbound.WithInName(conn.(mierucommon.UserContext).UserName()),
inbound.WithInUser(user),
inbound.WithSrcAddr(conn.RemoteAddr()),
inbound.WithInAddr(conn.LocalAddr()),
)
inbound.ApplyAdditions(metadata, additions...)
tunnel.HandleTCPConn(conn, metadata)
case mieruconstant.Socks5UDPAssociateCmd: // UDP
additions = append(additions, inbound.WithInUser(user))
pc := mierucommon.NewPacketOverStreamTunnel(conn)
ep := N.NewEnhancePacketConn(pc)
defer ep.Close()
+1 -1
View File
@@ -64,7 +64,7 @@ func ParseListener(mapping map[string]any) (C.InboundListener, error) {
listener, err = IN.NewTunnel(tunnelOption)
case "tun":
tunOption := &IN.TunOption{
Stack: C.TunGvisor,
Stack: C.TunMips,
DNSHijack: []string{"0.0.0.0:53"}, // default hijack all dns query
}
err = decoder.Decode(mapping, tunOption)
+1
View File
@@ -140,6 +140,7 @@ func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel,
}
func (l *Listener) Close() error {
l.closed = true
var retErr error
for _, lis := range l.listeners {
err := lis.Close()
+10 -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,
@@ -497,6 +504,7 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
Logger: log.SingLogger,
ForwarderBindInterface: forwarderBindInterface,
InterfaceFinder: interfaceFinder,
TCPCongestionControl: options.CongestionController,
EnforceBindInterface: EnforceBindInterface,
}
l.tunIf = tunIf
@@ -542,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
}
+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
}
+2 -1
View File
@@ -174,9 +174,10 @@ func (c *Client) idleCleanup() {
func (c *Client) idleCleanupExpTime(expTime time.Time) {
activeCount := 0
sessionToClose := make([]*Session, 0, c.idleSession.Len())
c.idleSessionLock.Lock()
sessionToClose := make([]*Session, 0, c.idleSession.Len())
it := c.idleSession.Iterate()
for it.IsNotEnd() {
session := it.Value()
+19 -6
View File
@@ -220,9 +220,7 @@ func (d *DataChannel) encryptAEAD(packet []byte, packetID uint32) ([]byte, error
var packetIDBytes [4]byte
binary.BigEndian.PutUint32(packetIDBytes[:], packetID)
nonce := d.nonce(packetID, d.sendImplicitIV)
ad := make([]byte, 0, len(header)+len(packetIDBytes))
ad = append(ad, header...)
ad = append(ad, packetIDBytes[:]...)
ad := aeadAdditionalData(header, packetIDBytes[:])
sealed := d.sendAEAD.Seal(nil, nonce[:], packet, ad)
out := make([]byte, 0, len(header)+4+DataChannelTagSize+len(packet))
@@ -288,9 +286,7 @@ func (d *DataChannel) decryptAEAD(packet []byte, headerSize int) ([]byte, error)
combined := make([]byte, 0, len(ciphertext)+DataChannelTagSize)
combined = append(combined, ciphertext...)
combined = append(combined, tag...)
ad := make([]byte, 0, len(header)+len(packetIDBytes))
ad = append(ad, header...)
ad = append(ad, packetIDBytes...)
ad := aeadAdditionalData(header, packetIDBytes)
nonce := d.nonce(packetID, d.recvImplicitIV)
plain, err := d.recvAEAD.Open(nil, nonce[:], combined, ad)
@@ -426,6 +422,23 @@ func (d *DataChannel) acceptPacketID(packetID uint32) error {
return nil
}
// aeadAdditionalData returns the AEAD additional data of a data channel packet.
//
// OpenVPN only authenticates the opcode/peer-id header for P_DATA_V2. For
// P_DATA_V1 the additional data is the packet ID alone: in OpenVPN's
// handle_data_channel_packet (ssl.c) ad_start is set after the opcode byte has
// been skipped for P_DATA_V1, but before it for P_DATA_V2. Servers that only
// speak P_DATA_V1 (e.g. SoftEther) reject packets that include the opcode.
func aeadAdditionalData(header, packetID []byte) []byte {
ad := make([]byte, 0, len(header)+len(packetID))
if len(header) > 0 {
if opcode, _ := parseOpcodeKeyID(header[0]); opcode == PDataV2 {
ad = append(ad, header...)
}
}
return append(ad, packetID...)
}
func dataHeader(peerID uint32, keyID uint8) []byte {
if peerID != PeerIDUnset {
return []byte{
+185
View File
@@ -0,0 +1,185 @@
package openvpn
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"testing"
)
// These tests pin the P_DATA_V1 / P_DATA_V2 AEAD wire format against the
// OpenVPN protocol definition rather than against mihomo itself, so that a
// consistently-wrong implementation on both ends cannot pass.
//
// OpenVPN 2.x (src/openvpn/ssl.c, handle_data_channel_packet): for P_DATA_V2
// ad_start is taken *before* skipping the opcode byte, so the additional data
// is opcode|peer-id|packet-id; for P_DATA_V1 it is taken *after* skipping the
// opcode, so the additional data is the 4-byte packet-id only. SoftEther's
// OpenVPN server (Interop_OpenVPN.c) does the same for V1.
func v1TestKeys() (client, server *KeyMaterial) {
client = &KeyMaterial{
SendCipherKey: bytes.Repeat([]byte{0x11}, 32),
SendHMACKey: bytes.Repeat([]byte{0x22}, maxHMACKeyLength),
RecvCipherKey: bytes.Repeat([]byte{0x33}, 32),
RecvHMACKey: bytes.Repeat([]byte{0x44}, maxHMACKeyLength),
}
server = &KeyMaterial{
SendCipherKey: client.RecvCipherKey,
SendHMACKey: client.RecvHMACKey,
RecvCipherKey: client.SendCipherKey,
RecvHMACKey: client.SendHMACKey,
}
return
}
// refAEAD is an independent reference implementation of the OpenVPN AEAD
// data channel: nonce = packet-id || implicit IV (first 8 bytes of the HMAC key),
// wire = header || packet-id || tag || ciphertext.
func refAEAD(t *testing.T, cipherKey, hmacKey []byte) (cipher.AEAD, func(uint32) []byte) {
t.Helper()
block, err := aes.NewCipher(cipherKey)
if err != nil {
t.Fatal(err)
}
aead, err := cipher.NewGCM(block)
if err != nil {
t.Fatal(err)
}
nonce := func(pid uint32) []byte {
n := make([]byte, 12)
binary.BigEndian.PutUint32(n[:4], pid)
copy(n[4:], hmacKey[:8])
return n
}
return aead, nonce
}
func refSeal(t *testing.T, cipherKey, hmacKey, header []byte, pid uint32, ad, plain []byte) []byte {
aead, nonce := refAEAD(t, cipherKey, hmacKey)
sealed := aead.Seal(nil, nonce(pid), plain, ad)
tagStart := len(sealed) - DataChannelTagSize
var pidb [4]byte
binary.BigEndian.PutUint32(pidb[:], pid)
out := append([]byte{}, header...)
out = append(out, pidb[:]...)
out = append(out, sealed[tagStart:]...)
return append(out, sealed[:tagStart]...)
}
func refOpen(t *testing.T, cipherKey, hmacKey []byte, packet []byte, headerSize int, ad []byte) ([]byte, error) {
aead, nonce := refAEAD(t, cipherKey, hmacKey)
pid := binary.BigEndian.Uint32(packet[headerSize : headerSize+4])
tag := packet[headerSize+4 : headerSize+4+DataChannelTagSize]
ct := packet[headerSize+4+DataChannelTagSize:]
return aead.Open(nil, nonce(pid), append(append([]byte{}, ct...), tag...), ad)
}
var testIPPacket = []byte{0x45, 0, 0, 20, 1, 2, 3, 4, 64, 6, 0, 0, 10, 8, 0, 2, 1, 1, 1, 1}
func TestDataChannelAESGCMV1RoundTrip(t *testing.T) {
ck, sk := v1TestKeys()
client, err := NewDataChannel(ck, CipherAES256GCM, AuthSHA1, PeerIDUnset, 0)
if err != nil {
t.Fatal(err)
}
server, err := NewDataChannel(sk, CipherAES256GCM, AuthSHA1, PeerIDUnset, 0)
if err != nil {
t.Fatal(err)
}
enc, err := client.Encrypt(testIPPacket)
if err != nil {
t.Fatal(err)
}
if opcode, _ := parseOpcodeKeyID(enc[0]); opcode != PDataV1 {
t.Fatalf("unexpected data opcode: %s", opcode)
}
plain, err := server.Decrypt(enc)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(plain, testIPPacket) {
t.Fatalf("unexpected decrypted packet: %x", plain)
}
}
// mihomo -> standard OpenVPN/SoftEther peer: our V1 packet must authenticate
// with AD = packet-id only, and must NOT authenticate with opcode|packet-id.
func TestDataChannelAEADV1EncryptMatchesOpenVPN(t *testing.T) {
ck, _ := v1TestKeys()
client, err := NewDataChannel(ck, CipherAES256GCM, AuthSHA1, PeerIDUnset, 4)
if err != nil {
t.Fatal(err)
}
enc, err := client.Encrypt(testIPPacket)
if err != nil {
t.Fatal(err)
}
if enc[0] != 0x34 { // P_DATA_V1, key-id 4, as seen on the wire from OpenVPN 2.6
t.Fatalf("unexpected first byte %#02x", enc[0])
}
pidOnly := enc[1:5]
plain, err := refOpen(t, ck.SendCipherKey, ck.SendHMACKey, enc, 1, pidOnly)
if err != nil {
t.Fatalf("standard peer rejects our P_DATA_V1 packet (AD must be packet-id only): %v", err)
}
if !bytes.Equal(plain, testIPPacket) {
t.Fatalf("unexpected plaintext: %x", plain)
}
if _, err := refOpen(t, ck.SendCipherKey, ck.SendHMACKey, enc, 1, enc[:5]); err == nil {
t.Fatal("P_DATA_V1 must not authenticate the opcode byte")
}
}
// standard OpenVPN/SoftEther peer -> mihomo: a V1 packet sealed with
// AD = packet-id only must decrypt.
func TestDataChannelAEADV1DecryptMatchesOpenVPN(t *testing.T) {
ck, sk := v1TestKeys()
client, err := NewDataChannel(ck, CipherAES256GCM, AuthSHA1, PeerIDUnset, 4)
if err != nil {
t.Fatal(err)
}
header := []byte{0x34}
var pidb [4]byte
binary.BigEndian.PutUint32(pidb[:], 1)
pkt := refSeal(t, sk.SendCipherKey, sk.SendHMACKey, header, 1, pidb[:], testIPPacket)
plain, err := client.Decrypt(pkt)
if err != nil {
t.Fatalf("failed to decrypt standard P_DATA_V1 packet: %v", err)
}
if !bytes.Equal(plain, testIPPacket) {
t.Fatalf("unexpected plaintext: %x", plain)
}
// tampering with the (unauthenticated-by-AD) opcode key-id must not be
// what makes or breaks decryption, but tampering with the packet id must.
binary.BigEndian.PutUint32(pidb[:], 2)
pkt = refSeal(t, sk.SendCipherKey, sk.SendHMACKey, header, 2, pidb[:], testIPPacket)
pkt[4] ^= 0xff
if _, err := client.Decrypt(pkt); err == nil {
t.Fatal("expected authentication failure after packet id tamper")
}
}
// Regression guard: P_DATA_V2 must keep authenticating opcode|peer-id|packet-id.
func TestDataChannelAEADV2StillAuthenticatesHeader(t *testing.T) {
ck, sk := v1TestKeys()
client, err := NewDataChannel(ck, CipherAES256GCM, AuthSHA1, 7, 0)
if err != nil {
t.Fatal(err)
}
enc, err := client.Encrypt(testIPPacket)
if err != nil {
t.Fatal(err)
}
if _, err := refOpen(t, ck.SendCipherKey, ck.SendHMACKey, enc, 4, enc[:8]); err != nil {
t.Fatalf("standard peer rejects our P_DATA_V2 packet: %v", err)
}
header := []byte{opcodeKeyID(PDataV2, 0), 0, 0, 7}
var pidb [4]byte
binary.BigEndian.PutUint32(pidb[:], 1)
pkt := refSeal(t, sk.SendCipherKey, sk.SendHMACKey, header, 1, append(append([]byte{}, header...), pidb[:]...), testIPPacket)
if _, err := client.Decrypt(pkt); err != nil {
t.Fatalf("failed to decrypt standard P_DATA_V2 packet: %v", err)
}
}
+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
}