Compare commits

..
58 Commits
Author SHA1 Message Date
Guanni Qu 5184081ac3 fix: socks4 readUntilNull unbounded memory allocation 2026-06-06 01:03:54 +08:00
Guanni Qu dbaf85b71b fix: vision TLS filter out-of-bounds read via crafted session_id length 2026-06-06 01:03:54 +08:00
Guanni Qu 5bdb1cc7e1 fix: trojan protocol WaitReadFrom panic via oversized UDP relay length field 2026-06-06 01:03:54 +08:00
Guanni Qu 11848509fb fix: quic sniffer out-of-bounds read causes process crash via single UDP packet 2026-06-06 01:03:54 +08:00
saba-futai ab56858d00 chore: sync sudoku v0.4.7 optimizations (#2879) 2026-06-06 00:19:38 +08:00
wwqgtxx 01edf45ce0 chore: improve internal api 2026-06-05 17:25:40 +08:00
wwqgtxx e928ef59c1 feat: add path-in-bundle to rule-providers to support extract from BundleMRS.7z when the local file does not exist 2026-06-05 12:13:12 +08:00
wwqgtxx c710025559 fix: readMsg in doq out-of-bounds access 2026-06-05 09:22:17 +08:00
wwqgtxx dafdd06b30 fix: variable capture in dns outbound 2026-06-05 09:21:57 +08:00
ECHSFXY fd2112ecbe feat: add built-in proxy PASS-RULE (#2873)
when a PASS-RULE is hit in a sub-rule, the sub-rule will not be skipped; instead, the currently hit rule branch will be skipped, and the matching of rules will continue in the sub-rule.
2026-06-04 21:23:39 +08:00
wwqgtxx 9761bcd7f9 fix: exchangeQUIC not fully respecting context 2026-06-04 19:15:52 +08:00
wwqgtxx 1e62d55418 feat: add empty-fallback to group options allows for customization instead of hardcoding COMPATIBLE 2026-06-04 15:07:53 +08:00
wwqgtxx 1abd12619a fix: validation error handling for age-secret-key 2026-06-04 13:49:33 +08:00
wwqgtxx f99d4e1be6 chore: adjust internal age component api 2026-06-04 09:30:58 +08:00
xream fb590a845f doc: fix typo in config docs (#2866) 2026-06-03 19:52:18 +08:00
wwqgtxx b60e687eb7 chore: support convert age-secret-key to age-public-key for build-in age tool 2026-06-03 16:15:02 +08:00
wwqgtxx 316f5df1f1 chore: add WithDialer option to component/http for api user 2026-06-03 12:25:51 +08:00
wwqgtxx d7ac7b5239 chore: support std input/output for age encrypt/decrypt tool 2026-06-03 12:25:37 +08:00
wwqgtxx 358fa5eb24 feat: add age-secret-key for proxy-provider and -age-secret-key for cmdline to support age armor format config decryption 2026-06-03 11:53:58 +08:00
puppywang 90b1066e1a feat: add ping keepalive support for OpenVPN (#2859) 2026-06-02 11:33:59 +08:00
wwqgtxx bd72c65b5e feat: remove global-client-fingerprint, please set client-fingerprint directly on the proxy instead 2026-06-02 10:40:38 +08:00
wwqgtxx 317bfc206a feat: add allow-insecure config to anytls/trojan/vless listeners for nginx/caddy front users 2026-06-02 10:22:22 +08:00
Zhiqiang Zhang fc8c5a24b1 feat: support comp-lzo for OpenVPN (#2841) 2026-05-30 09:14:40 +08:00
enfein 8f2d84f915 chore: update mieru version to v3.33.0 (#2840) 2026-05-29 08:37:53 +08:00
wwqgtxx 38cb06d3a5 fix: hysteria2 realm stun domain resolve 2026-05-27 22:32:31 +08:00
wwqgtxx 4065583ae4 fix: masque retry condition 2026-05-26 21:03:44 +08:00
wwqgtxx f30a64f93f feat: support hysteria2 gecko obfs 2026-05-25 15:35:22 +08:00
wwqgtxx f1c365611d feat: support AES-192-GCM/AES-192-CBC OpenVPN data ciphers 2026-05-25 13:53:36 +08:00
wwqgtxx 2dd7d59942 feat: support MD5/SHA384/SHA512 OpenVPN auth methods 2026-05-25 13:41:15 +08:00
wwqgtxx d610afef1b chore: clear parameter passing 2026-05-25 09:49:30 +08:00
saba-futai 5b28a0ee46 chore: optimize sudoku packed hot paths (#2833) 2026-05-25 07:52:43 +08:00
Romanov Caesar 5639e93f72 fix: improve OpenVPN transport reliability (#2824) 2026-05-23 21:54:22 +08:00
wwqgtxx 03e1f44921 fix: interface structs do not copy correctly 2026-05-23 11:58:21 +08:00
wwqgtxx f69331f45f fix: config struct not exported 2026-05-22 01:26:42 +08:00
xream 52edebd155 feat: add snell version 4/5 outbound and inbound (#2817) 2026-05-22 01:14:58 +08:00
Romanov Caesar 7a6a650902 feat: support OpenVPN CBC ciphers (#2818) 2026-05-21 23:41:08 +08:00
wwqgtxx 6e15299cab chore: remove AF_ALG in tailscale-wireguard-go 2026-05-21 20:52:19 +08:00
wwqgtxx 72f133f4bd chore: more logging for tailscale debug 2026-05-21 09:54:07 +08:00
wwqgtxx 301d580d8a fix: compile issue of tailscale-wireguard-go dependency 2026-05-20 23:40:06 +08:00
wwqgtxx 3809a03c9f fix: stack panic after dispatcher attach nil 2026-05-20 23:26:50 +08:00
wwqgtxx 0ddf4bbffd chore: update sing-tun 2026-05-20 11:07:10 +08:00
wwqgtxx d27f3201ab chore: use pre-go1.27 tls.QUICConfig.ClientHelloInfoConn API for quic-go to avoid cloning tls.Config 2026-05-20 10:13:55 +08:00
wwqgtxx a2aca027e4 fix: pinger in tailscale not under our control 2026-05-20 09:33:22 +08:00
wwqgtxx cb652ddb7d chore: make the handler-related SNAT key in NewPacket 2026-05-19 10:30:57 +08:00
wwqgtxx a52a27ed56 fix: errors.ErrUnsupported backport 2026-05-19 01:53:05 +08:00
wwqgtxx 060711fb7d chore: more netip.AddrPort using in tproxy 2026-05-18 22:48:45 +08:00
wwqgtxx 8c26d61ce3 fix: tproxy did not pass the additions correctly 2026-05-18 22:23:16 +08:00
wwqgtxx f2da5b7c27 chore: reduce internal circular dependencies 2026-05-18 21:31:08 +08:00
ayanamist d60b336dfc chore: use mihomo name & ver to tailscale reported ver to avoid update prompts (#2801) 2026-05-18 10:44:01 +08:00
wwqgtxx a531449b84 fix: missing param passing in vless listener config 2026-05-17 23:21:48 +08:00
wwqgtxx a05c94b4ad chore: make the proxydialer module no longer directly depend on the tunnel module 2026-05-17 21:55:16 +08:00
Lanlan13-14 ff98700df2 feat: support CHACHA20-POLY1305 data cipher for OpenVPN (#2798) 2026-05-17 17:45:26 +08:00
wwqgtxx 0dec35ed69 chore: always dial tcp on netstack for tailscale 2026-05-17 17:07:26 +08:00
wwqgtxx d2fcf71c4a fix: tailscale panic when working with dialer-proxy 2026-05-17 13:05:30 +08:00
wwqgtxx b230c90d13 fix: shadowtls v3 client HMAC handling for TLS 1.3 HelloRetryRequest 2026-05-17 10:16:53 +08:00
wwqgtxx b1a07d2006 chore: remove unnecessary member variables added by xsync/v3 2026-05-17 09:47:39 +08:00
wwqgtxx 31ece04ab0 chore: upgrade the embedded xsync.Map to v4.5.0 2026-05-17 08:49:48 +08:00
wwqgtxx e9e23c4e98 chore: tailscale must be compiled under the with_gvisor build tag 2026-05-16 23:45:08 +08:00
111 changed files with 6062 additions and 1268 deletions

No files matched your search

+1 -1
View File
@@ -210,7 +210,7 @@ func (b *BasicOption) NewDialer(opts []dialer.Option) C.Dialer {
cDialer := b.DialerForAPI
if cDialer == nil {
if b.DialerProxy != "" {
cDialer = proxydialer.NewByName(b.DialerProxy)
cDialer = proxydialer.NewByName(b.DialerProxy, b.NewTunnel())
} else {
cDialer = dialer.NewDialer(opts...)
}
+1 -1
View File
@@ -107,7 +107,7 @@ func (d *dnsPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
ctx, cancel := context.WithTimeout(d.ctx, resolver.DefaultDnsRelayTimeout)
defer cancel()
buf, err = resolver.RelayDnsPacket(ctx, buf[:len(p)], buf)
buf, err := resolver.RelayDnsPacket(ctx, buf[:len(p)], buf)
if err != nil {
put()
return
+5 -4
View File
@@ -9,6 +9,7 @@ import (
"strconv"
"time"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/ech"
@@ -19,7 +20,7 @@ import (
"github.com/metacubex/mihomo/transport/hysteria/obfs"
"github.com/metacubex/mihomo/transport/hysteria/pmtud_fix"
"github.com/metacubex/mihomo/transport/hysteria/transport"
"github.com/metacubex/mihomo/transport/hysteria/utils"
hyUtils "github.com/metacubex/mihomo/transport/hysteria/utils"
"github.com/metacubex/tls"
@@ -69,7 +70,7 @@ func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata
return newPacketConn(&hyPacketConn{udpConn}, h), nil
}
func (h *Hysteria) genHdc(ctx context.Context) utils.PacketDialer {
func (h *Hysteria) genHdc(ctx context.Context) hyUtils.PacketDialer {
return &hyDialerWithContext{
ctx: context.Background(),
hyDialer: func(network string, rAddr net.Addr) (net.PacketConn, error) {
@@ -128,12 +129,12 @@ type HysteriaOption struct {
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
var up, down uint64
up = StringToBps(c.Up)
up = utils.StringToBps(c.Up)
if up == 0 {
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
}
down = StringToBps(c.Down)
down = utils.StringToBps(c.Down)
if down == 0 {
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
}
+33 -22
View File
@@ -38,26 +38,28 @@ type Hysteria2 struct {
type Hysteria2Option struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port,omitempty"`
Ports string `proxy:"ports,omitempty"`
HopInterval string `proxy:"hop-interval,omitempty"`
Up string `proxy:"up,omitempty"`
Down string `proxy:"down,omitempty"`
Password string `proxy:"password,omitempty"`
Obfs string `proxy:"obfs,omitempty"`
ObfsPassword string `proxy:"obfs-password,omitempty"`
SNI string `proxy:"sni,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
ALPN []string `proxy:"alpn,omitempty"`
CWND int `proxy:"cwnd,omitempty"`
BBRProfile string `proxy:"bbr-profile,omitempty"`
UdpMTU int `proxy:"udp-mtu,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port,omitempty"`
Ports string `proxy:"ports,omitempty"`
HopInterval string `proxy:"hop-interval,omitempty"`
Up string `proxy:"up,omitempty"`
Down string `proxy:"down,omitempty"`
Password string `proxy:"password,omitempty"`
Obfs string `proxy:"obfs,omitempty"`
ObfsPassword string `proxy:"obfs-password,omitempty"`
ObfsMinPacketSize int `proxy:"obfs-min-packet-size,omitempty"`
ObfsMaxPacketSize int `proxy:"obfs-max-packet-size,omitempty"`
SNI string `proxy:"sni,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
ALPN []string `proxy:"alpn,omitempty"`
CWND int `proxy:"cwnd,omitempty"`
BBRProfile string `proxy:"bbr-profile,omitempty"`
UdpMTU int `proxy:"udp-mtu,omitempty"`
RealmOpts Hysteria2RealmOption `proxy:"realm-opts,omitempty"`
@@ -139,6 +141,8 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
outbound.dialer = option.NewDialer(outbound.DialOptions())
var salamanderPassword string
var geckoPassword string
var geckoMinPacketSize, geckoMaxPacketSize int
if len(option.Obfs) > 0 {
if option.ObfsPassword == "" {
return nil, errors.New("missing obfs password")
@@ -146,6 +150,10 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
switch option.Obfs {
case hysteria2.ObfsTypeSalamander:
salamanderPassword = option.ObfsPassword
case hysteria2.ObfsTypeGecko:
geckoPassword = option.ObfsPassword
geckoMinPacketSize = option.ObfsMinPacketSize
geckoMaxPacketSize = option.ObfsMaxPacketSize
default:
return nil, fmt.Errorf("unknown obfs type: %s", option.Obfs)
}
@@ -196,9 +204,12 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
clientOptions := hysteria2.ClientOptions{
Context: context.TODO(),
Logger: log.SingLogger,
SendBPS: StringToBps(option.Up),
ReceiveBPS: StringToBps(option.Down),
SendBPS: utils.StringToBps(option.Up),
ReceiveBPS: utils.StringToBps(option.Down),
SalamanderPassword: salamanderPassword,
GeckoPassword: geckoPassword,
GeckoMinPacketSize: geckoMinPacketSize,
GeckoMaxPacketSize: geckoMaxPacketSize,
Password: option.Password,
TLSConfig: tlsClientConfig,
QUICConfig: quicConfig,
+2 -2
View File
@@ -314,7 +314,7 @@ func (w *Masque) run(ctx context.Context) error {
}
icmp, err := ipConn.WritePacket(buf[:sizes[0]])
if err != nil {
if errors.Is(err, net.ErrClosed) {
if errors.Is(err, net.ErrClosed) || errors.Is(err, io.ErrClosedPipe) {
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
return
}
@@ -335,7 +335,7 @@ func (w *Masque) run(ctx context.Context) error {
for runCtx.Err() == nil {
buf, err := ipConn.ReadPacket()
if err != nil {
if errors.Is(err, net.ErrClosed) {
if errors.Is(err, net.ErrClosed) || errors.Is(err, io.ErrClosedPipe) {
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
return
}
+172 -61
View File
@@ -8,7 +8,9 @@ import (
"net/netip"
"os"
"sync"
"time"
"github.com/metacubex/mihomo/common/contextutils"
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
@@ -19,6 +21,7 @@ import (
wireguard "github.com/metacubex/sing-wireguard"
E "github.com/metacubex/sing/common/exceptions"
M "github.com/metacubex/sing/common/metadata"
"golang.org/x/sync/semaphore"
)
type OpenVPN struct {
@@ -33,27 +36,30 @@ type OpenVPN struct {
runCtx context.Context
runCancel context.CancelFunc
runMutex sync.Mutex
runLock *semaphore.Weighted
running bool
}
type OpenVPNOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Proto string `proxy:"proto,omitempty"`
Dev string `proxy:"dev,omitempty"`
Cipher string `proxy:"cipher,omitempty"`
Auth string `proxy:"auth,omitempty"`
CA string `proxy:"ca"`
Cert string `proxy:"cert,omitempty"`
Key string `proxy:"key,omitempty"`
TLSCrypt string `proxy:"tls-crypt"`
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Proto string `proxy:"proto,omitempty"`
Dev string `proxy:"dev,omitempty"`
Cipher string `proxy:"cipher,omitempty"`
Auth string `proxy:"auth,omitempty"`
CompLZO string `proxy:"comp-lzo,omitempty"`
CA string `proxy:"ca"`
Cert string `proxy:"cert,omitempty"`
Key string `proxy:"key,omitempty"`
TLSCrypt string `proxy:"tls-crypt,omitempty"`
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
Ping int `proxy:"ping,omitempty"`
PingRestart int `proxy:"ping-restart,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
Dns []string `proxy:"dns,omitempty"`
@@ -61,18 +67,21 @@ type OpenVPNOption struct {
func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
cfg := &ovpn.ClientConfig{
RemoteHost: option.Server,
RemotePort: uint16(option.Port),
Proto: option.Proto,
Dev: option.Dev,
Cipher: option.Cipher,
Auth: option.Auth,
CA: []byte(option.CA),
Cert: []byte(option.Cert),
Key: []byte(option.Key),
TLSCrypt: []byte(option.TLSCrypt),
Username: option.Username,
Password: option.Password,
RemoteHost: option.Server,
RemotePort: uint16(option.Port),
Proto: option.Proto,
Dev: option.Dev,
Cipher: option.Cipher,
Auth: option.Auth,
CompLZO: option.CompLZO,
CA: []byte(option.CA),
Cert: []byte(option.Cert),
Key: []byte(option.Key),
TLSCrypt: []byte(option.TLSCrypt),
Username: option.Username,
Password: option.Password,
PingInterval: time.Duration(option.Ping) * time.Second,
PingRestart: time.Duration(option.PingRestart) * time.Second,
}
if err := cfg.Prepare(); err != nil {
return nil, err
@@ -91,8 +100,9 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
RoutingMark: option.RoutingMark,
Prefer: option.IPVersion,
}),
option: &option,
config: cfg,
option: &option,
config: cfg,
runLock: semaphore.NewWeighted(1),
}
if option.RemoteDnsResolve && len(option.Dns) > 0 {
nss, err := dns.ParseNameServer(option.Dns)
@@ -107,21 +117,21 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
}
func (o *OpenVPN) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
if err = o.run(ctx); err != nil {
tunDevice, r, err := o.run(ctx)
if err != nil {
return nil, err
}
var conn net.Conn
if !metadata.Resolved() || o.resolver != nil {
r := resolver.DefaultResolver
if o.resolver != nil {
r = o.resolver
if !metadata.Resolved() || r != nil {
if r == nil {
r = resolver.DefaultResolver
}
options := o.DialOptions()
options = append(options, dialer.WithResolver(r))
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: o.tunDevice}))
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: tunDevice}))
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
} else {
conn, err = o.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
conn, err = tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
}
if err != nil {
return nil, err
@@ -134,13 +144,14 @@ func (o *OpenVPN) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Co
func (o *OpenVPN) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
var pc net.PacketConn
if err = o.run(ctx); err != nil {
tunDevice, r, err := o.run(ctx)
if err != nil {
return nil, err
}
if err = o.ResolveUDP(ctx, metadata); err != nil {
if err = o.resolveUDP(ctx, metadata, r); err != nil {
return nil, err
}
pc, err = o.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
pc, err = tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
if err != nil {
return nil, err
}
@@ -151,10 +162,17 @@ func (o *OpenVPN) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
}
func (o *OpenVPN) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
if (!metadata.Resolved() || o.resolver != nil) && metadata.Host != "" {
r := resolver.DefaultResolver
if o.resolver != nil {
r = o.resolver
_, r, err := o.run(ctx)
if err != nil {
return err
}
return o.resolveUDP(ctx, metadata, r)
}
func (o *OpenVPN) resolveUDP(ctx context.Context, metadata *C.Metadata, r resolver.Resolver) error {
if (!metadata.Resolved() || r != nil) && metadata.Host != "" {
if r == nil {
r = resolver.DefaultResolver
}
ip, err := resolveIPWithResolver(ctx, metadata.Host, o.prefer, r)
if err != nil {
@@ -179,13 +197,13 @@ func (o *OpenVPN) Close() error {
if o.runCancel != nil {
o.runCancel()
}
o.runMutex.Lock()
_ = o.runLock.Acquire(context.Background(), 1)
client := o.client
tunDevice := o.tunDevice
o.client = nil
o.tunDevice = nil
o.running = false
o.runMutex.Unlock()
o.runLock.Release(1)
if client != nil {
_ = client.Close()
@@ -196,31 +214,45 @@ func (o *OpenVPN) Close() error {
return nil
}
func (o *OpenVPN) run(ctx context.Context) error {
o.runMutex.Lock()
defer o.runMutex.Unlock()
func (o *OpenVPN) run(ctx context.Context) (wireguard.Device, resolver.Resolver, error) {
if err := o.lockRun(ctx); err != nil {
return nil, nil, err
}
defer o.runLock.Release(1)
if o.running {
return nil
if o.tunDevice == nil {
return nil, nil, net.ErrClosed
}
return o.tunDevice, o.resolver, nil
}
if o.runCtx.Err() != nil {
return o.runCtx.Err()
return nil, nil, o.runCtx.Err()
}
packetIO, err := o.openPacketIO(ctx)
handshakeCtx, cancel := o.handshakeContext(ctx)
defer cancel()
packetIO, err := o.openPacketIO(handshakeCtx)
if err != nil {
return err
if ctxErr := o.contextErr(ctx); ctxErr != nil {
return nil, nil, ctxErr
}
return nil, nil, E.Cause(err, "connect OpenVPN server")
}
client, err := ovpn.NewClient(o.config, packetIO)
if err != nil {
_ = packetIO.Close()
return err
return nil, nil, err
}
push, err := client.Handshake(ctx)
push, err := client.Handshake(handshakeCtx)
if err != nil {
_ = client.Close()
return err
if ctxErr := o.contextErr(ctx); ctxErr != nil {
return nil, nil, ctxErr
}
return nil, nil, E.Cause(err, "OpenVPN handshake")
}
log.Debugln("[OpenVPN](%s) handshake complete: prefixes=%v peer-id=%d dns=%v redirect=%t block-ipv6=%t", o.name, push.Prefixes, push.PeerID, push.DNS, push.Redirect, push.BlockIPv6)
log.Debugln("[OpenVPN](%s) handshake complete: prefixes=%v routes=%v peer-id=%d dns=%v redirect=%t block-ipv6=%t", o.name, push.Prefixes, push.Routes, push.PeerID, push.DNS, push.Redirect, push.BlockIPv6)
mtu := o.option.MTU
if mtu == 0 {
@@ -229,12 +261,12 @@ func (o *OpenVPN) run(ctx context.Context) error {
tunDevice, err := wireguard.NewStackDevice(push.Prefixes, uint32(mtu))
if err != nil {
_ = client.Close()
return E.Cause(err, "create OpenVPN stack device")
return nil, nil, E.Cause(err, "create OpenVPN stack device")
}
if err := tunDevice.Start(); err != nil {
_ = client.Close()
_ = tunDevice.Close()
return err
return nil, nil, err
}
o.client = client
o.tunDevice = tunDevice
@@ -250,9 +282,41 @@ func (o *OpenVPN) run(ctx context.Context) error {
})
}
o.startPacketLoops()
return o.tunDevice, o.resolver, nil
}
func (o *OpenVPN) lockRun(ctx context.Context) error {
lockCtx, cancel := context.WithCancel(ctx)
stop := contextutils.AfterFunc(o.runCtx, cancel)
defer func() {
stop()
cancel()
}()
if err := o.runLock.Acquire(lockCtx, 1); err != nil {
if ctxErr := o.contextErr(ctx); ctxErr != nil {
return ctxErr
}
return err
}
return nil
}
func (o *OpenVPN) handshakeContext(ctx context.Context) (context.Context, context.CancelFunc) {
handshakeCtx, handshakeCancel := context.WithTimeout(ctx, ovpn.DefaultHandshakeTimeout)
stop := contextutils.AfterFunc(o.runCtx, handshakeCancel)
return handshakeCtx, func() {
stop()
handshakeCancel()
}
}
func (o *OpenVPN) contextErr(ctx context.Context) error {
if err := ctx.Err(); err != nil {
return err
}
return o.runCtx.Err()
}
func openVPNPrefixesHas6(prefixes []netip.Prefix) bool {
for _, prefix := range prefixes {
if !prefix.Addr().Unmap().Is4() {
@@ -291,13 +355,13 @@ func (o *OpenVPN) startPacketLoops() {
runCancel()
_ = client.Close()
_ = tunDevice.Close()
o.runMutex.Lock()
_ = o.runLock.Acquire(context.Background(), 1)
if o.client == client {
o.client = nil
o.tunDevice = nil
o.running = false
}
o.runMutex.Unlock()
o.runLock.Release(1)
})
}
go func() {
@@ -342,4 +406,51 @@ func (o *OpenVPN) startPacketLoops() {
}
}
}()
if o.config.PingInterval > 0 {
go func() {
defer stop()
ticker := time.NewTicker(o.config.PingInterval)
defer ticker.Stop()
for runCtx.Err() == nil {
select {
case <-ticker.C:
if sinceSend := client.SinceSend(); sinceSend >= o.config.PingInterval {
if err := client.WritePing(runCtx); err != nil {
if !errors.Is(err, context.Canceled) && !errors.Is(err, net.ErrClosed) {
log.Warnln("[OpenVPN](%s) error writing ping packet: %v", o.name, err)
}
return
}
log.Debugln("[OpenVPN](%s) sent ping packet after %s idle", o.name, sinceSend.Round(time.Second))
}
case <-runCtx.Done():
return
}
}
}()
}
if o.config.PingRestart > 0 {
go func() {
defer stop()
ticker := time.NewTicker(o.config.PingRestart)
defer ticker.Stop()
for runCtx.Err() == nil {
select {
case <-ticker.C:
if sinceReceive := client.SinceReceive(); sinceReceive >= o.config.PingRestart {
log.Warnln(
"[OpenVPN](%s) ping-restart timeout: no packet received for %s",
o.name,
sinceReceive.Round(time.Second),
)
return
}
case <-runCtx.Done():
return
}
}
}()
}
}
+11
View File
@@ -88,6 +88,17 @@ func NewPass() *Reject {
}
}
func NewPassRule() *Reject {
return &Reject{
Base: &Base{
name: "PASS-RULE",
tp: C.PassRule,
udp: true,
prefer: C.DualStack,
},
}
}
type nopConn struct{}
func (rw nopConn) Read(b []byte) (int, error) { return 0, io.EOF }
+3 -2
View File
@@ -4,6 +4,7 @@ import (
"context"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/proxydialer"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"
@@ -106,8 +107,8 @@ func NewSingMux(option SingMuxOption, proxy ProxyAdapter) (ProxyAdapter, error)
TCPTimeout: C.DefaultTCPTimeout,
Brutal: mux.BrutalOptions{
Enabled: option.BrutalOpts.Enabled,
SendBPS: StringToBps(option.BrutalOpts.Up),
ReceiveBPS: StringToBps(option.BrutalOpts.Down),
SendBPS: utils.StringToBps(option.BrutalOpts.Up),
ReceiveBPS: utils.StringToBps(option.BrutalOpts.Down),
},
})
if err != nil {
+20 -4
View File
@@ -20,6 +20,7 @@ type Snell struct {
pool *snell.Pool
obfsOption *simpleObfsOption
version int
reuse bool
}
type SnellOption struct {
@@ -30,6 +31,7 @@ type SnellOption struct {
Psk string `proxy:"psk"`
UDP bool `proxy:"udp,omitempty"`
Version int `proxy:"version,omitempty"`
Reuse bool `proxy:"reuse,omitempty"`
ObfsOpts map[string]any `proxy:"obfs-opts,omitempty"`
}
@@ -66,15 +68,20 @@ func (s *Snell) writeHeaderContext(ctx context.Context, c net.Conn, metadata *C.
if metadata.NetWork == C.UDP {
err = snell.WriteUDPHeader(c, s.version)
if err == nil && s.version >= snell.Version4 {
if sc, ok := c.(*snell.Snell); ok {
err = sc.ReadReply()
}
}
return
}
err = snell.WriteHeader(c, metadata.String(), uint(metadata.DstPort), s.version)
err = snell.WriteHeaderWithReuse(c, metadata.String(), uint(metadata.DstPort), s.version, s.reuse)
return
}
// DialContext implements C.ProxyAdapter
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
if s.version == snell.Version2 {
if s.reuse {
c, err := s.pool.Get()
if err != nil {
return nil, err
@@ -115,6 +122,9 @@ func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (
}(c)
c, err = s.StreamConnContext(ctx, c, metadata)
if err != nil {
return nil, err
}
pc := snell.PacketConn(c)
return newPacketConn(pc, s), nil
@@ -153,12 +163,17 @@ func NewSnell(option SnellOption) (*Snell, error) {
if option.Version == 0 {
option.Version = snell.DefaultSnellVersion
}
if option.Version == snell.Version5 {
// Snell v5 servers are backward-compatible with v4 clients.
option.Version = snell.Version4
}
reuse := option.Version == snell.Version2 || (option.Version == snell.Version4 && option.Reuse)
switch option.Version {
case snell.Version1, snell.Version2:
if option.UDP {
return nil, fmt.Errorf("snell version %d not support UDP", option.Version)
}
case snell.Version3:
case snell.Version3, snell.Version4:
default:
return nil, fmt.Errorf("snell version error: %d", option.Version)
}
@@ -180,10 +195,11 @@ func NewSnell(option SnellOption) (*Snell, error) {
psk: psk,
obfsOption: obfsOption,
version: option.Version,
reuse: reuse,
}
s.dialer = option.NewDialer(s.DialOptions())
if option.Version == snell.Version2 {
if s.reuse {
s.pool = snell.NewPool(func(ctx context.Context) (*snell.Snell, error) {
c, err := s.dialer.DialContext(ctx, "tcp", addr)
if err != nil {
+1 -1
View File
@@ -66,7 +66,7 @@ func (s *Sudoku) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Con
}
muxMode := normalizeHTTPMaskMultiplex(cfg.HTTPMaskMultiplex)
if muxMode == "on" && !cfg.DisableHTTPMask && httpTunnelModeEnabled(cfg.HTTPMaskMode) {
if muxMode == "on" {
stream, muxErr := s.dialMultiplex(ctx, cfg.TargetAddress)
if muxErr == nil {
return NewConn(stream, s), nil
+67 -37
View File
@@ -1,4 +1,4 @@
//go:build !no_tailscale
//go:build with_gvisor && !no_tailscale
package outbound
@@ -21,10 +21,13 @@ import (
"github.com/metacubex/mihomo/log"
"github.com/metacubex/tailscale/envknob"
"github.com/metacubex/tailscale/hostinfo"
"github.com/metacubex/tailscale/ipn"
"github.com/metacubex/tailscale/net/netmon"
"github.com/metacubex/tailscale/tailcfg"
"github.com/metacubex/tailscale/tsnet"
D "github.com/miekg/dns"
"github.com/samber/lo"
)
type Tailscale struct {
@@ -62,23 +65,44 @@ type TailscaleOption struct {
}
func init() {
hostinfo.RegisterHostinfoNewHook(func(hi *tailcfg.Hostinfo) {
hi.IPNVersion = C.MihomoName + " " + C.Version
})
envknob.SetNoLogsNoSupport()
if runtime.GOOS == "android" { // Android SDK 30 no longer permits Go's net.Interfaces to work (Issue 2293)
netmon.RegisterInterfaceGetter(func() (nif []netmon.Interface, err error) {
log.Debugln("[Tailscale] InterfaceGetter: start, IsForceAnet: %v", anet.IsForceAnet())
ifaces, err := anet.Interfaces()
if err != nil {
log.Warnln("[Tailscale] anet.Interfaces failed: %v", err)
return nil, err
}
for _, iff := range ifaces {
addrs, err := anet.InterfaceAddrsByInterface(&iff)
if err != nil {
log.Warnln("[Tailscale] anet.InterfaceAddrsByInterface(%v) failed: %v", iff.Name, err)
continue
}
nif = append(nif, netmon.Interface{
Interface: &iff,
AltAddrs: addrs,
Interface: &net.Interface{
Index: iff.Index,
MTU: iff.MTU,
Name: iff.Name,
HardwareAddr: iff.HardwareAddr,
Flags: iff.Flags,
},
AltAddrs: addrs,
})
}
log.Debugln("[Tailscale] InterfaceGetter: %v", lo.Map(nif, func(item netmon.Interface, index int) string {
var addrs any
addrs, err := item.Addrs()
if err != nil {
addrs = err
}
return fmt.Sprintf("{Name: %s, Addrs: %v, IsUp: %v, IsLoopback: %v}", item.Name, addrs, item.IsUp(), item.IsLoopback())
}))
return
})
}
@@ -119,15 +143,30 @@ func NewTailscale(option TailscaleOption) (*Tailscale, error) {
}
outbound.dialer = option.NewDialer(outbound.DialOptions())
outbound.server = &tsnet.Server{
Dir: option.StateDir,
Hostname: option.Hostname,
AuthKey: option.AuthKey,
ControlURL: option.ControlURL,
Ephemeral: option.Ephemeral,
SystemDialer: outbound.dialer.DialContext,
SystemPacketListener: tailscalePacketListener{dialer: outbound.dialer},
ExtraRootCAs: ca.GetCertPool(),
LookupHook: tailscaleLookupHook,
Dir: option.StateDir,
Hostname: option.Hostname,
AuthKey: option.AuthKey,
ControlURL: option.ControlURL,
Ephemeral: option.Ephemeral,
SystemDialer: func(ctx context.Context, network, address string) (net.Conn, error) {
log.Debugln("[Tailscale](%s) SystemDialer: start dial %s %s", option.Name, network, address)
conn, err := outbound.dialer.DialContext(ctx, network, address)
log.Debugln("[Tailscale](%s) SystemDialer: finish dial %s %s, err: %v", option.Name, network, address, err)
return conn, err
},
SystemPacketListener: func(ctx context.Context, network, address string) (net.PacketConn, error) {
log.Debugln("[Tailscale](%s) SystemPacketListener: start listen %s %s", option.Name, network, address)
pc, err := outbound.dialer.ListenPacket(ctx, network, address, netip.AddrPort{})
log.Debugln("[Tailscale](%s) SystemPacketListener: finish listen %s %s, err: %v", option.Name, network, address, err)
return pc, err
},
ExtraRootCAs: ca.GetCertPool(),
LookupHook: func(ctx context.Context, host string) ([]netip.Addr, error) {
log.Debugln("[Tailscale](%s) LookupHook: start lookup %s", option.Name, host)
ips, err := resolver.LookupIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
log.Debugln("[Tailscale](%s) LookupHook: finish lookup %s, ips: %v, err: %v", option.Name, host, ips, err)
return ips, err
},
UserLogf: func(format string, args ...any) {
log.Infoln("[Tailscale](%s) %s", option.Name, fmt.Sprintf(format, args...))
},
@@ -304,21 +343,31 @@ func tailscaleExitNodeNeedsStatus(option TailscaleOption) bool {
return !ok
}
func tailscaleLookupHook(ctx context.Context, host string) ([]netip.Addr, error) {
return resolver.LookupIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
}
func (t *Tailscale) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
if err = t.ensureStarted(ctx); err != nil {
return nil, err
}
netStack, err := t.server.Netstack(ctx)
if err != nil {
return nil, err
}
v4, v6 := t.server.TailscaleIPs()
options := t.DialOptions()
options = append(options, dialer.WithResolver(t.dnsResolver))
options = append(options, dialer.WithNetDialer(dialer.NetDialerFunc(func(ctx context.Context, network, address string) (net.Conn, error) {
if err = t.checkTailscaleRoute(ctx, network, address); err != nil {
dst, err := netip.ParseAddrPort(address) // the dialer will resolve the domain to ip
if err != nil {
return nil, err
}
return t.server.Dial(ctx, network, address)
src := v4
if dst.Addr().Is6() {
src = v6
}
tcpConn, err := netStack.DialContextTCPWithBind(ctx, src, dst)
if err != nil {
return nil, err
}
return tcpConn, nil
})))
var conn net.Conn
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
@@ -364,17 +413,6 @@ func (t *Tailscale) ResolveUDP(ctx context.Context, metadata *C.Metadata) error
return nil
}
func (t *Tailscale) checkTailscaleRoute(ctx context.Context, network, address string) error {
ipp, viaTailscale, err := t.server.DialPlan(ctx, network, address)
if err != nil {
return err
}
if !viaTailscale {
return fmt.Errorf("destination %s is not routed by Tailscale; configure exit-node or accept an advertised subnet route", ipp)
}
return nil
}
type tailscaleDNSTransport struct {
tailscale *Tailscale
}
@@ -436,11 +474,3 @@ func (t *Tailscale) Close() error {
}
return nil
}
type tailscalePacketListener struct {
dialer C.Dialer
}
func (l tailscalePacketListener) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
return l.dialer.ListenPacket(ctx, network, address, netip.AddrPort{})
}
+2 -2
View File
@@ -1,4 +1,4 @@
//go:build no_tailscale
//go:build !with_gvisor || no_tailscale
package outbound
@@ -24,5 +24,5 @@ type TailscaleOption struct {
}
func NewTailscale(option TailscaleOption) (*Tailscale, error) {
return nil, fmt.Errorf("tailscale support is disabled by no_tailscale build tag")
return nil, fmt.Errorf("tailscale support is disabled by \"no_tailscale\" build tag or not include \"with_gvisor\" build tag")
}
-41
View File
@@ -3,10 +3,8 @@ package outbound
import (
"bytes"
"context"
"fmt"
"net"
"net/netip"
"regexp"
"strconv"
"github.com/metacubex/mihomo/component/resolver"
@@ -78,42 +76,3 @@ func safeConnClose(c net.Conn, err error) {
_ = c.Close()
}
}
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
func StringToBps(s string) uint64 {
if s == "" {
return 0
}
// when have not unit, use Mbps
if v, err := strconv.Atoi(s); err == nil {
return StringToBps(fmt.Sprintf("%d Mbps", v))
}
m := rateStringRegexp.FindStringSubmatch(s)
if m == nil {
return 0
}
var n uint64 = 1
switch m[2] {
case "T":
n *= 1000
fallthrough
case "G":
n *= 1000
fallthrough
case "M":
n *= 1000
fallthrough
case "K":
n *= 1000
}
v, _ := strconv.ParseUint(m[1], 10, 64)
n *= v
if m[3] == "b" {
// Bits, need to convert to bytes
n /= 8
}
return n
}
+3 -1
View File
@@ -90,6 +90,7 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
"fixed": f.selected,
"hidden": f.Hidden(),
"icon": f.Icon(),
"emptyFallback": f.EmptyFallback().Name(),
})
}
@@ -156,7 +157,7 @@ func (f *Fallback) Proxies() []C.Proxy {
return f.GetProxies(false)
}
func NewFallback(option *GroupCommonOption, providers []P.ProxyProvider) *Fallback {
func NewFallback(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.ProxyProvider) *Fallback {
return &Fallback{
GroupBase: NewGroupBase(GroupBaseOption{
Name: option.Name,
@@ -168,6 +169,7 @@ func NewFallback(option *GroupCommonOption, providers []P.ProxyProvider) *Fallba
ExcludeType: option.ExcludeType,
TestTimeout: option.TestTimeout,
MaxFailedTimes: option.MaxFailedTimes,
EmptyFallback: emptyFallback,
Providers: providers,
}),
disableUDP: option.DisableUDP,
+8 -2
View File
@@ -14,7 +14,6 @@ import (
C "github.com/metacubex/mihomo/constant"
P "github.com/metacubex/mihomo/constant/provider"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/tunnel"
"github.com/dlclark/regexp2"
"golang.org/x/exp/slices"
@@ -34,6 +33,7 @@ type GroupBase struct {
failedTesting atomic.Bool
testTimeout int
maxFailedTimes int
emptyFallback C.Proxy
// for GetProxies
getProxiesMutex sync.Mutex
@@ -51,6 +51,7 @@ type GroupBaseOption struct {
ExcludeType string
TestTimeout int
MaxFailedTimes int
EmptyFallback C.Proxy
Providers []P.ProxyProvider
}
@@ -87,6 +88,7 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
failedTesting: atomic.NewBool(false),
testTimeout: opt.TestTimeout,
maxFailedTimes: opt.MaxFailedTimes,
emptyFallback: opt.EmptyFallback,
}
if gb.testTimeout == 0 {
@@ -107,6 +109,10 @@ func (gb *GroupBase) Icon() string {
return gb.icon
}
func (gb *GroupBase) EmptyFallback() C.Proxy {
return gb.emptyFallback
}
func (gb *GroupBase) Touch() {
for _, pd := range gb.providers {
pd.Touch()
@@ -218,7 +224,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
}
if len(proxies) == 0 {
return []C.Proxy{tunnel.Proxies()["COMPATIBLE"]}
return []C.Proxy{gb.EmptyFallback()}
}
// only cache when proxies not empty
+3 -1
View File
@@ -234,6 +234,7 @@ func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
"expectedStatus": lb.expectedStatus,
"hidden": lb.Hidden(),
"icon": lb.Icon(),
"emptyFallback": lb.EmptyFallback().Name(),
})
}
@@ -249,7 +250,7 @@ func (lb *LoadBalance) Now() string {
return ""
}
func NewLoadBalance(option *GroupCommonOption, providers []P.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
func NewLoadBalance(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
var strategyFn strategyFn
switch strategy {
case "consistent-hashing":
@@ -272,6 +273,7 @@ func NewLoadBalance(option *GroupCommonOption, providers []P.ProxyProvider, stra
ExcludeType: option.ExcludeType,
TestTimeout: option.TestTimeout,
MaxFailedTimes: option.MaxFailedTimes,
EmptyFallback: emptyFallback,
Providers: providers,
}),
strategyFn: strategyFn,
+14 -5
View File
@@ -31,6 +31,7 @@ type GroupCommonOption struct {
Interval int `group:"interval,omitempty"`
TestTimeout int `group:"timeout,omitempty"`
MaxFailedTimes int `group:"max-failed-times,omitempty"`
EmptyFallback string `group:"empty-fallback,omitempty"`
Lazy bool `group:"lazy,omitempty"`
DisableUDP bool `group:"disable-udp,omitempty"`
Filter string `group:"filter,omitempty"`
@@ -70,6 +71,14 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
groupName := groupOption.Name
if groupOption.EmptyFallback == "" {
groupOption.EmptyFallback = "COMPATIBLE"
}
emptyFallback, ok := proxyMap[groupOption.EmptyFallback]
if !ok {
return nil, fmt.Errorf("%s: empty fallback proxy '%s' not found", groupName, groupOption.EmptyFallback)
}
providers := []P.ProxyProvider{}
if groupOption.IncludeAll {
@@ -98,7 +107,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
groupOption.Proxies = append(groupOption.Proxies, AllProxies...)
}
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
groupOption.Proxies = []string{"COMPATIBLE"}
groupOption.Proxies = []string{groupOption.EmptyFallback}
}
}
@@ -176,14 +185,14 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
switch groupOption.Type {
case "url-test":
opts := parseURLTestOption(config)
group = NewURLTest(groupOption, providers, opts...)
group = NewURLTest(groupOption, emptyFallback, providers, opts...)
case "select":
group = NewSelector(groupOption, providers)
group = NewSelector(groupOption, emptyFallback, providers)
case "fallback":
group = NewFallback(groupOption, providers)
group = NewFallback(groupOption, emptyFallback, providers)
case "load-balance":
strategy := parseStrategy(config)
return NewLoadBalance(groupOption, providers, strategy)
return NewLoadBalance(groupOption, emptyFallback, providers, strategy)
case "relay":
return nil, fmt.Errorf("%w: The group [%s] with relay type was removed, please using dialer-proxy instead", errType, groupName)
default:
+10 -8
View File
@@ -62,12 +62,13 @@ func (s *Selector) MarshalJSON() ([]byte, error) {
}
return json.Marshal(map[string]any{
"type": s.Type().String(),
"now": s.Now(),
"all": all,
"testUrl": url,
"hidden": s.Hidden(),
"icon": s.Icon(),
"type": s.Type().String(),
"now": s.Now(),
"all": all,
"testUrl": url,
"hidden": s.Hidden(),
"icon": s.Icon(),
"emptyFallback": s.EmptyFallback().Name(),
})
}
@@ -114,7 +115,7 @@ func (s *Selector) Proxies() []C.Proxy {
return s.GetProxies(false)
}
func NewSelector(option *GroupCommonOption, providers []P.ProxyProvider) *Selector {
func NewSelector(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.ProxyProvider) *Selector {
return &Selector{
GroupBase: NewGroupBase(GroupBaseOption{
Name: option.Name,
@@ -126,9 +127,10 @@ func NewSelector(option *GroupCommonOption, providers []P.ProxyProvider) *Select
ExcludeType: option.ExcludeType,
TestTimeout: option.TestTimeout,
MaxFailedTimes: option.MaxFailedTimes,
EmptyFallback: emptyFallback,
Providers: providers,
}),
selected: "COMPATIBLE",
selected: emptyFallback.Name(),
disableUDP: option.DisableUDP,
testUrl: option.URL,
}
+3 -1
View File
@@ -180,6 +180,7 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
"fixed": u.selected,
"hidden": u.Hidden(),
"icon": u.Icon(),
"emptyFallback": u.EmptyFallback().Name(),
})
}
@@ -208,7 +209,7 @@ func parseURLTestOption(config map[string]any) []urlTestOption {
return opts
}
func NewURLTest(option *GroupCommonOption, providers []P.ProxyProvider, options ...urlTestOption) *URLTest {
func NewURLTest(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.ProxyProvider, options ...urlTestOption) *URLTest {
urlTest := &URLTest{
GroupBase: NewGroupBase(GroupBaseOption{
Name: option.Name,
@@ -220,6 +221,7 @@ func NewURLTest(option *GroupCommonOption, providers []P.ProxyProvider, options
ExcludeType: option.ExcludeType,
TestTimeout: option.TestTimeout,
MaxFailedTimes: option.MaxFailedTimes,
EmptyFallback: emptyFallback,
Providers: providers,
}),
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
+2 -1
View File
@@ -37,6 +37,7 @@ type proxyProviderSchema struct {
DialerProxy string `provider:"dialer-proxy,omitempty"`
SizeLimit int64 `provider:"size-limit,omitempty"`
Payload []map[string]any `provider:"payload,omitempty"`
AgeSecretKey string `provider:"age-secret-key,omitempty"`
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
Override overrideSchema `provider:"override,omitempty"`
@@ -69,7 +70,7 @@ func ParseProxyProvider(name string, mapping map[string]any, tunnel C.Tunnel) (P
}
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, uint(schema.HealthCheck.TestTimeout), hcInterval, schema.HealthCheck.Lazy, expectedStatus)
parser, err := NewProxiesParser(name, tunnel, schema.Filter, schema.ExcludeFilter, schema.ExcludeType, schema.DialerProxy, schema.Override)
parser, err := NewProxiesParser(name, tunnel, schema.Filter, schema.ExcludeFilter, schema.ExcludeType, schema.DialerProxy, schema.Override, schema.AgeSecretKey)
if err != nil {
return nil, err
}
+15 -2
View File
@@ -13,6 +13,7 @@ import (
"github.com/metacubex/mihomo/common/convert"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/common/yaml"
"github.com/metacubex/mihomo/component/age"
"github.com/metacubex/mihomo/component/profile/cachefile"
"github.com/metacubex/mihomo/component/resource"
C "github.com/metacubex/mihomo/constant"
@@ -204,7 +205,7 @@ func NewProxySetProvider(name string, interval time.Duration, payload []map[stri
hc.setProxies(proxies)
}
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, parser, pd.setProxies)
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, nil, parser, pd.setProxies)
pd.Fetcher = fetcher
if httpVehicle, ok := vehicle.(*resource.HTTPVehicle); ok {
httpVehicle.SetInRead(func(resp *http.Response) {
@@ -339,7 +340,7 @@ func (cp *CompatibleProvider) Close() error {
return cp.compatibleProvider.Close()
}
func NewProxiesParser(pdName string, tunnel C.Tunnel, filter string, excludeFilter string, excludeType string, dialerProxy string, override overrideSchema) (resource.Parser[[]C.Proxy], error) {
func NewProxiesParser(pdName string, tunnel C.Tunnel, filter string, excludeFilter string, excludeType string, dialerProxy string, override overrideSchema, ageSecretKey string) (resource.Parser[[]C.Proxy], error) {
var excludeTypeArray []string
if excludeType != "" {
excludeTypeArray = strings.Split(excludeType, "|")
@@ -365,9 +366,21 @@ func NewProxiesParser(pdName string, tunnel C.Tunnel, filter string, excludeFilt
filterRegs = append(filterRegs, filterReg)
}
if ageSecretKey != "" {
if err := age.VeritySecretKeys(ageSecretKey); err != nil {
return nil, fmt.Errorf("invalid age-secret-key: %w", err)
}
}
return func(buf []byte) ([]C.Proxy, error) {
schema := &ProxySchema{}
// decrypt config
buf, err := age.DecryptBytes(buf, ageSecretKey)
if err != nil {
return nil, fmt.Errorf("decrypt config error: %w", err)
}
if err := yaml.Unmarshal(buf, schema); err != nil {
proxies, err1 := convert.ConvertsV2Ray(buf)
if err1 != nil {
+46
View File
@@ -0,0 +1,46 @@
package utils
import (
"fmt"
"regexp"
"strconv"
)
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
func StringToBps(s string) uint64 {
if s == "" {
return 0
}
// when have not unit, use Mbps
if v, err := strconv.Atoi(s); err == nil {
return StringToBps(fmt.Sprintf("%d Mbps", v))
}
m := rateStringRegexp.FindStringSubmatch(s)
if m == nil {
return 0
}
var n uint64 = 1
switch m[2] {
case "T":
n *= 1000
fallthrough
case "G":
n *= 1000
fallthrough
case "M":
n *= 1000
fallthrough
case "K":
n *= 1000
}
v, _ := strconv.ParseUint(m[1], 10, 64)
n *= v
if m[3] == "b" {
// Bits, need to convert to bytes
n /= 8
}
return n
}
+380 -88
View File
@@ -1,11 +1,12 @@
package xsync
// copy and modified from https://github.com/puzpuzpuz/xsync/blob/v4.2.0/map.go
// copy and modified from https://github.com/puzpuzpuz/xsync/blob/v4.5.0/map.go
// which is licensed under Apache v2.
//
// mihomo modified:
// 1. restore xsync/v3's LoadOrCompute api and rename to LoadOrStoreFn.
// 2. the zero Map is ready for use.
// 3. remove unnecessary member variables added by xsync/v3's "optimize Map for integer keys"
import (
"fmt"
@@ -37,11 +38,10 @@ const (
// minimum counter stripes to use
minMapCounterLen = 8
// maximum counter stripes to use; stands for around 4KB of memory
maxMapCounterLen = 32
defaultMeta uint64 = 0x8080808080808080
metaMask uint64 = 0xffffffffff
defaultMetaMasked uint64 = defaultMeta & metaMask
emptyMetaSlot uint8 = 0x80
maxMapCounterLen = 32
metaMask = 0xffffffffff
occupiedMeta = 0x8080808080808080
occupiedMetaMasked = occupiedMeta & metaMask
// minimal number of buckets to transfer when participating in cooperative
// resize; should be at least defaultMinMapTableLen
minResizeTransferStride = 64
@@ -212,7 +212,7 @@ func NewMap[K comparable, V any](options ...func(*MapConfig)) *Map[K, V] {
m := &Map[K, V]{}
if c.sizeHint > defaultMinMapTableLen*entriesPerMapBucket {
tableLen := nextPowOf2(uint32((float64(c.sizeHint) / entriesPerMapBucket) / mapLoadFactor))
tableLen := nextPowOf2(uint64((float64(c.sizeHint) / entriesPerMapBucket) / mapLoadFactor))
m.minTableLen = int(tableLen)
}
m.growOnly = c.growOnly
@@ -229,11 +229,46 @@ func (m *Map[K, V]) init() {
m.table.Store(table)
}
// detectIntKey returns true if the key type is an integer type.
func detectIntKey[K comparable]() bool {
var zero K
switch any(zero).(type) {
case int, uint, uintptr, int64, uint64, int32, uint32, int16, uint16, int8, uint8:
return true
default:
return false
}
}
// hashUint64 computes a hash for integer keys using two rounds of
// multiply-xorshift mixing (wyhash-style).
// This is significantly faster than maphash.Comparable for integer types.
func hashUint64(seed maphash.Seed, v uint64) uint64 {
// maphash.Seed is just a uint64, so we can convert it directly
hi, lo := bits.Mul64(v^(*(*uint64)(unsafe.Pointer(&seed))), 0x2d358dccaa6c78a5)
hi2, lo2 := bits.Mul64(hi^lo, 0x8bb84b93962eacc9)
return hi2 ^ lo2
}
// toUint64 reinterprets integer-like keys as uint64 for hashUint64.
// The size switch is folded per instantiated K by the compiler.
func toUint64[K any](k K) uint64 {
switch unsafe.Sizeof(k) {
case 8:
return *(*uint64)(unsafe.Pointer(&k))
case 4:
return uint64(*(*uint32)(unsafe.Pointer(&k)))
case 2:
return uint64(*(*uint16)(unsafe.Pointer(&k)))
case 1:
return uint64(*(*uint8)(unsafe.Pointer(&k)))
default:
panic("unreachable")
}
}
func newMapTable[K comparable, V any](minTableLen int, seed maphash.Seed) *mapTable[K, V] {
buckets := make([]bucketPadded, minTableLen)
for i := range buckets {
buckets[i].meta = defaultMeta
}
counterLen := minTableLen >> 10
if counterLen < minMapCounterLen {
counterLen = minMapCounterLen
@@ -270,17 +305,33 @@ func ToPlainMap[K comparable, V any](m *Map[K, V]) map[K]V {
func (m *Map[K, V]) Load(key K) (value V, ok bool) {
m.initOnce.Do(m.init)
table := m.table.Load()
hash := maphash.Comparable(table.seed, key)
var hash uint64
if detectIntKey[K]() {
hash = hashUint64(table.seed, toUint64(key))
} else {
hash = maphash.Comparable(table.seed, key)
}
h1 := h1(hash)
h2w := broadcast(h2(hash))
bidx := uint64(len(table.buckets)-1) & h1
b := &table.buckets[bidx]
// Same as: b := &table.buckets[bidx]
// Inline bounds check elimination via unsafe pointer arithmetic.
// Safety: bidx is always < len(table.buckets) since it's masked with (len-1).
b := (*bucketPadded)(unsafe.Add(unsafe.Pointer(&table.buckets[0]),
uintptr(bidx)*unsafe.Sizeof(bucketPadded{})))
for {
metaw := atomic.LoadUint64(&b.meta)
markedw := markZeroBytes(metaw^h2w) & metaMask
for markedw != 0 {
idx := firstMarkedByteIndex(markedw)
eptr := atomic.LoadPointer(&b.entries[idx])
// Same as: eptr := atomic.LoadPointer(&b.entries[idx])
// Inline bounds check elimination via unsafe pointer arithmetic.
// Safety: idx is always < entriesPerMapBucket (5) since it comes from
// firstMarkedByteIndex which returns index of a marked byte in the
// 5-byte metadata mask (metaMask).
eptr := atomic.LoadPointer((*unsafe.Pointer)(unsafe.Add(
unsafe.Pointer(&b.entries[0]),
uintptr(idx)*unsafe.Sizeof(b.entries[0]))))
if eptr != nil {
e := (*entry[K, V])(eptr)
if e.key == key {
@@ -299,14 +350,109 @@ func (m *Map[K, V]) Load(key K) (value V, ok bool) {
// Store sets the value for a key.
func (m *Map[K, V]) Store(key K, value V) {
m.doCompute(
key,
func(V, bool) (V, ComputeOp) {
return value, UpdateOp
},
noLoadOp,
false,
)
m.initOnce.Do(m.init)
// Store is a popular operation, hence instead of using doCompute,
// it uses a simplified and slightly faster version of it.
for {
store_attempt:
var (
emptyb *bucketPadded
emptyidx int
)
table := m.table.Load()
tableLen := len(table.buckets)
var hash uint64
if detectIntKey[K]() {
hash = hashUint64(table.seed, toUint64(key))
} else {
hash = maphash.Comparable(table.seed, key)
}
h1 := h1(hash)
h2 := h2(hash)
h2w := broadcast(h2)
bidx := uint64(len(table.buckets)-1) & h1
rootb := &table.buckets[bidx]
rootb.mu.Lock()
// The following two checks must go in reverse to what's
// in the resize method.
if seq := resizeSeq(m.resizeCtl.Load()); seq&1 == 1 {
// Resize is in progress. Help with the transfer, then go for another attempt.
rootb.mu.Unlock()
m.helpResize(seq)
goto store_attempt
}
if m.newerTableExists(table) {
// Someone resized the table. Go for another attempt.
rootb.mu.Unlock()
goto store_attempt
}
b := rootb
for {
metaw := b.meta
markedw := markZeroBytes(metaw^h2w) & metaMask
for markedw != 0 {
idx := firstMarkedByteIndex(markedw)
eptr := b.entries[idx]
if eptr != nil {
e := (*entry[K, V])(eptr)
if e.key == key {
// In-place update.
newe := new(entry[K, V])
newe.key = key
newe.value = value
atomic.StorePointer(&b.entries[idx], unsafe.Pointer(newe))
rootb.mu.Unlock()
return
}
}
markedw &= markedw - 1
}
if emptyb == nil {
// Search for empty entries (up to 5 per bucket).
emptyw := ^metaw & occupiedMetaMasked
if emptyw != 0 {
idx := firstMarkedByteIndex(emptyw)
emptyb = b
emptyidx = idx
}
}
if b.next == nil {
if emptyb != nil {
// Insertion into an existing bucket.
newe := new(entry[K, V])
newe.key = key
newe.value = value
// First we update meta, then the entry.
atomic.StoreUint64(&emptyb.meta, setByte(emptyb.meta, h2, emptyidx))
atomic.StorePointer(&emptyb.entries[emptyidx], unsafe.Pointer(newe))
rootb.mu.Unlock()
table.addSize(bidx, 1)
return
}
growThreshold := float64(tableLen) * entriesPerMapBucket * mapLoadFactor
if table.sumSize() > int64(growThreshold) {
// Need to grow the table. Then go for another attempt.
rootb.mu.Unlock()
m.resize(table, mapGrowHint)
goto store_attempt
}
// Insertion into a new bucket.
// Create and append a bucket.
newb := new(bucketPadded)
newb.meta = setByte(0, h2, 0)
newe := new(entry[K, V])
newe.key = key
newe.value = value
newb.entries[0] = unsafe.Pointer(newe)
atomic.StorePointer(&b.next, unsafe.Pointer(newb))
rootb.mu.Unlock()
table.addSize(bidx, 1)
return
}
b = (*bucketPadded)(b.next)
}
}
}
// LoadOrStore returns the existing value for the key if present.
@@ -436,7 +582,12 @@ func (m *Map[K, V]) doCompute(
)
table := m.table.Load()
tableLen := len(table.buckets)
hash := maphash.Comparable(table.seed, key)
var hash uint64
if detectIntKey[K]() {
hash = hashUint64(table.seed, toUint64(key))
} else {
hash = maphash.Comparable(table.seed, key)
}
h1 := h1(hash)
h2 := h2(hash)
h2w := broadcast(h2)
@@ -509,13 +660,13 @@ func (m *Map[K, V]) doCompute(
case DeleteOp:
// Deletion.
// First we update the hash, then the entry.
newmetaw := setByte(metaw, emptyMetaSlot, idx)
newmetaw := setByte(metaw, 0, idx)
atomic.StoreUint64(&b.meta, newmetaw)
atomic.StorePointer(&b.entries[idx], nil)
rootb.mu.Unlock()
table.addSize(bidx, -1)
// Might need to shrink the table if we left bucket empty.
if newmetaw == defaultMeta {
if newmetaw == 0 {
m.resize(table, mapShrinkHint)
}
return oldv, !computeOnly
@@ -540,7 +691,7 @@ func (m *Map[K, V]) doCompute(
}
if emptyb == nil {
// Search for empty entries (up to 5 per bucket).
emptyw := metaw & defaultMetaMasked
emptyw := ^metaw & occupiedMetaMasked
if emptyw != 0 {
idx := firstMarkedByteIndex(emptyw)
emptyb = b
@@ -581,11 +732,11 @@ func (m *Map[K, V]) doCompute(
switch op {
case DeleteOp, CancelOp:
rootb.mu.Unlock()
return newValue, false
return zeroV, false
default:
// Create and append a bucket.
newb := new(bucketPadded)
newb.meta = setByte(defaultMeta, h2, 0)
newb.meta = setByte(0, h2, 0)
newe := new(entry[K, V])
newe.key = key
newe.value = newValue
@@ -655,10 +806,10 @@ func (m *Map[K, V]) resize(knownTable *mapTable[K, V], hint mapResizeHint) {
shrinkThreshold := int64((tableLen * entriesPerMapBucket) / mapShrinkFraction)
if tableLen > m.minTableLen && table.sumSize() <= shrinkThreshold {
// Shrink the table with factor of 2.
// It's fine to generate a new seed since full locking
// is required anyway.
// Analogous to growth, we must preserve the seed to ensure stable
// hash mapping, enabling lock-free writes to destination buckets.
m.totalShrinks.Add(1)
newTable = newMapTable[K, V](tableLen>>1, maphash.MakeSeed())
newTable = newMapTable[K, V](tableLen>>1, table.seed)
} else {
// No need to shrink. Wake up all waiters and give up.
m.resizeMu.Lock()
@@ -740,6 +891,20 @@ func (m *Map[K, V]) helpResize(seq uint64) {
func (m *Map[K, V]) transfer(table, newTable *mapTable[K, V]) {
tableLen := len(table.buckets)
newTableLen := len(newTable.buckets)
// Determines the concurrent task range for destination buckets.
// We iterate based on these properties to avoid locking destination
// buckets:
// - Grow (Pow2): baseLen == tableLen
// Entries from source bucket i move to dest buckets i and i+baseLen
// - Shrink (Pow2): baseLen == newTableLen
// Entries from source buckets i and i+baseLen move to dest bucket i
// By iterating 0..baseLen and processing all possible source buckets
// (srcIdx += baseLen) in the inner loop, a single goroutine exclusively
// owns the write operations for its assigned destination buckets.
baseLen := tableLen
if baseLen > newTableLen {
baseLen = newTableLen
}
stride := (tableLen >> 3) / int(maxResizeHelpers)
if stride < minResizeTransferStride {
stride = minResizeTransferStride
@@ -751,27 +916,20 @@ func (m *Map[K, V]) transfer(table, newTable *mapTable[K, V]) {
if start < 0 {
start = 0
}
if start > tableLen {
if start >= baseLen {
break
}
end := int(nextIdx)
if end > tableLen {
end = tableLen
if end > baseLen {
end = baseLen
}
// Transfer buckets in this range.
total := 0
if newTableLen > tableLen {
// We're growing the table with 2x multiplier, so entries from a N bucket can
// only be transferred to N and 2*N buckets in the new table. Thus, destination
// buckets written by the resize helpers don't intersect, so we don't need to
// acquire locks in the destination buckets.
for i := start; i < end; i++ {
total += transferBucketUnsafe(&table.buckets[i], newTable)
}
} else {
// We're shrinking the table, so all locks must be acquired.
for i := start; i < end; i++ {
total += transferBucket(&table.buckets[i], newTable)
for i := start; i < end; i++ {
// Visit all source buckets that map to this destination bucket.
// When growing, runs once. When shrinking, runs twice.
for srcIdx := i; srcIdx < tableLen; srcIdx += baseLen {
total += transferBucketUnsafe(&table.buckets[srcIdx], newTable)
}
}
// The exact counter stripe doesn't matter here, so pick up the one
@@ -791,7 +949,12 @@ func transferBucketUnsafe[K comparable, V any](
for i := 0; i < entriesPerMapBucket; i++ {
if eptr := b.entries[i]; eptr != nil {
e := (*entry[K, V])(eptr)
hash := maphash.Comparable(destTable.seed, e.key)
var hash uint64
if detectIntKey[K]() {
hash = hashUint64(destTable.seed, toUint64(e.key))
} else {
hash = maphash.Comparable(destTable.seed, e.key)
}
bidx := uint64(len(destTable.buckets)-1) & h1(hash)
destb := &destTable.buckets[bidx]
appendToBucket(h2(hash), e, destb)
@@ -806,33 +969,6 @@ func transferBucketUnsafe[K comparable, V any](
}
}
func transferBucket[K comparable, V any](
b *bucketPadded,
destTable *mapTable[K, V],
) (copied int) {
rootb := b
rootb.mu.Lock()
for {
for i := 0; i < entriesPerMapBucket; i++ {
if eptr := b.entries[i]; eptr != nil {
e := (*entry[K, V])(eptr)
hash := maphash.Comparable(destTable.seed, e.key)
bidx := uint64(len(destTable.buckets)-1) & h1(hash)
destb := &destTable.buckets[bidx]
destb.mu.Lock()
appendToBucket(h2(hash), e, destb)
destb.mu.Unlock()
copied++
}
}
if b.next == nil {
rootb.mu.Unlock()
return
}
b = (*bucketPadded)(b.next)
}
}
// Range calls f sequentially for each key and value present in the
// map. If f returns false, range stops the iteration.
//
@@ -846,6 +982,9 @@ func transferBucket[K comparable, V any](
// creation, modification and deletion. However, the concurrent
// modification rule apply, i.e. the changes may be not reflected
// in the subsequently iterated entries.
//
// For a faster, lock-free alternative with relaxed consistency
// guarantees, see [RangeRelaxed].
func (m *Map[K, V]) Range(f func(key K, value V) bool) {
m.initOnce.Do(m.init)
// Pre-allocate array big enough to fit entries for most hash tables.
@@ -882,6 +1021,167 @@ func (m *Map[K, V]) Range(f func(key K, value V) bool) {
}
}
// All is similar to [Range], but returns an [iter.Seq2], so is compatible with
// Go 1.23+ iterators. All of the same caveats and behaviour from [Range] apply
// to All.
//
// For a faster, lock-free alternative with relaxed consistency
// guarantees, see [AllRelaxed].
func (m *Map[K, V]) All() func(func(key K, value V) bool) {
return m.Range
}
// RangeRelaxed calls f sequentially for each key and value present
// in the map. If f returns false, range stops the iteration.
//
// RangeRelaxed is a faster, lock-free alternative to [Range]. Unlike
// Range, it does not acquire bucket locks and does not allocate memory
// for entry snapshots. Instead, it reads entries directly using atomic
// loads.
//
// RangeRelaxed does not necessarily correspond to any consistent
// snapshot of the Map's contents: if the value for any key is stored
// or deleted concurrently, RangeRelaxed may reflect any mapping for
// that key from any point during the RangeRelaxed call. Unlike [Range],
// the same key may be visited more than once if it is concurrently
// deleted and re-inserted during the iteration.
//
// It is safe to modify the map while iterating it, including entry
// creation, modification and deletion. However, the concurrent
// modification rule apply, i.e. the changes may be not reflected
// in the subsequently iterated entries.
//
// For stronger consistency guarantees where each key is visited at
// most once, see [Range].
func (m *Map[K, V]) RangeRelaxed(f func(key K, value V) bool) {
m.initOnce.Do(m.init)
table := m.table.Load()
for i := range table.buckets {
b := &table.buckets[i]
for {
metaw := atomic.LoadUint64(&b.meta)
markedw := metaw & occupiedMeta
for markedw != 0 {
idx := firstMarkedByteIndex(markedw)
eptr := atomic.LoadPointer(&b.entries[idx])
if eptr != nil {
e := (*entry[K, V])(eptr)
if !f(e.key, e.value) {
return
}
}
markedw &= markedw - 1
}
bptr := atomic.LoadPointer(&b.next)
if bptr == nil {
break
}
b = (*bucketPadded)(bptr)
}
}
}
// AllRelaxed is similar to [RangeRelaxed], but returns an [iter.Seq2],
// so is compatible with Go 1.23+ iterators. All of the same caveats
// and behaviour from [RangeRelaxed] apply to AllRelaxed.
//
// For stronger consistency guarantees where each key is visited at
// most once, see [All].
func (m *Map[K, V]) AllRelaxed() func(func(key K, value V) bool) {
return m.RangeRelaxed
}
// DeleteMatching deletes all entries for which the delete return
// value of f is true. If the stop return value is true, the
// iteration stops immediately. The function returns the number
// of deleted entries.
//
// DeleteMatching does not necessarily correspond to any consistent
// snapshot of the Map's contents: if the value for any key is stored
// or deleted concurrently (including by a concurrent DeleteMatching
// call), DeleteMatching may reflect any mapping for that key from
// any point during the call. In particular, if the map is resized
// during the call (for example, due to concurrent modifications),
// the iteration restarts internally with the new table, which may
// result in calling f with the same key more than once.
//
// This call locks a hash table bucket for the duration of
// evaluating f for all entries in the bucket and performing
// deletions. It means that modifications on other entries in
// the bucket will be blocked until f executes. Consider this when
// the function includes long-running operations.
func (m *Map[K, V]) DeleteMatching(f func(key K, value V) (delete, stop bool)) int {
m.initOnce.Do(m.init)
var totalDeleted int
var anyBucketEmptied bool
delete_loop_attempt:
table := m.table.Load()
for bidx := range table.buckets {
rootb := &table.buckets[bidx]
rootb.mu.Lock()
// The following two checks must go in reverse to what's
// in the resize method.
if seq := resizeSeq(m.resizeCtl.Load()); seq&1 == 1 {
// Resize is in progress. Help with the transfer, then go for another attempt.
rootb.mu.Unlock()
m.helpResize(seq)
goto delete_loop_attempt
}
if m.newerTableExists(table) {
// Someone resized the table. Go for another attempt.
rootb.mu.Unlock()
goto delete_loop_attempt
}
var bucketDeleted int
b := rootb
for {
for i := 0; i < entriesPerMapBucket; i++ {
eptr := b.entries[i]
if eptr != nil {
e := (*entry[K, V])(eptr)
del, stop := f(e.key, e.value)
if del {
// Deletion.
// First we update the meta, then the entry.
newmetaw := setByte(b.meta, 0, i)
atomic.StoreUint64(&b.meta, newmetaw)
atomic.StorePointer(&b.entries[i], nil)
bucketDeleted++
if newmetaw == 0 {
anyBucketEmptied = true
}
}
if stop {
rootb.mu.Unlock()
totalDeleted += bucketDeleted
if bucketDeleted > 0 {
table.addSize(uint64(bidx), -bucketDeleted)
}
if anyBucketEmptied {
m.resize(table, mapShrinkHint)
}
return totalDeleted
}
}
}
if b.next == nil {
break
}
b = (*bucketPadded)(b.next)
}
rootb.mu.Unlock()
if bucketDeleted > 0 {
totalDeleted += bucketDeleted
table.addSize(uint64(bidx), -bucketDeleted)
}
}
if anyBucketEmptied {
m.resize(table, mapShrinkHint)
}
return totalDeleted
}
// Clear deletes all keys and values currently stored in the map.
func (m *Map[K, V]) Clear() {
m.initOnce.Do(m.init)
@@ -907,7 +1207,7 @@ func appendToBucket[K comparable, V any](h2 uint8, e *entry[K, V], b *bucketPadd
}
if b.next == nil {
newb := new(bucketPadded)
newb.meta = setByte(defaultMeta, h2, 0)
newb.meta = setByte(0, h2, 0)
newb.entries[0] = unsafe.Pointer(e)
b.next = unsafe.Pointer(newb)
return
@@ -917,7 +1217,7 @@ func appendToBucket[K comparable, V any](h2 uint8, e *entry[K, V], b *bucketPadd
}
func (table *mapTable[K, V]) addSize(bucketIdx uint64, delta int) {
cidx := uint64(len(table.size)-1) & bucketIdx
cidx := bucketIdx & uint64(len(table.size)-1)
atomic.AddInt64(&table.size[cidx].c, int64(delta))
}
@@ -934,7 +1234,7 @@ func h1(h uint64) uint64 {
}
func h2(h uint64) uint8 {
return uint8(h & 0x7f)
return 0x80 | uint8(h&0x7f)
}
// MapStats is Map statistics.
@@ -1052,20 +1352,12 @@ const (
cacheLineSize = 64
)
// nextPowOf2 computes the next highest power of 2 of 32-bit v.
// Source: https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
func nextPowOf2(v uint32) uint32 {
if v == 0 {
// nextPowOf2 computes the next highest power of 2 of 64-bit v.
func nextPowOf2(v uint64) uint64 {
if v <= 1 {
return 1
}
v--
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v++
return v
return 1 << bits.Len64(v-1)
}
func parallelism() uint32 {
+845 -341
View File
File diff suppressed because it is too large. Load diff
+250
View File
@@ -0,0 +1,250 @@
package age
import (
"bytes"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/metacubex/age"
"github.com/metacubex/age/armor"
)
const FileHeader = armor.Header
var globalSecretKeys []string
// parseIdentities parse age-secret-key to age.Identity
func parseIdentities(secretKey string) ([]age.Identity, error) {
return age.ParseIdentities(strings.NewReader(secretKey))
}
// parseRecipients parse age-public-key to age.Recipient
func parseRecipients(publicKey string) ([]age.Recipient, error) {
return age.ParseRecipients(strings.NewReader(publicKey))
}
// convertToRecipient convert age.Identity to age.Recipient
func convertToRecipient(identity age.Identity) (age.Recipient, error) {
switch identity := identity.(type) {
case *age.X25519Identity:
return identity.Recipient(), nil
case *age.HybridIdentity:
return identity.Recipient(), nil
default:
return nil, fmt.Errorf("unexpected identity type: %T", identity)
}
}
// ToPublicKeys convert age-secret-key to age-public-key
func ToPublicKeys(secretKeys ...string) (publicKeys []string, err error) {
for _, secretKey := range secretKeys {
identities, err := parseIdentities(secretKey)
if err != nil {
return nil, err
}
for _, identity := range identities {
recipient, err := convertToRecipient(identity)
if err != nil {
return nil, err
}
publicKeys = append(publicKeys, fmt.Sprint(recipient))
}
}
return
}
// SetGlobalSecretKeys set global secret keys, which will be used when decrypting
func SetGlobalSecretKeys(secretKeys ...string) {
globalSecretKeys = append(globalSecretKeys[:0], secretKeys...)
}
// VeritySecretKeys check if the secret key is valid
func VeritySecretKeys(secretKeys ...string) error {
for _, secretKey := range secretKeys {
if _, err := parseIdentities(secretKey); err != nil {
return err
}
}
return nil
}
// VerityPublicKeys check if the public key is valid
func VerityPublicKeys(publicKeys ...string) error {
for _, publicKey := range publicKeys {
if _, err := parseRecipients(publicKey); err != nil {
return err
}
}
return nil
}
// DecryptBytes decrypt age armor format encrypted data
// if not the age armor format, return original data
func DecryptBytes(data []byte, secretKeys ...string) ([]byte, error) {
if !strings.HasPrefix(string(data), FileHeader) { // not age armor format
return data, nil
}
var identities []age.Identity
for _, secretKey := range secretKeys {
identity, err := parseIdentities(secretKey)
if err != nil {
return nil, err
}
identities = append(identities, identity...)
}
for _, secretKey := range globalSecretKeys {
identity, err := parseIdentities(secretKey)
if err != nil {
return nil, err
}
identities = append(identities, identity...)
}
r, err := age.Decrypt(armor.NewReader(bytes.NewReader(data)), identities...)
if err != nil {
return nil, err
}
return io.ReadAll(r)
}
// EncryptBytes encrypt data with age armor format
func EncryptBytes(data []byte, publicKeys ...string) ([]byte, error) {
var recipients []age.Recipient
for _, publicKey := range publicKeys {
recipient, err := parseRecipients(publicKey)
if err != nil {
return nil, err
}
recipients = append(recipients, recipient...)
}
buf := &bytes.Buffer{}
armorWriter := armor.NewWriter(buf)
w, err := age.Encrypt(armorWriter, recipients...)
if err != nil {
return nil, err
}
_, err = w.Write(data)
if err != nil {
return nil, err
}
err = w.Close()
if err != nil {
return nil, err
}
err = armorWriter.Close()
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// GenX25519KeyPair generate x25519 recipient type age-secret-key and age-public-key
func GenX25519KeyPair() (secretKey string, publicKey string, err error) {
identity, err := age.GenerateX25519Identity()
if err != nil {
return "", "", err
}
return identity.String(), identity.Recipient().String(), nil
}
// GenHybridKeyPair generate mlkem768-x25519 hybrid post-quantum recipient type age-secret-key and age-public-key
func GenHybridKeyPair() (secretKey string, publicKey string, err error) {
identity, err := age.GenerateHybridIdentity()
if err != nil {
return "", "", err
}
return identity.String(), identity.Recipient().String(), nil
}
func Main(args []string) {
if len(args) < 1 {
panic("Using: age keygen/keygen-pq/convert/decrypt/encrypt")
}
switch args[0] {
case "keygen":
secretKey, publicKey, err := GenX25519KeyPair()
if err != nil {
panic(err)
}
fmt.Printf("# created: %s\n", time.Now().Format(time.RFC3339))
fmt.Printf("# public key: %s\n", publicKey)
fmt.Printf("%s\n", secretKey)
case "keygen-pq":
secretKey, publicKey, err := GenHybridKeyPair()
if err != nil {
panic(err)
}
fmt.Printf("# created: %s\n", time.Now().Format(time.RFC3339))
fmt.Printf("# public key: %s\n", publicKey)
fmt.Printf("%s\n", secretKey)
case "convert":
if len(args) < 1 {
panic("Using: age convert <secret_key>")
}
publicKeys, err := ToPublicKeys(args[1])
if err != nil {
panic(err)
}
if len(publicKeys) == 0 {
panic("no public keys found in the input")
}
for _, publicKey := range publicKeys {
fmt.Println(publicKey)
}
case "decrypt":
if len(args) < 3 {
panic("Using: age decrypt <secret_key> <source_file> <target_file>")
}
var data []byte
var err error
if args[2] == "-" {
data, err = io.ReadAll(os.Stdin)
} else {
data, err = os.ReadFile(args[2])
}
if err != nil {
panic(err)
}
result, err := DecryptBytes(data, args[1])
if err != nil {
panic(err)
}
if args[3] == "-" {
_, err = os.Stdout.Write(result)
} else {
err = os.WriteFile(args[3], result, 0644)
}
if err != nil {
panic(err)
}
case "encrypt":
if len(args) < 3 {
panic("Using: age encrypt <public_key> <source_file> <target_file>")
}
var data []byte
var err error
if args[2] == "-" {
data, err = io.ReadAll(os.Stdin)
} else {
data, err = os.ReadFile(args[2])
}
if err != nil {
panic(err)
}
result, err := EncryptBytes(data, args[1])
if err != nil {
panic(err)
}
if args[3] == "-" {
_, err = os.Stdout.Write(result)
} else {
err = os.WriteFile(args[3], result, 0644)
}
if err != nil {
panic(err)
}
}
}
+50
View File
@@ -0,0 +1,50 @@
package age_test
import (
"testing"
"github.com/metacubex/mihomo/component/age"
)
func TestAge(t *testing.T) {
testCases := []struct {
name string
gen func() (string, string, error)
}{
{"X25519", age.GenX25519KeyPair},
{"MLKEM768X25519", age.GenHybridKeyPair},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
secretKey, publicKey, err := tc.gen()
if err != nil {
t.Fatal(err)
}
t.Log(secretKey, publicKey)
publicKeys, err := age.ToPublicKeys(secretKey)
if err != nil {
t.Fatal(err)
}
if len(publicKeys) != 1 {
t.Fatal("public keys length is not equal to 1")
}
if publicKeys[0] != publicKey {
t.Fatal("public key is not equal")
}
rawData := []byte("hello world")
encryptData, err := age.EncryptBytes(rawData, publicKey)
if err != nil {
t.Fatal(err)
}
t.Log(string(encryptData))
decryptData, err := age.DecryptBytes(encryptData, secretKey)
if err != nil {
t.Fatal(err)
}
if string(decryptData) != string(rawData) {
t.Fatal("decrypt data is not equal to raw data")
}
})
}
}
+12 -2
View File
@@ -11,6 +11,7 @@ import (
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/mihomo/component/dialer"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/listener/inner"
"github.com/metacubex/http"
@@ -74,11 +75,13 @@ func HttpRequest(ctx context.Context, url, method string, header map[string][]st
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
if opt.dialer != nil {
return opt.dialer.DialContext(ctx, network, address)
}
if conn, err := inner.HandleTcp(inner.GetTunnel(), address, opt.specialProxy); err == nil {
return conn, nil
} else {
return dialer.DialContext(ctx, network, address)
}
return dialer.DialContext(ctx, network, address)
},
TLSClientConfig: tlsConfig,
}
@@ -91,6 +94,7 @@ type Option func(opt *option)
type option struct {
specialProxy string
dialer C.Dialer
caOption ca.Option
}
@@ -100,6 +104,12 @@ func WithSpecialProxy(name string) Option {
}
}
func WithDialer(dialer C.Dialer) Option {
return func(opt *option) {
opt.dialer = dialer
}
}
func WithCAOption(caOption ca.Option) Option {
return func(opt *option) {
opt.caOption = caOption
+11
View File
@@ -0,0 +1,11 @@
package anet
import (
"os"
"strconv"
)
func IsForceAnet() bool {
force, _ := strconv.ParseBool(os.Getenv("FORCE_ANET"))
return force
}
+23 -15
View File
@@ -21,11 +21,13 @@ type ifReq [40]byte
// Interfaces returns a list of the system's network interfaces.
func Interfaces() ([]net.Interface, error) {
ift, err := net.Interfaces()
if err == nil {
return ift, nil
if !IsForceAnet() {
ift, err := net.Interfaces()
if err == nil {
return ift, nil
}
}
ift, err = interfaceTable(0)
ift, err := interfaceTable(0)
if err != nil {
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
}
@@ -38,11 +40,13 @@ func Interfaces() ([]net.Interface, error) {
// The returned list does not identify the associated interface; use
// Interfaces and Interface.Addrs for more detail.
func InterfaceAddrs() ([]net.Addr, error) {
ifat, err := net.InterfaceAddrs()
if err == nil {
return ifat, nil
if !IsForceAnet() {
ifat, err := net.InterfaceAddrs()
if err == nil {
return ifat, nil
}
}
ifat, err = interfaceAddrTable(nil)
ifat, err := interfaceAddrTable(nil)
if err != nil {
err = &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
}
@@ -55,9 +59,11 @@ func InterfaceAddrs() ([]net.Addr, error) {
// sharing the logical data link; for more precision use
// InterfaceByName.
func InterfaceByIndex(index int) (*net.Interface, error) {
ifi, err := net.InterfaceByIndex(index)
if err == nil {
return ifi, nil
if !IsForceAnet() {
ifi, err := net.InterfaceByIndex(index)
if err == nil {
return ifi, nil
}
}
if index <= 0 {
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: errInvalidInterfaceIndex}
@@ -66,7 +72,7 @@ func InterfaceByIndex(index int) (*net.Interface, error) {
if err != nil {
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
}
ifi, err = interfaceByIndex(ift, index)
ifi, err := interfaceByIndex(ift, index)
if err != nil {
err = &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
}
@@ -75,9 +81,11 @@ func InterfaceByIndex(index int) (*net.Interface, error) {
// InterfaceByName returns the interface specified by name.
func InterfaceByName(name string) (*net.Interface, error) {
ifi, err := net.InterfaceByName(name)
if err == nil {
return ifi, nil
if !IsForceAnet() {
ifi, err := net.InterfaceByName(name)
if err == nil {
return ifi, nil
}
}
if name == "" {
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: errInvalidInterfaceName}
+16 -3
View File
@@ -7,14 +7,23 @@ import (
"net/netip"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/tunnel"
)
type Tunnel interface {
C.Tunnel
Proxies() map[string]C.Proxy
}
type byNameProxyDialer struct {
proxyName string
tunnel C.Tunnel
}
func (d byNameProxyDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
tunnel, _ := d.tunnel.(Tunnel)
if tunnel == nil {
return nil, fmt.Errorf("tunnel is invalid, must be proxydialer.Tunnel, but got: %T", d.tunnel)
}
proxies := tunnel.Proxies()
proxy, ok := proxies[d.proxyName]
if !ok {
@@ -24,6 +33,10 @@ func (d byNameProxyDialer) DialContext(ctx context.Context, network, address str
}
func (d byNameProxyDialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
tunnel, _ := d.tunnel.(Tunnel)
if tunnel == nil {
return nil, fmt.Errorf("tunnel is invalid, must be proxydialer.Tunnel, but got: %T", d.tunnel)
}
proxies := tunnel.Proxies()
proxy, ok := proxies[d.proxyName]
if !ok {
@@ -32,6 +45,6 @@ func (d byNameProxyDialer) ListenPacket(ctx context.Context, network, address st
return New(proxy, true).ListenPacket(ctx, network, address, rAddrPort)
}
func NewByName(proxyName string) C.Dialer {
return byNameProxyDialer{proxyName: proxyName}
func NewByName(proxyName string, tunnel C.Tunnel) C.Dialer {
return byNameProxyDialer{proxyName: proxyName, tunnel: tunnel}
}
+4
View File
@@ -2,6 +2,7 @@ package proxydialer
import (
"context"
"fmt"
"net"
"net/netip"
"strings"
@@ -50,6 +51,9 @@ func (p proxyDialer) DialContext(ctx context.Context, network, address string) (
}
func (p proxyDialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
if !strings.HasPrefix(network, "udp") {
return nil, fmt.Errorf("proxyDialer only support udp network, but got: %s", network)
}
currentMeta := &C.Metadata{Type: C.INNER, DstIP: rAddrPort.Addr(), DstPort: rAddrPort.Port()}
return p.listenPacket(ctx, currentMeta)
}
+40 -8
View File
@@ -2,6 +2,8 @@ package resource
import (
"context"
"io"
"io/fs"
"os"
"sync"
"time"
@@ -16,6 +18,7 @@ import (
)
type Parser[V any] func([]byte) (V, error)
type BundleFile func() (fs.File, error)
type Fetcher[V any] struct {
ctx context.Context
@@ -23,6 +26,7 @@ type Fetcher[V any] struct {
resourceType string
name string
vehicle P.Vehicle
bundleFile BundleFile
updatedAt time.Time
hash utils.HashType
parser Parser[V]
@@ -66,6 +70,33 @@ func (f *Fetcher[V]) Initial() (V, error) {
}
}
// parse local file error, fallback to bundle file
if f.bundleFile != nil {
// bundle file exists, use it first
if file, fErr := f.bundleFile(); fErr == nil {
defer file.Close()
buf, err := io.ReadAll(file)
var modTime time.Time
if stat, sErr := file.Stat(); sErr == nil {
modTime = stat.ModTime()
}
contents, _, err := f.loadBuf(buf, utils.MakeHash(buf), true)
f.updatedAt = modTime // reset updatedAt to file's modTime
if err == nil {
log.Infoln("[Provider] %s extract successful from bundle file", f.Name())
err = f.startPullLoop(time.Since(modTime) > f.interval)
if err != nil {
return lo.Empty[V](), err
}
return contents, nil
}
log.Warnln("[Provider] %s read bundle file error: %s", f.Name(), err.Error())
} else {
log.Warnln("[Provider] %s read bundle file error: %s", f.Name(), fErr.Error())
}
}
// parse local file error, fallback to remote
contents, _, updateErr := f.Update()
@@ -218,20 +249,21 @@ func (f *Fetcher[V]) updateWithLog() {
return
}
func NewFetcher[V any](name string, interval time.Duration, vehicle P.Vehicle, parser Parser[V], onUpdate func(V)) *Fetcher[V] {
func NewFetcher[V any](name string, interval time.Duration, vehicle P.Vehicle, bundleFile BundleFile, parser Parser[V], onUpdate func(V)) *Fetcher[V] {
ctx, cancel := context.WithCancel(context.Background())
minBackoff := 10 * time.Second
if interval < minBackoff {
minBackoff = interval
}
return &Fetcher[V]{
ctx: ctx,
ctxCancel: cancel,
name: name,
vehicle: vehicle,
parser: parser,
onUpdate: onUpdate,
interval: interval,
ctx: ctx,
ctxCancel: cancel,
name: name,
bundleFile: bundleFile,
vehicle: vehicle,
parser: parser,
onUpdate: onUpdate,
interval: interval,
backoff: slowdown.Backoff{
Factor: 2,
Jitter: false,
+4
View File
@@ -236,6 +236,10 @@ func (q *quicPacketSender) readQuicData(b []byte) error {
cache := buf.NewPacket()
defer cache.Release()
if hdrLen+4+16 > len(b) {
return errNotQuic
}
mask := cache.Extend(block.BlockSize())
block.Encrypt(mask, b[hdrLen+4:hdrLen+4+16])
firstByte := b[0]
-13
View File
@@ -40,9 +40,6 @@ func NewListener(inner net.Listener, config *Config) net.Listener {
}
func GetFingerprint(clientFingerprint string) (UClientHelloID, bool) {
if len(clientFingerprint) == 0 {
clientFingerprint = globalFingerprint
}
if len(clientFingerprint) == 0 || clientFingerprint == "none" {
return UClientHelloID{}, false
}
@@ -319,13 +316,3 @@ func GetTLSConnectionState(conn net.Conn) (tlsState tls.ConnectionState) {
}
return
}
var globalFingerprint string
func SetGlobalFingerprint(fingerprint string) {
globalFingerprint = fingerprint
}
func GetGlobalFingerprint() string {
return globalFingerprint
}
+47 -36
View File
@@ -18,6 +18,7 @@ import (
"github.com/metacubex/mihomo/common/orderedmap"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/common/yaml"
"github.com/metacubex/mihomo/component/age"
"github.com/metacubex/mihomo/component/auth"
"github.com/metacubex/mihomo/component/cidr"
"github.com/metacubex/mihomo/component/fakeip"
@@ -34,6 +35,7 @@ import (
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/log"
R "github.com/metacubex/mihomo/rules"
RB "github.com/metacubex/mihomo/rules/bundle"
RC "github.com/metacubex/mihomo/rules/common"
RP "github.com/metacubex/mihomo/rules/provider"
RW "github.com/metacubex/mihomo/rules/wrapper"
@@ -45,27 +47,26 @@ import (
// General config
type General struct {
Inbound
Mode T.TunnelMode `json:"mode"`
UnifiedDelay bool `json:"unified-delay"`
LogLevel log.LogLevel `json:"log-level"`
IPv6 bool `json:"ipv6"`
Interface string `json:"interface-name"`
RoutingMark int `json:"routing-mark"`
GeoXUrl GeoXUrl `json:"geox-url"`
GeoAutoUpdate bool `json:"geo-auto-update"`
GeoUpdateInterval int `json:"geo-update-interval"`
GeodataMode bool `json:"geodata-mode"`
GeodataLoader string `json:"geodata-loader"`
GeositeMatcher string `json:"geosite-matcher"`
TCPConcurrent bool `json:"tcp-concurrent"`
FindProcessMode process.FindProcessMode `json:"find-process-mode"`
Sniffing bool `json:"sniffing"`
GlobalClientFingerprint string `json:"global-client-fingerprint"`
GlobalUA string `json:"global-ua"`
ETagSupport bool `json:"etag-support"`
KeepAliveIdle int `json:"keep-alive-idle"`
KeepAliveInterval int `json:"keep-alive-interval"`
DisableKeepAlive bool `json:"disable-keep-alive"`
Mode T.TunnelMode `json:"mode"`
UnifiedDelay bool `json:"unified-delay"`
LogLevel log.LogLevel `json:"log-level"`
IPv6 bool `json:"ipv6"`
Interface string `json:"interface-name"`
RoutingMark int `json:"routing-mark"`
GeoXUrl GeoXUrl `json:"geox-url"`
GeoAutoUpdate bool `json:"geo-auto-update"`
GeoUpdateInterval int `json:"geo-update-interval"`
GeodataMode bool `json:"geodata-mode"`
GeodataLoader string `json:"geodata-loader"`
GeositeMatcher string `json:"geosite-matcher"`
TCPConcurrent bool `json:"tcp-concurrent"`
FindProcessMode process.FindProcessMode `json:"find-process-mode"`
Sniffing bool `json:"sniffing"`
GlobalUA string `json:"global-ua"`
ETagSupport bool `json:"etag-support"`
KeepAliveIdle int `json:"keep-alive-idle"`
KeepAliveInterval int `json:"keep-alive-interval"`
DisableKeepAlive bool `json:"disable-keep-alive"`
}
// Inbound config
@@ -595,6 +596,12 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
// config with default value
rawCfg := DefaultRawConfig()
// decrypt config
buf, err := age.DecryptBytes(buf)
if err != nil {
return nil, fmt.Errorf("decrypt config error: %w", err)
}
if err := yaml.Unmarshal(buf, rawCfg); err != nil {
return nil, err
}
@@ -739,6 +746,9 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
func temporaryUpdateGeneral(general *General) func()
func parseGeneral(cfg *RawConfig) (*General, error) {
if cfg.GlobalClientFingerprint != "" {
log.Errorln("The `global-client-fingerprint` configuration is removed, please set `client-fingerprint` directly on the proxy instead")
}
return &General{
Inbound: Inbound{
Port: cfg.Port,
@@ -768,19 +778,18 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
ASN: cfg.GeoXUrl.ASN,
GeoSite: cfg.GeoXUrl.GeoSite,
},
GeoAutoUpdate: cfg.GeoAutoUpdate,
GeoUpdateInterval: cfg.GeoUpdateInterval,
GeodataMode: cfg.GeodataMode,
GeodataLoader: cfg.GeodataLoader,
GeositeMatcher: cfg.GeositeMatcher,
TCPConcurrent: cfg.TCPConcurrent,
FindProcessMode: cfg.FindProcessMode,
GlobalClientFingerprint: cfg.GlobalClientFingerprint,
GlobalUA: cfg.GlobalUA,
ETagSupport: cfg.ETagSupport,
KeepAliveIdle: cfg.KeepAliveIdle,
KeepAliveInterval: cfg.KeepAliveInterval,
DisableKeepAlive: cfg.DisableKeepAlive,
GeoAutoUpdate: cfg.GeoAutoUpdate,
GeoUpdateInterval: cfg.GeoUpdateInterval,
GeodataMode: cfg.GeodataMode,
GeodataLoader: cfg.GeodataLoader,
GeositeMatcher: cfg.GeositeMatcher,
TCPConcurrent: cfg.TCPConcurrent,
FindProcessMode: cfg.FindProcessMode,
GlobalUA: cfg.GlobalUA,
ETagSupport: cfg.ETagSupport,
KeepAliveIdle: cfg.KeepAliveIdle,
KeepAliveInterval: cfg.KeepAliveInterval,
DisableKeepAlive: cfg.DisableKeepAlive,
}, nil
}
@@ -872,6 +881,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
proxies["REJECT-DROP"] = adapter.NewProxy(outbound.NewRejectDrop())
proxies["COMPATIBLE"] = adapter.NewProxy(outbound.NewCompatible())
proxies["PASS"] = adapter.NewProxy(outbound.NewPass())
proxies["PASS-RULE"] = adapter.NewProxy(outbound.NewPassRule())
proxyList = append(proxyList, "DIRECT", "REJECT")
// parse proxy
@@ -942,7 +952,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
var ps []C.Proxy
for _, v := range proxyList {
if proxies[v].Type() == C.Pass {
if proxies[v].Type() == C.Pass || proxies[v].Type() == C.PassRule {
continue
}
ps = append(ps, proxies[v])
@@ -956,6 +966,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
&outboundgroup.GroupCommonOption{
Name: "GLOBAL",
},
proxies["COMPATIBLE"],
[]P.ProxyProvider{pd},
)
proxies["GLOBAL"] = adapter.NewProxy(global)
@@ -993,7 +1004,7 @@ func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]P.RuleProvider
ruleProviders = map[string]P.RuleProvider{}
// parse rule provider
for name, mapping := range cfg.RuleProvider {
rp, err := RP.ParseRuleProvider(name, mapping, R.ParseRule)
rp, err := RP.ParseRuleProvider(name, mapping, R.ParseRule, RB.MakeBundleFile)
if err != nil {
return nil, err
}
+3
View File
@@ -21,6 +21,7 @@ const (
RejectDrop
Compatible
Pass
PassRule
Dns
Relay
@@ -183,6 +184,8 @@ func (at AdapterType) String() string {
return "Compatible"
case Pass:
return "Pass"
case PassRule:
return "PassRule"
case Dns:
return "Dns"
case Shadowsocks:
+5
View File
@@ -28,6 +28,7 @@ const (
SOCKS4
SOCKS5
SHADOWSOCKS
SNELL
VMESS
VLESS
REDIR
@@ -92,6 +93,8 @@ func (t Type) String() string {
return "Socks5"
case SHADOWSOCKS:
return "ShadowSocks"
case SNELL:
return "Snell"
case VMESS:
return "Vmess"
case VLESS:
@@ -138,6 +141,8 @@ func ParseType(t string) (*Type, error) {
res = SOCKS5
case "SHADOWSOCKS":
res = SHADOWSOCKS
case "SNELL":
res = SNELL
case "VMESS":
res = VMESS
case "VLESS":
+23 -3
View File
@@ -15,9 +15,10 @@ import (
const Name = "mihomo"
var (
GeositeName = "GeoSite.dat"
GeoipName = "GeoIP.dat"
ASNName = "ASN.mmdb"
GeositeName = "GeoSite.dat"
GeoipName = "GeoIP.dat"
ASNName = "ASN.mmdb"
BundleMRSName = "BundleMRS.7z"
)
// Path is used to get the configuration path
@@ -162,6 +163,25 @@ func (p *path) ASN() string {
return P.Join(p.homeDir, ASNName)
}
func (p *path) BundleMRS() string {
files, err := os.ReadDir(p.homeDir)
if err != nil {
return ""
}
for _, fi := range files {
if fi.IsDir() {
// 目录则直接跳过
continue
} else {
if strings.EqualFold(fi.Name(), "BundleMRS.7z") {
BundleMRSName = fi.Name()
return P.Join(p.homeDir, fi.Name())
}
}
}
return P.Join(p.homeDir, BundleMRSName)
}
func (p *path) OldCache() string {
return P.Join(p.homeDir, ".cache")
}
+1
View File
@@ -152,6 +152,7 @@ type RuleWrapper interface {
type RuleMatchHelper struct {
ResolveIP func()
FindProcess func()
CheckPassRule func(adapterName string) bool
}
type RuleGroup interface {
+47 -40
View File
@@ -5,12 +5,14 @@ import (
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"runtime"
"strconv"
"sync"
"time"
"github.com/metacubex/mihomo/common/contextutils"
"github.com/metacubex/mihomo/common/pool"
"github.com/metacubex/mihomo/component/ca"
C "github.com/metacubex/mihomo/constant"
@@ -112,7 +114,7 @@ func (doq *dnsOverQUIC) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.M
// make DoQ usable. We need to make 2 attempts in the case when the
// connection was closed (due to inactivity for example) AND the server
// refuses to open a 0-RTT connection.
for i := 0; hasConnection && doq.shouldRetry(err) && i < 2; i++ {
for i := 0; hasConnection && doq.shouldRetry(err) && ctx.Err() == nil && i < 2; i++ {
log.Debugln("re-creating the QUIC connection and retrying due to %v", err)
// Close the active connection to make sure we'll try to re-connect.
@@ -152,25 +154,39 @@ func (doq *dnsOverQUIC) ResetConnection() {
// exchangeQUIC attempts to open a QUIC connection, send the DNS message
// through it and return the response it got from the server.
func (doq *dnsOverQUIC) exchangeQUIC(ctx context.Context, msg *D.Msg) (resp *D.Msg, err error) {
// All DNS messages (queries and responses) sent over DoQ connections MUST
// be encoded as a 2-octet length field followed by the message content as
// specified in [RFC1035].
// Note: we do not support receiving multiple messages over a single connection.
buf := pool.Get(2 + MaxMsgSize)
defer pool.Put(buf)
b, err := msg.PackBuffer(buf[2:])
if err != nil {
return nil, fmt.Errorf("failed to pack DNS message for DoQ: %w", err)
}
if len(b) > MaxMsgSize {
return nil, fmt.Errorf("DNS message is too large: %d > %d", len(b), MaxMsgSize)
}
binary.BigEndian.PutUint16(buf, uint16(len(b)))
var conn *quic.Conn
conn, err = doq.getConnection(ctx, true)
if err != nil {
return nil, err
}
var buf []byte
buf, err = msg.Pack()
if err != nil {
return nil, fmt.Errorf("failed to pack DNS message for DoQ: %w", err)
}
var stream *quic.Stream
stream, err = doq.openStream(ctx, conn)
if err != nil {
return nil, err
}
_, err = stream.Write(AddPrefix(buf))
stop := contextutils.AfterFunc(ctx, func() {
_ = stream.SetDeadline(time.Now()) // cancel any read or write operation on this stream
})
defer stop()
_, err = stream.Write(buf[:2+len(b)])
if err != nil {
return nil, fmt.Errorf("failed to write to a QUIC stream: %w", err)
}
@@ -181,16 +197,31 @@ func (doq *dnsOverQUIC) exchangeQUIC(ctx context.Context, msg *D.Msg) (resp *D.M
// write-direction of the stream, but does not prevent reading from it.
_ = stream.Close()
return doq.readMsg(stream)
}
// -- reading the response ---
var respLen uint16
err = binary.Read(stream, binary.BigEndian, &respLen)
if err != nil {
return nil, fmt.Errorf("reading response length from %s: %w", doq.Address(), err)
}
if respLen == 0 {
return nil, fmt.Errorf("received empty response from %s", doq.Address())
}
if respLen > MaxMsgSize {
return nil, fmt.Errorf("received response that is too large: %d > %d", respLen, MaxMsgSize)
}
// AddPrefix adds a 2-byte prefix with the DNS message length.
func AddPrefix(b []byte) (m []byte) {
m = make([]byte, 2+len(b))
binary.BigEndian.PutUint16(m, uint16(len(b)))
copy(m[2:], b)
_, err = io.ReadFull(stream, buf[:respLen])
if err != nil {
return nil, fmt.Errorf("reading response from %s: %w", doq.Address(), err)
}
return m
resp = new(D.Msg)
err = resp.Unpack(buf[:respLen])
if err != nil {
return nil, fmt.Errorf("unpacking response from %s: %w", doq.Address(), err)
}
return resp, nil
}
// shouldRetry checks what error we received and decides whether it is required
@@ -363,30 +394,6 @@ func (doq *dnsOverQUIC) closeConnWithError(err error) {
doq.conn = nil
}
// readMsg reads the incoming DNS message from the QUIC stream.
func (doq *dnsOverQUIC) readMsg(stream *quic.Stream) (m *D.Msg, err error) {
respBuf := pool.Get(MaxMsgSize)
defer pool.Put(respBuf)
n, err := stream.Read(respBuf)
if err != nil && n == 0 {
return nil, fmt.Errorf("reading response from %s: %w", doq.Address(), err)
}
// All DNS messages (queries and responses) sent over DoQ connections MUST
// be encoded as a 2-octet length field followed by the message content as
// specified in [RFC1035].
// IMPORTANT: Note, that we ignore this prefix here as this implementation
// does not support receiving multiple messages over a single connection.
m = new(D.Msg)
err = m.Unpack(respBuf[2:])
if err != nil {
return nil, fmt.Errorf("unpacking response from %s: %w", doq.Address(), err)
}
return m, nil
}
// newQUICTokenStore creates a new quic.TokenStore that is necessary to have
// in order to benefit from 0-RTT.
func newQUICTokenStore() (s quic.TokenStore) {
+2
View File
@@ -10,6 +10,7 @@ import (
)
type ResolverEnhancer struct {
ipv6 bool
mode C.DNSMode
fakeIPPool *fakeip.Pool
fakeIPPool6 *fakeip.Pool
@@ -169,6 +170,7 @@ type EnhancerConfig struct {
func NewEnhancer(cfg EnhancerConfig) *ResolverEnhancer {
e := &ResolverEnhancer{
ipv6: cfg.IPv6,
mode: cfg.EnhancedMode,
useHosts: cfg.UseHosts,
}
+4 -4
View File
@@ -196,14 +196,14 @@ func withFakeIP(skipper *fakeip.Skipper, fakePool *fakeip.Pool, fakePool6 *fakei
}
}
func withResolver(resolver *Resolver) handler {
func withResolver(resolver resolver.Resolver, ipv6 bool) handler {
return func(ctx *icontext.DNSContext, r *D.Msg) (*D.Msg, error) {
ctx.SetType(icontext.DNSTypeRaw)
q := r.Question[0]
// return a empty AAAA msg when ipv6 disabled
if !resolver.ipv6 && q.Qtype == D.TypeAAAA {
if !ipv6 && q.Qtype == D.TypeAAAA {
return handleMsgWithEmptyAnswer(r), nil
}
@@ -230,7 +230,7 @@ func compose(middlewares []middleware, endpoint handler) handler {
return h
}
func newHandler(resolver *Resolver, mapper *ResolverEnhancer) handler {
func newHandler(resolver resolver.Resolver, mapper *ResolverEnhancer) handler {
var middlewares []middleware
if mapper.useHosts {
@@ -245,5 +245,5 @@ func newHandler(resolver *Resolver, mapper *ResolverEnhancer) handler {
middlewares = append(middlewares, withMapping(mapper.mapping))
}
return compose(middlewares, withResolver(resolver))
return compose(middlewares, withResolver(resolver, mapper.ipv6))
}
+1 -1
View File
@@ -24,6 +24,6 @@ func (s *Service) ServeMsg(ctx context.Context, msg *D.Msg) (*D.Msg, error) {
var _ resolver.Service = (*Service)(nil)
func NewService(resolver *Resolver, mapper *ResolverEnhancer) *Service {
func NewService(resolver resolver.Resolver, mapper *ResolverEnhancer) *Service {
return &Service{handler: newHandler(resolver, mapper)}
}
+59 -14
View File
@@ -394,13 +394,14 @@ proxies: # socks5
# ip-version: dual
# Snell
# Beware that there's currently no UDP support yet
- name: "snell"
type: snell
server: server
port: 44046
psk: yourpsk
# version: 2
# version: 4 # support 1/2/3/4/5
# udp: true # support UDP on version 3/4/5
# reuse: false # v4/5 only
# obfs-opts:
# mode: http # or tls
# host: bing.com
@@ -1054,8 +1055,10 @@ proxies: # socks5
# down: "200 Mbps" # 若不写单位,默认为 Mbps
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
password: yourpassword
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前仅支持 salamander
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前支持 salamander 和 gecko
# obfs-password: yourpassword
# obfs-min-packet-size: 512 # 最小线上数据包大小(字节)。仅限 Gecko。
# obfs-max-packet-size: 1200 # 最大线上数据包大小(字节)。仅限 Gecko。
# sni: server.com
# ech-opts:
# enable: true # 必须手动开启
@@ -1169,8 +1172,9 @@ proxies: # socks5
port: 1194
proto: udp # udp/tcp,默认 udp
# dev: tun # 目前仅支持 tun,默认 tun
# cipher: AES-128-GCM # 支持 AES-128-GCM / AES-256-GCM,默认 AES-128-GCM
# auth: SHA256 # 目前仅支持 SHA256,默认 SHA256
# cipher: AES-128-GCM # 支持 AES-128-GCM / AES-192-GCM / AES-256-GCM / AES-128-CBC / AES-192-CBC / AES-256-CBC / CHACHA20-POLY1305,默认 AES-128-GCM;AES-CBC 会按 AES-128-CBC 处理
# auth: SHA256 # 支持 MD5 / SHA1 / SHA256 / SHA384 / SHA512,默认 SHA256;AEAD cipher 会忽略 auth
# comp-lzo: "no" # 可选值:"yes", "no", "adaptive"
# username / password: auth-user-pass 模式(与下方 cert+key 二选一,不能都不填)
# username: "user"
# password: "pass"
@@ -1189,12 +1193,14 @@ proxies: # socks5
-----BEGIN PRIVATE KEY-----
MIIE...example
-----END PRIVATE KEY-----
# 从 .ovpn 中复制 <tls-crypt></tls-crypt> 内的内容,不需要保留 <tls-crypt> 标签
tls-crypt: |
-----BEGIN OpenVPN Static key V1-----
00000000000000000000000000000000
...
-----END OpenVPN Static key V1-----
# 从 .ovpn 中复制 <tls-crypt></tls-crypt> 内的内容,不需要保留 <tls-crypt> 标签;没有 tls-crypt 的配置可省略
# tls-crypt: |
# -----BEGIN OpenVPN Static key V1-----
# 00000000000000000000000000000000
# ...
# -----END OpenVPN Static key V1-----
# ping: 10 # 默认值为 0
# ping-restart: 60 # 默认值为 0
# mtu: 1500
udp: true
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
@@ -1453,6 +1459,7 @@ proxy-groups:
proxies:
- Proxy
- DIRECT
# empty-fallback: COMPATIBLE # 设置当组为空时的回退proxy
# Mihomo 格式的节点或支持 *ray 的分享格式
proxy-providers:
@@ -1463,6 +1470,22 @@ proxy-providers:
path: ./provider1.yaml # 默认只允许存储在 mihomo 的 Home Dir,如果想存储到其他位置,请通过设置 SAFE_PATHS 环境变量指定额外的安全路径。该环境变量的语法同本操作系统的PATH环境变量解析规则(即Windows下以分号分割,其他系统下以冒号分割)
proxy: DIRECT
# size-limit: 10240 # 限制下载文件最大为10kb,默认为0即不限制文件大小
# #
# # 如果设置会age-secret-key尝试通过此secret解密age armor格式加密的配置文件
# #
# # 注意:
# # 对于加密内容,目前仅支持 age-encryption.org/v1 的 official ASCII "armor" format
# # 对于key格式,目前仅支持 age-encryption.org/v1 的 x25519 recipient type 和 The mlkem768-x25519 hybrid post-quantum recipient type
# # 实用工具:
# # 您可以通过 "mihomo age keygen" 生成符合要求的 x25519 key
# # 您可以通过 "mihomo age keygen-pq" 生成符合要求的 mlkem768-x25519 key
# # 您可以通过 "mihomo age convert <secret_key>" 从 age-secret-key 导出 age-public-key
# # 您可以通过 "mihomo age decrypt <secret_key> <source_file> <target_file>" 将已加密文件解密,<source_file> 为 - 时会从标准输入读取,<target_file> 为 - 时会往标准输出写入
# # 您可以通过 "mihomo age encrypt <public_key> <source_file> <target_file>" 将未加密文件加密,<source_file> 为 - 时会从标准输入读取,<target_file> 为 - 时会往标准输出写入
# # 参考实现:
# # https://github.com/FiloSottile/awesome-age#implementations
# #
# age-secret-key: AGE-SECRET-KEY-1ZTQLLN0A4U3ZTT3DCZKYN0CGZEZQLWX2DFTXUWMT4ZHR0N2UG6LSW9NT0N
header:
User-Agent:
- "Clash/v1.18.0"
@@ -1471,6 +1494,8 @@ proxy-providers:
# - 'application/vnd.github.v3.raw'
# Authorization:
# - 'token 1231231'
# X-Age-Public-Key:
# - 'age1xh86kh9v23vattr58yedspm3f57sxvnswu9krr6ns438amekx5gsd09uma'
health-check:
enable: true
interval: 600
@@ -1545,6 +1570,7 @@ rule-providers:
format: mrs
behavior: domain
path: /path/to/save/file.mrs
# path-in-bundle: "geo/geosite/cn.mrs" # 当设置该选项时,如果本地文件不存在,会优先从 Home Dir的 BundleMRS.7z 中解压该文件,此项的值用于指定在 BundleMRS.7z 中的路径
rule4:
type: inline
behavior: domain # classical / ipcidr
@@ -1725,6 +1751,19 @@ listeners:
# streambuf: 2097152 # per stream receive buffer in bytes, smux v2+
# keepalive: 10 # seconds between heartbeats
- name: snell-in-1
type: snell
port: 10815 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
psk: your-password
version: 4 # 仅支持 4/5
udp: true # UDP over TCP tunnel,默认 true
# obfs-opts:
# mode: http # 可选:http / tls
# host: bing.com
# rule: sub-rule-name1
# proxy: proxy
- name: vmess-in-1
type: vmess
port: 10814 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
@@ -1887,7 +1926,8 @@ listeners:
after-bytes: 0 # 传输指定字节后开始限速
bytes-per-sec: 0 # 基准速率(字节/秒)
burst-bytes-per-sec: 0 # 突发速率(字节/秒),大于 bytesPerSec 时生效
### 注意,对于vless listener, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “decryption” 的其中一项 ###
### 注意,对于vless listener, 如果 "allow-insecure" 不为 true, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “decryption” 的其中一项 ###
# allow-insecure: false # 是否允许不开启tls加密(注意:仅用于有 nginx, caddy 前置的情况)
- name: anytls-in-1
type: anytls
@@ -1909,6 +1949,8 @@ listeners:
# madSJjYQIf9o1N5GXjkW4DEEeb17qMxHdwMdNnwADAABAAEAAQACAAEAAwAIdGVz
# dC5jb20AAA==
# -----END ECH KEYS-----
### 注意,anytls listener, 如果 "allow-insecure" 不为 true, 必须填写 “certificate和private-key” ###
# allow-insecure: false # 是否允许不开启tls加密(注意:仅用于有 nginx, caddy 前置的情况)
# padding-scheme: "" # https://github.com/anytls/anytls-go/blob/main/docs/protocol.md#cmdupdatepaddingscheme
- name: mieru-in-1
@@ -1993,7 +2035,8 @@ listeners:
# enabled: false
# method: aes-128-gcm # aes-128-gcm/aes-256-gcm/chacha20-ietf-poly1305
# password: "example"
### 注意,对于trojan listener, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “ss-option” 的其中一项 ###
### 注意,对于trojan listener, 如果 "allow-insecure" 不为 true, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “ss-option” 的其中一项 ###
# allow-insecure: false # 是否允许不开启tls加密(注意:仅用于有 nginx, caddy 前置的情况)
- name: hysteria2-in-1
type: hysteria2
@@ -2019,8 +2062,10 @@ listeners:
## up 和 down 均不写或为 0 则使用 BBR 流控
# up: "30 Mbps" # 若不写单位,默认为 Mbps
# down: "200 Mbps" # 若不写单位,默认为 Mbps
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前仅支持 salamander
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前支持 salamander 和 gecko
# obfs-password: yourpassword
# obfs-min-packet-size: 512 # 最小线上数据包大小(字节)。仅限 Gecko。
# obfs-max-packet-size: 1200 # 最大线上数据包大小(字节)。仅限 Gecko。
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
# max-idle-time: 15000
# alpn:
+20 -12
View File
@@ -6,10 +6,11 @@ require (
github.com/bahlo/generic-list-go v0.2.0
github.com/coreos/go-iptables v0.8.0
github.com/dlclark/regexp2 v1.12.0
github.com/enfein/mieru/v3 v3.31.0
github.com/enfein/mieru/v3 v3.33.0
github.com/gobwas/ws v1.4.0
github.com/gofrs/uuid/v5 v5.4.0
github.com/golang/snappy v1.0.0
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d
github.com/metacubex/bart v0.26.0
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b
@@ -25,27 +26,29 @@ require (
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604
github.com/metacubex/mhurl v0.1.0
github.com/metacubex/mlkem v0.1.0
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306
github.com/metacubex/quic-go v0.59.1-0.20260520020949-fcd18c7b6ace
github.com/metacubex/randv2 v0.2.0
github.com/metacubex/restls-client-go v0.1.7
github.com/metacubex/sevenzip v1.6.4
github.com/metacubex/sing v0.5.7
github.com/metacubex/sing-mux v0.3.9
github.com/metacubex/sing-quic v0.0.0-20260512151354-8475655be853
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3
github.com/metacubex/sing-shadowsocks v0.2.12
github.com/metacubex/sing-shadowsocks2 v0.2.7
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2
github.com/metacubex/sing-tun v0.4.18
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc
github.com/metacubex/sing-tun v0.4.20
github.com/metacubex/sing-vmess v0.2.5
github.com/metacubex/sing-wireguard v0.0.0-20260507084707-690d479ec947
github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141
github.com/metacubex/ssh v0.1.0
github.com/metacubex/tailscale v0.0.0-20260516120020-a21c2c99dcbe
github.com/metacubex/tailscale v0.0.0-20260520011538-f23132fac4b7
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443
github.com/metacubex/tls v0.1.5
github.com/metacubex/tls v0.1.6
github.com/metacubex/utls v1.8.4
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f
github.com/mroth/weightedrand/v2 v2.1.0
github.com/openacid/low v0.1.21
github.com/rasky/go-lzo v0.0.0-20200203143853-96a758eda86e
github.com/samber/lo v1.53.0
github.com/sirupsen/logrus v1.9.4
github.com/stretchr/testify v1.11.1
@@ -78,7 +81,9 @@ require (
github.com/ajg/form v1.5.1 // indirect
github.com/akutz/memconn v0.1.0 // indirect
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa // indirect
github.com/andybalholm/brotli v1.0.6 // indirect
github.com/andybalholm/brotli v1.1.1 // indirect
github.com/bodgit/plumbing v1.3.0 // indirect
github.com/bodgit/windows v1.0.1 // indirect
github.com/coder/websocket v1.8.12 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dunglas/httpsfv v1.0.2 // indirect
@@ -97,6 +102,7 @@ require (
github.com/google/btree v1.1.3 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/huin/goupnp v1.3.0 // indirect
github.com/josharian/native v1.1.0 // indirect
github.com/jsimonetti/rtnetlink v1.4.0 // indirect
@@ -108,14 +114,14 @@ require (
github.com/metacubex/gvisor v0.0.0-20251227095601-261ec1326fe8 // indirect
github.com/metacubex/hkdf v0.1.0 // indirect
github.com/metacubex/hpke v0.1.0 // indirect
github.com/metacubex/jsonv2 v0.0.0-20260513175203-1c6abea7534c // indirect
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df // indirect
github.com/metacubex/nftables v0.0.0-20260426003805-208c2c1ba2cb // indirect
github.com/metacubex/qpack v0.6.0 // indirect
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260513233728-8bc7ee255d04 // indirect
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260521124654-e1bf77ef79af // indirect
github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49 // indirect
github.com/mitchellh/go-ps v1.0.0 // indirect
github.com/oasisprotocol/deoxysii v0.0.0-20220228165953-2091330c22b7 // indirect
github.com/pierrec/lz4/v4 v4.1.14 // indirect
github.com/pierrec/lz4/v4 v4.1.27 // indirect
github.com/pires/go-proxyproto v0.8.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/safchain/ethtool v0.3.0 // indirect
@@ -123,11 +129,13 @@ require (
github.com/sina-ghaderi/poly1305 v0.0.0-20220724002748-c5926b03988b // indirect
github.com/sina-ghaderi/rabaead v0.0.0-20220730151906-ab6e06b96e8c // indirect
github.com/sina-ghaderi/rabbitio v0.0.0-20220730151941-9ce26f4f872e // indirect
github.com/stangelandcl/ppmd v0.1.1 // indirect
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d // indirect
github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 // indirect
github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a // indirect
github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc // indirect
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 // indirect
github.com/ulikunitz/xz v0.5.15 // indirect
github.com/vishvananda/netns v0.0.5 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
github.com/x448/float16 v0.8.4 // indirect
+48 -23
View File
@@ -9,11 +9,15 @@ github.com/akutz/memconn v0.1.0 h1:NawI0TORU4hcOMsMr11g7vwlCdkYeLKXBcxWu2W/P8A=
github.com/akutz/memconn v0.1.0/go.mod h1:Jo8rI7m0NieZyLI5e2CDlRdRqRRB4S7Xp77ukDjH+Fw=
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI=
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI=
github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk=
github.com/bodgit/plumbing v1.3.0 h1:pf9Itz1JOQgn7vEOE7v7nlEfBykYqvUYioC61TwWCFU=
github.com/bodgit/plumbing v1.3.0/go.mod h1:JOTb4XiRu5xfnmdnDJo6GmSbSbtSyufrsyZFByMtKEs=
github.com/bodgit/windows v1.0.1 h1:tF7K6KOluPYygXa3Z2594zxlkbKPAOvqr97etrGNIz4=
github.com/bodgit/windows v1.0.1/go.mod h1:a6JLwrB4KrTR5hBpp8FI9/9W9jJfeQ2h4XDXU74ZCdM=
github.com/cilium/ebpf v0.12.3 h1:8ht6F9MquybnY97at+VDZb3eQQr8ev79RueWeVaEcG4=
github.com/coder/websocket v1.8.12 h1:5bUXkEPPIbewrnkU8LTCLVaxi4N4J8ahufH2vlo4NAo=
github.com/coder/websocket v1.8.12/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
@@ -27,8 +31,8 @@ github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz
github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dunglas/httpsfv v1.0.2 h1:iERDp/YAfnojSDJ7PW3dj1AReJz4MrwbECSSE59JWL0=
github.com/dunglas/httpsfv v1.0.2/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg=
github.com/enfein/mieru/v3 v3.31.0 h1:Fl2ocRCRXJzMygzdRjBHgqI996ZuIDHUmyQyovSf9sA=
github.com/enfein/mieru/v3 v3.31.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
github.com/enfein/mieru/v3 v3.33.0 h1:hv2jK8nqYHwpSG86U2rpZR2I8Aff1/J3ifRmd9NBbFc=
github.com/enfein/mieru/v3 v3.33.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 h1:kXYqH/sL8dS/FdoFjr12ePjnLPorPo2FsnrHNuXSDyo=
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358/go.mod h1:hkIFzoiIPZYxdFOOLyDho59b7SrDfo+w3h+yWdlg45I=
github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 h1:8j2RH289RJplhA6WfdaPqzg1MjH2K8wX5e0uhAxrw2g=
@@ -69,6 +73,8 @@ github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN
github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8 h1:FKHo8hFI3A+7w0aUQuYXQ+6EN5stWmeY/AZqtM8xk9k=
github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo=
github.com/google/tink/go v1.6.1 h1:t7JHqO8Ath2w2ig5vjwQYJzhGEZymedQc90lQXUBa4I=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc=
github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8=
github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905 h1:q3OEI9RaN/wwcx+qgGo6ZaoJkCiDYe/gjDLfq7lQQF4=
@@ -91,6 +97,8 @@ github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/
github.com/mdlayher/netlink v1.7.2/go.mod h1:xraEF7uJbxLhc5fpHL4cPe221LI2bdttWlU+ZGLfQSw=
github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78 h1:LqWr0vb9zDNuQS+jJd4fnRYk/SEI7KJ7TDe/L4WFK48=
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78/go.mod h1:BTBG/iVY7rg3qq5WdVCg0GFk58CSvCDSbjy8I7kEx/c=
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d h1:vAJ0ZT4aO803F1uw2roIA9yH7Sxzox34tVVyye1bz6c=
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d/go.mod h1:MsM/5czONyXMJ3PRr5DbQ4O/BxzAnJWOIcJdLzW6qHY=
github.com/metacubex/ascon v0.1.0 h1:6ZWxmXYszT1XXtwkf6nxfFhc/OTtQ9R3Vyj1jN32lGM=
@@ -123,8 +131,8 @@ 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.6 h1:xvXuvXMCMxCWMF5nEJF4yiKvXL+p2atWMzs37e80m1I=
github.com/metacubex/http v0.1.6/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
github.com/metacubex/jsonv2 v0.0.0-20260513175203-1c6abea7534c h1:KGhBHDe6FveU0ury+9RyX329nclM1CHODa0Fi+uOAYM=
github.com/metacubex/jsonv2 v0.0.0-20260513175203-1c6abea7534c/go.mod h1:F4sVXat6QjPXkNsKRDyyG3BhSkxPFFnRPEIwmmyCgbg=
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df h1:S0vBzqjXok24VopstOgPd1JdgglW9tXehrqvwpQWbQ8=
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df/go.mod h1:F4sVXat6QjPXkNsKRDyyG3BhSkxPFFnRPEIwmmyCgbg=
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604 h1:hJwCVlE3ojViC35MGHB+FBr8TuIf3BUFn2EQ1VIamsI=
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=
@@ -137,42 +145,44 @@ github.com/metacubex/protobuf-go v0.0.0-20260306035419-7ceee0674686 h1:PIXmYT2an
github.com/metacubex/protobuf-go v0.0.0-20260306035419-7ceee0674686/go.mod h1:eQV7juxFZIdRgjMxtVqP+6BssKoTZQ1RM0fc58BsCZY=
github.com/metacubex/qpack v0.6.0 h1:YqClGIMOpiRYLjV1qOs483Od08MdPgRnHjt90FuaAKw=
github.com/metacubex/qpack v0.6.0/go.mod h1:lKGSi7Xk94IMvHGOmxS9eIei3bvIqpOAImEBsaOwTkA=
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306 h1:HlGLmLsWJMLSu0CMI9z/BmEnithB4oXM5Rom6/0Qxtg=
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306/go.mod h1:oNzMrmylS897M3zSMuapIdwSwfq6F2qW01Z3NhVRJhk=
github.com/metacubex/quic-go v0.59.1-0.20260520020949-fcd18c7b6ace h1:KXacx7dp1GYVMgxezwXRt5BMsEbvAYuA6rPFUmdAvcQ=
github.com/metacubex/quic-go v0.59.1-0.20260520020949-fcd18c7b6ace/go.mod h1:2YEQEvFrZ5V76oynMBDTlN+4fdnSHCa2uNJxv3cm1HU=
github.com/metacubex/randv2 v0.2.0 h1:uP38uBvV2SxYfLj53kuvAjbND4RUDfFJjwr4UigMiLs=
github.com/metacubex/randv2 v0.2.0/go.mod h1:kFi2SzrQ5WuneuoLLCMkABtiBu6VRrMrWFqSPyj2cxY=
github.com/metacubex/restls-client-go v0.1.7 h1:eCwiXCTQb5WJu9IlgYvDBA1OgrINv58dEe7hcN5H15k=
github.com/metacubex/restls-client-go v0.1.7/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.9 h1:/aoBD2+sK2qsXDlNDe3hkR0GZuFDtwIZhOeGUx9W0Yk=
github.com/metacubex/sing-mux v0.3.9/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
github.com/metacubex/sing-quic v0.0.0-20260512151354-8475655be853 h1:nZ5WNU6kjj6kBu4+2eMySFkUVGCop64rZnLMm+HPh8w=
github.com/metacubex/sing-quic v0.0.0-20260512151354-8475655be853/go.mod h1:6ayFGfzzBE85csgQkM3gf4neFq6s0losHlPRSxY+nuk=
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3 h1:PnMby5+kZXTl/CFDHfxMbMTaSRD+uMKMsrDYVQyAmX8=
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3/go.mod h1:6ayFGfzzBE85csgQkM3gf4neFq6s0losHlPRSxY+nuk=
github.com/metacubex/sing-shadowsocks v0.2.12 h1:Wqzo8bYXrK5aWqxu/TjlTnYZzAKtKsaFQBdr6IHFaBE=
github.com/metacubex/sing-shadowsocks v0.2.12/go.mod h1:2e5EIaw0rxKrm1YTRmiMnDulwbGxH9hAFlrwQLQMQkU=
github.com/metacubex/sing-shadowsocks2 v0.2.7 h1:hSuuc0YpsfiqYqt1o+fP4m34BQz4e6wVj3PPBVhor3A=
github.com/metacubex/sing-shadowsocks2 v0.2.7/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE=
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2 h1:gXU+MYPm7Wme3/OAY2FFzVq9d9GxPHOqu5AQfg/ddhI=
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2/go.mod h1:mbfboaXauKJNIHJYxQRa+NJs4JU9NZfkA+I33dS2+9E=
github.com/metacubex/sing-tun v0.4.18 h1:WRzAosG0YkT3aZq5RJWtF+RdCgeJ8EpooS5ZM1lkXo0=
github.com/metacubex/sing-tun v0.4.18/go.mod h1:g4I/JNplDBhXLF+aQWgFbhNeJPSXQOWS9HvLeNvkgeA=
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc h1:8wLoFfYQ88iGPL+krQ5tJsI8IAmkFjKpQL2q+y3pvss=
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc/go.mod h1:mbfboaXauKJNIHJYxQRa+NJs4JU9NZfkA+I33dS2+9E=
github.com/metacubex/sing-tun v0.4.20 h1:xdupzizRoZKyDzP0l68WAx5Sk4ooiuT1GiWsiJyOGPw=
github.com/metacubex/sing-tun v0.4.20/go.mod h1:g4I/JNplDBhXLF+aQWgFbhNeJPSXQOWS9HvLeNvkgeA=
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-20260507084707-690d479ec947 h1:IB03BvRQtvjWScyOK5jSQVJYY8osmZXHL+4VCEFMWcM=
github.com/metacubex/sing-wireguard v0.0.0-20260507084707-690d479ec947/go.mod h1:jpAkVLPnCpGSfNyVmj6Cq4YbuZsFepm/Dc+9BAOcR80=
github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c h1:tH9FuQW357zp2xAGzkoZTGpNGMVmEFZov0iV5M2S5ew=
github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c/go.mod h1:eQZDJTx+IH3k4mXqaOJ3VJ9h9ZqOl60F7TLi5wAU51Q=
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141 h1:DK2l6m2Fc85H2BhiAPgbJygiWhesPlfGmF+9Vw6ARdk=
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141/go.mod h1:/yI4OiGOSn0SURhZdJF3CbtPg3nwK700bG8TZLMBvAg=
github.com/metacubex/ssh v0.1.0 h1:iGfr99qk/eMHzUnQ/0bTxXT8+8SWqLSHBWDHoAhngzw=
github.com/metacubex/ssh v0.1.0/go.mod h1:NUtl0d+/f2cG9ECEpMM8iCVOpmggQlC13oLeDUONDlU=
github.com/metacubex/tailscale v0.0.0-20260516120020-a21c2c99dcbe h1:ZdAKshacNruZGuKTE8WMTuxyGgpv/LySLoE/EEmgF9c=
github.com/metacubex/tailscale v0.0.0-20260516120020-a21c2c99dcbe/go.mod h1:2G1V82OGXgxT7m7046GA80I9SlcvczljCK0C7NQ3c10=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260513233728-8bc7ee255d04 h1:zk+mDDSBl5lv80WWtaFUbpj8XLb7AhjCUbn2pB37N0U=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260513233728-8bc7ee255d04/go.mod h1:pKUKBy7IcQ5r0i66gWENHgxKvBn8tlgAGx0DZMq8h5M=
github.com/metacubex/tailscale v0.0.0-20260520011538-f23132fac4b7 h1:LoJR4NMyNKHeEJoeGDtcsao7sV0NRkzMeV5H/0J0MIE=
github.com/metacubex/tailscale v0.0.0-20260520011538-f23132fac4b7/go.mod h1:MAo3HhE7968rIwmDvYTYE8xCsV4x+hLnkChdXeP3X4c=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260521124654-e1bf77ef79af h1:c60IbBMUq2h1M2m7+grMJJmBmrObxL8SwvNtm6Ozbwk=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260521124654-e1bf77ef79af/go.mod h1:i3zLKytWkOnyT1i9OmiLevWvrN5J5HE1+yjE7UYNfcQ=
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443 h1:H6TnfM12tOoTizYE/qBHH3nEuibIelmHI+BVSxVJr8o=
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443/go.mod h1:l9oLnLoEXyGZ5RVLsh7QCC5XsouTUyKk4F2nLm2DHLw=
github.com/metacubex/tls v0.1.5 h1:ECcB83dj+zadnhlKcLnUUf1Sq6+vU0f/zoyU0+9oPTc=
github.com/metacubex/tls v0.1.5/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
github.com/metacubex/tls v0.1.6 h1:t2ubLneYa4ceyIC++54a57BLqZFA/QYUrhdjLk2GPwo=
github.com/metacubex/tls v0.1.6/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
github.com/metacubex/utls v1.8.4 h1:HmL9nUApDdWSkgUyodfwF6hSjtiwCGGdyhaSpEejKpg=
github.com/metacubex/utls v1.8.4/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f h1:FGBPRb1zUabhPhDrlKEjQ9lgIwQ6cHL4x8M9lrERhbk=
@@ -194,14 +204,17 @@ github.com/openacid/must v0.1.3/go.mod h1:luPiXCuJlEo3UUFQngVQokV0MPGryeYvtCbQPs
github.com/openacid/testkeys v0.1.6/go.mod h1:MfA7cACzBpbiwekivj8StqX0WIRmqlMsci1c37CA3Do=
github.com/oschwald/maxminddb-golang v1.12.0 h1:9FnTOD0YOhP7DGxGsq4glzpGy5+w7pq50AS6wALUMYs=
github.com/oschwald/maxminddb-golang v1.12.0/go.mod h1:q0Nob5lTCqyQ8WT6FYgS1L7PXKVVbgiymefNwIjPzgY=
github.com/pierrec/lz4/v4 v4.1.14 h1:+fL8AQEZtz/ijeNnpduH0bROTu0O3NZAlPjQxGn8LwE=
github.com/pierrec/lz4/v4 v4.1.14/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
github.com/pierrec/lz4/v4 v4.1.27 h1:+PhzhWDrjRj89TH2sw43nE3+4+W8lSxIuQadEHZyjUk=
github.com/pierrec/lz4/v4 v4.1.27/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
github.com/pires/go-proxyproto v0.8.0 h1:5unRmEAPbHXHuLjDg01CxJWf91cw3lKHc/0xzKpXEe0=
github.com/pires/go-proxyproto v0.8.0/go.mod h1:iknsfgnH8EkjrMeMyvfKByp9TiBZCKZM0jx2xmKqnVY=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g=
github.com/rasky/go-lzo v0.0.0-20200203143853-96a758eda86e h1:dCWirM5F3wMY+cmRda/B1BiPsFtmzXqV9b0hLWtVBMs=
github.com/rasky/go-lzo v0.0.0-20200203143853-96a758eda86e/go.mod h1:9leZcVcItj6m9/CfHY5Em/iBrCz7js8LcRQGTKEEv2M=
github.com/safchain/ethtool v0.3.0 h1:gimQJpsI6sc1yIqP/y8GYgiXn/NjgvpM0RNoWLVVmP0=
github.com/safchain/ethtool v0.3.0/go.mod h1:SA9BwrgyAqNo7M+uaL6IYbxpm5wk3L7Mm6ocLW+CJUs=
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a h1:ObwtHN2VpqE0ZNjr6sGeT00J8uU7JF4cNUdb44/Duis=
@@ -216,10 +229,18 @@ github.com/sina-ghaderi/rabbitio v0.0.0-20220730151941-9ce26f4f872e h1:ur8uMsPIF
github.com/sina-ghaderi/rabbitio v0.0.0-20220730151941-9ce26f4f872e/go.mod h1:+e5fBW3bpPyo+3uLo513gIUblc03egGjMM0+5GKbzK8=
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
github.com/stangelandcl/ppmd v0.1.1 h1:c25QazhlWUn5nmR1QOzafKhQxBicAr7GGCKER2aJ8H8=
github.com/stangelandcl/ppmd v0.1.1/go.mod h1:Rrv7M+/2P5jYr/GMLhBl7Ug3uJ1bUiVzr5LbbaV6xgY=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d h1:JcGKBZAL7ePLwOhUdN8qGQZlP5GueEiIZwY7R62pejE=
@@ -232,6 +253,8 @@ github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc h1:24heQPtnFR+y
github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc/go.mod h1:f93CXfllFsO9ZQVq+Zocb1Gp4G5Fz0b0rXHLOzt/Djc=
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 h1:tHNk7XK9GkmKUR6Gh8gVBKXc2MVSZ4G/NnWLtzw4gNA=
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923/go.mod h1:eLL9Nub3yfAho7qB0MzZizFhTU2QkLeoVsWdHtDW264=
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE=
github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU=
github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0=
@@ -244,6 +267,8 @@ github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
gitlab.com/go-extension/aes-ccm v0.0.0-20230221065045-e58665ef23c7 h1:UNrDfkQqiEYzdMlNsVvBYOAJWZjdktqFE9tQh5BT2+4=
+16 -22
View File
@@ -26,7 +26,6 @@ import (
"github.com/metacubex/mihomo/component/resolver"
"github.com/metacubex/mihomo/component/resource"
"github.com/metacubex/mihomo/component/sniffer"
tlsC "github.com/metacubex/mihomo/component/tls"
"github.com/metacubex/mihomo/component/trie"
"github.com/metacubex/mihomo/component/updater"
"github.com/metacubex/mihomo/config"
@@ -166,20 +165,19 @@ func GetGeneral() *config.General {
ASN: geodata.ASNUrl(),
GeoSite: geodata.GeoSiteUrl(),
},
GeoAutoUpdate: updater.GeoAutoUpdate(),
GeoUpdateInterval: updater.GeoUpdateInterval(),
GeodataMode: geodata.GeodataMode(),
GeodataLoader: geodata.LoaderName(),
GeositeMatcher: geodata.SiteMatcherName(),
TCPConcurrent: dialer.GetTcpConcurrent(),
FindProcessMode: tunnel.FindProcessMode(),
Sniffing: tunnel.IsSniffing(),
GlobalClientFingerprint: tlsC.GetGlobalFingerprint(),
GlobalUA: mihomoHttp.UA(),
ETagSupport: resource.ETag(),
KeepAliveInterval: int(keepalive.KeepAliveInterval() / time.Second),
KeepAliveIdle: int(keepalive.KeepAliveIdle() / time.Second),
DisableKeepAlive: keepalive.DisableKeepAlive(),
GeoAutoUpdate: updater.GeoAutoUpdate(),
GeoUpdateInterval: updater.GeoUpdateInterval(),
GeodataMode: geodata.GeodataMode(),
GeodataLoader: geodata.LoaderName(),
GeositeMatcher: geodata.SiteMatcherName(),
TCPConcurrent: dialer.GetTcpConcurrent(),
FindProcessMode: tunnel.FindProcessMode(),
Sniffing: tunnel.IsSniffing(),
GlobalUA: mihomoHttp.UA(),
ETagSupport: resource.ETag(),
KeepAliveInterval: int(keepalive.KeepAliveInterval() / time.Second),
KeepAliveIdle: int(keepalive.KeepAliveIdle() / time.Second),
DisableKeepAlive: keepalive.DisableKeepAlive(),
}
return general
@@ -229,10 +227,11 @@ func updateNTP(c *config.NTP) {
net.JoinHostPort(c.Server, strconv.Itoa(c.Port)),
time.Duration(c.Interval),
c.DialerProxy,
tunnel.Tunnel,
c.WriteToSystem,
)
} else {
ntp.ReCreateNTPService("", 0, "", false)
ntp.ReCreateNTPService("", 0, "", nil, false)
}
}
@@ -279,7 +278,7 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
m.PatchFrom(old.(*dns.ResolverEnhancer))
}
s := dns.NewService(r.Resolver, m)
s := dns.NewService(r, m)
resolver.DefaultResolver = r
resolver.DefaultHostMapper = m
@@ -424,11 +423,6 @@ func updateGeneral(general *config.General, logging bool) {
geodata.SetASNUrl(general.GeoXUrl.ASN)
mihomoHttp.SetUA(general.GlobalUA)
resource.SetETag(general.ETagSupport)
if general.GlobalClientFingerprint != "" {
log.Warnln("The `global-client-fingerprint` configuration is deprecated, please set `client-fingerprint` directly on the proxy instead")
}
tlsC.SetGlobalFingerprint(general.GlobalClientFingerprint)
}
func updateUsers(users []auth.AuthUser) {
+2 -2
View File
@@ -112,8 +112,8 @@ func New(config LC.AnyTLSServer, tunnel C.Tunnel, additions ...inbound.Addition)
}
if tlsConfig.GetCertificate != nil {
l = tls.NewListener(l, tlsConfig)
} else {
return nil, errors.New("disallow using AnyTLS without certificates config")
} else if !config.AllowInsecure {
return nil, errors.New("disallow using AnyTLS without certificates/allow-insecure config")
}
sl.listeners = append(sl.listeners, l)
+2 -1
View File
@@ -12,7 +12,8 @@ type AnyTLSServer struct {
PrivateKey string `yaml:"private-key" json:"private-key"`
ClientAuthType string `yaml:"client-auth-type" json:"client-auth-type,omitempty"`
ClientAuthCert string `yaml:"client-auth-cert" json:"client-auth-cert,omitempty"`
EchKey string `yaml:"ech-key" json:"ech-key"`
EchKey string `yaml:"ech-key" json:"ech-key,omitempty"`
AllowInsecure bool `yaml:"allow-insecure" json:"allow-insecure,omitempty"`
PaddingScheme string `yaml:"padding-scheme" json:"padding-scheme,omitempty"`
}
+2
View File
@@ -12,6 +12,8 @@ type Hysteria2Server struct {
Users map[string]string `yaml:"users" json:"users,omitempty"`
Obfs string `yaml:"obfs" json:"obfs,omitempty"`
ObfsPassword string `yaml:"obfs-password" json:"obfs-password,omitempty"`
ObfsMinPacketSize int `yaml:"obfs-min-packet-size" json:"obfs-min-packet-size,omitempty"`
ObfsMaxPacketSize int `yaml:"obfs-max-packet-size" json:"obfs-max-packet-size,omitempty"`
Certificate string `yaml:"certificate" json:"certificate"`
PrivateKey string `yaml:"private-key" json:"private-key"`
ClientAuthType string `yaml:"client-auth-type" json:"client-auth-type,omitempty"`
+1
View File
@@ -23,6 +23,7 @@ type TrojanServer struct {
ClientAuthType string
ClientAuthCert string
EchKey string
AllowInsecure bool
RealityConfig reality.Config
MuxOption sing.MuxOption
TrojanSSOption TrojanSSOption
+1
View File
@@ -26,6 +26,7 @@ type VlessServer struct {
ClientAuthType string
ClientAuthCert string
EchKey string
AllowInsecure bool
RealityConfig reality.Config
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
}
+2
View File
@@ -17,6 +17,7 @@ type AnyTLSOption struct {
ClientAuthType string `inbound:"client-auth-type,omitempty"`
ClientAuthCert string `inbound:"client-auth-cert,omitempty"`
EchKey string `inbound:"ech-key,omitempty"`
AllowInsecure bool `inbound:"allow-insecure,omitempty"`
PaddingScheme string `inbound:"padding-scheme,omitempty"`
}
@@ -48,6 +49,7 @@ func NewAnyTLS(options *AnyTLSOption) (*AnyTLS, error) {
ClientAuthType: options.ClientAuthType,
ClientAuthCert: options.ClientAuthCert,
EchKey: options.EchKey,
AllowInsecure: options.AllowInsecure,
PaddingScheme: options.PaddingScheme,
},
}, nil
+4
View File
@@ -14,6 +14,8 @@ type Hysteria2Option struct {
Users map[string]string `inbound:"users,omitempty"`
Obfs string `inbound:"obfs,omitempty"`
ObfsPassword string `inbound:"obfs-password,omitempty"`
ObfsMinPacketSize int `inbound:"obfs-min-packet-size,omitempty"`
ObfsMaxPacketSize int `inbound:"obfs-max-packet-size,omitempty"`
Certificate string `inbound:"certificate"`
PrivateKey string `inbound:"private-key"`
ClientAuthType string `inbound:"client-auth-type,omitempty"`
@@ -98,6 +100,8 @@ func NewHysteria2(options *Hysteria2Option) (*Hysteria2, error) {
Users: options.Users,
Obfs: options.Obfs,
ObfsPassword: options.ObfsPassword,
ObfsMinPacketSize: options.ObfsMinPacketSize,
ObfsMaxPacketSize: options.ObfsMaxPacketSize,
Certificate: options.Certificate,
PrivateKey: options.PrivateKey,
ClientAuthType: options.ClientAuthType,
+15
View File
@@ -114,6 +114,21 @@ func TestInboundHysteria2_Salamander(t *testing.T) {
testInboundHysteria2TLS(t, inboundOptions, outboundOptions)
}
func TestInboundHysteria2_Gecko(t *testing.T) {
inboundOptions := inbound.Hysteria2Option{
Certificate: tlsCertificate,
PrivateKey: tlsPrivateKey,
Obfs: "gecko",
ObfsPassword: userUUID,
}
outboundOptions := outbound.Hysteria2Option{
Fingerprint: tlsFingerprint,
Obfs: "gecko",
ObfsPassword: userUUID,
}
testInboundHysteria2TLS(t, inboundOptions, outboundOptions)
}
func TestInboundHysteria2_Brutal(t *testing.T) {
inboundOptions := inbound.Hysteria2Option{
Certificate: tlsCertificate,
+90
View File
@@ -0,0 +1,90 @@
package inbound
import (
"fmt"
"strings"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/listener/snell"
"github.com/metacubex/mihomo/log"
)
type SnellOption struct {
BaseOption
Psk string `inbound:"psk"`
Version int `inbound:"version,omitempty"`
UDP bool `inbound:"udp,omitempty"`
ObfsOpts SnellObfsOption `inbound:"obfs-opts,omitempty"`
}
func (o SnellOption) Equal(config C.InboundConfig) bool {
return optionToString(o) == optionToString(config)
}
type SnellObfsOption struct {
Mode string `obfs:"mode,omitempty"`
Host string `obfs:"host,omitempty"`
}
type Snell struct {
*Base
config *SnellOption
l C.MultiAddrListener
snell snell.Config
}
func NewSnell(options *SnellOption) (*Snell, error) {
base, err := NewBase(&options.BaseOption)
if err != nil {
return nil, err
}
if options.Version == 0 {
options.Version = 4
}
if options.Version != 4 && options.Version != 5 {
return nil, fmt.Errorf("snell inbound version %d is not supported", options.Version)
}
return &Snell{
Base: base,
config: options,
snell: snell.Config{
Listen: base.RawAddress(),
Psk: options.Psk,
Version: options.Version,
UDP: options.UDP,
ObfsMode: options.ObfsOpts.Mode,
ObfsHost: options.ObfsOpts.Host,
},
}, nil
}
func (s *Snell) Config() C.InboundConfig {
return s.config
}
func (s *Snell) Address() string {
var addrList []string
if s.l != nil {
for _, addr := range s.l.AddrList() {
addrList = append(addrList, addr.String())
}
}
return strings.Join(addrList, ",")
}
func (s *Snell) Listen(tunnel C.Tunnel) error {
var err error
s.l, err = snell.New(s.snell, tunnel, s.Additions()...)
if err != nil {
return err
}
log.Infoln("Snell[%s] inbound listening at: %s", s.Name(), s.Address())
return nil
}
func (s *Snell) Close() error {
return s.l.Close()
}
var _ C.InboundListener = (*Snell)(nil)
+72
View File
@@ -0,0 +1,72 @@
package inbound_test
import (
"net/netip"
"testing"
"github.com/metacubex/mihomo/adapter/outbound"
"github.com/metacubex/mihomo/listener/inbound"
"github.com/stretchr/testify/assert"
)
func testInboundSnell(t *testing.T, inboundOptions inbound.SnellOption, outboundOptions outbound.SnellOption) {
t.Parallel()
inboundOptions.BaseOption = inbound.BaseOption{
NameStr: "snell_inbound",
Listen: "127.0.0.1",
Port: "0",
}
inboundOptions.Psk = userUUID
in, err := inbound.NewSnell(&inboundOptions)
if !assert.NoError(t, err) {
return
}
tunnel := NewHttpTestTunnel()
defer tunnel.Close()
err = in.Listen(tunnel)
if !assert.NoError(t, err) {
return
}
defer in.Close()
addrPort, err := netip.ParseAddrPort(in.Address())
if !assert.NoError(t, err) {
return
}
outboundOptions.Name = "snell_outbound"
outboundOptions.Server = addrPort.Addr().String()
outboundOptions.Port = int(addrPort.Port())
outboundOptions.Psk = userUUID
outboundOptions.DialerForAPI = tunnel.NewDialer()
outboundOptions.TunnelForAPI = tunnel
out, err := outbound.NewSnell(outboundOptions)
if !assert.NoError(t, err) {
return
}
defer out.Close()
tunnel.DoTest(t, out)
}
func TestInboundSnell(t *testing.T) {
testCase := []struct {
name string
version int
}{
{"v4", 4},
{"v5", 5},
}
for _, tc := range testCase {
tc := tc
t.Run(tc.name, func(t *testing.T) {
inboundOptions := inbound.SnellOption{Version: tc.version}
outboundOptions := outbound.SnellOption{Version: tc.version}
testInboundSnell(t, inboundOptions, outboundOptions)
})
}
}
+2
View File
@@ -19,6 +19,7 @@ type TrojanOption struct {
ClientAuthType string `inbound:"client-auth-type,omitempty"`
ClientAuthCert string `inbound:"client-auth-cert,omitempty"`
EchKey string `inbound:"ech-key,omitempty"`
AllowInsecure bool `inbound:"allow-insecure,omitempty"`
RealityConfig RealityConfig `inbound:"reality-config,omitempty"`
MuxOption MuxOption `inbound:"mux-option,omitempty"`
SSOption TrojanSSOption `inbound:"ss-option,omitempty"`
@@ -73,6 +74,7 @@ func NewTrojan(options *TrojanOption) (*Trojan, error) {
ClientAuthType: options.ClientAuthType,
ClientAuthCert: options.ClientAuthCert,
EchKey: options.EchKey,
AllowInsecure: options.AllowInsecure,
RealityConfig: options.RealityConfig.Build(),
MuxOption: options.MuxOption.Build(),
TrojanSSOption: LC.TrojanSSOption{
+3
View File
@@ -21,6 +21,7 @@ type VlessOption struct {
ClientAuthType string `inbound:"client-auth-type,omitempty"`
ClientAuthCert string `inbound:"client-auth-cert,omitempty"`
EchKey string `inbound:"ech-key,omitempty"`
AllowInsecure bool `inbound:"allow-insecure,omitempty"`
RealityConfig RealityConfig `inbound:"reality-config,omitempty"`
MuxOption MuxOption `inbound:"mux-option,omitempty"`
}
@@ -66,6 +67,7 @@ func (o XHTTPConfig) Build() LC.XHTTPConfig {
XPaddingKey: o.XPaddingKey,
XPaddingHeader: o.XPaddingHeader,
XPaddingPlacement: o.XPaddingPlacement,
XPaddingMethod: o.XPaddingMethod,
UplinkHTTPMethod: o.UplinkHTTPMethod,
SessionPlacement: o.SessionPlacement,
SessionKey: o.SessionKey,
@@ -120,6 +122,7 @@ func NewVless(options *VlessOption) (*Vless, error) {
ClientAuthType: options.ClientAuthType,
ClientAuthCert: options.ClientAuthCert,
EchKey: options.EchKey,
AllowInsecure: options.AllowInsecure,
RealityConfig: options.RealityConfig.Build(),
MuxOption: options.MuxOption.Build(),
},
+7
View File
@@ -79,6 +79,13 @@ func ParseListener(mapping map[string]any) (C.InboundListener, error) {
return nil, err
}
listener, err = IN.NewShadowSocks(shadowsocksOption)
case "snell":
snellOption := &IN.SnellOption{UDP: true}
err = decoder.Decode(mapping, snellOption)
if err != nil {
return nil, err
}
listener, err = IN.NewSnell(snellOption)
case "vmess":
vmessOption := &IN.VmessOption{}
err = decoder.Decode(mapping, vmessOption)
+11 -4
View File
@@ -3,18 +3,19 @@ package sing
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"sync"
"time"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/adapter/outbound"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"
"github.com/gofrs/uuid/v5"
mux "github.com/metacubex/sing-mux"
vmess "github.com/metacubex/sing-vmess"
"github.com/metacubex/sing-vmess/packetaddr"
@@ -51,6 +52,7 @@ type BrutalOptions struct {
type ListenerHandler struct {
ListenerConfig
handlerId uuid.UUID
muxService *mux.Service
}
@@ -71,6 +73,7 @@ func ConvertMetadata(metadata *C.Metadata) M.Metadata {
func NewListenerHandler(lc ListenerConfig) (h *ListenerHandler, err error) {
h = &ListenerHandler{ListenerConfig: lc}
h.handlerId = utils.NewUUIDV4()
h.muxService, err = mux.NewService(mux.ServiceOptions{
NewStreamContext: func(ctx context.Context, conn net.Conn) context.Context {
return ctx
@@ -80,8 +83,8 @@ func NewListenerHandler(lc ListenerConfig) (h *ListenerHandler, err error) {
Padding: lc.MuxOption.Padding,
Brutal: mux.BrutalOptions{
Enabled: lc.MuxOption.Brutal.Enabled,
SendBPS: outbound.StringToBps(lc.MuxOption.Brutal.Up),
ReceiveBPS: outbound.StringToBps(lc.MuxOption.Brutal.Down),
SendBPS: utils.StringToBps(lc.MuxOption.Brutal.Up),
ReceiveBPS: utils.StringToBps(lc.MuxOption.Brutal.Down),
},
})
return
@@ -214,9 +217,13 @@ func (h *ListenerHandler) NewPacket(ctx context.Context, key netip.AddrPort, buf
cPacket := &packet{
writer: &writer,
mutex: &mutex,
rAddr: metadata.Source.UDPAddr(), // TODO: using key argument to make a SNAT key
rAddr: metadata.Source.UDPAddr(),
buff: buffer,
}
if h.Type != C.TUN { // make the handler-related SNAT key for not TUN listener
connID := fmt.Sprintf("%s:%s", h.handlerId, key)
cPacket.rAddr = N.NewCustomAddr(h.Type.String(), connID, cPacket.rAddr) // for tunnel's handleUDPConn
}
if conn, ok := common.Cast[localAddr](writer); ok { // tun does not have real inAddr
cPacket.lAddr = conn.LocalAddr()
}
+12 -3
View File
@@ -11,8 +11,8 @@ import (
"time"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/adapter/outbound"
"github.com/metacubex/mihomo/common/sockopt"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/mihomo/component/ech"
"github.com/metacubex/mihomo/component/resolver"
@@ -100,6 +100,8 @@ func New(config LC.Hysteria2Server, tunnel C.Tunnel, additions ...inbound.Additi
}
var salamanderPassword string
var geckoPassword string
var geckoMinPacketSize, geckoMaxPacketSize int
if len(config.Obfs) > 0 {
if config.ObfsPassword == "" {
return nil, errors.New("missing obfs password")
@@ -107,6 +109,10 @@ func New(config LC.Hysteria2Server, tunnel C.Tunnel, additions ...inbound.Additi
switch config.Obfs {
case hysteria2.ObfsTypeSalamander:
salamanderPassword = config.ObfsPassword
case hysteria2.ObfsTypeGecko:
geckoPassword = config.ObfsPassword
geckoMinPacketSize = config.ObfsMinPacketSize
geckoMaxPacketSize = config.ObfsMaxPacketSize
default:
return nil, fmt.Errorf("unknown obfs type: %s", config.Obfs)
}
@@ -209,9 +215,12 @@ func New(config LC.Hysteria2Server, tunnel C.Tunnel, additions ...inbound.Additi
service, err := hysteria2.NewService[string](hysteria2.ServiceOptions{
Context: context.Background(),
Logger: log.SingLogger,
SendBPS: outbound.StringToBps(config.Up),
ReceiveBPS: outbound.StringToBps(config.Down),
SendBPS: utils.StringToBps(config.Up),
ReceiveBPS: utils.StringToBps(config.Down),
SalamanderPassword: salamanderPassword,
GeckoPassword: geckoPassword,
GeckoMinPacketSize: geckoMinPacketSize,
GeckoMaxPacketSize: geckoMaxPacketSize,
TLSConfig: tlsConfig,
QUICConfig: quicConfig,
IgnoreClientBandwidth: config.IgnoreClientBandwidth,
+2 -2
View File
@@ -229,8 +229,8 @@ func New(config LC.VlessServer, tunnel C.Tunnel, additions ...inbound.Addition)
l = realityBuilder.NewListener(l)
} else if tlsConfig.GetCertificate != nil {
l = tls.NewListener(l, tlsConfig)
} else if sl.decryption == nil {
return nil, errors.New("disallow using Vless without any certificates/reality/decryption config")
} else if sl.decryption == nil && !config.AllowInsecure {
return nil, errors.New("disallow using Vless without any certificates/reality/decryption/allow-insecure config")
}
sl.listeners = append(sl.listeners, l)
+377
View File
@@ -0,0 +1,377 @@
package snell
import (
"bufio"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/netip"
"strings"
"sync"
"github.com/metacubex/mihomo/adapter/inbound"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/shadowsocks/shadowaead"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
"github.com/metacubex/mihomo/transport/snell"
)
const maxPacketLength = 0x3fff
type Config struct {
Listen string
Psk string
Version int
UDP bool
ObfsMode string
ObfsHost string
}
func (c Config) String() string {
b, _ := json.Marshal(c)
return string(b)
}
type Listener struct {
closed bool
config Config
listeners []net.Listener
}
func New(config Config, tunnel C.Tunnel, additions ...inbound.Addition) (C.MultiAddrListener, error) {
if config.Version == 0 {
config.Version = snell.Version4
}
if config.Version != snell.Version4 && config.Version != snell.Version5 {
return nil, fmt.Errorf("snell inbound version %d is not supported", config.Version)
}
if config.Psk == "" {
return nil, errors.New("snell inbound requires psk")
}
switch config.ObfsMode {
case "", "http", "tls":
default:
return nil, fmt.Errorf("snell inbound obfs mode error: %s", config.ObfsMode)
}
l := &Listener{config: config}
for _, addr := range strings.Split(config.Listen, ",") {
addr = strings.TrimSpace(addr)
if addr == "" {
continue
}
ln, err := inbound.Listen("tcp", addr)
if err != nil {
_ = l.Close()
return nil, err
}
l.listeners = append(l.listeners, ln)
go func(ln net.Listener) {
for {
conn, err := ln.Accept()
if err != nil {
if l.closed {
return
}
continue
}
go l.HandleConn(conn, tunnel, additions...)
}
}(ln)
}
return l, nil
}
func (l *Listener) Close() error {
l.closed = true
var retErr error
for _, ln := range l.listeners {
if err := ln.Close(); err != nil {
retErr = err
}
}
return retErr
}
func (l *Listener) Config() string {
return l.config.String()
}
func (l *Listener) AddrList() (addrList []net.Addr) {
for _, ln := range l.listeners {
addrList = append(addrList, ln.Addr())
}
return
}
func (l *Listener) HandleConn(rawConn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
defer rawConn.Close()
conn := rawConn
switch l.config.ObfsMode {
case "http":
conn = obfs.NewHTTPObfsServer(conn)
case "tls":
conn = obfs.NewTLSObfsServer(conn)
case "":
default:
return
}
stream := snell.ServerStreamConn(conn, []byte(l.config.Psk), l.config.Version)
for {
reuse, err := l.handleRequest(stream, tunnel, additions...)
if err != nil || !reuse {
return
}
}
}
func (l *Listener) handleRequest(stream *snell.Snell, tunnel C.Tunnel, additions ...inbound.Addition) (bool, error) {
br := bufio.NewReader(stream)
version, err := br.ReadByte()
if err != nil {
return false, err
}
if version != snell.Version {
return false, fmt.Errorf("snell invalid protocol version: %d", version)
}
command, err := br.ReadByte()
if err != nil {
return false, err
}
if command == snell.CommandPing {
_, _ = stream.Write([]byte{snell.CommandPong})
return false, nil
}
clientID, err := readClientID(br)
if err != nil {
return false, err
}
switch command {
case snell.CommandConnect, snell.CommandConnectV2:
return l.handleTCP(stream, br, command == snell.CommandConnectV2, clientID, tunnel, additions...)
case snell.CommandUDP:
if !l.config.UDP {
return false, errors.New("snell UDP is disabled")
}
return false, l.handleUDP(stream, clientID, tunnel, additions...)
default:
return false, fmt.Errorf("snell unknown command: %d", command)
}
}
func readClientID(r *bufio.Reader) (string, error) {
length, err := r.ReadByte()
if err != nil {
return "", err
}
if length == 0 {
return "", nil
}
id := make([]byte, int(length))
if _, err := io.ReadFull(r, id); err != nil {
return "", err
}
return string(id), nil
}
func (l *Listener) handleTCP(stream *snell.Snell, br *bufio.Reader, reuse bool, clientID string, tunnel C.Tunnel, additions ...inbound.Addition) (bool, error) {
hostLen, err := br.ReadByte()
if err != nil {
return false, err
}
if hostLen == 0 {
return false, errors.New("snell connect host is empty")
}
hostBytes := make([]byte, int(hostLen))
if _, err := io.ReadFull(br, hostBytes); err != nil {
return false, err
}
var portBytes [2]byte
if _, err := io.ReadFull(br, portBytes[:]); err != nil {
return false, err
}
metadata := l.metadata(C.TCP, string(hostBytes), binary.BigEndian.Uint16(portBytes[:]), stream, clientID, additions...)
conn := &tcpRequestConn{
Conn: stream,
reader: br,
reuse: reuse,
}
tunnel.HandleTCPConn(conn, metadata)
if !reuse {
return false, nil
}
return true, nil
}
func (l *Listener) handleUDP(stream *snell.Snell, clientID string, tunnel C.Tunnel, additions ...inbound.Addition) error {
if _, err := stream.Write([]byte{snell.CommandTunnel}); err != nil {
return err
}
connID := utils.NewUUIDV4().String()
localAddr := N.NewCustomAddr(C.SNELL.String(), connID, stream.RemoteAddr())
writeMu := &sync.Mutex{}
buf := make([]byte, maxPacketLength)
for {
n, err := stream.Read(buf)
if err != nil {
if errors.Is(err, io.EOF) || errors.Is(err, shadowaead.ErrZeroChunk) {
return nil
}
return err
}
request, err := snell.ParseUDPRequest(buf[:n])
if err != nil {
return err
}
metadata := l.metadata(C.UDP, request.Host, request.Port, stream, clientID, additions...)
if request.Ip.IsValid() {
metadata.Host = ""
metadata.DstIP = request.Ip
}
payload := append([]byte(nil), request.Payload...)
packet := &udpPacket{
data: payload,
conn: stream,
writeMu: writeMu,
localAddr: localAddr,
dstAddr: metadata.UDPAddr(),
}
tunnel.HandleUDPPacket(packet, metadata)
}
}
func (l *Listener) metadata(network C.NetWork, host string, port uint16, conn net.Conn, clientID string, additions ...inbound.Addition) *C.Metadata {
metadata := &C.Metadata{
NetWork: network,
Type: C.SNELL,
DstPort: port,
}
if ip, err := netip.ParseAddr(host); err == nil {
metadata.DstIP = ip.Unmap()
} else {
metadata.Host = host
}
inbound.ApplyAdditions(metadata, inbound.WithSrcAddr(conn.RemoteAddr()), inbound.WithInAddr(conn.LocalAddr()))
inbound.ApplyAdditions(metadata, additions...)
if clientID != "" {
inbound.ApplyAdditions(metadata, inbound.WithInUser(clientID))
}
return metadata
}
func writeCommandError(w io.Writer, code byte, message string) error {
msg := []byte(message)
if len(msg) > 255 {
msg = msg[:255]
}
buf := make([]byte, 0, 3+len(msg))
buf = append(buf, snell.CommandError, code, byte(len(msg)))
buf = append(buf, msg...)
_, err := w.Write(buf)
return err
}
type tcpRequestConn struct {
net.Conn
reader *bufio.Reader
reuse bool
writeMu sync.Mutex
closeOnce sync.Once
replyWritten bool
}
func (c *tcpRequestConn) Read(p []byte) (int, error) {
n, err := c.reader.Read(p)
if errors.Is(err, shadowaead.ErrZeroChunk) {
err = io.EOF
}
return n, err
}
func (c *tcpRequestConn) Write(p []byte) (int, error) {
c.writeMu.Lock()
defer c.writeMu.Unlock()
if !c.replyWritten {
payload := make([]byte, 1+len(p))
payload[0] = snell.CommandTunnel
copy(payload[1:], p)
if _, err := c.Conn.Write(payload); err != nil {
return 0, err
}
c.replyWritten = true
return len(p), nil
}
return c.Conn.Write(p)
}
func (c *tcpRequestConn) CloseWrite() error {
return c.Close()
}
func (c *tcpRequestConn) Close() error {
var err error
c.closeOnce.Do(func() {
c.writeMu.Lock()
defer c.writeMu.Unlock()
if !c.replyWritten {
err = writeCommandError(c.Conn, 0x65, "Remote EOF")
if !c.reuse {
err = errors.Join(err, c.Conn.Close())
}
return
}
if c.reuse {
_, err = c.Conn.Write(nil)
return
}
err = c.Conn.Close()
})
return err
}
type udpPacket struct {
data []byte
conn *snell.Snell
writeMu *sync.Mutex
localAddr net.Addr
dstAddr net.Addr
}
func (p *udpPacket) Data() []byte {
return p.data
}
func (p *udpPacket) WriteBack(b []byte, addr net.Addr) (int, error) {
if addr == nil {
addr = p.dstAddr
}
p.writeMu.Lock()
defer p.writeMu.Unlock()
return snell.WritePacketResponse(p.conn, addr, b)
}
func (p *udpPacket) Drop() {
p.data = nil
}
func (p *udpPacket) LocalAddr() net.Addr {
return p.localAddr
}
var _ C.MultiAddrListener = (*Listener)(nil)
var _ C.UDPPacket = (*udpPacket)(nil)
+15 -18
View File
@@ -13,10 +13,11 @@ import (
)
type packet struct {
pc net.PacketConn
lAddr netip.AddrPort
buf []byte
tunnel C.Tunnel
pc net.PacketConn
lAddr netip.AddrPort
buf []byte
tunnel C.Tunnel
additions []inbound.Addition
}
func (c *packet) Data() []byte {
@@ -25,9 +26,9 @@ func (c *packet) Data() []byte {
// WriteBack opens a new socket binding `addr` to write UDP packet back
func (c *packet) WriteBack(b []byte, addr net.Addr) (n int, err error) {
tc, err := createOrGetLocalConn(addr, c.LocalAddr(), c.tunnel)
rAddr := addr.(*net.UDPAddr).AddrPort() // tunnel's handleUDPToLocal will ensure addr is *net.UDPAddr
tc, err := createOrGetLocalConn(rAddr, c.lAddr, c.tunnel, c.additions...)
if err != nil {
n = 0
return
}
n, err = tc.Write(b)
@@ -36,7 +37,7 @@ func (c *packet) WriteBack(b []byte, addr net.Addr) (n int, err error) {
// LocalAddr returns the source IP/Port of UDP Packet
func (c *packet) LocalAddr() net.Addr {
return &net.UDPAddr{IP: c.lAddr.Addr().AsSlice(), Port: int(c.lAddr.Port()), Zone: c.lAddr.Addr().Zone()}
return net.UDPAddrFromAddrPort(c.lAddr)
}
func (c *packet) Drop() {
@@ -51,7 +52,7 @@ func (c *packet) InAddr() net.Addr {
// this function listen at rAddr and write to lAddr
// for here, rAddr is the ip/port client want to access
// lAddr is the ip/port client opened
func createOrGetLocalConn(rAddr, lAddr net.Addr, tunnel C.Tunnel) (*net.UDPConn, error) {
func createOrGetLocalConn(rAddr, lAddr netip.AddrPort, tunnel C.Tunnel, additions ...inbound.Addition) (*net.UDPConn, error) {
remote := rAddr.String()
local := lAddr.String()
natTable := tunnel.NatTable()
@@ -76,7 +77,7 @@ func createOrGetLocalConn(rAddr, lAddr net.Addr, tunnel C.Tunnel) (*net.UDPConn,
natTable.DeleteLockForLocalConn(local, remote)
cond.Broadcast()
}()
conn, err := listenLocalConn(rAddr, lAddr, tunnel)
conn, err := listenLocalConn(rAddr, lAddr, tunnel, additions...)
if err != nil {
log.Errorln("listenLocalConn failed with error: %s, packet loss (rAddr[%T]=%s lAddr[%T]=%s)", err.Error(), rAddr, remote, lAddr, local)
return nil, err
@@ -90,30 +91,26 @@ func createOrGetLocalConn(rAddr, lAddr net.Addr, tunnel C.Tunnel) (*net.UDPConn,
// this function listen at rAddr
// and send what received to program itself, then send to real remote
func listenLocalConn(rAddr, lAddr net.Addr, tunnel C.Tunnel) (*net.UDPConn, error) {
additions := []inbound.Addition{
inbound.WithInName("DEFAULT-TPROXY"),
inbound.WithSpecialRules(""),
}
lc, err := dialUDP("udp", rAddr.(*net.UDPAddr).AddrPort(), lAddr.(*net.UDPAddr).AddrPort())
func listenLocalConn(rAddr, lAddr netip.AddrPort, tunnel C.Tunnel, additions ...inbound.Addition) (*net.UDPConn, error) {
lc, err := dialUDP("udp", rAddr, lAddr)
if err != nil {
return nil, err
}
go func() {
log.Debugln("TProxy listenLocalConn rAddr=%s lAddr=%s", rAddr.String(), lAddr.String())
log.Debugln("TProxy listenLocalConn rAddr=%s lAddr=%s", rAddr, lAddr)
for {
buf := pool.Get(pool.UDPBufferSize)
br, err := lc.Read(buf)
if err != nil {
if errors.Is(err, net.ErrClosed) {
log.Debugln("TProxy local conn listener exit.. rAddr=%s lAddr=%s", rAddr.String(), lAddr.String())
log.Debugln("TProxy local conn listener exit.. rAddr=%s lAddr=%s", rAddr, lAddr)
pool.Put(buf)
return
}
}
// since following localPackets are pass through this socket which listen rAddr
// I choose current listener as packet's packet conn
handlePacketConn(lc, tunnel, buf[:br], lAddr.(*net.UDPAddr).AddrPort(), rAddr.(*net.UDPAddr).AddrPort(), additions...)
handlePacketConn(lc, tunnel, buf[:br], lAddr, rAddr, additions...)
}
}()
return lc, nil
+8 -5
View File
@@ -8,6 +8,8 @@ import (
"github.com/metacubex/mihomo/common/pool"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/socks5"
"golang.org/x/exp/slices"
)
type UDPListener struct {
@@ -81,7 +83,7 @@ func NewUDP(addr string, tunnel C.Tunnel, additions ...inbound.Addition) (*UDPLi
}
dscp, _ := getDSCP(oob[:oobn])
additions := append(additions, inbound.WithDSCP(dscp)) // don't change outside additions
additions := append(slices.Clip(additions), inbound.WithDSCP(dscp)) // don't change outside additions
if rAddr.Addr().Is4() {
// try to unmap 4in6 address
@@ -97,10 +99,11 @@ func NewUDP(addr string, tunnel C.Tunnel, additions ...inbound.Addition) (*UDPLi
func handlePacketConn(pc net.PacketConn, tunnel C.Tunnel, buf []byte, lAddr, rAddr netip.AddrPort, additions ...inbound.Addition) {
target := socks5.AddrFromStdAddrPort(rAddr)
pkt := &packet{
pc: pc,
lAddr: lAddr,
buf: buf,
tunnel: tunnel,
pc: pc,
lAddr: lAddr,
buf: buf,
tunnel: tunnel,
additions: additions,
}
tunnel.HandleUDPPacket(inbound.NewPacket(target, pkt, C.TPROXY, additions...))
}
+2 -2
View File
@@ -168,8 +168,8 @@ func New(config LC.TrojanServer, tunnel C.Tunnel, additions ...inbound.Addition)
l = realityBuilder.NewListener(l)
} else if tlsConfig.GetCertificate != nil {
l = tls.NewListener(l, tlsConfig)
} else if !config.TrojanSSOption.Enabled {
return nil, errors.New("disallow using Trojan without both certificates/reality/ss config")
} else if !config.TrojanSSOption.Enabled && !config.AllowInsecure {
return nil, errors.New("disallow using Trojan without both certificates/reality/ss/allow-insecure config")
}
sl.listeners = append(sl.listeners, l)
+15
View File
@@ -15,6 +15,7 @@ import (
"syscall"
"github.com/metacubex/mihomo/common/cmd"
"github.com/metacubex/mihomo/component/age"
"github.com/metacubex/mihomo/component/generator"
"github.com/metacubex/mihomo/component/geodata"
"github.com/metacubex/mihomo/component/updater"
@@ -37,6 +38,7 @@ var (
configFile string
configString string
configBytes []byte
ageSecretKey string
externalUI string
externalController string
externalControllerUnix string
@@ -50,6 +52,7 @@ func init() {
flag.StringVar(&homeDir, "d", os.Getenv("CLASH_HOME_DIR"), "set configuration directory")
flag.StringVar(&configFile, "f", os.Getenv("CLASH_CONFIG_FILE"), "specify configuration file")
flag.StringVar(&configString, "config", os.Getenv("CLASH_CONFIG_STRING"), "specify base64-encoded configuration string")
flag.StringVar(&ageSecretKey, "age-secret-key", os.Getenv("CLASH_AGE_SECRET_KEY"), "specify age secret key to decrypt configuration")
flag.StringVar(&externalUI, "ext-ui", os.Getenv("CLASH_OVERRIDE_EXTERNAL_UI_DIR"), "override external ui directory")
flag.StringVar(&externalController, "ext-ctl", os.Getenv("CLASH_OVERRIDE_EXTERNAL_CONTROLLER"), "override external controller address")
flag.StringVar(&externalControllerUnix, "ext-ctl-unix", os.Getenv("CLASH_OVERRIDE_EXTERNAL_CONTROLLER_UNIX"), "override external controller unix address")
@@ -94,6 +97,11 @@ func main() {
return
}
if len(os.Args) > 1 && os.Args[1] == "age" {
age.Main(os.Args[2:])
return
}
if version {
fmt.Printf("Mihomo Meta %s %s %s with %s %s\n",
C.Version, runtime.GOOS, runtime.GOARCH, runtime.Version(), C.BuildTime)
@@ -116,6 +124,13 @@ func main() {
geodata.SetGeodataMode(true)
}
if ageSecretKey != "" {
if err := age.VeritySecretKeys(ageSecretKey); err != nil {
log.Errorln("Parse age-secret-key error: %s", err.Error())
}
age.SetGlobalSecretKeys(ageSecretKey)
}
if configString != "" {
var err error
configBytes, err = base64.StdEncoding.DecodeString(configString)
+2 -2
View File
@@ -27,7 +27,7 @@ type Service struct {
syncSystemTime bool
}
func ReCreateNTPService(server string, interval time.Duration, dialerProxy string, syncSystemTime bool) {
func ReCreateNTPService(server string, interval time.Duration, dialerProxy string, tunnel C.Tunnel, syncSystemTime bool) {
globalMu.Lock()
defer globalMu.Unlock()
if globalSrv != nil {
@@ -39,7 +39,7 @@ func ReCreateNTPService(server string, interval time.Duration, dialerProxy strin
ctx, cancel := context.WithCancel(context.Background())
var cDialer C.Dialer = dialer.NewDialer()
if dialerProxy != "" {
cDialer = proxydialer.NewByName(dialerProxy)
cDialer = proxydialer.NewByName(dialerProxy, tunnel)
}
globalSrv = &Service{
server: M.ParseSocksaddr(server),
+46
View File
@@ -0,0 +1,46 @@
package bundle
import (
"errors"
"fmt"
"io"
"io/fs"
"github.com/metacubex/mihomo/component/resource"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/sevenzip"
)
func MakeBundleFile(path string) resource.BundleFile {
if path == "" {
return nil
}
return func() (fs.File, error) {
return Open(path)
}
}
func Open(path string) (fs.File, error) {
r, err := sevenzip.OpenReader(C.Path.BundleMRS())
if err != nil {
return nil, fmt.Errorf("open bundle file error: %w", err)
}
f, err := r.Open(path)
if err != nil {
_ = r.Close()
return nil, fmt.Errorf("open path in bundle file error: %w", err)
}
return file{f, r}, nil
}
type file struct {
fs.File
closer io.Closer
}
func (f file) Close() error {
err1 := f.File.Close()
err2 := f.closer.Close()
return errors.Join(err1, err2)
}
+5 -3
View File
@@ -180,10 +180,12 @@ func matchSubRules(metadata *C.Metadata, name string, subRules map[string][]C.Ru
for _, rule := range subRules[name] {
if m, a := rule.Match(metadata, helper); m {
if rule.RuleType() == C.SubRules {
return matchSubRules(metadata, rule.Adapter(), subRules, helper)
} else {
return m, a
m, a = matchSubRules(metadata, rule.Adapter(), subRules, helper)
}
if m && (a == "PASS-RULE" || (helper.CheckPassRule != nil && helper.CheckPassRule(a))) {
continue
}
return m, a
}
}
return false, ""
+13 -12
View File
@@ -12,19 +12,20 @@ import (
)
type ruleProviderSchema struct {
Type string `provider:"type"`
Behavior string `provider:"behavior"`
Path string `provider:"path,omitempty"`
URL string `provider:"url,omitempty"`
Proxy string `provider:"proxy,omitempty"`
Format string `provider:"format,omitempty"`
Interval int `provider:"interval,omitempty"`
SizeLimit int64 `provider:"size-limit,omitempty"`
Payload []string `provider:"payload,omitempty"`
Header map[string][]string `provider:"header,omitempty"`
Type string `provider:"type"`
Behavior string `provider:"behavior"`
Path string `provider:"path,omitempty"`
URL string `provider:"url,omitempty"`
Proxy string `provider:"proxy,omitempty"`
Format string `provider:"format,omitempty"`
Interval int `provider:"interval,omitempty"`
SizeLimit int64 `provider:"size-limit,omitempty"`
Payload []string `provider:"payload,omitempty"`
Header map[string][]string `provider:"header,omitempty"`
PathInBundle string `provider:"path-in-bundle,omitempty"`
}
func ParseRuleProvider(name string, mapping map[string]any, parse common.ParseRuleFunc) (P.RuleProvider, error) {
func ParseRuleProvider(name string, mapping map[string]any, parse common.ParseRuleFunc, makeBundleFile func(pathInBundle string) resource.BundleFile) (P.RuleProvider, error) {
schema := &ruleProviderSchema{}
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
if err := decoder.Decode(mapping, schema); err != nil {
@@ -64,5 +65,5 @@ func ParseRuleProvider(name string, mapping map[string]any, parse common.ParseRu
interval := time.Duration(uint(schema.Interval)) * time.Second
return NewRuleSetProvider(name, behavior, format, interval, vehicle, schema.Payload, parse), nil
return NewRuleSetProvider(name, behavior, format, interval, vehicle, schema.Payload, makeBundleFile(schema.PathInBundle), parse), nil
}
+2 -2
View File
@@ -122,7 +122,7 @@ func (rp *RuleSetProvider) Close() error {
return rp.ruleSetProvider.Close()
}
func NewRuleSetProvider(name string, behavior P.RuleBehavior, format P.RuleFormat, interval time.Duration, vehicle P.Vehicle, payload []string, parse common.ParseRuleFunc) P.RuleProvider {
func NewRuleSetProvider(name string, behavior P.RuleBehavior, format P.RuleFormat, interval time.Duration, vehicle P.Vehicle, payload []string, bundleFile resource.BundleFile, parse common.ParseRuleFunc) P.RuleProvider {
rp := &ruleSetProvider{
baseProvider: baseProvider{
behavior: behavior,
@@ -139,7 +139,7 @@ func NewRuleSetProvider(name string, behavior P.RuleBehavior, format P.RuleForma
if len(payload) > 0 { // using as fallback rules
rp.strategy = rulesParseInline(payload, rp.strategy)
}
rp.Fetcher = resource.NewFetcher(name, interval, vehicle, func(bytes []byte) (ruleStrategy, error) {
rp.Fetcher = resource.NewFetcher(name, interval, vehicle, bundleFile, func(bytes []byte) (ruleStrategy, error) {
return rulesParse(bytes, newStrategy(behavior, parse), format)
}, onUpdate)
+98 -13
View File
@@ -9,12 +9,17 @@ import (
"io"
"net"
"strings"
"sync/atomic"
"time"
"github.com/metacubex/tls"
"golang.org/x/sync/semaphore"
)
const defaultHandshakeTimeout = 30 * time.Second
const (
DefaultHandshakeTimeout = 30 * time.Second
ControlRetransmitDelay = time.Second
)
type Client struct {
config *ClientConfig
@@ -26,6 +31,11 @@ type Client struct {
push *PushReply
cancel context.CancelFunc
writeSem semaphore.Weighted
lastSendNano atomic.Int64
lastReceiveNano atomic.Int64
}
func NewClient(config *ClientConfig, io PacketIO) (*Client, error) {
@@ -35,9 +45,13 @@ func NewClient(config *ClientConfig, io PacketIO) (*Client, error) {
if io == nil {
return nil, errors.New("nil openvpn packet io")
}
crypt, err := NewTLSCrypt(config.TLSCryptKey, true)
if err != nil {
return nil, err
var crypt *TLSCrypt
if len(config.TLSCryptKey) > 0 {
var err error
crypt, err = NewTLSCrypt(config.TLSCryptKey, true)
if err != nil {
return nil, err
}
}
local, err := NewSessionID()
if err != nil {
@@ -46,12 +60,15 @@ func NewClient(config *ClientConfig, io PacketIO) (*Client, error) {
runCtx, cancel := context.WithCancel(context.Background())
mux := NewPacketMux(io)
go mux.Run(runCtx)
return &Client{
client := &Client{
config: config,
mux: mux,
control: NewControlChannel(mux, crypt, local),
cancel: cancel,
}, nil
}
client.markSend()
client.markReceive()
return client, nil
}
func (c *Client) Handshake(ctx context.Context) (*PushReply, error) {
@@ -60,7 +77,7 @@ func (c *Client) Handshake(ctx context.Context) (*PushReply, error) {
}
if _, ok := ctx.Deadline(); !ok {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, defaultHandshakeTimeout)
ctx, cancel = context.WithTimeout(ctx, DefaultHandshakeTimeout)
defer cancel()
}
if err := c.control.SendReset(ctx); err != nil {
@@ -84,8 +101,8 @@ func (c *Client) Handshake(ctx context.Context) (*PushReply, error) {
}
clientRecord, err := NewClientKeyMethod2Record(
InstallScriptOptionsString(c.config.Proto, c.config.Cipher, c.config.Auth),
InstallScriptPeerInfo(c.config.Cipher),
InstallScriptOptionsString(c.config.Proto, c.config.Cipher, c.config.Auth, c.config.CompLZO),
InstallScriptPeerInfo(c.config.Cipher, c.config.CompLZO),
strings.TrimSpace(c.config.Username),
c.config.Password,
)
@@ -119,22 +136,48 @@ func (c *Client) Handshake(ctx context.Context) (*PushReply, error) {
return nil, err
}
c.push = push
c.data, err = NewDataChannel(keys, push.PeerID)
c.data, err = NewDataChannel(keys, c.config.Cipher, c.config.Auth, push.PeerID)
if err != nil {
return nil, err
}
c.markSend()
c.markReceive()
return push, nil
}
func (c *Client) WriteIPPacket(ctx context.Context, packet []byte) error {
return c.writeDataPacket(ctx, packet, true)
}
func (c *Client) WritePing(ctx context.Context) error {
return c.writeDataPacket(ctx, openVPNPingPacket, false)
}
func (c *Client) writeDataPacket(ctx context.Context, packet []byte, compress bool) error {
if c.data == nil {
return errors.New("openvpn data channel is not ready")
}
if err := c.writeSem.Acquire(ctx, 1); err != nil {
return err
}
defer c.writeSem.Release(1)
if compress && c.config.CompLZO == CompLzoYes {
compressed, err := lzo1xCompressSafe(packet)
if err != nil {
return err
}
packet = compressed
}
encrypted, err := c.data.Encrypt(packet)
if err != nil {
return err
}
return c.mux.WritePacket(ctx, encrypted)
err = c.mux.WritePacket(ctx, encrypted)
if err != nil {
return err
}
c.markSend()
return nil
}
func (c *Client) ReadIPPacket(ctx context.Context) ([]byte, error) {
@@ -150,10 +193,38 @@ func (c *Client) ReadIPPacket(ctx context.Context) ([]byte, error) {
if err != nil {
continue
}
c.markReceive()
if IsPingPacket(plain) {
continue
}
if c.config.CompLZO == CompLzoYes && len(plain) > 0 {
return lzo1xDecompressSafe(plain)
}
return plain, nil
}
}
func (c *Client) SinceSend() time.Duration {
return time.Duration(int64(time.Since(start)) - c.lastSendNano.Load())
}
func (c *Client) SinceReceive() time.Duration {
return time.Duration(int64(time.Since(start)) - c.lastReceiveNano.Load())
}
func (c *Client) markSend() {
c.lastSendNano.Store(int64(time.Since(start)))
}
func (c *Client) markReceive() {
c.lastReceiveNano.Store(int64(time.Since(start)))
}
// The absolute value doesn't matter, but it should be in the past,
// so that every timestamp obtained with Now() is non-zero,
// even on systems with low timer resolutions (e.g. Windows).
var start = time.Now().Add(-time.Hour)
func (c *Client) Close() error {
if c.cancel != nil {
c.cancel()
@@ -168,10 +239,24 @@ func (c *Client) Close() error {
}
func (c *Client) waitServerReset(ctx context.Context) error {
retransmits := 0
for {
packet, err := c.control.Read(ctx)
readCtx := ctx
cancel := func() {}
if c.config.Proto == ProtoUDP {
readCtx, cancel = context.WithTimeout(ctx, ControlRetransmitDelay)
}
packet, err := c.control.Read(readCtx)
cancel()
if err != nil {
return fmt.Errorf("read hard reset response: %w", err)
if c.config.Proto == ProtoUDP && errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil {
if err := c.control.RetransmitPending(ctx); err != nil {
return fmt.Errorf("retransmit hard reset: %w", err)
}
retransmits++
continue
}
return fmt.Errorf("read hard reset response after %d retransmits: %w", retransmits, err)
}
switch packet.Opcode {
case PControlHardResetServerV2:
+75 -23
View File
@@ -9,15 +9,28 @@ import (
"net"
"strconv"
"strings"
"time"
)
const (
ProtoUDP = "udp"
ProtoTCP = "tcp"
CipherAES128GCM = "AES-128-GCM"
CipherAES256GCM = "AES-256-GCM"
AuthSHA256 = "SHA256"
CipherAES128GCM = "AES-128-GCM"
CipherAES192GCM = "AES-192-GCM"
CipherAES256GCM = "AES-256-GCM"
CipherAESCBC = "AES-CBC"
CipherAES128CBC = "AES-128-CBC"
CipherAES192CBC = "AES-192-CBC"
CipherAES256CBC = "AES-256-CBC"
CipherChaCha20Poly1305 = "CHACHA20-POLY1305"
AuthMD5 = "MD5"
AuthSHA1 = "SHA1"
AuthSHA256 = "SHA256"
AuthSHA384 = "SHA384"
AuthSHA512 = "SHA512"
CompLzoYes = "yes"
)
// ClientConfig is the normalized subset generated by hwdsl2/openvpn-install.
@@ -28,6 +41,7 @@ type ClientConfig struct {
Dev string
Cipher string
Auth string
CompLZO string
CA []byte
Cert []byte
@@ -37,14 +51,19 @@ type ClientConfig struct {
Username string
Password string
PingInterval time.Duration
PingRestart time.Duration
TLSCryptKey []byte
}
// DataCipherKeyLength returns the AES key size for the negotiated data cipher.
// DataCipherKeyLength returns the key size for the negotiated data cipher.
func (c ClientConfig) DataCipherKeyLength() int {
switch c.Cipher {
case CipherAES256GCM:
case CipherAES256GCM, CipherAES256CBC, CipherChaCha20Poly1305:
return 32
case CipherAES192GCM, CipherAES192CBC:
return 24
default:
return 16
}
@@ -67,6 +86,37 @@ func normalizeProto(proto string) string {
}
}
func normalizeCipher(cipher string) string {
switch strings.ToUpper(strings.TrimSpace(cipher)) {
case "":
return CipherAES128GCM
case CipherAESCBC:
return CipherAES128CBC
default:
return strings.ToUpper(strings.TrimSpace(cipher))
}
}
func normalizeAuth(auth string) string {
switch strings.ToUpper(strings.TrimSpace(auth)) {
case "":
return AuthSHA256
case "SHA-1":
return AuthSHA1
default:
return strings.ToUpper(strings.TrimSpace(auth))
}
}
func normalizeCompLZO(compLZO string) string {
switch strings.ToLower(strings.TrimSpace(compLZO)) {
case "yes", "adaptive":
return CompLzoYes
default:
return strings.ToLower(strings.TrimSpace(compLZO))
}
}
func (c *ClientConfig) Prepare() error {
if c == nil {
return errors.New("nil openvpn client config")
@@ -77,22 +127,19 @@ func (c *ClientConfig) Prepare() error {
c.Dev = "tun"
}
c.Dev = strings.ToLower(strings.TrimSpace(c.Dev))
if c.Cipher == "" {
c.Cipher = CipherAES128GCM
}
c.Cipher = strings.ToUpper(strings.TrimSpace(c.Cipher))
if c.Auth == "" {
c.Auth = AuthSHA256
}
c.Auth = strings.ToUpper(strings.TrimSpace(c.Auth))
c.Cipher = normalizeCipher(c.Cipher)
c.Auth = normalizeAuth(c.Auth)
c.CompLZO = normalizeCompLZO(c.CompLZO)
if err := c.ValidateInstallScriptSubset(); err != nil {
return err
}
key, err := DecodeStaticKey(c.TLSCrypt)
if err != nil {
return fmt.Errorf("parse tls-crypt key: %w", err)
if len(bytes.TrimSpace(c.TLSCrypt)) > 0 {
key, err := DecodeStaticKey(c.TLSCrypt)
if err != nil {
return fmt.Errorf("parse tls-crypt key: %w", err)
}
c.TLSCryptKey = key
}
c.TLSCryptKey = key
return nil
}
@@ -109,15 +156,14 @@ func (c *ClientConfig) ValidateInstallScriptSubset() error {
if c.Proto != ProtoUDP && c.Proto != ProtoTCP {
return fmt.Errorf("unsupported openvpn proto %q: only udp and tcp are supported", c.Proto)
}
if c.Cipher != CipherAES128GCM && c.Cipher != CipherAES256GCM {
return fmt.Errorf("unsupported openvpn cipher %q: only %s and %s are supported", c.Cipher, CipherAES128GCM, CipherAES256GCM)
if c.Cipher != CipherAES128GCM && c.Cipher != CipherAES192GCM && c.Cipher != CipherAES256GCM && c.Cipher != CipherAES128CBC && c.Cipher != CipherAES192CBC && c.Cipher != CipherAES256CBC && c.Cipher != CipherChaCha20Poly1305 {
return fmt.Errorf("unsupported openvpn cipher %q: only %s, %s, %s, %s, %s, %s and %s are supported", c.Cipher, CipherAES128GCM, CipherAES192GCM, CipherAES256GCM, CipherAES128CBC, CipherAES192CBC, CipherAES256CBC, CipherChaCha20Poly1305)
}
if c.Auth != AuthSHA256 {
return fmt.Errorf("unsupported openvpn auth %q: only %s is supported", c.Auth, AuthSHA256)
if c.Auth != AuthMD5 && c.Auth != AuthSHA1 && c.Auth != AuthSHA256 && c.Auth != AuthSHA384 && c.Auth != AuthSHA512 {
return fmt.Errorf("unsupported openvpn auth %q: only %s, %s, %s, %s and %s are supported", c.Auth, AuthMD5, AuthSHA1, AuthSHA256, AuthSHA384, AuthSHA512)
}
for name, value := range map[string][]byte{
"ca": c.CA,
"tls-crypt": c.TLSCrypt,
"ca": c.CA,
} {
if len(bytes.TrimSpace(value)) == 0 {
return fmt.Errorf("openvpn config requires inline <%s> block", name)
@@ -140,6 +186,12 @@ func (c *ClientConfig) ValidateInstallScriptSubset() error {
} else if strings.TrimSpace(c.Username) == "" {
return errors.New("openvpn requires either cert+key or username (auth-user-pass)")
}
if c.PingInterval < 0 {
return errors.New("openvpn ping interval must be positive")
}
if c.PingRestart < 0 {
return errors.New("openvpn ping restart must be positive")
}
return nil
}
+53 -6
View File
@@ -89,15 +89,14 @@ func TestClientConfigRejectsUnsupportedProto(t *testing.T) {
}
}
func TestClientConfigRequiresTLSCrypt(t *testing.T) {
func TestClientConfigAllowsMissingTLSCrypt(t *testing.T) {
cfg := yamlStyleConfig()
cfg.TLSCrypt = nil
err := cfg.Prepare()
if err == nil {
t.Fatal("expected missing tls-crypt error")
if err := cfg.Prepare(); err != nil {
t.Fatal(err)
}
if !strings.Contains(err.Error(), "tls-crypt") {
t.Fatalf("unexpected error: %v", err)
if len(cfg.TLSCryptKey) != 0 {
t.Fatalf("unexpected tls-crypt key length: %d", len(cfg.TLSCryptKey))
}
}
@@ -125,6 +124,30 @@ func TestClientConfigAuthUserPassAES256(t *testing.T) {
}
}
func TestClientConfigAESCBCSHA1(t *testing.T) {
cfg := &ClientConfig{
RemoteHost: "vpn.example.com",
RemotePort: 1194,
Proto: "udp",
Dev: "tun",
Cipher: "AES-CBC",
Auth: "sha-1",
CA: []byte(testCert),
Username: "user",
Password: "secret",
TLSCrypt: []byte(testTLSCryptBlock()),
}
if err := cfg.Prepare(); err != nil {
t.Fatal(err)
}
if cfg.Cipher != CipherAES128CBC || cfg.Auth != AuthSHA1 {
t.Fatalf("unexpected crypto: %s/%s", cfg.Cipher, cfg.Auth)
}
if cfg.DataCipherKeyLength() != 16 {
t.Fatalf("unexpected data key length helper: %d", cfg.DataCipherKeyLength())
}
}
func TestClientConfigRequiresAuth(t *testing.T) {
cfg := yamlStyleConfig()
cfg.Cert = nil
@@ -138,3 +161,27 @@ func TestClientConfigRequiresAuth(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
}
func TestClientConfigAuthUserPassChaCha20Poly1305(t *testing.T) {
cfg := &ClientConfig{
RemoteHost: "vpn.example.com",
RemotePort: 31194,
Proto: "udp",
Dev: "tun",
Cipher: "chacha20-poly1305",
Auth: "SHA256",
CA: []byte(testCert),
Username: "user",
Password: "secret",
TLSCrypt: []byte(testTLSCryptBlock()),
}
if err := cfg.Prepare(); err != nil {
t.Fatal(err)
}
if cfg.Cipher != CipherChaCha20Poly1305 {
t.Fatalf("unexpected cipher: %s", cfg.Cipher)
}
if cfg.DataCipherKeyLength() != 32 {
t.Fatalf("unexpected data key length helper: %d", cfg.DataCipherKeyLength())
}
}
+135 -75
View File
@@ -8,6 +8,8 @@ import (
"net"
"sync"
"time"
"github.com/metacubex/mihomo/common/pool"
)
type PacketIO interface {
@@ -29,19 +31,22 @@ type ControlChannel struct {
mu sync.Mutex
sendPacketID uint32
sendMessage uint32
recvMessage uint32
ackPending []uint32
pending map[uint32]*ControlPacket
recvPending map[uint32]*ControlPacket
readDeadline time.Time
writeDeadline time.Time
}
func NewControlChannel(io PacketIO, crypt *TLSCrypt, local SessionID) *ControlChannel {
return &ControlChannel{
io: io,
crypt: crypt,
clock: time.Now,
local: local,
pending: make(map[uint32]*ControlPacket),
io: io,
crypt: crypt,
clock: time.Now,
local: local,
pending: make(map[uint32]*ControlPacket),
recvPending: make(map[uint32]*ControlPacket),
}
}
@@ -113,11 +118,23 @@ func (c *ControlChannel) SendAck(ctx context.Context) error {
func (c *ControlChannel) Read(ctx context.Context) (*ControlPacket, error) {
for {
c.mu.Lock()
if packet, ok := c.recvPending[c.recvMessage]; ok {
delete(c.recvPending, c.recvMessage)
c.recvMessage++
c.mu.Unlock()
return packet, nil
}
c.mu.Unlock()
packet, err := c.readControlPacket(ctx)
if err != nil {
return nil, err
}
var deliver *ControlPacket
sendAck := false
c.mu.Lock()
if c.remote == (SessionID{}) && packet.LocalSession != c.local {
c.remote = packet.LocalSession
@@ -128,12 +145,33 @@ func (c *ControlChannel) Read(ctx context.Context) (*ControlPacket, error) {
if packet.Opcode.HasMessageID() {
c.ackPending = appendAck(c.ackPending, packet.MessageID)
}
switch {
case packet.Opcode == PAckV1:
case !packet.Opcode.HasMessageID():
deliver = packet
case packet.MessageID < c.recvMessage:
sendAck = true
case packet.MessageID == c.recvMessage:
deliver = packet
c.recvMessage++
default:
if _, exists := c.recvPending[packet.MessageID]; !exists {
c.recvPending[packet.MessageID] = packet
}
sendAck = true
}
c.mu.Unlock()
if packet.Opcode == PAckV1 {
continue
if deliver != nil {
return deliver, nil
}
if sendAck {
if err := c.SendAck(ctx); err != nil {
return nil, err
}
}
return packet, nil
}
}
@@ -332,11 +370,17 @@ func (c *ControlConn) SetWriteDeadline(t time.Time) error {
}
type streamPacketIO struct {
conn net.Conn
conn net.Conn
deadlineMu sync.Mutex
readDeadline time.Time
writeDeadline time.Time
}
type datagramPacketIO struct {
conn net.Conn
conn net.Conn
deadlineMu sync.Mutex
readDeadline time.Time
writeDeadline time.Time
}
func NewDatagramPacketIO(conn net.Conn) PacketIO {
@@ -344,40 +388,23 @@ func NewDatagramPacketIO(conn net.Conn) PacketIO {
}
func (d *datagramPacketIO) ReadPacket(ctx context.Context) ([]byte, error) {
done := make(chan struct{})
var (
packet []byte
err error
)
go func() {
defer close(done)
buf := make([]byte, 64*1024)
var n int
n, err = d.conn.Read(buf)
if err == nil {
packet = cloneBytes(buf[:n])
}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-done:
return packet, err
if err := setReadDeadlineFromContext(d.conn, ctx, &d.deadlineMu, &d.readDeadline); err != nil {
return nil, err
}
buf := make([]byte, 64*1024)
n, err := d.conn.Read(buf)
if err != nil {
return nil, contextIOError(ctx, err)
}
return buf[:n], nil
}
func (d *datagramPacketIO) WritePacket(ctx context.Context, packet []byte) error {
done := make(chan error, 1)
go func() {
_, err := d.conn.Write(packet)
done <- err
}()
select {
case <-ctx.Done():
return ctx.Err()
case err := <-done:
if err := setWriteDeadlineFromContext(d.conn, ctx, &d.deadlineMu, &d.writeDeadline); err != nil {
return err
}
_, err := d.conn.Write(packet)
return contextIOError(ctx, err)
}
func (d *datagramPacketIO) Close() error {
@@ -397,52 +424,38 @@ func NewTCPPacketIO(conn net.Conn) PacketIO {
}
func (s *streamPacketIO) ReadPacket(ctx context.Context) ([]byte, error) {
done := make(chan struct{})
var (
packet []byte
err error
)
go func() {
defer close(done)
var lenBuf [2]byte
if _, err = io.ReadFull(s.conn, lenBuf[:]); err != nil {
return
}
size := int(lenBuf[0])<<8 | int(lenBuf[1])
if size == 0 {
err = errors.New("empty openvpn tcp packet")
return
}
packet = make([]byte, size)
_, err = io.ReadFull(s.conn, packet)
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-done:
return packet, err
if err := setReadDeadlineFromContext(s.conn, ctx, &s.deadlineMu, &s.readDeadline); err != nil {
return nil, err
}
var lenBuf [2]byte
if _, err := io.ReadFull(s.conn, lenBuf[:]); err != nil {
return nil, contextIOError(ctx, err)
}
size := int(lenBuf[0])<<8 | int(lenBuf[1])
if size == 0 {
return nil, errors.New("empty openvpn tcp packet")
}
packet := make([]byte, size)
if _, err := io.ReadFull(s.conn, packet); err != nil {
return nil, contextIOError(ctx, err)
}
return packet, nil
}
func (s *streamPacketIO) WritePacket(ctx context.Context, packet []byte) error {
if len(packet) > 0xffff {
return fmt.Errorf("openvpn tcp packet too large: %d", len(packet))
}
done := make(chan error, 1)
go func() {
frame := make([]byte, 2+len(packet))
frame[0] = byte(len(packet) >> 8)
frame[1] = byte(len(packet))
copy(frame[2:], packet)
_, err := s.conn.Write(frame)
done <- err
}()
select {
case <-ctx.Done():
return ctx.Err()
case err := <-done:
if err := setWriteDeadlineFromContext(s.conn, ctx, &s.deadlineMu, &s.writeDeadline); err != nil {
return err
}
frame := pool.Get(2 + len(packet))
defer pool.Put(frame)
frame[0] = byte(len(packet) >> 8)
frame[1] = byte(len(packet))
copy(frame[2:], packet)
_, err := s.conn.Write(frame)
return contextIOError(ctx, err)
}
func (s *streamPacketIO) Close() error {
@@ -456,3 +469,50 @@ func (s *streamPacketIO) LocalAddr() net.Addr {
func (s *streamPacketIO) RemoteAddr() net.Addr {
return s.conn.RemoteAddr()
}
func setReadDeadlineFromContext(conn net.Conn, ctx context.Context, mu *sync.Mutex, current *time.Time) error {
deadline, hasDeadline := ctx.Deadline()
mu.Lock()
defer mu.Unlock()
if current.Equal(deadline) {
return nil
}
if hasDeadline {
if err := conn.SetReadDeadline(deadline); err != nil {
return err
}
} else if err := conn.SetReadDeadline(time.Time{}); err != nil {
return err
}
*current = deadline
return nil
}
func setWriteDeadlineFromContext(conn net.Conn, ctx context.Context, mu *sync.Mutex, current *time.Time) error {
deadline, hasDeadline := ctx.Deadline()
mu.Lock()
defer mu.Unlock()
if current.Equal(deadline) {
return nil
}
if hasDeadline {
if err := conn.SetWriteDeadline(deadline); err != nil {
return err
}
} else if err := conn.SetWriteDeadline(time.Time{}); err != nil {
return err
}
*current = deadline
return nil
}
func contextIOError(ctx context.Context, err error) error {
if err == nil {
return nil
}
var netErr net.Error
if errors.As(err, &netErr) && netErr.Timeout() && ctx.Err() != nil {
return ctx.Err()
}
return err
}
+110
View File
@@ -157,6 +157,116 @@ func TestControlConnCarriesTLSBytes(t *testing.T) {
}
}
func TestControlChannelReordersReliableMessages(t *testing.T) {
packets := make(chan []byte, 4)
acks := make(chan []byte, 4)
io := &memoryPacketIO{in: packets, out: acks, closed: make(chan struct{})}
var clientID SessionID
copy(clientID[:], []byte("client01"))
var serverID SessionID
copy(serverID[:], []byte("server01"))
server := NewControlChannel(io, nil, serverID)
second, err := (ControlPacket{
Opcode: PControlV1,
LocalSession: clientID,
MessageID: 1,
Payload: []byte("second"),
}).Encode(nil, 0, 0)
if err != nil {
t.Fatal(err)
}
first, err := (ControlPacket{
Opcode: PControlV1,
LocalSession: clientID,
MessageID: 0,
Payload: []byte("first"),
}).Encode(nil, 0, 0)
if err != nil {
t.Fatal(err)
}
packets <- second
packets <- first
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
packet, err := server.Read(ctx)
if err != nil {
t.Fatal(err)
}
if packet.MessageID != 0 || string(packet.Payload) != "first" {
t.Fatalf("unexpected first delivered packet: id=%d payload=%q", packet.MessageID, packet.Payload)
}
packet, err = server.Read(ctx)
if err != nil {
t.Fatal(err)
}
if packet.MessageID != 1 || string(packet.Payload) != "second" {
t.Fatalf("unexpected second delivered packet: id=%d payload=%q", packet.MessageID, packet.Payload)
}
}
func TestClientWaitServerResetRetransmitsUDP(t *testing.T) {
clientIO, serverIO := newMemoryPacketPair()
var clientID SessionID
copy(clientID[:], []byte("client01"))
var serverID SessionID
copy(serverID[:], []byte("server01"))
clientControl := NewControlChannel(clientIO, nil, clientID)
serverControl := NewControlChannel(serverIO, nil, serverID)
client := &Client{
config: &ClientConfig{Proto: ProtoUDP},
control: clientControl,
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := clientControl.SendReset(ctx); err != nil {
t.Fatal(err)
}
errCh := make(chan error, 1)
go func() {
packet, err := serverControl.Read(ctx)
if err != nil {
errCh <- err
return
}
if packet.Opcode != PControlHardResetClientV2 {
errCh <- errors.New("unexpected reset opcode")
return
}
raw, err := serverIO.ReadPacket(ctx)
if err != nil {
errCh <- err
return
}
packet, _, _, err = DecodeControlPacket(nil, raw)
if err != nil {
errCh <- err
return
}
if packet.Opcode != PControlHardResetClientV2 || packet.MessageID != 0 {
errCh <- errors.New("unexpected retransmitted reset packet")
return
}
_, err = serverControl.Send(ctx, PControlHardResetServerV2, nil)
errCh <- err
}()
if err := client.waitServerReset(ctx); err != nil {
t.Fatal(err)
}
if err := <-errCh; err != nil {
t.Fatal(err)
}
if clientControl.PendingMessages() != 0 {
t.Fatalf("expected client reset to be acked, pending=%d", clientControl.PendingMessages())
}
}
func TestTCPPacketIOFraming(t *testing.T) {
client, server := net.Pipe()
defer client.Close()
+371 -62
View File
@@ -1,94 +1,241 @@
package openvpn
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/md5"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/binary"
"errors"
"fmt"
"hash"
"sync"
"golang.org/x/crypto/chacha20poly1305"
)
const (
AESGCMTagSize = 16
AESGCMIVSize = 12
DataChannelTagSize = 16
DataChannelIVSize = 12
DataChannelCBCIVSize = aes.BlockSize
dataChannelIVRandBuf = 32 * 1024
dataChannelReplayWindow = 64
PeerIDUnset uint32 = 0xffffff
)
type DataChannel struct {
send cipher.AEAD
recv cipher.AEAD
// OpenVPN data-channel ping payload, matching PING_STRING in upstream OpenVPN.
var openVPNPingPacket = []byte{
0x2a, 0x18, 0x7b, 0xf3,
0x64, 0x1e, 0xb4, 0xcb,
0x07, 0xed, 0x2d, 0x0a,
0x98, 0x1f, 0xc7, 0x48,
}
sendImplicitIV [AESGCMIVSize]byte
recvImplicitIV [AESGCMIVSize]byte
func IsPingPacket(packet []byte) bool {
return bytes.Equal(packet, openVPNPingPacket)
}
type DataChannel struct {
sendAEAD cipher.AEAD
recvAEAD cipher.AEAD
sendBlock cipher.Block
recvBlock cipher.Block
sendHMACKey []byte
recvHMACKey []byte
authHash func() hash.Hash
authSize int
sendMACPool sync.Pool
recvMACPool sync.Pool
sendImplicitIV [DataChannelIVSize]byte
recvImplicitIV [DataChannelIVSize]byte
keyID uint8
peerID uint32
header []byte
mu sync.Mutex
sendPacketID uint32
recvHighest uint32
recvWindow uint64
recvSeen bool
randMu sync.Mutex
randBuf []byte
randOffset int
}
func NewDataChannel(keys *KeyMaterial, peerID uint32) (*DataChannel, error) {
func NewDataChannel(keys *KeyMaterial, cipherName, authName string, peerID uint32) (*DataChannel, error) {
if keys == nil {
return nil, errors.New("nil openvpn key material")
}
sendBlock, err := aes.NewCipher(keys.SendCipherKey)
if isDataChannelAEAD(cipherName) {
send, err := newDataChannelAEAD(cipherName, keys.SendCipherKey)
if err != nil {
return nil, fmt.Errorf("create send cipher: %w", err)
}
recv, err := newDataChannelAEAD(cipherName, keys.RecvCipherKey)
if err != nil {
return nil, fmt.Errorf("create recv cipher: %w", err)
}
if len(keys.SendHMACKey) < DataChannelIVSize-4 || len(keys.RecvHMACKey) < DataChannelIVSize-4 {
return nil, errors.New("openvpn implicit IV keys are too short")
}
d := &DataChannel{
sendAEAD: send,
recvAEAD: recv,
peerID: peerID,
header: dataHeader(peerID, 0),
}
copy(d.sendImplicitIV[4:], keys.SendHMACKey[:DataChannelIVSize-4])
copy(d.recvImplicitIV[4:], keys.RecvHMACKey[:DataChannelIVSize-4])
return d, nil
}
send, err := newDataChannelCBC(cipherName, keys.SendCipherKey)
if err != nil {
return nil, fmt.Errorf("create send cipher: %w", err)
}
recvBlock, err := aes.NewCipher(keys.RecvCipherKey)
recv, err := newDataChannelCBC(cipherName, keys.RecvCipherKey)
if err != nil {
return nil, fmt.Errorf("create recv cipher: %w", err)
}
send, err := cipher.NewGCMWithTagSize(sendBlock, AESGCMTagSize)
authHash, authSize, err := newDataChannelAuth(authName)
if err != nil {
return nil, fmt.Errorf("create send gcm: %w", err)
return nil, err
}
recv, err := cipher.NewGCMWithTagSize(recvBlock, AESGCMTagSize)
if err != nil {
return nil, fmt.Errorf("create recv gcm: %w", err)
}
if len(keys.SendHMACKey) < AESGCMIVSize-4 || len(keys.RecvHMACKey) < AESGCMIVSize-4 {
return nil, errors.New("openvpn implicit IV keys are too short")
if len(keys.SendHMACKey) < authSize || len(keys.RecvHMACKey) < authSize {
return nil, errors.New("openvpn HMAC keys are too short")
}
d := &DataChannel{
send: send,
recv: recv,
peerID: peerID,
sendBlock: send,
recvBlock: recv,
sendHMACKey: append([]byte(nil), keys.SendHMACKey[:authSize]...),
recvHMACKey: append([]byte(nil), keys.RecvHMACKey[:authSize]...),
authHash: authHash,
authSize: authSize,
peerID: peerID,
header: dataHeader(peerID, 0),
}
d.sendMACPool.New = func() any {
return hmac.New(d.authHash, d.sendHMACKey)
}
d.recvMACPool.New = func() any {
return hmac.New(d.authHash, d.recvHMACKey)
}
copy(d.sendImplicitIV[4:], keys.SendHMACKey[:AESGCMIVSize-4])
copy(d.recvImplicitIV[4:], keys.RecvHMACKey[:AESGCMIVSize-4])
return d, nil
}
func isDataChannelAEAD(cipherName string) bool {
switch cipherName {
case CipherAES128GCM, CipherAES192GCM, CipherAES256GCM, CipherChaCha20Poly1305:
return true
default:
return false
}
}
func newDataChannelAEAD(cipherName string, key []byte) (cipher.AEAD, error) {
switch cipherName {
case CipherAES128GCM, CipherAES192GCM, CipherAES256GCM:
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return cipher.NewGCMWithTagSize(block, DataChannelTagSize)
case CipherChaCha20Poly1305:
return chacha20poly1305.New(key)
default:
return nil, fmt.Errorf("unsupported openvpn cipher %q", cipherName)
}
}
func newDataChannelCBC(cipherName string, key []byte) (cipher.Block, error) {
switch cipherName {
case CipherAESCBC, CipherAES128CBC, CipherAES192CBC, CipherAES256CBC:
return aes.NewCipher(key)
default:
return nil, fmt.Errorf("unsupported openvpn cipher %q", cipherName)
}
}
func newDataChannelAuth(authName string) (func() hash.Hash, int, error) {
switch authName {
case AuthMD5:
return md5.New, md5.Size, nil
case AuthSHA1:
return sha1.New, sha1.Size, nil
case AuthSHA256:
return sha256.New, sha256.Size, nil
case AuthSHA384:
return sha512.New384, sha512.Size384, nil
case AuthSHA512:
return sha512.New, sha512.Size, nil
default:
return nil, 0, fmt.Errorf("unsupported openvpn auth %q", authName)
}
}
func (d *DataChannel) Encrypt(packet []byte) ([]byte, error) {
if d == nil {
return nil, errors.New("nil openvpn data channel")
}
d.mu.Lock()
d.sendPacketID++
packetID := d.sendPacketID
d.mu.Unlock()
packetID := d.nextPacketID()
if d.sendAEAD != nil {
return d.encryptAEAD(packet, packetID)
}
return d.encryptCBC(packet, packetID)
}
header := d.dataHeader()
func (d *DataChannel) encryptAEAD(packet []byte, packetID uint32) ([]byte, error) {
header := d.header
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[:]...)
sealed := d.send.Seal(nil, nonce[:], packet, ad)
sealed := d.sendAEAD.Seal(nil, nonce[:], packet, ad)
out := make([]byte, 0, len(header)+4+AESGCMTagSize+len(packet))
out := make([]byte, 0, len(header)+4+DataChannelTagSize+len(packet))
out = append(out, header...)
out = append(out, packetIDBytes[:]...)
out = append(out, sealed[len(sealed)-AESGCMTagSize:]...)
out = append(out, sealed[:len(sealed)-AESGCMTagSize]...)
out = append(out, sealed[len(sealed)-DataChannelTagSize:]...)
out = append(out, sealed[:len(sealed)-DataChannelTagSize]...)
return out, nil
}
func (d *DataChannel) encryptCBC(packet []byte, packetID uint32) ([]byte, error) {
header := d.header
blockSize := d.sendBlock.BlockSize()
plainLen := 4 + len(packet)
padding := blockSize - plainLen%blockSize
if padding == 0 {
padding = blockSize
}
out := make([]byte, len(header)+d.authSize+DataChannelCBCIVSize+plainLen+padding)
copy(out, header)
authenticated := out[len(header)+d.authSize:]
iv := authenticated[:DataChannelCBCIVSize]
if err := d.fillCBCIV(iv); err != nil {
return nil, err
}
ciphertext := authenticated[DataChannelCBCIVSize:]
binary.BigEndian.PutUint32(ciphertext[:4], packetID)
copy(ciphertext[4:], packet)
for i := plainLen; i < len(ciphertext); i++ {
ciphertext[i] = byte(padding)
}
cipher.NewCBCEncrypter(d.sendBlock, iv).CryptBlocks(ciphertext, ciphertext)
_ = d.hmacAppend(&d.sendMACPool, authenticated, out[len(header):len(header)])
return out, nil
}
@@ -96,26 +243,29 @@ func (d *DataChannel) Decrypt(packet []byte) ([]byte, error) {
if d == nil {
return nil, errors.New("nil openvpn data channel")
}
headerSize, err := dataPacketHeaderSize(packet)
if err != nil {
return nil, err
}
if d.recvAEAD != nil {
return d.decryptAEAD(packet, headerSize)
}
return d.decryptCBC(packet, headerSize)
}
func (d *DataChannel) decryptAEAD(packet []byte, headerSize int) ([]byte, error) {
if len(packet) < 1 {
return nil, errors.New("empty openvpn data packet")
}
opcode, _ := parseOpcodeKeyID(packet[0])
headerSize := 1
if opcode == PDataV2 {
headerSize = 4
}
if opcode != PDataV1 && opcode != PDataV2 {
return nil, fmt.Errorf("not an openvpn data packet: %s", opcode)
}
if len(packet) < headerSize+4+AESGCMTagSize+1 {
if len(packet) < headerSize+4+DataChannelTagSize+1 {
return nil, errors.New("openvpn data packet too short")
}
header := packet[:headerSize]
packetIDBytes := packet[headerSize : headerSize+4]
packetID := binary.BigEndian.Uint32(packetIDBytes)
tag := packet[headerSize+4 : headerSize+4+AESGCMTagSize]
ciphertext := packet[headerSize+4+AESGCMTagSize:]
combined := make([]byte, 0, len(ciphertext)+AESGCMTagSize)
tag := packet[headerSize+4 : headerSize+4+DataChannelTagSize]
ciphertext := packet[headerSize+4+DataChannelTagSize:]
combined := make([]byte, 0, len(ciphertext)+DataChannelTagSize)
combined = append(combined, ciphertext...)
combined = append(combined, tag...)
ad := make([]byte, 0, len(header)+len(packetIDBytes))
@@ -123,40 +273,199 @@ func (d *DataChannel) Decrypt(packet []byte) ([]byte, error) {
ad = append(ad, packetIDBytes...)
nonce := d.nonce(packetID, d.recvImplicitIV)
plain, err := d.recv.Open(nil, nonce[:], combined, ad)
plain, err := d.recvAEAD.Open(nil, nonce[:], combined, ad)
if err != nil {
return nil, err
}
d.mu.Lock()
if d.recvSeen && packetID <= d.recvHighest {
d.mu.Unlock()
return nil, fmt.Errorf("openvpn replayed data packet id %d", packetID)
if err := d.acceptPacketID(packetID); err != nil {
return nil, err
}
d.recvHighest = packetID
d.recvSeen = true
d.mu.Unlock()
return plain, nil
}
func (d *DataChannel) dataHeader() []byte {
if d.peerID != PeerIDUnset {
return []byte{
opcodeKeyID(PDataV2, d.keyID),
byte(d.peerID >> 16),
byte(d.peerID >> 8),
byte(d.peerID),
}
func (d *DataChannel) decryptCBC(packet []byte, headerSize int) ([]byte, error) {
blockSize := d.recvBlock.BlockSize()
minPacketLen := headerSize + d.authSize + blockSize + blockSize
if len(packet) < minPacketLen {
return nil, errors.New("openvpn CBC data packet too short")
}
return []byte{opcodeKeyID(PDataV1, d.keyID)}
body := packet[headerSize:]
tag := body[:d.authSize]
authenticated := body[d.authSize:]
var expectedBuf [sha256.Size]byte
expected := d.hmacAppend(&d.recvMACPool, authenticated, expectedBuf[:0])
if !hmac.Equal(tag, expected) {
return nil, errors.New("openvpn CBC data packet HMAC authentication failed")
}
iv := authenticated[:blockSize]
ciphertext := authenticated[blockSize:]
if len(ciphertext) == 0 || len(ciphertext)%blockSize != 0 {
return nil, errors.New("invalid openvpn CBC ciphertext length")
}
cipher.NewCBCDecrypter(d.recvBlock, iv).CryptBlocks(ciphertext, ciphertext)
plain, err := pkcs7Unpad(ciphertext, blockSize)
if err != nil {
return nil, err
}
if len(plain) < 4 {
return nil, errors.New("openvpn CBC plaintext missing packet id")
}
packetID := binary.BigEndian.Uint32(plain[:4])
if err := d.acceptPacketID(packetID); err != nil {
return nil, err
}
return plain[4:], nil
}
func (d *DataChannel) nonce(packetID uint32, implicit [AESGCMIVSize]byte) [AESGCMIVSize]byte {
func dataPacketHeaderSize(packet []byte) (int, error) {
if len(packet) < 1 {
return 0, errors.New("empty openvpn data packet")
}
opcode, _ := parseOpcodeKeyID(packet[0])
switch opcode {
case PDataV1:
return 1, nil
case PDataV2:
if len(packet) < 4 {
return 0, errors.New("openvpn P_DATA_V2 packet missing peer id")
}
return 4, nil
default:
return 0, fmt.Errorf("not an openvpn data packet: %s", opcode)
}
}
func (d *DataChannel) nextPacketID() uint32 {
d.mu.Lock()
defer d.mu.Unlock()
d.sendPacketID++
return d.sendPacketID
}
func (d *DataChannel) acceptPacketID(packetID uint32) error {
d.mu.Lock()
defer d.mu.Unlock()
if !d.recvSeen {
d.recvHighest = packetID
d.recvWindow = 1
d.recvSeen = true
return nil
}
if packetID > d.recvHighest {
shift := packetID - d.recvHighest
if shift >= dataChannelReplayWindow {
d.recvWindow = 1
} else {
d.recvWindow = d.recvWindow<<shift | 1
}
d.recvHighest = packetID
return nil
}
diff := d.recvHighest - packetID
if diff >= dataChannelReplayWindow {
return fmt.Errorf("openvpn replayed data packet id %d", packetID)
}
mask := uint64(1) << diff
if d.recvWindow&mask != 0 {
return fmt.Errorf("openvpn replayed data packet id %d", packetID)
}
d.recvWindow |= mask
return nil
}
func dataHeader(peerID uint32, keyID uint8) []byte {
if peerID != PeerIDUnset {
return []byte{
opcodeKeyID(PDataV2, keyID),
byte(peerID >> 16),
byte(peerID >> 8),
byte(peerID),
}
}
return []byte{opcodeKeyID(PDataV1, keyID)}
}
func (d *DataChannel) nonce(packetID uint32, implicit [DataChannelIVSize]byte) [DataChannelIVSize]byte {
nonce := implicit
binary.BigEndian.PutUint32(nonce[:4], binary.BigEndian.Uint32(nonce[:4])^packetID)
return nonce
}
func (d *DataChannel) fillCBCIV(iv []byte) error {
d.randMu.Lock()
defer d.randMu.Unlock()
for len(iv) > 0 {
if d.randOffset == len(d.randBuf) {
if d.randBuf == nil {
d.randBuf = make([]byte, dataChannelIVRandBuf)
}
if _, err := rand.Read(d.randBuf); err != nil {
return err
}
d.randOffset = 0
}
n := copy(iv, d.randBuf[d.randOffset:])
d.randOffset += n
iv = iv[n:]
}
return nil
}
func dataChannelHMAC(newHash func() hash.Hash, key, data []byte) []byte {
return dataChannelHMACAppend(newHash, key, data, nil)
}
func dataChannelHMACAppend(newHash func() hash.Hash, key, data, dst []byte) []byte {
mac := hmac.New(newHash, key)
_, _ = mac.Write(data)
return mac.Sum(dst)
}
func (d *DataChannel) hmacAppend(pool *sync.Pool, data, dst []byte) []byte {
mac := pool.Get().(hash.Hash)
defer pool.Put(mac)
mac.Reset()
_, _ = mac.Write(data)
return mac.Sum(dst)
}
func pkcs7Pad(plain []byte, blockSize int) []byte {
padding := blockSize - len(plain)%blockSize
if padding == 0 {
padding = blockSize
}
out := make([]byte, len(plain)+padding)
copy(out, plain)
for i := len(plain); i < len(out); i++ {
out[i] = byte(padding)
}
return out
}
func pkcs7Unpad(padded []byte, blockSize int) ([]byte, error) {
if len(padded) == 0 || len(padded)%blockSize != 0 {
return nil, errors.New("invalid openvpn CBC padding length")
}
padding := int(padded[len(padded)-1])
if padding == 0 || padding > blockSize || padding > len(padded) {
return nil, errors.New("invalid openvpn CBC padding")
}
for _, b := range padded[len(padded)-padding:] {
if int(b) != padding {
return nil, errors.New("invalid openvpn CBC padding")
}
}
return padded[:len(padded)-padding], nil
}
func ParsePeerID(options string) uint32 {
for _, field := range splitPushOptions(options) {
if len(field) > len("peer-id ") && field[:len("peer-id ")] == "peer-id " {
+167 -2
View File
@@ -2,6 +2,8 @@ package openvpn
import (
"bytes"
"crypto/aes"
"crypto/sha1"
"encoding/binary"
"testing"
)
@@ -19,11 +21,11 @@ func TestDataChannelAESGCMV2RoundTrip(t *testing.T) {
RecvCipherKey: clientKeys.SendCipherKey,
RecvHMACKey: clientKeys.SendHMACKey,
}
client, err := NewDataChannel(clientKeys, 7)
client, err := NewDataChannel(clientKeys, CipherAES128GCM, AuthSHA256, 7)
if err != nil {
t.Fatal(err)
}
server, err := NewDataChannel(serverKeys, 7)
server, err := NewDataChannel(serverKeys, CipherAES128GCM, AuthSHA256, 7)
if err != nil {
t.Fatal(err)
}
@@ -60,6 +62,56 @@ func TestDataChannelAESGCMV2RoundTrip(t *testing.T) {
}
}
func TestDataChannelAcceptsOutOfOrderPacketsWithinReplayWindow(t *testing.T) {
clientKeys := &KeyMaterial{
SendCipherKey: bytes.Repeat([]byte{0x11}, 16),
SendHMACKey: bytes.Repeat([]byte{0x22}, maxHMACKeyLength),
RecvCipherKey: bytes.Repeat([]byte{0x33}, 16),
RecvHMACKey: bytes.Repeat([]byte{0x44}, maxHMACKeyLength),
}
serverKeys := &KeyMaterial{
SendCipherKey: clientKeys.RecvCipherKey,
SendHMACKey: clientKeys.RecvHMACKey,
RecvCipherKey: clientKeys.SendCipherKey,
RecvHMACKey: clientKeys.SendHMACKey,
}
client, err := NewDataChannel(clientKeys, CipherAES128GCM, AuthSHA256, 7)
if err != nil {
t.Fatal(err)
}
server, err := NewDataChannel(serverKeys, CipherAES128GCM, AuthSHA256, 7)
if err != nil {
t.Fatal(err)
}
packets := [][]byte{
{0x45, 0, 0, 20, 1, 2, 3, 4, 64, 6, 0, 0, 10, 8, 0, 2, 1, 1, 1, 1},
{0x45, 0, 0, 20, 1, 2, 3, 5, 64, 6, 0, 0, 10, 8, 0, 2, 1, 1, 1, 1},
{0x45, 0, 0, 20, 1, 2, 3, 6, 64, 6, 0, 0, 10, 8, 0, 2, 1, 1, 1, 1},
}
encrypted := make([][]byte, 0, len(packets))
for _, packet := range packets {
out, err := client.Encrypt(packet)
if err != nil {
t.Fatal(err)
}
encrypted = append(encrypted, out)
}
for _, index := range []int{0, 2, 1} {
plain, err := server.Decrypt(encrypted[index])
if err != nil {
t.Fatalf("decrypt packet %d: %v", index+1, err)
}
if !bytes.Equal(plain, packets[index]) {
t.Fatalf("unexpected packet %d plaintext: %x", index+1, plain)
}
}
if _, err := server.Decrypt(encrypted[1]); err == nil {
t.Fatal("expected duplicate packet to be rejected")
}
}
func TestParsePushReply(t *testing.T) {
reply, err := ParsePushReply("PUSH_REPLY,redirect-gateway def1,dhcp-option DNS 8.8.8.8,ifconfig 10.8.0.2 255.255.255.0,peer-id 3,block-ipv6\x00")
if err != nil {
@@ -75,3 +127,116 @@ func TestParsePushReply(t *testing.T) {
t.Fatalf("unexpected DNS: %#v", reply.DNS)
}
}
func TestParsePushReplyPointToPointIfconfig(t *testing.T) {
reply, err := ParsePushReply("PUSH_REPLY,redirect-gateway def1,dhcp-option DNS 10.211.254.254,ifconfig 10.211.1.37 10.211.254.254,peer-id 16777215\x00")
if err != nil {
t.Fatal(err)
}
if len(reply.Prefixes) != 1 || reply.Prefixes[0].String() != "10.211.1.37/32" {
t.Fatalf("unexpected prefixes: %#v", reply.Prefixes)
}
if len(reply.DNS) != 1 || reply.DNS[0].String() != "10.211.254.254" {
t.Fatalf("unexpected DNS: %#v", reply.DNS)
}
}
func TestDataChannelChaCha20Poly1305V2RoundTrip(t *testing.T) {
clientKeys := &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),
}
serverKeys := &KeyMaterial{
SendCipherKey: clientKeys.RecvCipherKey,
SendHMACKey: clientKeys.RecvHMACKey,
RecvCipherKey: clientKeys.SendCipherKey,
RecvHMACKey: clientKeys.SendHMACKey,
}
client, err := NewDataChannel(clientKeys, CipherChaCha20Poly1305, AuthSHA256, 7)
if err != nil {
t.Fatal(err)
}
server, err := NewDataChannel(serverKeys, CipherChaCha20Poly1305, AuthSHA256, 7)
if err != nil {
t.Fatal(err)
}
ipPacket := []byte{0x45, 0, 0, 20, 1, 2, 3, 4, 64, 17, 0, 0, 10, 8, 0, 2, 1, 1, 1, 1}
encrypted, err := client.Encrypt(ipPacket)
if err != nil {
t.Fatal(err)
}
plain, err := server.Decrypt(encrypted)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(plain, ipPacket) {
t.Fatalf("unexpected decrypted packet: %x", plain)
}
encrypted[len(encrypted)-1] ^= 0xff
if _, err := server.Decrypt(encrypted); err == nil {
t.Fatal("expected authentication failure")
}
}
func TestDataChannelAESCBCSHA1V2RoundTrip(t *testing.T) {
clientKeys := &KeyMaterial{
SendCipherKey: bytes.Repeat([]byte{0x11}, 16),
SendHMACKey: bytes.Repeat([]byte{0x22}, maxHMACKeyLength),
RecvCipherKey: bytes.Repeat([]byte{0x33}, 16),
RecvHMACKey: bytes.Repeat([]byte{0x44}, maxHMACKeyLength),
}
serverKeys := &KeyMaterial{
SendCipherKey: clientKeys.RecvCipherKey,
SendHMACKey: clientKeys.RecvHMACKey,
RecvCipherKey: clientKeys.SendCipherKey,
RecvHMACKey: clientKeys.SendHMACKey,
}
client, err := NewDataChannel(clientKeys, CipherAES128CBC, AuthSHA1, 7)
if err != nil {
t.Fatal(err)
}
server, err := NewDataChannel(serverKeys, CipherAES128CBC, AuthSHA1, 7)
if err != nil {
t.Fatal(err)
}
ipPacket := []byte{0x45, 0, 0, 20, 1, 2, 3, 4, 64, 6, 0, 0, 10, 8, 0, 2, 1, 1, 1, 1}
encrypted, err := client.Encrypt(ipPacket)
if err != nil {
t.Fatal(err)
}
if opcode, _ := parseOpcodeKeyID(encrypted[0]); opcode != PDataV2 {
t.Fatalf("unexpected data opcode: %s", opcode)
}
headerSize := 4
if len(encrypted) < headerSize+sha1.Size+DataChannelCBCIVSize+aes.BlockSize {
t.Fatalf("encrypted CBC packet too short: %d", len(encrypted))
}
if len(encrypted[headerSize+sha1.Size+DataChannelCBCIVSize:])%aes.BlockSize != 0 {
t.Fatal("encrypted CBC payload is not block aligned")
}
plain, err := server.Decrypt(encrypted)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(plain, ipPacket) {
t.Fatalf("unexpected decrypted packet: %x", plain)
}
encrypted[len(encrypted)-1] ^= 0xff
if _, err := server.Decrypt(encrypted); err == nil {
t.Fatal("expected HMAC authentication failure")
}
encrypted, err = client.Encrypt(ipPacket)
if err != nil {
t.Fatal(err)
}
encrypted[headerSize+sha1.Size] ^= 0xff
if _, err := server.Decrypt(encrypted); err == nil {
t.Fatal("expected HMAC authentication failure after IV tamper")
}
}
+16 -6
View File
@@ -114,7 +114,7 @@ func ParseServerKeyMethod2Record(packet []byte) (*KeyMethod2Record, error) {
}
func DeriveClientKeyMaterial(sources KeySource2, clientSession, serverSession SessionID, cipherKeyLen int) (*KeyMaterial, error) {
if cipherKeyLen != 16 && cipherKeyLen != 32 {
if cipherKeyLen != 16 && cipherKeyLen != 24 && cipherKeyLen != 32 {
return nil, fmt.Errorf("unsupported data cipher key length %d", cipherKeyLen)
}
var master [48]byte
@@ -153,20 +153,30 @@ func DeriveClientKeyMaterial(sources KeySource2, clientSession, serverSession Se
}, nil
}
func InstallScriptOptionsString(proto, cipher, auth string) string {
func InstallScriptOptionsString(proto, cipher, auth string, compLZO string) string {
protoName := "UDPv4"
if proto == ProtoTCP {
protoName = "TCPv4_CLIENT"
}
keysize := "128"
if cipher == CipherAES256GCM {
if cipher == CipherAES256GCM || cipher == CipherAES256CBC || cipher == CipherChaCha20Poly1305 {
keysize = "256"
}
return fmt.Sprintf("V4,dev-type tun,link-mtu 1550,tun-mtu 1500,proto %s,cipher %s,auth %s,keysize %s,key-method 2,tls-client", protoName, cipher, auth, keysize)
mtu := "1550"
comp := ""
if compLZO == CompLzoYes {
mtu = "1544"
comp = "comp-lzo,"
}
return fmt.Sprintf("V4,dev-type tun,link-mtu %s,tun-mtu 1500,proto %s,%scipher %s,auth %s,keysize %s,key-method 2,tls-client", mtu, protoName, comp, cipher, auth, keysize)
}
func InstallScriptPeerInfo(cipher string) string {
return fmt.Sprintf("IV_VER=mihomo-openvpn\nIV_PROTO=6\nIV_CIPHERS=%s\n", cipher)
func InstallScriptPeerInfo(cipher string, compLZO string) string {
lzo := ""
if compLZO == CompLzoYes {
lzo = "IV_LZO=1\n"
}
return fmt.Sprintf("IV_VER=mihomo-openvpn\nIV_PROTO=6\n%sIV_CIPHERS=%s\n", lzo, cipher)
}
func appendOpenVPNString(out []byte, s string) []byte {
+13 -4
View File
@@ -8,8 +8,8 @@ import (
func TestKeyMethod2ClientMarshalAndDerive(t *testing.T) {
record := &KeyMethod2Record{
Options: InstallScriptOptionsString(ProtoUDP, CipherAES128GCM, AuthSHA256),
PeerInfo: InstallScriptPeerInfo(CipherAES128GCM),
Options: InstallScriptOptionsString(ProtoUDP, CipherAES128GCM, AuthSHA256, ""),
PeerInfo: InstallScriptPeerInfo(CipherAES128GCM, ""),
}
for i := range record.Sources.Client.PreMaster {
record.Sources.Client.PreMaster[i] = byte(i + 1)
@@ -52,8 +52,8 @@ func TestKeyMethod2ClientMarshalAndDerive(t *testing.T) {
func TestKeyMethod2DeriveAES256(t *testing.T) {
record := &KeyMethod2Record{
Options: InstallScriptOptionsString(ProtoUDP, CipherAES256GCM, AuthSHA256),
PeerInfo: InstallScriptPeerInfo(CipherAES256GCM),
Options: InstallScriptOptionsString(ProtoUDP, CipherAES256GCM, AuthSHA256, ""),
PeerInfo: InstallScriptPeerInfo(CipherAES256GCM, ""),
}
for i := range record.Sources.Client.PreMaster {
record.Sources.Client.PreMaster[i] = byte(i + 1)
@@ -82,6 +82,15 @@ func TestKeyMethod2DeriveAES256(t *testing.T) {
}
}
func TestInstallScriptOptionsCBCSHA1(t *testing.T) {
options := InstallScriptOptionsString(ProtoTCP, CipherAES256CBC, AuthSHA1, "")
for _, want := range []string{"proto TCPv4_CLIENT", "cipher AES-256-CBC", "auth SHA1", "keysize 256"} {
if !bytes.Contains([]byte(options), []byte(want)) {
t.Fatalf("options missing %q: %s", want, options)
}
}
}
func TestParseServerKeyMethod2Record(t *testing.T) {
var packet []byte
packet = binary.BigEndian.AppendUint32(packet, 0)
+52
View File
@@ -0,0 +1,52 @@
package openvpn
import (
"bytes"
"errors"
"github.com/rasky/go-lzo"
)
const (
lzoCompressNone = 0xFA // not compressed
lzoCompressLZO = 0x66 // LZO compressed
)
var ErrLZODecompress = errors.New("lzo decompression failed")
// lzo1xDecompressSafe handles OpenVPN comp-lzo data packets.
// First byte is the compression header, followed by the payload.
func lzo1xDecompressSafe(src []byte) ([]byte, error) {
if len(src) == 0 {
return nil, ErrLZODecompress
}
switch src[0] {
case lzoCompressNone:
if len(src) > 1 {
return src[1:], nil
}
return nil, nil
case lzoCompressLZO:
if len(src) > 1 {
r := bytes.NewReader(src[1:])
out, err := lzo.Decompress1X(r, len(src)-1, 0)
if err != nil {
return nil, ErrLZODecompress
}
return out, nil
}
return nil, nil
default:
return nil, ErrLZODecompress
}
}
// lzo1xCompressSafe handles OpenVPN comp-lzo data packets.
// Prepend comp-lzo header (0xfa = not compressed) to satisfy servers expecting the framing.
func lzo1xCompressSafe(src []byte) ([]byte, error) {
lzoPacket := make([]byte, 1+len(src))
lzoPacket[0] = lzoCompressNone
copy(lzoPacket[1:], src)
return lzoPacket, nil
}
+23
View File
@@ -0,0 +1,23 @@
package openvpn
import (
"bytes"
"crypto/rand"
"testing"
)
func TestLzo1xSafe(t *testing.T) {
data := make([]byte, 1024)
rand.Read(data)
compressed, err := lzo1xCompressSafe(data)
if err != nil {
t.Fatal(err)
}
decompressed, err := lzo1xDecompressSafe(compressed)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(data, decompressed) {
t.Fatal("decompressed data is not equal to original")
}
}
+29 -4
View File
@@ -168,9 +168,6 @@ func DecodeControlPlain(opcode Opcode, plain []byte) (ackIDs []uint32, ackRemote
}
func (p ControlPacket) Encode(crypt *TLSCrypt, packetID uint32, unixTime uint32) ([]byte, error) {
if crypt == nil {
return nil, errors.New("tls-crypt is required")
}
plain, err := p.EncodePlain()
if err != nil {
return nil, err
@@ -179,12 +176,40 @@ func (p ControlPacket) Encode(crypt *TLSCrypt, packetID uint32, unixTime uint32)
header := make([]byte, TLSCryptHeaderSize)
header[0] = opcodeKeyID(p.Opcode, p.KeyID)
copy(header[1:], p.LocalSession[:])
if crypt == nil {
out := make([]byte, 0, len(header)+len(plain))
out = append(out, header...)
out = append(out, plain...)
return out, nil
}
return crypt.Wrap(header, packetID, unixTime, plain)
}
func DecodeControlPacket(crypt *TLSCrypt, packet []byte) (*ControlPacket, uint32, uint32, error) {
if crypt == nil {
return nil, 0, 0, errors.New("tls-crypt is required")
if len(packet) < TLSCryptHeaderSize+1 {
return nil, 0, 0, errors.New("control packet too short")
}
header := packet[:TLSCryptHeaderSize]
opcode, keyID := parseOpcodeKeyID(header[0])
if !opcode.IsControl() {
return nil, 0, 0, fmt.Errorf("opcode %s is not a control opcode", opcode)
}
var local SessionID
copy(local[:], header[1:])
ackIDs, ackRemote, messageID, payload, err := DecodeControlPlain(opcode, packet[TLSCryptHeaderSize:])
if err != nil {
return nil, 0, 0, err
}
return &ControlPacket{
Opcode: opcode,
KeyID: keyID,
LocalSession: local,
AckIDs: ackIDs,
AckRemoteSession: ackRemote,
MessageID: messageID,
Payload: payload,
}, 0, 0, nil
}
header, packetID, unixTime, plain, err := crypt.Unwrap(packet)
if err != nil {
+46
View File
@@ -58,6 +58,52 @@ func TestControlPacketEncodeDecodeWithTLSCrypt(t *testing.T) {
}
}
func TestControlPacketEncodeDecodePlain(t *testing.T) {
var local SessionID
copy(local[:], []byte("client01"))
var remote SessionID
copy(remote[:], []byte("server01"))
packet := ControlPacket{
Opcode: PControlV1,
KeyID: 1,
LocalSession: local,
AckIDs: []uint32{11},
AckRemoteSession: remote,
MessageID: 12,
Payload: []byte("plain control"),
}
encoded, err := packet.Encode(nil, 0, 0)
if err != nil {
t.Fatal(err)
}
decoded, packetID, unixTime, err := DecodeControlPacket(nil, encoded)
if err != nil {
t.Fatal(err)
}
if packetID != 0 || unixTime != 0 {
t.Fatalf("unexpected plain packet id/time: %d/%d", packetID, unixTime)
}
if decoded.Opcode != packet.Opcode || decoded.KeyID != packet.KeyID {
t.Fatalf("unexpected opcode/key-id: %s/%d", decoded.Opcode, decoded.KeyID)
}
if decoded.LocalSession != local {
t.Fatalf("unexpected local session: %x", decoded.LocalSession)
}
if decoded.MessageID != packet.MessageID {
t.Fatalf("unexpected message id: %d", decoded.MessageID)
}
if !bytes.Equal(decoded.Payload, packet.Payload) {
t.Fatalf("unexpected payload: %q", decoded.Payload)
}
if len(decoded.AckIDs) != 1 || decoded.AckIDs[0] != 11 {
t.Fatalf("unexpected ack ids: %#v", decoded.AckIDs)
}
if decoded.AckRemoteSession != remote {
t.Fatalf("unexpected ack remote session: %x", decoded.AckRemoteSession)
}
}
func TestAckPacketRejectsTrailingPayload(t *testing.T) {
_, _, _, _, err := DecodeControlPlain(PAckV1, []byte{0, 1})
if err == nil {
+59 -6
View File
@@ -12,6 +12,7 @@ const PushRequest = "PUSH_REQUEST"
type PushReply struct {
Raw string
Prefixes []netip.Prefix
Routes []netip.Prefix
DNS []netip.Addr
PeerID uint32
Redirect bool
@@ -49,6 +50,22 @@ func ParsePushReply(message string) (*PushReply, error) {
}
reply.Prefixes = append(reply.Prefixes, prefix)
}
case "route":
if len(fields) >= 3 {
prefix, err := parseIPv4Route(fields[1], fields[2])
if err != nil {
continue
}
reply.Routes = append(reply.Routes, prefix)
}
case "route-ipv6":
if len(fields) >= 2 {
prefix, err := netip.ParsePrefix(fields[1])
if err != nil {
continue
}
reply.Routes = append(reply.Routes, prefix)
}
case "dhcp-option":
if len(fields) >= 3 && fields[1] == "DNS" {
if addr, err := netip.ParseAddr(fields[2]); err == nil {
@@ -91,27 +108,63 @@ func splitPushOptions(message string) []string {
return out
}
func parseIPv4Ifconfig(address, mask string) (netip.Prefix, error) {
func parseIPv4Ifconfig(address, maskOrPeer string) (netip.Prefix, error) {
addr, err := netip.ParseAddr(address)
if err != nil {
return netip.Prefix{}, fmt.Errorf("parse pushed ipv4 address %q: %w", address, err)
}
maskAddr, err := netip.ParseAddr(mask)
maskAddr, err := netip.ParseAddr(maskOrPeer)
if err != nil {
return netip.Prefix{}, fmt.Errorf("parse pushed ipv4 mask %q: %w", mask, err)
return netip.Prefix{}, fmt.Errorf("parse pushed ipv4 mask %q: %w", maskOrPeer, err)
}
if !addr.Is4() || !maskAddr.Is4() {
return netip.Prefix{}, fmt.Errorf("openvpn ifconfig requires ipv4 address and mask")
}
maskBytes := maskAddr.As4()
if ones, ok := ipv4MaskSize(maskAddr); ok {
return netip.PrefixFrom(addr, ones), nil
}
// Some servers, including SoftEther/VPNGate in net30/p2p mode, push
// "ifconfig <local> <remote>" rather than "ifconfig <local> <netmask>".
// Use a host prefix for that local tunnel address.
return netip.PrefixFrom(addr, 32), nil
}
func parseIPv4Route(network, mask string) (netip.Prefix, error) {
addr, err := netip.ParseAddr(network)
if err != nil {
return netip.Prefix{}, fmt.Errorf("parse route network %q: %w", network, err)
}
maskAddr, err := netip.ParseAddr(mask)
if err != nil {
return netip.Prefix{}, fmt.Errorf("parse route mask %q: %w", mask, err)
}
if !addr.Is4() || !maskAddr.Is4() {
return netip.Prefix{}, fmt.Errorf("openvpn route requires ipv4 address and mask")
}
ones, ok := ipv4MaskSize(maskAddr)
if !ok {
return netip.Prefix{}, fmt.Errorf("invalid route mask %q", mask)
}
return netip.PrefixFrom(addr, ones), nil
}
func ipv4MaskSize(mask netip.Addr) (int, bool) {
maskBytes := mask.As4()
ones := 0
seenZero := false
for _, b := range maskBytes {
for i := 7; i >= 0; i-- {
if b&(1<<i) == 0 {
return netip.PrefixFrom(addr, ones), nil
seenZero = true
continue
}
if seenZero {
return 0, false
}
ones++
}
}
return netip.PrefixFrom(addr, ones), nil
return ones, true
}
+34 -16
View File
@@ -2,7 +2,9 @@ package snell
import (
"context"
"io"
"net"
"sync"
"time"
"github.com/metacubex/mihomo/component/pool"
@@ -23,7 +25,7 @@ func (p *Pool) GetContext(ctx context.Context) (net.Conn, error) {
return nil, err
}
return &PoolConn{elm, p}, nil
return &PoolConn{Snell: elm, pool: p}, nil
}
func (p *Pool) Put(conn *Snell) {
@@ -32,26 +34,26 @@ func (p *Pool) Put(conn *Snell) {
return
}
p.put(conn)
}
func (p *Pool) put(conn *Snell) {
p.pool.Put(conn)
}
type PoolConn struct {
*Snell
pool *Pool
pool *Pool
closeWriteOnce sync.Once
closeWriteErr error
closeOnce sync.Once
closeErr error
}
func (pc *PoolConn) Read(b []byte) (int, error) {
// save old status of reply (it mutable by Read)
reply := pc.Snell.reply
n, err := pc.Snell.Read(b)
if err == shadowaead.ErrZeroChunk {
// if reply is false, it should be client halfclose.
// ignore error and read data again.
if !reply {
pc.Snell.reply = false
return pc.Snell.Read(b)
}
return n, io.EOF
}
return n, err
}
@@ -60,12 +62,28 @@ func (pc *PoolConn) Write(b []byte) (int, error) {
return pc.Snell.Write(b)
}
func (pc *PoolConn) CloseWrite() error {
pc.closeWriteOnce.Do(func() {
pc.closeWriteErr = writeZeroChunk(pc.Snell)
})
return pc.closeWriteErr
}
func (pc *PoolConn) Close() error {
// mihomo use SetReadDeadline to break bidirectional copy between client and server.
// reset it before reuse connection to avoid io timeout error.
_ = pc.Snell.Conn.SetReadDeadline(time.Time{})
pc.pool.Put(pc.Snell)
return nil
pc.closeOnce.Do(func() {
if err := pc.CloseWrite(); err != nil {
pc.closeErr = err
_ = pc.Snell.Close()
return
}
// mihomo use SetReadDeadline to break bidirectional copy between client and server.
// reset it before reuse connection to avoid io timeout error.
_ = pc.Snell.Conn.SetReadDeadline(time.Time{})
pc.Snell.reply = false
pc.pool.put(pc.Snell)
})
return pc.closeErr
}
func NewPool(factory func(context.Context) (*Snell, error)) *Pool {
+180
View File
@@ -0,0 +1,180 @@
package snell
import (
"context"
"errors"
"io"
"net"
"testing"
"time"
"github.com/metacubex/mihomo/transport/shadowsocks/shadowaead"
)
func TestPoolConnCloseIsIdempotent(t *testing.T) {
rawConn := &recordingConn{}
pooledConn := &Snell{Conn: rawConn}
pool := NewPool(func(context.Context) (*Snell, error) {
return nil, errors.New("factory should not be called")
})
conn := &PoolConn{Snell: pooledConn, pool: pool}
if err := conn.Close(); err != nil {
t.Fatal(err)
}
if err := conn.Close(); err != nil {
t.Fatal(err)
}
if rawConn.writes != 1 {
t.Fatalf("close should send one half-close record, got %d", rawConn.writes)
}
got, err := pool.pool.Get()
if err != nil {
t.Fatal(err)
}
if got != pooledConn {
t.Fatal("pooled connection mismatch")
}
}
func TestPoolConnCloseWriteDoesNotReturnConnectionToPool(t *testing.T) {
rawConn := &recordingConn{}
pooledConn := &Snell{Conn: rawConn, reply: true}
factoryConn := &Snell{Conn: &recordingConn{}}
pool := NewPool(func(context.Context) (*Snell, error) {
return factoryConn, nil
})
conn := &PoolConn{Snell: pooledConn, pool: pool}
if err := conn.CloseWrite(); err != nil {
t.Fatal(err)
}
got, err := pool.pool.Get()
if err != nil {
t.Fatal(err)
}
if got != factoryConn {
t.Fatal("CloseWrite should not put the active connection back into the pool")
}
if rawConn.writes != 1 {
t.Fatalf("CloseWrite should send one half-close record, got %d", rawConn.writes)
}
if !pooledConn.reply {
t.Fatal("CloseWrite should not reset reply while the read side may still be active")
}
if err = conn.Close(); err != nil {
t.Fatal(err)
}
got, err = pool.pool.Get()
if err != nil {
t.Fatal(err)
}
if got != pooledConn {
t.Fatal("Close should return the connection to the pool after CloseWrite")
}
if rawConn.writes != 1 {
t.Fatalf("Close after CloseWrite should not send another half-close record, got %d", rawConn.writes)
}
if pooledConn.reply {
t.Fatal("Close should reset reply before returning the connection to the pool")
}
}
func TestPoolConnReadZeroChunkReturnsEOF(t *testing.T) {
conn := &PoolConn{Snell: &Snell{Conn: zeroChunkConn{}, reply: true}}
n, err := conn.Read(make([]byte, 1))
if n != 0 {
t.Fatalf("read length mismatch: %d", n)
}
if !errors.Is(err, io.EOF) {
t.Fatalf("expected EOF for zero chunk, got %v", err)
}
}
type recordingConn struct {
writes int
closed bool
}
func (c *recordingConn) Read([]byte) (int, error) {
return 0, io.EOF
}
func (c *recordingConn) Write(b []byte) (int, error) {
c.writes++
return len(b), nil
}
func (c *recordingConn) Close() error {
c.closed = true
return nil
}
func (*recordingConn) LocalAddr() net.Addr {
return recordingAddr("local")
}
func (*recordingConn) RemoteAddr() net.Addr {
return recordingAddr("remote")
}
func (*recordingConn) SetDeadline(time.Time) error {
return nil
}
func (*recordingConn) SetReadDeadline(time.Time) error {
return nil
}
func (*recordingConn) SetWriteDeadline(time.Time) error {
return nil
}
type recordingAddr string
func (a recordingAddr) Network() string {
return string(a)
}
func (a recordingAddr) String() string {
return string(a)
}
type zeroChunkConn struct{}
func (zeroChunkConn) Read([]byte) (int, error) {
return 0, shadowaead.ErrZeroChunk
}
func (zeroChunkConn) Write(b []byte) (int, error) {
return len(b), nil
}
func (zeroChunkConn) Close() error {
return nil
}
func (zeroChunkConn) LocalAddr() net.Addr {
return recordingAddr("local")
}
func (zeroChunkConn) RemoteAddr() net.Addr {
return recordingAddr("remote")
}
func (zeroChunkConn) SetDeadline(time.Time) error {
return nil
}
func (zeroChunkConn) SetReadDeadline(time.Time) error {
return nil
}
func (zeroChunkConn) SetWriteDeadline(time.Time) error {
return nil
}
+196 -33
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net"
"net/netip"
"sync"
"github.com/metacubex/mihomo/common/pool"
@@ -17,6 +18,8 @@ const (
Version1 = 1
Version2 = 2
Version3 = 3
Version4 = 4
Version5 = 5
DefaultSnellVersion = Version1
// max packet length
@@ -39,6 +42,10 @@ const (
var endSignal = []byte{}
type packetFrameWriter interface {
WritePacketFrame([]byte) (int, error)
}
type Snell struct {
net.Conn
buffer [1]byte
@@ -46,47 +53,58 @@ type Snell struct {
}
func (s *Snell) Read(b []byte) (int, error) {
if s.reply {
return s.Conn.Read(b)
}
s.reply = true
if _, err := io.ReadFull(s.Conn, s.buffer[:]); err != nil {
if err := s.ReadReply(); err != nil {
return 0, err
}
return s.Conn.Read(b)
}
func (s *Snell) ReadReply() error {
if s.reply {
return nil
}
if _, err := io.ReadFull(s.Conn, s.buffer[:]); err != nil {
return err
}
s.reply = true
if s.buffer[0] == CommandTunnel {
return s.Conn.Read(b)
return nil
} else if s.buffer[0] != CommandError {
return 0, errors.New("command not support")
return errors.New("command not support")
}
// CommandError
// 1 byte error code
if _, err := io.ReadFull(s.Conn, s.buffer[:]); err != nil {
return 0, err
return err
}
errcode := int(s.buffer[0])
// 1 byte error message length
if _, err := io.ReadFull(s.Conn, s.buffer[:]); err != nil {
return 0, err
return err
}
length := int(s.buffer[0])
msg := make([]byte, length)
if _, err := io.ReadFull(s.Conn, msg); err != nil {
return 0, err
return err
}
return 0, fmt.Errorf("server reported code: %d, message: %s", errcode, string(msg))
return fmt.Errorf("server reported code: %d, message: %s", errcode, string(msg))
}
func WriteHeader(conn net.Conn, host string, port uint, version int) error {
return WriteHeaderWithReuse(conn, host, port, version, false)
}
func WriteHeaderWithReuse(conn net.Conn, host string, port uint, version int, reuse bool) error {
buf := pool.GetBuffer()
defer pool.PutBuffer(buf)
buf.WriteByte(Version)
if version == Version2 {
if version == Version2 || reuse {
buf.WriteByte(CommandConnectV2)
} else {
buf.WriteByte(CommandConnect)
@@ -117,12 +135,18 @@ func WriteUDPHeader(conn net.Conn, version int) error {
return err
}
// HalfClose works only on version2
func HalfClose(conn net.Conn) error {
func writeZeroChunk(conn net.Conn) error {
if _, err := conn.Write(endSignal); err != nil {
return err
}
return nil
}
// HalfClose only works after the request negotiated the reuse command.
func HalfClose(conn net.Conn) error {
if err := writeZeroChunk(conn); err != nil {
return err
}
if s, ok := conn.(*Snell); ok {
s.reply = false
}
@@ -130,6 +154,10 @@ func HalfClose(conn net.Conn) error {
}
func StreamConn(conn net.Conn, psk []byte, version int) *Snell {
if version >= Version4 {
return &Snell{Conn: newV4Conn(conn, psk)}
}
var cipher shadowaead.Cipher
if version != Version1 {
cipher = NewAES128GCM(psk)
@@ -139,12 +167,25 @@ func StreamConn(conn net.Conn, psk []byte, version int) *Snell {
return &Snell{Conn: shadowaead.NewConn(conn, cipher)}
}
func ServerStreamConn(conn net.Conn, psk []byte, version int) *Snell {
stream := StreamConn(conn, psk, version)
stream.reply = true
return stream
}
func PacketConn(conn net.Conn) net.PacketConn {
return &packetConn{
Conn: conn,
}
}
func (s *Snell) WritePacketFrame(b []byte) (int, error) {
if fw, ok := s.Conn.(packetFrameWriter); ok {
return fw.WritePacketFrame(b)
}
return s.Conn.Write(b)
}
func writePacket(w io.Writer, socks5Addr, payload []byte) (int, error) {
buf := pool.GetBuffer()
defer pool.PutBuffer(buf)
@@ -155,16 +196,35 @@ func writePacket(w io.Writer, socks5Addr, payload []byte) (int, error) {
switch socks5Addr[0] {
case socks5.AtypDomainName:
hostLen := socks5Addr[1]
if len(socks5Addr) < 1+1+int(hostLen)+2 {
return 0, errors.New("snell UDP address invalid")
}
buf.Write(socks5Addr[1 : 1+1+hostLen+2])
case socks5.AtypIPv4:
if len(socks5Addr) < 1+net.IPv4len+2 {
return 0, errors.New("snell UDP address invalid")
}
buf.Write([]byte{0x00, 0x04})
buf.Write(socks5Addr[1 : 1+net.IPv4len+2])
case socks5.AtypIPv6:
if len(socks5Addr) < 1+net.IPv6len+2 {
return 0, errors.New("snell UDP address invalid")
}
buf.Write([]byte{0x00, 0x06})
buf.Write(socks5Addr[1 : 1+net.IPv6len+2])
default:
return 0, errors.New("snell UDP address invalid")
}
buf.Write(payload)
if fw, ok := w.(packetFrameWriter); ok {
_, err := fw.WritePacketFrame(buf.Bytes())
if err != nil {
return 0, err
}
return len(payload), nil
}
_, err := w.Write(buf.Bytes())
if err != nil {
return 0, err
@@ -173,30 +233,124 @@ func writePacket(w io.Writer, socks5Addr, payload []byte) (int, error) {
}
func WritePacket(w io.Writer, socks5Addr, payload []byte) (int, error) {
if len(payload) <= maxLength {
maxPayloadLength := maxLength - UdpRequestHeaderLength(socks5Addr)
if maxPayloadLength <= 0 {
return 0, errors.New("snell UDP address too large")
}
if len(payload) <= maxPayloadLength {
return writePacket(w, socks5Addr, payload)
}
return 0, errors.New("snell UDP payload too large")
}
offset := 0
total := len(payload)
for {
cursor := offset + maxLength
if cursor > total {
cursor = total
}
func WritePacketResponse(w io.Writer, addr net.Addr, payload []byte) (int, error) {
buf := pool.GetBuffer()
defer pool.PutBuffer(buf)
n, err := writePacket(w, socks5Addr, payload[offset:cursor])
if err != nil {
return offset + n, err
}
offset = cursor
if offset == total {
break
}
socks5Addr := socks5.ParseAddrToSocksAddr(addr)
if len(socks5Addr) == 0 {
return 0, errors.New("snell UDP response address invalid")
}
switch socks5Addr[0] {
case socks5.AtypIPv4:
if len(socks5Addr) < 1+net.IPv4len+2 {
return 0, errors.New("snell UDP response address invalid")
}
buf.WriteByte(0x04)
buf.Write(socks5Addr[1 : 1+net.IPv4len+2])
case socks5.AtypIPv6:
if len(socks5Addr) < 1+net.IPv6len+2 {
return 0, errors.New("snell UDP response address invalid")
}
buf.WriteByte(0x06)
buf.Write(socks5Addr[1 : 1+net.IPv6len+2])
default:
return 0, errors.New("snell UDP response address invalid")
}
buf.Write(payload)
return total, nil
var err error
if fw, ok := w.(packetFrameWriter); ok {
_, err = fw.WritePacketFrame(buf.Bytes())
} else {
_, err = w.Write(buf.Bytes())
}
if err != nil {
return 0, err
}
return len(payload), nil
}
type UDPRequest struct {
Host string
Ip netip.Addr
Port uint16
Payload []byte
}
func ParseUDPRequest(packet []byte) (UDPRequest, error) {
if len(packet) < 2 || packet[0] != CommondUDPForward {
return UDPRequest{}, errors.New("snell invalid UDP request")
}
if hostLen := int(packet[1]); hostLen != 0 {
if len(packet) <= 2+hostLen+2 {
return UDPRequest{}, errors.New("snell invalid UDP domain request")
}
offset := 2 + hostLen
return UDPRequest{
Host: string(packet[2:offset]),
Port: binary.BigEndian.Uint16(packet[offset : offset+2]),
Payload: packet[offset+2:],
}, nil
}
if len(packet) < 3 {
return UDPRequest{}, errors.New("snell invalid UDP IP request")
}
switch packet[2] {
case 0x04:
if len(packet) < 3+net.IPv4len+2 {
return UDPRequest{}, errors.New("snell invalid UDP IPv4 request")
}
offset := 3 + net.IPv4len
ip, _ := netip.AddrFromSlice(packet[3:offset])
return UDPRequest{
Ip: ip.Unmap(),
Port: binary.BigEndian.Uint16(packet[offset : offset+2]),
Payload: packet[offset+2:],
}, nil
case 0x06:
if len(packet) < 3+net.IPv6len+2 {
return UDPRequest{}, errors.New("snell invalid UDP IPv6 request")
}
offset := 3 + net.IPv6len
ip, _ := netip.AddrFromSlice(packet[3:offset])
return UDPRequest{
Ip: ip.Unmap(),
Port: binary.BigEndian.Uint16(packet[offset : offset+2]),
Payload: packet[offset+2:],
}, nil
default:
return UDPRequest{}, errors.New("snell invalid UDP address type")
}
}
func UdpRequestHeaderLength(socks5Addr []byte) int {
if len(socks5Addr) == 0 {
return maxLength + 1
}
switch socks5Addr[0] {
case socks5.AtypDomainName:
if len(socks5Addr) < 2 {
return maxLength + 1
}
return 1 + 1 + int(socks5Addr[1]) + 2
case socks5.AtypIPv4:
return 1 + 2 + net.IPv4len + 2
case socks5.AtypIPv6:
return 1 + 2 + net.IPv6len + 2
default:
return maxLength + 1
}
}
func ReadPacket(r io.Reader, payload []byte) (net.Addr, int, error) {
@@ -260,6 +414,15 @@ type packetConn struct {
wMux sync.Mutex
}
func (pc *packetConn) WritePacketFrame(b []byte) (int, error) {
if s, ok := pc.Conn.(*Snell); ok {
if fw, ok := s.Conn.(packetFrameWriter); ok {
return fw.WritePacketFrame(b)
}
}
return pc.Conn.Write(b)
}
func (pc *packetConn) WriteTo(b []byte, addr net.Addr) (int, error) {
pc.wMux.Lock()
defer pc.wMux.Unlock()
+490
View File
@@ -0,0 +1,490 @@
package snell
import (
"crypto/cipher"
cryptorand "crypto/rand"
"encoding/binary"
"errors"
"io"
"math"
"math/big"
"math/bits"
"net"
"sync"
"time"
"github.com/metacubex/mihomo/transport/shadowsocks/shadowaead"
)
const (
v4SaltSize = 16
v4NonceSize = 12
v4HeaderPlainSize = 7
v4HeaderCipherSize = v4HeaderPlainSize + 16
v4FrameSize = 1460
v4InitialPaddingMin = 0x100
v4InitialPaddingSpan = 0x100
)
type v4Conn struct {
net.Conn
psk []byte
r *v4Reader
w *v4Writer
}
func newV4Conn(conn net.Conn, psk []byte) *v4Conn {
return &v4Conn{Conn: conn, psk: psk}
}
func (c *v4Conn) initReader() error {
salt := make([]byte, v4SaltSize)
if _, err := io.ReadFull(c.Conn, salt); err != nil {
return err
}
aead, err := v4AEAD(c.psk, salt)
if err != nil {
return err
}
c.r = &v4Reader{Reader: c.Conn, aead: aead}
return nil
}
func (c *v4Conn) initWriter() error {
w, err := newV4Writer(c.Conn, c.psk)
if err != nil {
return err
}
c.w = w
return nil
}
func (c *v4Conn) Read(b []byte) (int, error) {
if c.r == nil {
if err := c.initReader(); err != nil {
return 0, err
}
}
return c.r.Read(b)
}
func (c *v4Conn) Write(b []byte) (int, error) {
if c.w == nil {
if err := c.initWriter(); err != nil {
return 0, err
}
}
return c.w.Write(b)
}
func (c *v4Conn) WritePacketFrame(b []byte) (int, error) {
if len(b) > maxLength {
return 0, errors.New("snell v4 frame too large")
}
if c.w == nil {
if err := c.initWriter(); err != nil {
return 0, err
}
}
c.w.mux.Lock()
defer c.w.mux.Unlock()
if err := c.w.writeFrame(b, c.w.nextFramePaddingLength(len(b))); err != nil {
return 0, err
}
return len(b), nil
}
func (c *v4Conn) WriteTo(w io.Writer) (int64, error) {
if c.r == nil {
if err := c.initReader(); err != nil {
return 0, err
}
}
var written int64
buf := make([]byte, maxLength)
for {
n, err := c.r.Read(buf)
if n > 0 {
nw, ew := w.Write(buf[:n])
written += int64(nw)
if ew != nil {
return written, ew
}
if nw != n {
return written, io.ErrShortWrite
}
}
if err != nil {
if err == io.EOF {
err = nil
}
return written, err
}
}
}
func (c *v4Conn) ReadFrom(r io.Reader) (int64, error) {
if c.w == nil {
if err := c.initWriter(); err != nil {
return 0, err
}
}
var read int64
buf := make([]byte, maxLength)
for {
n, err := r.Read(buf)
if n > 0 {
read += int64(n)
if _, ew := c.w.Write(buf[:n]); ew != nil {
return read, ew
}
}
if err != nil {
if err == io.EOF {
err = nil
}
return read, err
}
}
}
func v4AEAD(psk, salt []byte) (cipher.AEAD, error) {
return aesGCM(snellKDF(psk, salt, 16))
}
type v4Reader struct {
io.Reader
aead cipher.AEAD
nonce [v4NonceSize]byte
buf []byte
mux sync.Mutex
}
func (r *v4Reader) Read(b []byte) (int, error) {
r.mux.Lock()
defer r.mux.Unlock()
if len(r.buf) == 0 {
payload, err := r.readFrame()
if err != nil {
return 0, err
}
r.buf = payload
}
n := copy(b, r.buf)
r.buf = r.buf[n:]
return n, nil
}
func (r *v4Reader) readFrame() ([]byte, error) {
headerCipher := make([]byte, v4HeaderCipherSize)
if _, err := io.ReadFull(r.Reader, headerCipher); err != nil {
return nil, err
}
header, err := r.aead.Open(headerCipher[:0], r.nonce[:], headerCipher, nil)
incrementV4Nonce(r.nonce[:])
if err != nil {
return nil, err
}
if len(header) != v4HeaderPlainSize || header[0] != 4 {
return nil, errors.New("snell v4 invalid frame header")
}
paddingLength := int(binary.BigEndian.Uint16(header[3:5]))
payloadLength := int(binary.BigEndian.Uint16(header[5:7]))
if payloadLength == 0 {
if paddingLength != 0 {
return nil, errors.New("snell v4 zero chunk with padding")
}
return nil, shadowaead.ErrZeroChunk
}
if payloadLength > maxLength || paddingLength > maxLength {
return nil, errors.New("snell v4 frame too large")
}
payloadCipherLength := payloadLength + r.aead.Overhead()
frame := make([]byte, paddingLength+payloadCipherLength)
if _, err := io.ReadFull(r.Reader, frame); err != nil {
return nil, err
}
if paddingLength > 0 {
swapPadding(frame[:paddingLength], frame[paddingLength:])
}
payloadCipher := frame[paddingLength:]
payload, err := r.aead.Open(payloadCipher[:0], r.nonce[:], payloadCipher, nil)
incrementV4Nonce(r.nonce[:])
if err != nil {
return nil, err
}
return payload, nil
}
type v4Writer struct {
io.Writer
aead cipher.AEAD
nonce [v4NonceSize]byte
salt [v4SaltSize]byte
saltSent bool
initialPaddingLength uint16
payloadLimit uint16
lastWrite time.Time
mux sync.Mutex
}
func newV4Writer(w io.Writer, psk []byte) (*v4Writer, error) {
var salt [v4SaltSize]byte
if _, err := io.ReadFull(cryptorand.Reader, salt[:]); err != nil {
return nil, err
}
aead, err := v4AEAD(psk, salt[:])
if err != nil {
return nil, err
}
paddingDelta, err := cryptoRandomInt(v4InitialPaddingSpan)
if err != nil {
return nil, err
}
return &v4Writer{
Writer: w,
aead: aead,
salt: salt,
initialPaddingLength: uint16(v4InitialPaddingMin + paddingDelta),
}, nil
}
func (w *v4Writer) Write(b []byte) (int, error) {
w.mux.Lock()
defer w.mux.Unlock()
if len(b) == 0 {
return 0, w.writeFrame(nil, 0)
}
written := 0
for written < len(b) {
payloadLimit := int(w.nextPayloadLimit())
if payloadLimit <= 0 || payloadLimit > maxLength {
payloadLimit = maxLength
}
end := written + payloadLimit
if end > len(b) {
end = len(b)
}
paddingLength := w.nextFramePaddingLength(end - written)
if err := w.writeFrame(b[written:end], paddingLength); err != nil {
return written, err
}
written = end
}
return written, nil
}
func (w *v4Writer) nextPayloadLimit() uint16 {
now := time.Now()
var payloadLimit uint16
switch {
case w.lastWrite.IsZero():
payloadLimit = v4FrameSize - 55 - w.initialPaddingLength
case now.Sub(w.lastWrite) > 30*time.Second:
payloadLimit = v4FrameSize - 39
default:
payloadLimit = w.payloadLimit
}
w.lastWrite = now
if payloadLimit <= maxLength-1 {
next := int(payloadLimit) + v4FrameSize - 39
if next > maxLength {
next = maxLength
}
w.payloadLimit = uint16(next)
} else {
w.payloadLimit = maxLength
}
return payloadLimit
}
func (w *v4Writer) nextFramePaddingLength(payloadLength int) int {
if w.saltSent || payloadLength == 0 {
return 0
}
return int(w.initialPaddingLength)
}
func (w *v4Writer) writeFrame(payload []byte, paddingLength int) error {
if len(payload) > maxLength || paddingLength > maxLength {
return errors.New("snell v4 frame too large")
}
if len(payload) == 0 && paddingLength != 0 {
return errors.New("snell v4 zero chunk with padding")
}
header := make([]byte, v4HeaderPlainSize)
header[0] = 4
binary.BigEndian.PutUint16(header[3:5], uint16(paddingLength))
binary.BigEndian.PutUint16(header[5:7], uint16(len(payload)))
headerCipher := w.aead.Seal(nil, w.nonce[:], header, nil)
incrementV4Nonce(w.nonce[:])
var payloadCipher []byte
if len(payload) > 0 {
payloadCipher = w.aead.Seal(nil, w.nonce[:], payload, nil)
incrementV4Nonce(w.nonce[:])
}
frameLength := len(headerCipher) + paddingLength + len(payloadCipher)
if !w.saltSent {
frameLength += v4SaltSize
}
frame := make([]byte, 0, frameLength)
if !w.saltSent {
frame = append(frame, w.salt[:]...)
w.saltSent = true
}
frame = append(frame, headerCipher...)
if paddingLength > 0 {
padding, err := makeV4Padding(payloadCipher, paddingLength)
if err != nil {
return err
}
swapPadding(padding, payloadCipher)
frame = append(frame, padding...)
}
frame = append(frame, payloadCipher...)
return writeFull(w.Writer, frame)
}
func swapPadding(padding, payloadCipher []byte) {
limit := len(padding)
if len(payloadCipher) < limit {
limit = len(payloadCipher)
}
for i := 0; i < limit; i += 2 {
padding[i], payloadCipher[i] = payloadCipher[i], padding[i]
}
}
func makeV4Padding(payloadCipher []byte, paddingLength int) ([]byte, error) {
if paddingLength <= 0 {
return nil, nil
}
payloadOnes := countV4PayloadOnes(payloadCipher)
payloadZeros := 8*len(payloadCipher) - payloadOnes
if payloadZeros <= 0 {
return makeV4RandomPadding(paddingLength)
}
ratio := float64(payloadOnes) / float64(payloadZeros)
if ratio <= 0.5 || ratio >= 1.6 {
return makeV4RandomPadding(paddingLength)
}
targetRatioBase := 1.6
if payloadZeros < payloadOnes {
targetRatioBase = 0.4
}
jitter, err := randomUnitFloat64()
if err != nil {
return nil, err
}
targetRatio := targetRatioBase + jitter/10
totalBits := 8 * (paddingLength + len(payloadCipher))
targetOnes := int(float64(totalBits)*(targetRatio/(targetRatio+1)) - float64(payloadOnes))
if targetOnes < 0 || targetOnes > 8*paddingLength {
return makeV4RandomPadding(paddingLength)
}
return makeV4BitCountPadding(paddingLength, targetOnes)
}
func countV4PayloadOnes(payloadCipher []byte) int {
limit := len(payloadCipher) &^ 3
ones := 0
for _, b := range payloadCipher[:limit] {
ones += bits.OnesCount8(b)
}
return ones
}
func makeV4RandomPadding(length int) ([]byte, error) {
padding := make([]byte, length)
_, err := io.ReadFull(cryptorand.Reader, padding)
return padding, err
}
func makeV4BitCountPadding(length, oneBits int) ([]byte, error) {
totalBits := 8 * length
if oneBits < 0 || oneBits > totalBits {
return nil, errors.New("snell v4 invalid padding bit count")
}
bitset := make([]byte, totalBits)
for i := 0; i < oneBits; i++ {
bitset[i] = 1
}
for i := totalBits - 1; i > 0; i-- {
j, err := cryptoRandomInt(i + 1)
if err != nil {
return nil, err
}
bitset[i], bitset[j] = bitset[j], bitset[i]
}
padding := make([]byte, length)
for i, bit := range bitset {
if bit == 1 {
padding[i/8] |= 1 << uint(i%8)
}
}
return padding, nil
}
func cryptoRandomInt(max int) (int, error) {
n, err := cryptorand.Int(cryptorand.Reader, big.NewInt(int64(max)))
if err != nil {
return 0, err
}
return int(n.Int64()), nil
}
func randomUnitFloat64() (float64, error) {
n, err := cryptorand.Int(cryptorand.Reader, big.NewInt(1<<53))
if err != nil {
return 0, err
}
return float64(n.Int64()) / math.Exp2(53), nil
}
func writeFull(w io.Writer, p []byte) error {
for len(p) > 0 {
n, err := w.Write(p)
if err != nil {
return err
}
if n == 0 {
return io.ErrShortWrite
}
p = p[n:]
}
return nil
}
func incrementV4Nonce(nonce []byte) {
for i := range nonce {
nonce[i]++
if nonce[i] != 0 {
return
}
}
}
+408
View File
@@ -0,0 +1,408 @@
package snell
import (
"bytes"
"encoding/binary"
"errors"
"io"
"net"
"testing"
"time"
"github.com/metacubex/mihomo/transport/shadowsocks/shadowaead"
"github.com/metacubex/mihomo/transport/socks5"
)
func TestSnellV4RoundTrip(t *testing.T) {
clientRaw, serverRaw := net.Pipe()
defer clientRaw.Close()
defer serverRaw.Close()
client := newV4Conn(clientRaw, []byte("password"))
server := newV4Conn(serverRaw, []byte("password"))
writeErr := make(chan error, 1)
go func() {
_, err := client.Write([]byte("hello"))
writeErr <- err
}()
buf := make([]byte, 5)
if _, err := io.ReadFull(server, buf); err != nil {
t.Fatal(err)
}
if string(buf) != "hello" {
t.Fatalf("unexpected plaintext: %q", buf)
}
if err := <-writeErr; err != nil {
t.Fatal(err)
}
go func() {
_, err := server.Write([]byte("world"))
writeErr <- err
}()
if _, err := io.ReadFull(client, buf); err != nil {
t.Fatal(err)
}
if string(buf) != "world" {
t.Fatalf("unexpected response plaintext: %q", buf)
}
if err := <-writeErr; err != nil {
t.Fatal(err)
}
}
func TestSnellV4ZeroChunk(t *testing.T) {
clientRaw, serverRaw := net.Pipe()
defer clientRaw.Close()
defer serverRaw.Close()
client := newV4Conn(clientRaw, []byte("password"))
server := newV4Conn(serverRaw, []byte("password"))
writeErr := make(chan error, 1)
go func() {
_, err := client.Write(nil)
writeErr <- err
}()
_, err := server.Read(make([]byte, 1))
if !errors.Is(err, shadowaead.ErrZeroChunk) {
t.Fatalf("expected zero chunk, got %v", err)
}
if err := <-writeErr; err != nil {
t.Fatal(err)
}
}
func TestSnellV4FirstFrameIncludesInitialPadding(t *testing.T) {
clientRaw, serverRaw := net.Pipe()
defer clientRaw.Close()
defer serverRaw.Close()
client := newV4Conn(clientRaw, []byte("password"))
writeErr := make(chan error, 1)
go func() {
_, err := client.Write([]byte("x"))
writeErr <- err
}()
salt := make([]byte, v4SaltSize)
if _, err := io.ReadFull(serverRaw, salt); err != nil {
t.Fatal(err)
}
headerCipher := make([]byte, v4HeaderCipherSize)
if _, err := io.ReadFull(serverRaw, headerCipher); err != nil {
t.Fatal(err)
}
aead, err := v4AEAD([]byte("password"), salt)
if err != nil {
t.Fatal(err)
}
var nonce [v4NonceSize]byte
header, err := aead.Open(nil, nonce[:], headerCipher, nil)
if err != nil {
t.Fatal(err)
}
paddingLength := int(binary.BigEndian.Uint16(header[3:5]))
payloadLength := int(binary.BigEndian.Uint16(header[5:7]))
if paddingLength < v4InitialPaddingMin || paddingLength >= v4InitialPaddingMin+v4InitialPaddingSpan {
t.Fatalf("unexpected initial padding length: %d", paddingLength)
}
if payloadLength != 1 {
t.Fatalf("unexpected first payload length: %d", payloadLength)
}
rest := make([]byte, paddingLength+payloadLength+aead.Overhead())
if _, err := io.ReadFull(serverRaw, rest); err != nil {
t.Fatal(err)
}
if err := <-writeErr; err != nil {
t.Fatal(err)
}
}
func TestSnellV4PaddedFrame(t *testing.T) {
var raw bytes.Buffer
writer, err := newV4Writer(&raw, []byte("password"))
if err != nil {
t.Fatal(err)
}
if err := writer.writeFrame([]byte("payload"), 13); err != nil {
t.Fatal(err)
}
data := raw.Bytes()
aead, err := v4AEAD([]byte("password"), data[:v4SaltSize])
if err != nil {
t.Fatal(err)
}
reader := &v4Reader{
Reader: bytes.NewReader(data[v4SaltSize:]),
aead: aead,
}
buf := make([]byte, 7)
if _, err := io.ReadFull(reader, buf); err != nil {
t.Fatal(err)
}
if string(buf) != "payload" {
t.Fatalf("unexpected padded plaintext: %q", buf)
}
}
func TestSnellV4BitCountPadding(t *testing.T) {
padding, err := makeV4BitCountPadding(32, 77)
if err != nil {
t.Fatal(err)
}
if len(padding) != 32 {
t.Fatalf("unexpected padding length: got %d want 32", len(padding))
}
ones := 0
for _, b := range padding {
for b != 0 {
ones += int(b & 1)
b >>= 1
}
}
if ones != 77 {
t.Fatalf("unexpected padding bit count: got %d want 77", ones)
}
}
func TestSnellV4WriterDefersSaltUntilFirstFrame(t *testing.T) {
raw := &recordingWriter{}
writer, err := newV4Writer(raw, []byte("password"))
if err != nil {
t.Fatal(err)
}
if raw.Len() != 0 {
t.Fatalf("salt was written before first frame: %d bytes", raw.Len())
}
if raw.writes != 0 {
t.Fatalf("salt was written before first frame: %d writes", raw.writes)
}
if _, err := writer.Write([]byte("x")); err != nil {
t.Fatal(err)
}
wantLen := v4SaltSize + v4HeaderCipherSize + 1 + writer.aead.Overhead()
paddingLength, payloadLength := decodeV4HeaderForTest(t, raw.Bytes())
if paddingLength < v4InitialPaddingMin || paddingLength >= v4InitialPaddingMin+v4InitialPaddingSpan {
t.Fatalf("unexpected initial padding length: %d", paddingLength)
}
if payloadLength != 1 {
t.Fatalf("unexpected first payload length: %d", payloadLength)
}
wantLen += paddingLength
if raw.Len() != wantLen {
t.Fatalf("unexpected first frame length: got %d, want %d", raw.Len(), wantLen)
}
if raw.writes != 1 {
t.Fatalf("first frame should be written with salt in one write, got %d writes", raw.writes)
}
}
func TestSnellV4PayloadLimitMatchesServer(t *testing.T) {
writer, err := newV4Writer(io.Discard, []byte("password"))
if err != nil {
t.Fatal(err)
}
initialPaddingLength := writer.initialPaddingLength
if initialPaddingLength < v4InitialPaddingMin || initialPaddingLength >= v4InitialPaddingMin+v4InitialPaddingSpan {
t.Fatalf("unexpected initial padding length: %d", initialPaddingLength)
}
if got, want := writer.nextPayloadLimit(), uint16(v4FrameSize-55-initialPaddingLength); got != want {
t.Fatalf("initial payload limit mismatch: got %d want %d", got, want)
}
if got, want := writer.nextPayloadLimit(), uint16(v4FrameSize-55-initialPaddingLength+v4FrameSize-39); got != want {
t.Fatalf("grown payload limit mismatch: got %d want %d", got, want)
}
writer.lastWrite = time.Now().Add(-31 * time.Second)
if got, want := writer.nextPayloadLimit(), uint16(v4FrameSize-39); got != want {
t.Fatalf("reset payload limit mismatch: got %d want %d", got, want)
}
}
func TestSnellV4UDPWriteKeepsDatagramInSingleFrame(t *testing.T) {
clientRaw, serverRaw := net.Pipe()
defer clientRaw.Close()
defer serverRaw.Close()
client := &Snell{Conn: newV4Conn(clientRaw, []byte("password"))}
server := newV4Conn(serverRaw, []byte("password"))
pc := PacketConn(client)
payload := bytes.Repeat([]byte{0x42}, v4FrameSize)
addr := &net.UDPAddr{IP: net.IPv4(1, 2, 3, 4), Port: 53}
writeErr := make(chan error, 1)
go func() {
_, err := pc.WriteTo(payload, addr)
writeErr <- err
}()
buf := make([]byte, maxLength)
n, err := server.Read(buf)
if err != nil {
t.Fatal(err)
}
if err := <-writeErr; err != nil {
t.Fatal(err)
}
if want := 1 + 2 + net.IPv4len + 2 + len(payload); n != want {
t.Fatalf("UDP request was split or truncated: got %d want %d", n, want)
}
if got := buf[:9]; !bytes.Equal(got, []byte{CommondUDPForward, 0, 4, 1, 2, 3, 4, 0, 53}) {
t.Fatalf("unexpected UDP request header: %x", got)
}
}
func TestSnellWritePacketRejectsOversizedDatagram(t *testing.T) {
var raw recordingWriter
addr := &net.UDPAddr{IP: net.IPv4(1, 2, 3, 4), Port: 53}
payload := bytes.Repeat([]byte{0x42}, maxLength)
n, err := WritePacket(&raw, socks5.ParseAddrToSocksAddr(addr), payload)
if err == nil {
t.Fatal("expected oversized UDP payload to be rejected")
}
if got, want := err.Error(), "snell UDP payload too large"; got != want {
t.Fatalf("unexpected error: got %q want %q", got, want)
}
if n != 0 {
t.Fatalf("written payload length = %d, want 0", n)
}
if raw.Len() != 0 {
t.Fatalf("oversized datagram should not be written, got %d bytes", raw.Len())
}
}
func TestSnellWriteHeaderConnectCommand(t *testing.T) {
tests := []struct {
name string
version int
reuse bool
want byte
}{
{name: "v1", version: Version1, want: CommandConnect},
{name: "v2", version: Version2, want: CommandConnectV2},
{name: "v4 no reuse", version: Version4, want: CommandConnect},
{name: "v4 reuse", version: Version4, reuse: true, want: CommandConnectV2},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
conn := &bufferConn{}
if err := WriteHeaderWithReuse(conn, "example.com", 443, tt.version, tt.reuse); err != nil {
t.Fatal(err)
}
data := conn.Bytes()
if len(data) < 2 {
t.Fatalf("header too short: %x", data)
}
if data[1] != tt.want {
t.Fatalf("unexpected command: got %#x, want %#x", data[1], tt.want)
}
})
}
}
func TestSnellReadReplyPreservesBufferedPayload(t *testing.T) {
conn := &Snell{Conn: &bufferConn{}}
conn.Conn.(*bufferConn).Write([]byte{CommandTunnel, 'o', 'k'})
if err := conn.ReadReply(); err != nil {
t.Fatal(err)
}
buf := make([]byte, 2)
if _, err := io.ReadFull(conn, buf); err != nil {
t.Fatal(err)
}
if string(buf) != "ok" {
t.Fatalf("unexpected buffered payload: %q", buf)
}
}
func TestSnellReadReplyErrorResponse(t *testing.T) {
conn := &Snell{Conn: &bufferConn{}}
conn.Conn.(*bufferConn).Write([]byte{CommandError, 0x65, 10})
conn.Conn.(*bufferConn).WriteString("Remote EOF")
err := conn.ReadReply()
if err == nil {
t.Fatal("expected error response")
}
if got, want := err.Error(), "server reported code: 101, message: Remote EOF"; got != want {
t.Fatalf("unexpected error: got %q want %q", got, want)
}
}
func TestWritePacketResponseUsesSocksAddrParser(t *testing.T) {
var buf bytes.Buffer
n, err := WritePacketResponse(&buf, dummyAddr("127.0.0.1:53"), []byte("ok"))
if err != nil {
t.Fatal(err)
}
if n != 2 {
t.Fatalf("written payload length = %d, want 2", n)
}
want := []byte{0x04, 127, 0, 0, 1, 0, 53, 'o', 'k'}
if !bytes.Equal(buf.Bytes(), want) {
t.Fatalf("packet = %x, want %x", buf.Bytes(), want)
}
}
type bufferConn struct {
bytes.Buffer
}
func (c *bufferConn) Close() error { return nil }
func (c *bufferConn) LocalAddr() net.Addr { return dummyAddr("local") }
func (c *bufferConn) RemoteAddr() net.Addr { return dummyAddr("remote") }
func (c *bufferConn) SetDeadline(time.Time) error { return nil }
func (c *bufferConn) SetReadDeadline(time.Time) error { return nil }
func (c *bufferConn) SetWriteDeadline(time.Time) error { return nil }
type dummyAddr string
func (a dummyAddr) Network() string { return string(a) }
func (a dummyAddr) String() string { return string(a) }
type recordingWriter struct {
bytes.Buffer
writes int
}
func (w *recordingWriter) Write(b []byte) (int, error) {
w.writes++
return w.Buffer.Write(b)
}
func decodeV4HeaderForTest(t *testing.T, data []byte) (int, int) {
t.Helper()
if len(data) < v4SaltSize+v4HeaderCipherSize {
t.Fatalf("frame too short: %d", len(data))
}
aead, err := v4AEAD([]byte("password"), data[:v4SaltSize])
if err != nil {
t.Fatal(err)
}
var nonce [v4NonceSize]byte
header, err := aead.Open(nil, nonce[:], data[v4SaltSize:v4SaltSize+v4HeaderCipherSize], nil)
if err != nil {
t.Fatal(err)
}
if len(header) != v4HeaderPlainSize || header[0] != 4 {
t.Fatalf("invalid v4 header: %x", header)
}
return int(binary.BigEndian.Uint16(header[3:5])), int(binary.BigEndian.Uint16(header[5:7]))
}
+4
View File
@@ -181,6 +181,7 @@ func isReservedIP(ip netip.Addr) bool {
}
func readUntilNull(r io.Reader) ([]byte, error) {
const maxLen = 256
buf := &bytes.Buffer{}
var data [1]byte
@@ -191,6 +192,9 @@ func readUntilNull(r io.Reader) ([]byte, error) {
if data[0] == 0 {
return buf.Bytes(), nil
}
if buf.Len() >= maxLen {
return nil, errors.New("readUntilNull: data too long")
}
buf.WriteByte(data[0])
}
}
-3
View File
@@ -96,9 +96,6 @@ func buildEarlyClientObfsConn(raw net.Conn, cfg EarlyCodecConfig, table *sudokuo
func buildEarlyServerObfsConn(raw net.Conn, cfg EarlyCodecConfig, table *sudokuobfs.Table) net.Conn {
uplink := sudokuobfs.NewConn(raw, table, cfg.PaddingMin, cfg.PaddingMax, false)
downlinkWriter, closers := newServerDownlinkWriter(raw, table, cfg.PaddingMin, cfg.PaddingMax, cfg.EnablePureDownlink)
if downlinkWriter == nil {
return uplink
}
return newDirectionalConn(raw, uplink, downlinkWriter, closers...)
}
+2 -12
View File
@@ -258,14 +258,7 @@ func newClientDownlinkReader(raw net.Conn, table *sudoku.Table, paddingMin, padd
func newServerDownlinkWriter(raw net.Conn, table *sudoku.Table, paddingMin, paddingMax int, pureDownlink bool) (io.Writer, []func() error) {
downlinkTable := oppositeDirectionTable(table)
if pureDownlink {
if downlinkTable == table {
return nil, nil
}
return sudoku.NewConn(raw, downlinkTable, paddingMin, paddingMax, false), nil
}
packed := sudoku.NewPackedConn(raw, downlinkTable, paddingMin, paddingMax)
return packed, []func() error{packed.Flush}
return sudoku.NewServerDownlinkWriter(raw, downlinkTable, paddingMin, paddingMax, pureDownlink)
}
func buildClientObfsConn(raw net.Conn, cfg *ProtocolConfig, table *sudoku.Table) net.Conn {
@@ -280,9 +273,6 @@ func buildClientObfsConn(raw net.Conn, cfg *ProtocolConfig, table *sudoku.Table)
func buildServerObfsConn(raw net.Conn, cfg *ProtocolConfig, table *sudoku.Table, record bool) (*sudoku.Conn, net.Conn) {
uplinkSudoku := sudoku.NewConn(raw, table, cfg.PaddingMin, cfg.PaddingMax, record)
downlinkWriter, closers := newServerDownlinkWriter(raw, table, cfg.PaddingMin, cfg.PaddingMax, cfg.EnablePureDownlink)
if downlinkWriter == nil {
return uplinkSudoku, uplinkSudoku
}
return uplinkSudoku, newDirectionalConn(raw, uplinkSudoku, downlinkWriter, closers...)
}
@@ -439,7 +429,7 @@ func ServerHandshake(rawConn net.Conn, cfg *ProtocolConfig) (net.Conn, *Handshak
return nil, nil, &SuspiciousError{Err: fmt.Errorf("resolve table hint failed: %w", err), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
}
if resolvedTable != selectedTable {
downlinkWriter, closers := newServerDownlinkWriter(baseConn, resolvedTable, cfg.PaddingMin, cfg.PaddingMax, cfg.EnablePureDownlink)
downlinkWriter, closers := sudoku.NewServerDownlinkWriter(baseConn, resolvedTable.OppositeDirection(), cfg.PaddingMin, cfg.PaddingMax, cfg.EnablePureDownlink)
switchable, ok := obfsConn.(*directionalConn)
if !ok {
return nil, nil, &SuspiciousError{Err: fmt.Errorf("switch downlink writer failed"), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
+27 -13
View File
@@ -122,39 +122,40 @@ func runPackedTCPSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
target := fmt.Sprintf("1.1.1.%d:80", (id%200)+1)
payload := []byte{0x42, byte(id)}
// Server side
serverErr := make(chan error, 1)
go func() {
c, meta, err := ServerHandshake(serverConn, cfg)
if err != nil {
errCh <- fmt.Errorf("server handshake tcp: %w", err)
serverErr <- fmt.Errorf("server handshake tcp: %w", err)
return
}
defer c.Close()
session, err := ReadServerSession(c, meta)
if err != nil {
errCh <- fmt.Errorf("server read session tcp: %w", err)
serverErr <- fmt.Errorf("server read session tcp: %w", err)
return
}
if session.Type != SessionTypeTCP {
errCh <- fmt.Errorf("unexpected session type: %v", session.Type)
serverErr <- fmt.Errorf("unexpected session type: %v", session.Type)
return
}
if session.Target != target {
errCh <- fmt.Errorf("target mismatch want %s got %s", target, session.Target)
serverErr <- fmt.Errorf("target mismatch want %s got %s", target, session.Target)
return
}
if _, err := session.Conn.Write(payload); err != nil {
errCh <- fmt.Errorf("server write: %w", err)
serverErr <- fmt.Errorf("server write: %w", err)
return
}
serverErr <- nil
}()
// Client side
clientCfg := *cfg
cConn, err := ClientHandshake(clientConn, &clientCfg)
if err != nil {
errCh <- fmt.Errorf("client handshake tcp: %w", err)
_ = clientConn.Close()
return
}
defer cConn.Close()
@@ -178,6 +179,7 @@ func runPackedTCPSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
errCh <- fmt.Errorf("payload mismatch want %x got %x", payload, buf)
return
}
reportPackedServerErr(serverErr, errCh)
}
func runPackedUoTSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
@@ -185,35 +187,36 @@ func runPackedUoTSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
target := "8.8.8.8:53"
payload := []byte{0xaa, byte(id)}
// Server side
serverErr := make(chan error, 1)
go func() {
c, meta, err := ServerHandshake(serverConn, cfg)
if err != nil {
errCh <- fmt.Errorf("server handshake uot: %w", err)
serverErr <- fmt.Errorf("server handshake uot: %w", err)
return
}
defer c.Close()
session, err := ReadServerSession(c, meta)
if err != nil {
errCh <- fmt.Errorf("server read session uot: %w", err)
serverErr <- fmt.Errorf("server read session uot: %w", err)
return
}
if session.Type != SessionTypeUoT {
errCh <- fmt.Errorf("unexpected session type: %v", session.Type)
serverErr <- fmt.Errorf("unexpected session type: %v", session.Type)
return
}
if err := WriteDatagram(session.Conn, target, payload); err != nil {
errCh <- fmt.Errorf("server write datagram: %w", err)
serverErr <- fmt.Errorf("server write datagram: %w", err)
return
}
serverErr <- nil
}()
// Client side
clientCfg := *cfg
cConn, err := ClientHandshake(clientConn, &clientCfg)
if err != nil {
errCh <- fmt.Errorf("client handshake uot: %w", err)
_ = clientConn.Close()
return
}
defer cConn.Close()
@@ -236,6 +239,17 @@ func runPackedUoTSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
errCh <- fmt.Errorf("uot payload mismatch want %x got %x", payload, data)
return
}
reportPackedServerErr(serverErr, errCh)
}
func reportPackedServerErr(serverErr <-chan error, errCh chan<- error) {
select {
case err := <-serverErr:
if err != nil {
errCh <- err
}
default:
}
}
func TestCustomTableHandshake(t *testing.T) {
+25 -4
View File
@@ -18,9 +18,12 @@ const (
)
const (
headerSize = 1 + 4 + 4
maxFrameSize = 256 * 1024
maxDataPayload = 32 * 1024
headerSize = 1 + 4 + 4
// maxQueuedBytesPerStream bounds unread payload retained by a single logical stream.
// Backpressure is applied to the demux loop instead of dropping data.
maxQueuedBytesPerStream = 4 * 1024 * 1024
maxFrameSize = 256 * 1024
maxDataPayload = 128 * 1024
)
type acceptEvent struct {
@@ -344,6 +347,8 @@ type stream struct {
closeErr error
readBuf []byte
queue [][]byte
// queuedBytes includes unread bytes in readBuf and queue.
queuedBytes int
localAddr net.Addr
remoteAddr net.Addr
@@ -362,16 +367,20 @@ func newStream(session *Session, id uint32) *stream {
func (c *stream) enqueue(payload []byte) {
c.mu.Lock()
for !c.closed && c.queuedBytes+len(payload) > maxQueuedBytesPerStream {
c.cond.Wait()
}
if c.closed {
c.mu.Unlock()
return
}
c.queuedBytes += len(payload)
if len(c.readBuf) == 0 && len(c.queue) == 0 {
c.readBuf = payload
} else {
c.queue = append(c.queue, payload)
}
c.cond.Signal()
c.cond.Broadcast()
c.mu.Unlock()
}
@@ -413,7 +422,11 @@ func (c *stream) Read(p []byte) (int, error) {
}
if len(c.readBuf) == 0 && len(c.queue) > 0 {
c.readBuf = c.queue[0]
c.queue[0] = nil
c.queue = c.queue[1:]
if len(c.queue) == 0 {
c.queue = nil
}
}
if len(c.readBuf) == 0 && c.closed {
if c.closeErr == nil {
@@ -424,6 +437,14 @@ func (c *stream) Read(p []byte) (int, error) {
n := copy(p, c.readBuf)
c.readBuf = c.readBuf[n:]
if len(c.readBuf) == 0 {
c.readBuf = nil
}
c.queuedBytes -= n
if c.queuedBytes < 0 {
c.queuedBytes = 0
}
c.cond.Broadcast()
return n, nil
}
+7 -5
View File
@@ -244,7 +244,7 @@ type httpClientTarget struct {
func buildHTTPTransport(serverAddress string, tlsEnabled bool, hostOverride string, dialContext func(ctx context.Context, network, addr string) (net.Conn, error), maxIdleConns int) (*http.Transport, httpClientTarget, error) {
if dialContext == nil {
panic("httpmask: DialContext is nil")
return nil, httpClientTarget{}, errors.New("httpmask: DialContext is nil")
}
scheme, urlHost, dialAddr, serverName, err := normalizeHTTPDialTarget(serverAddress, tlsEnabled, hostOverride)
@@ -514,6 +514,8 @@ type queuedConn struct {
remoteAddr net.Addr
}
const queuedConnPayloadQueueDepth = 64
func (c *queuedConn) CloseWrite() error {
if c == nil || c.writeClosed == nil {
return nil
@@ -646,9 +648,9 @@ func newStreamSplitConnFromInfo(info *sessionDialInfo) *streamSplitConn {
headerHost: info.headerHost,
auth: info.auth,
queuedConn: queuedConn{
rxc: make(chan []byte, 256),
rxc: make(chan []byte, queuedConnPayloadQueueDepth),
closed: make(chan struct{}),
writeCh: make(chan []byte, 256),
writeCh: make(chan []byte, queuedConnPayloadQueueDepth),
writeClosed: make(chan struct{}),
localAddr: &net.TCPAddr{},
remoteAddr: &net.TCPAddr{},
@@ -1083,9 +1085,9 @@ func newPollConnFromInfo(info *sessionDialInfo) *pollConn {
headerHost: info.headerHost,
auth: info.auth,
queuedConn: queuedConn{
rxc: make(chan []byte, 128),
rxc: make(chan []byte, queuedConnPayloadQueueDepth),
closed: make(chan struct{}),
writeCh: make(chan []byte, 256),
writeCh: make(chan []byte, queuedConnPayloadQueueDepth),
writeClosed: make(chan struct{}),
localAddr: &net.TCPAddr{},
remoteAddr: &net.TCPAddr{},
+2 -1
View File
@@ -3,6 +3,7 @@ package httpmask
import (
"context"
"encoding/base64"
"errors"
"fmt"
"io"
mrand "math/rand"
@@ -96,7 +97,7 @@ func applyWSHeaders(h stdhttp.Header, host string) {
func dialWS(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) {
if opts.DialContext == nil {
panic("httpmask: DialContext is nil")
return nil, errors.New("httpmask: DialContext is nil")
}
scheme, urlHost, dialAddr, serverName, err := normalizeWSDialTarget(serverAddress, opts.TLSEnabled, opts.HostOverride)
+81 -20
View File
@@ -3,6 +3,7 @@ package sudoku
import (
"bufio"
"bytes"
"io"
"net"
"sync"
"sync/atomic"
@@ -10,6 +11,8 @@ import (
const IOBufferSize = 32 * 1024
const minDecodeReadSize = 64
var perm4 = [24][4]byte{
{0, 1, 2, 3},
{0, 1, 3, 2},
@@ -52,7 +55,7 @@ type Conn struct {
writeMu sync.Mutex
writeBuf []byte
rng randomSource
rng *sudokuRand
paddingThreshold uint64
}
@@ -97,6 +100,9 @@ func NewConn(c net.Conn, table *Table, pMin, pMax int, record bool) *Conn {
}
func (sc *Conn) StopRecording() {
if sc == nil {
return
}
sc.recordLock.Lock()
sc.recording.Store(false)
sc.recorder = nil
@@ -115,6 +121,9 @@ func (sc *Conn) GetBufferedAndRecorded() []byte {
if sc.recorder != nil {
recorded = sc.recorder.Bytes()
}
if sc.reader == nil {
return recorded
}
buffered := sc.reader.Buffered()
if buffered > 0 {
@@ -131,6 +140,9 @@ func (sc *Conn) Write(p []byte) (n int, err error) {
if len(p) == 0 {
return 0, nil
}
if sc == nil || sc.Conn == nil || sc.table == nil || sc.table.layout == nil || sc.rng == nil {
return 0, io.ErrClosedPipe
}
sc.writeMu.Lock()
defer sc.writeMu.Unlock()
@@ -140,16 +152,19 @@ func (sc *Conn) Write(p []byte) (n int, err error) {
}
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 {
return 0, io.ErrClosedPipe
}
if n, ok := drainPending(p, &sc.pendingData); ok {
return n, nil
}
outN := 0
for {
if sc.pendingData.available() > 0 {
break
}
nr, rErr := sc.reader.Read(sc.rawBuf)
nr, rErr := readRawLimited(sc.Conn, sc.reader, sc.rawBuf[:sudokuReadSize(len(p)-outN, len(sc.rawBuf))])
if nr > 0 {
chunk := sc.rawBuf[:nr]
if sc.recording.Load() {
@@ -160,34 +175,80 @@ func (sc *Conn) Read(p []byte) (n int, err error) {
sc.recordLock.Unlock()
}
layout := sc.table.layout
for _, b := range chunk {
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) {
key := packHintsToKey(sc.hintBuf)
val, ok := sc.table.DecodeMap[key]
if !ok {
return 0, ErrInvalidSudokuMapMiss
}
sc.pendingData.appendByte(val)
sc.hintCount = 0
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
}
}
if rErr != nil {
if outN > 0 {
return outN, nil
}
if n, ok := drainPending(p, &sc.pendingData); ok {
return n, nil
}
return 0, rErr
}
if sc.pendingData.available() > 0 {
break
if outN > 0 {
return outN, nil
}
}
}
n, _ = drainPending(p, &sc.pendingData)
return n, nil
func sudokuReadSize(decodedRemaining, maxRaw int) int {
if maxRaw <= minDecodeReadSize || decodedRemaining <= 0 {
return maxRaw
}
if decodedRemaining > (maxRaw-minDecodeReadSize)/5 {
return maxRaw
}
return decodedRemaining*5 + minDecodeReadSize
}
func readRawLimited(conn net.Conn, reader *bufio.Reader, dst []byte) (int, error) {
if len(dst) == 0 {
return 0, nil
}
if reader != nil && reader.Buffered() > 0 {
return reader.Read(dst)
}
if conn == nil {
return 0, io.ErrClosedPipe
}
return conn.Read(dst)
}
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more