mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-11-27 05:58:31 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc8c5a24b1 | ||
|
|
8f2d84f915 | ||
|
|
38cb06d3a5 | ||
|
|
4065583ae4 | ||
|
|
f30a64f93f | ||
|
|
f1c365611d | ||
|
|
2dd7d59942 | ||
|
|
d610afef1b | ||
|
|
5b28a0ee46 | ||
|
|
5639e93f72 | ||
|
|
03e1f44921 | ||
|
|
f69331f45f | ||
|
|
52edebd155 | ||
|
|
7a6a650902 | ||
|
|
6e15299cab | ||
|
|
72f133f4bd | ||
|
|
301d580d8a | ||
|
|
3809a03c9f | ||
|
|
0ddf4bbffd | ||
|
|
d27f3201ab | ||
|
|
a2aca027e4 | ||
|
|
cb652ddb7d | ||
|
|
a52a27ed56 | ||
|
|
060711fb7d | ||
|
|
8c26d61ce3 | ||
|
|
f2da5b7c27 | ||
|
|
d60b336dfc | ||
|
|
a531449b84 | ||
|
|
a05c94b4ad | ||
|
|
ff98700df2 | ||
|
|
0dec35ed69 | ||
|
|
d2fcf71c4a | ||
|
|
b230c90d13 | ||
|
|
b1a07d2006 | ||
|
|
31ece04ab0 | ||
|
|
e9e23c4e98 |
No files matched your search
@@ -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...)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
+94
-35
@@ -9,6 +9,7 @@ import (
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"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 +20,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,7 +35,7 @@ type OpenVPN struct {
|
||||
|
||||
runCtx context.Context
|
||||
runCancel context.CancelFunc
|
||||
runMutex sync.Mutex
|
||||
runLock *semaphore.Weighted
|
||||
running bool
|
||||
}
|
||||
|
||||
@@ -46,10 +48,11 @@ type OpenVPNOption struct {
|
||||
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"`
|
||||
TLSCrypt string `proxy:"tls-crypt,omitempty"`
|
||||
Username string `proxy:"username,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
MTU int `proxy:"mtu,omitempty"`
|
||||
@@ -67,6 +70,7 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
|
||||
Dev: option.Dev,
|
||||
Cipher: option.Cipher,
|
||||
Auth: option.Auth,
|
||||
CompLZO: option.CompLZO,
|
||||
CA: []byte(option.CA),
|
||||
Cert: []byte(option.Cert),
|
||||
Key: []byte(option.Key),
|
||||
@@ -91,8 +95,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 +112,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 +139,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 +157,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 +192,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 +209,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 +256,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 +277,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 +350,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() {
|
||||
|
||||
@@ -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,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,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{})
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,11 @@
|
||||
package anet
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func IsForceAnet() bool {
|
||||
force, _ := strconv.ParseBool(os.Getenv("FORCE_ANET"))
|
||||
return force
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -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
@@ -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
@@ -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)}
|
||||
}
|
||||
+31
-12
@@ -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,12 @@ 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-----
|
||||
# mtu: 1500
|
||||
udp: true
|
||||
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
|
||||
@@ -1725,6 +1729,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
|
||||
@@ -2019,8 +2036,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:
|
||||
|
||||
@@ -6,7 +6,7 @@ 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
|
||||
@@ -25,27 +25,28 @@ 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/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
|
||||
@@ -108,10 +109,10 @@ 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
|
||||
|
||||
@@ -27,8 +27,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=
|
||||
@@ -123,8 +123,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,8 +137,8 @@ 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=
|
||||
@@ -147,32 +147,32 @@ 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=
|
||||
@@ -202,6 +202,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
|
||||
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=
|
||||
|
||||
@@ -229,10 +229,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 +280,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
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,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,
|
||||
|
||||
@@ -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
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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,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
@@ -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),
|
||||
|
||||
+31
-10
@@ -14,7 +14,10 @@ import (
|
||||
"github.com/metacubex/tls"
|
||||
)
|
||||
|
||||
const defaultHandshakeTimeout = 30 * time.Second
|
||||
const (
|
||||
DefaultHandshakeTimeout = 30 * time.Second
|
||||
ControlRetransmitDelay = time.Second
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
config *ClientConfig
|
||||
@@ -35,9 +38,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 {
|
||||
@@ -60,7 +67,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 +91,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,7 +126,7 @@ 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, c.config.CompLZO)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -168,10 +175,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:
|
||||
|
||||
+65
-23
@@ -15,9 +15,21 @@ 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 +40,7 @@ type ClientConfig struct {
|
||||
Dev string
|
||||
Cipher string
|
||||
Auth string
|
||||
CompLZO string
|
||||
|
||||
CA []byte
|
||||
Cert []byte
|
||||
@@ -40,11 +53,13 @@ type ClientConfig struct {
|
||||
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 +82,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 +123,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 +152,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)
|
||||
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
+385
-63
@@ -3,92 +3,237 @@ package openvpn
|
||||
import (
|
||||
"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
|
||||
sendAEAD cipher.AEAD
|
||||
recvAEAD cipher.AEAD
|
||||
|
||||
sendImplicitIV [AESGCMIVSize]byte
|
||||
recvImplicitIV [AESGCMIVSize]byte
|
||||
sendBlock cipher.Block
|
||||
recvBlock cipher.Block
|
||||
sendHMACKey []byte
|
||||
recvHMACKey []byte
|
||||
authHash func() hash.Hash
|
||||
authSize int
|
||||
sendMACPool sync.Pool
|
||||
recvMACPool sync.Pool
|
||||
|
||||
keyID uint8
|
||||
peerID uint32
|
||||
sendImplicitIV [DataChannelIVSize]byte
|
||||
recvImplicitIV [DataChannelIVSize]byte
|
||||
|
||||
keyID uint8
|
||||
peerID uint32
|
||||
header []byte
|
||||
compLZO string
|
||||
|
||||
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, compLZO string) (*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),
|
||||
compLZO: compLZO,
|
||||
}
|
||||
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),
|
||||
compLZO: compLZO,
|
||||
}
|
||||
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()
|
||||
// Prepend comp-lzo header (0xfa = not compressed) to satisfy servers expecting the framing.
|
||||
if d.compLZO == CompLzoYes {
|
||||
lzoPacket := make([]byte, 1+len(packet))
|
||||
lzoPacket[0] = lzoCompressNone
|
||||
copy(lzoPacket[1:], packet)
|
||||
packet = lzoPacket
|
||||
}
|
||||
|
||||
header := d.dataHeader()
|
||||
packetID := d.nextPacketID()
|
||||
if d.sendAEAD != nil {
|
||||
return d.encryptAEAD(packet, packetID)
|
||||
}
|
||||
return d.encryptCBC(packet, packetID)
|
||||
}
|
||||
|
||||
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 +241,44 @@ 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
|
||||
}
|
||||
var plain []byte
|
||||
if d.recvAEAD != nil {
|
||||
plain, err = d.decryptAEAD(packet, headerSize)
|
||||
} else {
|
||||
plain, err = d.decryptCBC(packet, headerSize)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.compLZO == CompLzoYes && len(plain) > 0 {
|
||||
decompressed, err := lzo1xDecompressSafe(plain)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(decompressed) > 0 {
|
||||
return decompressed, nil
|
||||
}
|
||||
}
|
||||
return plain, nil
|
||||
}
|
||||
|
||||
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 +286,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 " {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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
@@ -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()
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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]))
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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() {
|
||||
@@ -174,20 +189,47 @@ func (sc *Conn) Read(p []byte) (n int, err error) {
|
||||
if !ok {
|
||||
return 0, ErrInvalidSudokuMapMiss
|
||||
}
|
||||
sc.pendingData.appendByte(val)
|
||||
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)
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
package sudoku
|
||||
|
||||
func encodeSudokuPayload(dst []byte, table *Table, rng randomSource, paddingThreshold uint64, p []byte) []byte {
|
||||
func encodeSudokuPayload(dst []byte, table *Table, rng *sudokuRand, paddingThreshold uint64, p []byte) []byte {
|
||||
if len(p) == 0 {
|
||||
return dst[:0]
|
||||
}
|
||||
if paddingThreshold == 0 {
|
||||
return encodeSudokuPayloadNoPadding(dst, table, rng, p)
|
||||
}
|
||||
|
||||
outCapacity := len(p)*6 + 1
|
||||
if cap(dst) < outCapacity {
|
||||
@@ -34,3 +37,19 @@ func encodeSudokuPayload(dst []byte, table *Table, rng randomSource, paddingThre
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func encodeSudokuPayloadNoPadding(dst []byte, table *Table, rng *sudokuRand, p []byte) []byte {
|
||||
outCapacity := len(p) * 4
|
||||
if cap(dst) < outCapacity {
|
||||
dst = make([]byte, 0, outCapacity)
|
||||
}
|
||||
out := dst[:0]
|
||||
|
||||
for _, b := range p {
|
||||
puzzles := table.EncodeTable[b]
|
||||
puzzle := puzzles[rng.Intn(len(puzzles))]
|
||||
perm := perm4[rng.Intn(len(perm4))]
|
||||
out = append(out, puzzle[perm[0]], puzzle[perm[1]], puzzle[perm[2]], puzzle[perm[3]])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -8,9 +8,9 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
RngBatchSize = 128
|
||||
|
||||
packedProtectedPrefixBytes = 14
|
||||
packedIOBufferSize = 64 * 1024
|
||||
packedDecodeBufferSize = 96 * 1024
|
||||
)
|
||||
|
||||
// PackedConn encodes traffic with the packed Sudoku layout while preserving
|
||||
@@ -35,7 +35,7 @@ type PackedConn struct {
|
||||
readBits int
|
||||
|
||||
// Padding selection matches Conn's threshold-based model.
|
||||
rng randomSource
|
||||
rng *sudokuRand
|
||||
paddingThreshold uint64
|
||||
padMarker byte
|
||||
padPool []byte
|
||||
@@ -67,18 +67,20 @@ func NewPackedConn(c net.Conn, table *Table, pMin, pMax int) *PackedConn {
|
||||
pc := &PackedConn{
|
||||
Conn: c,
|
||||
table: table,
|
||||
reader: bufio.NewReaderSize(c, IOBufferSize),
|
||||
rawBuf: make([]byte, IOBufferSize),
|
||||
reader: bufio.NewReaderSize(c, packedIOBufferSize),
|
||||
rawBuf: make([]byte, packedDecodeBufferSize),
|
||||
pendingData: newPendingBuffer(4096),
|
||||
writeBuf: make([]byte, 0, 4096),
|
||||
rng: localRng,
|
||||
paddingThreshold: pickPaddingThreshold(localRng, pMin, pMax),
|
||||
}
|
||||
|
||||
pc.padMarker = table.layout.padMarker
|
||||
for _, b := range table.PaddingPool {
|
||||
if b != pc.padMarker {
|
||||
pc.padPool = append(pc.padPool, b)
|
||||
if table != nil && table.layout != nil {
|
||||
pc.padMarker = table.layout.padMarker
|
||||
for _, b := range table.PaddingPool {
|
||||
if b != pc.padMarker {
|
||||
pc.padPool = append(pc.padPool, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(pc.padPool) == 0 {
|
||||
@@ -87,18 +89,6 @@ func NewPackedConn(c net.Conn, table *Table, pMin, pMax int) *PackedConn {
|
||||
return pc
|
||||
}
|
||||
|
||||
func (pc *PackedConn) maybeAddPadding(out []byte) []byte {
|
||||
if shouldPad(pc.rng, pc.paddingThreshold) {
|
||||
out = append(out, pc.getPaddingByte())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (pc *PackedConn) appendGroup(out []byte, group byte) []byte {
|
||||
out = pc.maybeAddPadding(out)
|
||||
return append(out, pc.table.layout.groupByte(group))
|
||||
}
|
||||
|
||||
func (pc *PackedConn) appendForcedPadding(out []byte) []byte {
|
||||
return append(out, pc.getPaddingByte())
|
||||
}
|
||||
@@ -134,7 +124,7 @@ func (pc *PackedConn) writeProtectedPrefix(out []byte, p []byte) ([]byte, int) {
|
||||
} else {
|
||||
pc.bitBuf &= (1 << pc.bitCount) - 1
|
||||
}
|
||||
out = pc.appendGroup(out, group&0x3F)
|
||||
out = appendPackedGroup(out, pc.table.layout, pc.rng, pc.paddingThreshold, pc.padPool, group)
|
||||
}
|
||||
|
||||
effective++
|
||||
@@ -148,19 +138,49 @@ func (pc *PackedConn) writeProtectedPrefix(out []byte, p []byte) ([]byte, int) {
|
||||
return out, limit
|
||||
}
|
||||
|
||||
func appendPackedGroup(out []byte, layout *byteLayout, rng *sudokuRand, paddingThreshold uint64, padPool []byte, group byte) []byte {
|
||||
if paddingThreshold != 0 {
|
||||
u := rng.Uint32()
|
||||
if uint64(u) < paddingThreshold {
|
||||
out = append(out, padPool[fastIntnFromUint32(rng.Uint32(), len(padPool))])
|
||||
}
|
||||
}
|
||||
return append(out, layout.encodeGroup[group&0x3F])
|
||||
}
|
||||
|
||||
func maybeAppendPackedPadding(out []byte, rng *sudokuRand, paddingThreshold uint64, padPool []byte) []byte {
|
||||
if paddingThreshold != 0 {
|
||||
u := rng.Uint32()
|
||||
if uint64(u) < paddingThreshold {
|
||||
out = append(out, padPool[fastIntnFromUint32(rng.Uint32(), len(padPool))])
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if pc == nil || pc.Conn == nil || pc.table == nil || pc.table.layout == nil || pc.rng == nil || len(pc.padPool) == 0 {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
|
||||
pc.writeMu.Lock()
|
||||
defer pc.writeMu.Unlock()
|
||||
|
||||
needed := len(p)*3/2 + 32
|
||||
if pc.paddingThreshold == 0 {
|
||||
needed = ((len(p)+2)/3)*4 + 32
|
||||
}
|
||||
if cap(pc.writeBuf) < needed {
|
||||
pc.writeBuf = make([]byte, 0, needed)
|
||||
}
|
||||
out := pc.writeBuf[:0]
|
||||
layout := pc.table.layout
|
||||
rng := pc.rng
|
||||
paddingThreshold := pc.paddingThreshold
|
||||
padPool := pc.padPool
|
||||
|
||||
var prefixN int
|
||||
out, prefixN = pc.writeProtectedPrefix(out, p)
|
||||
@@ -181,7 +201,7 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
} else {
|
||||
pc.bitBuf &= (1 << pc.bitCount) - 1
|
||||
}
|
||||
out = pc.appendGroup(out, group&0x3F)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, group)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,10 +215,10 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
g3 := ((b2 & 0x0F) << 2) | ((b3 >> 6) & 0x03)
|
||||
g4 := b3 & 0x3F
|
||||
|
||||
out = pc.appendGroup(out, g1)
|
||||
out = pc.appendGroup(out, g2)
|
||||
out = pc.appendGroup(out, g3)
|
||||
out = pc.appendGroup(out, g4)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g1)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g2)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g3)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g4)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,10 +231,10 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
g3 := ((b2 & 0x0F) << 2) | ((b3 >> 6) & 0x03)
|
||||
g4 := b3 & 0x3F
|
||||
|
||||
out = pc.appendGroup(out, g1)
|
||||
out = pc.appendGroup(out, g2)
|
||||
out = pc.appendGroup(out, g3)
|
||||
out = pc.appendGroup(out, g4)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g1)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g2)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g3)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g4)
|
||||
}
|
||||
|
||||
for ; i < n; i++ {
|
||||
@@ -229,7 +249,7 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
} else {
|
||||
pc.bitBuf &= (1 << pc.bitCount) - 1
|
||||
}
|
||||
out = pc.appendGroup(out, group&0x3F)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, group)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,11 +257,11 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
group := byte(pc.bitBuf << (6 - pc.bitCount))
|
||||
pc.bitBuf = 0
|
||||
pc.bitCount = 0
|
||||
out = pc.appendGroup(out, group&0x3F)
|
||||
out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, group)
|
||||
out = append(out, pc.padMarker)
|
||||
}
|
||||
|
||||
out = pc.maybeAddPadding(out)
|
||||
out = maybeAppendPackedPadding(out, rng, paddingThreshold, padPool)
|
||||
|
||||
if len(out) > 0 {
|
||||
pc.writeBuf = out[:0]
|
||||
@@ -252,6 +272,10 @@ func (pc *PackedConn) Write(p []byte) (int, error) {
|
||||
}
|
||||
|
||||
func (pc *PackedConn) Flush() error {
|
||||
if pc == nil || pc.Conn == nil || pc.table == nil || pc.table.layout == nil || pc.rng == nil || len(pc.padPool) == 0 {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
|
||||
pc.writeMu.Lock()
|
||||
defer pc.writeMu.Unlock()
|
||||
|
||||
@@ -265,7 +289,7 @@ func (pc *PackedConn) Flush() error {
|
||||
out = append(out, pc.padMarker)
|
||||
}
|
||||
|
||||
out = pc.maybeAddPadding(out)
|
||||
out = maybeAppendPackedPadding(out, pc.rng, pc.paddingThreshold, pc.padPool)
|
||||
|
||||
if len(out) > 0 {
|
||||
pc.writeBuf = out[:0]
|
||||
@@ -289,19 +313,44 @@ func writeFull(w io.Writer, b []byte) error {
|
||||
}
|
||||
|
||||
func (pc *PackedConn) Read(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if pc == nil || pc.Conn == nil || pc.reader == nil || len(pc.rawBuf) == 0 || pc.table == nil || pc.table.layout == nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
if n, ok := drainPending(p, &pc.pendingData); ok {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
outN := 0
|
||||
for {
|
||||
nr, rErr := pc.reader.Read(pc.rawBuf)
|
||||
nr, rErr := readRawLimited(pc.Conn, pc.reader, pc.rawBuf[:packedReadSize(len(p)-outN, len(pc.rawBuf))])
|
||||
if nr > 0 {
|
||||
rBuf := pc.readBitBuf
|
||||
rBits := pc.readBits
|
||||
padMarker := pc.padMarker
|
||||
layout := pc.table.layout
|
||||
|
||||
for _, b := range pc.rawBuf[:nr] {
|
||||
chunk := pc.rawBuf[:nr]
|
||||
for i := 0; i < len(chunk); {
|
||||
if rBits == 0 && outN+3 <= len(p) && i+3 < len(chunk) &&
|
||||
layout.hintTable[chunk[i]] && layout.hintTable[chunk[i+1]] &&
|
||||
layout.hintTable[chunk[i+2]] && layout.hintTable[chunk[i+3]] {
|
||||
g1 := layout.decodeGroup[chunk[i]]
|
||||
g2 := layout.decodeGroup[chunk[i+1]]
|
||||
g3 := layout.decodeGroup[chunk[i+2]]
|
||||
g4 := layout.decodeGroup[chunk[i+3]]
|
||||
p[outN] = (g1 << 2) | (g2 >> 4)
|
||||
p[outN+1] = (g2 << 4) | (g3 >> 2)
|
||||
p[outN+2] = (g3 << 6) | g4
|
||||
outN += 3
|
||||
i += 4
|
||||
continue
|
||||
}
|
||||
|
||||
b := chunk[i]
|
||||
i++
|
||||
if !layout.hintTable[b] {
|
||||
if b == padMarker {
|
||||
rBuf = 0
|
||||
@@ -321,7 +370,7 @@ func (pc *PackedConn) Read(p []byte) (int, error) {
|
||||
if rBits >= 8 {
|
||||
rBits -= 8
|
||||
val := byte(rBuf >> rBits)
|
||||
pc.pendingData.appendByte(val)
|
||||
outN = appendDecodedByte(p, outN, &pc.pendingData, val)
|
||||
if rBits == 0 {
|
||||
rBuf = 0
|
||||
} else {
|
||||
@@ -339,21 +388,32 @@ func (pc *PackedConn) Read(p []byte) (int, error) {
|
||||
pc.readBitBuf = 0
|
||||
pc.readBits = 0
|
||||
}
|
||||
if pc.pendingData.available() > 0 {
|
||||
break
|
||||
if outN > 0 {
|
||||
return outN, nil
|
||||
}
|
||||
if n, ok := drainPending(p, &pc.pendingData); ok {
|
||||
return n, nil
|
||||
}
|
||||
return 0, rErr
|
||||
}
|
||||
|
||||
if pc.pendingData.available() > 0 {
|
||||
break
|
||||
if outN > 0 {
|
||||
return outN, nil
|
||||
}
|
||||
}
|
||||
|
||||
n, _ := drainPending(p, &pc.pendingData)
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (pc *PackedConn) getPaddingByte() byte {
|
||||
return pc.padPool[pc.rng.Intn(len(pc.padPool))]
|
||||
}
|
||||
|
||||
func packedReadSize(decodedRemaining, maxRaw int) int {
|
||||
if maxRaw <= minDecodeReadSize || decodedRemaining <= 0 {
|
||||
return maxRaw
|
||||
}
|
||||
if decodedRemaining > (maxRaw-minDecodeReadSize)/2 {
|
||||
return maxRaw
|
||||
}
|
||||
|
||||
return decodedRemaining*2 + minDecodeReadSize
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package sudoku
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -39,7 +38,7 @@ func TestPackedConn_ProtectedPrefixPadding(t *testing.T) {
|
||||
table := NewTable("packed-prefix-seed", "prefer_ascii")
|
||||
mock := &mockConn{}
|
||||
writer := NewPackedConn(mock, table, 0, 0)
|
||||
writer.rng = rand.New(rand.NewSource(1))
|
||||
writer.rng = newSudokuRand(1)
|
||||
|
||||
payload := bytes.Repeat([]byte{0}, 32)
|
||||
if _, err := writer.Write(payload); err != nil {
|
||||
|
||||
@@ -2,7 +2,7 @@ package sudoku
|
||||
|
||||
const probOne = uint64(1) << 32
|
||||
|
||||
func pickPaddingThreshold(r randomSource, pMin, pMax int) uint64 {
|
||||
func pickPaddingThreshold(r *sudokuRand, pMin, pMax int) uint64 {
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
@@ -28,7 +28,7 @@ func pickPaddingThreshold(r randomSource, pMin, pMax int) uint64 {
|
||||
return min + (u * (max - min) >> 32)
|
||||
}
|
||||
|
||||
func shouldPad(r randomSource, threshold uint64) bool {
|
||||
func shouldPad(r *sudokuRand, threshold uint64) bool {
|
||||
if threshold == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -25,7 +25,10 @@ func (p *pendingBuffer) reset() {
|
||||
}
|
||||
|
||||
func (p *pendingBuffer) ensureAppendCapacity(extra int) {
|
||||
if p == nil || extra <= 0 || p.off == 0 {
|
||||
if p == nil || extra <= 0 {
|
||||
return
|
||||
}
|
||||
if p.off == 0 {
|
||||
return
|
||||
}
|
||||
if cap(p.data)-len(p.data) >= extra {
|
||||
@@ -43,6 +46,15 @@ func (p *pendingBuffer) appendByte(b byte) {
|
||||
p.data = append(p.data, b)
|
||||
}
|
||||
|
||||
func appendDecodedByte(dst []byte, n int, pending *pendingBuffer, b byte) int {
|
||||
if n < len(dst) {
|
||||
dst[n] = b
|
||||
return n + 1
|
||||
}
|
||||
pending.appendByte(b)
|
||||
return n
|
||||
}
|
||||
|
||||
func drainPending(dst []byte, pending *pendingBuffer) (int, bool) {
|
||||
if pending == nil || pending.available() == 0 {
|
||||
return 0, false
|
||||
|
||||
@@ -6,14 +6,10 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type randomSource interface {
|
||||
Uint32() uint32
|
||||
Uint64() uint64
|
||||
Intn(n int) int
|
||||
}
|
||||
|
||||
type sudokuRand struct {
|
||||
state uint64
|
||||
state uint64
|
||||
cached uint32
|
||||
haveCached bool
|
||||
}
|
||||
|
||||
func newSeededRand() *sudokuRand {
|
||||
@@ -37,20 +33,36 @@ func (r *sudokuRand) Uint64() uint64 {
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
r.state += 0x9e3779b97f4a7c15
|
||||
z := r.state
|
||||
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9
|
||||
z = (z ^ (z >> 27)) * 0x94d049bb133111eb
|
||||
return z ^ (z >> 31)
|
||||
r.haveCached = false
|
||||
x := r.state
|
||||
x ^= x >> 12
|
||||
x ^= x << 25
|
||||
x ^= x >> 27
|
||||
r.state = x
|
||||
return x * 0x2545f4914f6cdd1d
|
||||
}
|
||||
|
||||
func (r *sudokuRand) Uint32() uint32 {
|
||||
return uint32(r.Uint64() >> 32)
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
if r.haveCached {
|
||||
r.haveCached = false
|
||||
return r.cached
|
||||
}
|
||||
v := r.Uint64()
|
||||
r.cached = uint32(v)
|
||||
r.haveCached = true
|
||||
return uint32(v >> 32)
|
||||
}
|
||||
|
||||
func (r *sudokuRand) Intn(n int) int {
|
||||
if n <= 1 {
|
||||
return 0
|
||||
}
|
||||
return int((uint64(r.Uint32()) * uint64(n)) >> 32)
|
||||
return fastIntnFromUint32(r.Uint32(), n)
|
||||
}
|
||||
|
||||
func fastIntnFromUint32(u uint32, n int) int {
|
||||
return int((uint64(u) * uint64(n)) >> 32)
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/metacubex/mihomo/component/loopback"
|
||||
"github.com/metacubex/mihomo/component/nat"
|
||||
"github.com/metacubex/mihomo/component/process"
|
||||
"github.com/metacubex/mihomo/component/proxydialer"
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
"github.com/metacubex/mihomo/component/slowdown"
|
||||
"github.com/metacubex/mihomo/component/sniffer"
|
||||
@@ -72,6 +73,7 @@ type tunnel struct{}
|
||||
var Tunnel = tunnel{}
|
||||
var _ C.Tunnel = Tunnel
|
||||
var _ P.Tunnel = Tunnel
|
||||
var _ proxydialer.Tunnel = Tunnel
|
||||
|
||||
func (t tunnel) HandleTCPConn(conn net.Conn, metadata *C.Metadata) {
|
||||
connCtx := icontext.NewConnContext(conn, metadata)
|
||||
@@ -112,6 +114,10 @@ func (t tunnel) NatTable() C.NatTable {
|
||||
return natTable
|
||||
}
|
||||
|
||||
func (t tunnel) Proxies() map[string]C.Proxy {
|
||||
return proxies
|
||||
}
|
||||
|
||||
func (t tunnel) Providers() map[string]P.ProxyProvider {
|
||||
return providers
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user