mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-12-03 01:28:31 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97f25250a6 | ||
|
|
8b0bcb6740 | ||
|
|
022f677385 | ||
|
|
32799662ad | ||
|
|
86257fc83c | ||
|
|
f2222b5e02 | ||
|
|
3ac62152cb | ||
|
|
5516ca18fd | ||
|
|
3bca69c745 | ||
|
|
558b3840ea | ||
|
|
f94da9f2b3 | ||
|
|
2cfc4ba044 | ||
|
|
034f1d1e9b | ||
|
|
dede56fe4b | ||
|
|
5fda87d50e | ||
|
|
5e1b133e4e | ||
|
|
27a3ca6afc | ||
|
|
7573affdd4 | ||
|
|
17fbaf9100 | ||
|
|
710772f993 | ||
|
|
d36b024b10 | ||
|
|
f52c9356c2 | ||
|
|
e45c896185 | ||
|
|
d18a14afeb | ||
|
|
6aaabc97ca | ||
|
|
85c024a4a6 | ||
|
|
c33c90d7af | ||
|
|
65c3d3e4e2 | ||
|
|
98b3060558 | ||
|
|
b90100645e | ||
|
|
46ee1649c0 | ||
|
|
e3b8fc2b77 | ||
|
|
707fe8b207 | ||
|
|
1e1434d1de | ||
|
|
26052ba5e5 | ||
|
|
75a0cd5aff | ||
|
|
e03ba23f65 | ||
|
|
0c995a2479 | ||
|
|
3c526ae06e | ||
|
|
0b009b514c | ||
|
|
18d139a15d | ||
|
|
5f250413fe | ||
|
|
993595df73 | ||
|
|
828fd30dc3 |
No files matched your search
@@ -24,7 +24,7 @@ jobs:
|
||||
- 'ubuntu-24.04-arm' # arm64 linux
|
||||
- 'macos-15-intel' # amd64 macos
|
||||
go-version:
|
||||
- '1.26.0-rc.2'
|
||||
- '1.26.0-rc.3'
|
||||
- '1.25'
|
||||
- '1.24'
|
||||
- '1.23'
|
||||
@@ -51,13 +51,13 @@ jobs:
|
||||
check-latest: true # Always check for the latest patch release
|
||||
|
||||
- name: Revert Golang commit for Windows7/8
|
||||
if: ${{ runner.os == 'Windows' && matrix.go-version != '1.20' && matrix.go-version != '1.26.0-rc.2' }}
|
||||
if: ${{ runner.os == 'Windows' && matrix.go-version != '1.20' && matrix.go-version != '1.26.0-rc.3' }}
|
||||
run: |
|
||||
cd $(go env GOROOT)
|
||||
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go${{matrix.go-version}}.patch
|
||||
|
||||
- name: Revert Golang commit for Windows7/8
|
||||
if: ${{ runner.os == 'Windows' && matrix.go-version == '1.26.0-rc.2' }}
|
||||
if: ${{ runner.os == 'Windows' && matrix.go-version == '1.26.0-rc.3' }}
|
||||
run: |
|
||||
cd $(go env GOROOT)
|
||||
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.26.patch
|
||||
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
type ECHOptions struct {
|
||||
Enable bool `proxy:"enable,omitempty" obfs:"enable,omitempty"`
|
||||
Config string `proxy:"config,omitempty" obfs:"config,omitempty"`
|
||||
|
||||
QueryServerName string `proxy:"query-server-name,omitempty" obfs:"query-server-name,omitempty"`
|
||||
}
|
||||
|
||||
func (o ECHOptions) Parse() (*ech.Config, error) {
|
||||
@@ -29,6 +31,9 @@ func (o ECHOptions) Parse() (*ech.Config, error) {
|
||||
}
|
||||
} else {
|
||||
echConfig.GetEncryptedClientHelloConfigList = func(ctx context.Context, serverName string) ([]byte, error) {
|
||||
if o.QueryServerName != "" { // overrides the domain name used for ECH HTTPS record queries
|
||||
serverName = o.QueryServerName
|
||||
}
|
||||
return resolver.ResolveECHWithResolver(ctx, serverName, resolver.ProxyServerHostResolver)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/atomic"
|
||||
"github.com/metacubex/mihomo/common/contextutils"
|
||||
"github.com/metacubex/mihomo/common/pool"
|
||||
"github.com/metacubex/mihomo/component/dialer"
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/dns"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
"github.com/metacubex/mihomo/transport/masque"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
|
||||
connectip "github.com/metacubex/connect-ip-go"
|
||||
"github.com/metacubex/quic-go"
|
||||
wireguard "github.com/metacubex/sing-wireguard"
|
||||
M "github.com/metacubex/sing/common/metadata"
|
||||
"github.com/metacubex/tls"
|
||||
)
|
||||
|
||||
type Masque struct {
|
||||
*Base
|
||||
tlsConfig *tls.Config
|
||||
quicConfig *quic.Config
|
||||
tunDevice wireguard.Device
|
||||
resolver resolver.Resolver
|
||||
uri string
|
||||
|
||||
runCtx context.Context
|
||||
runCancel context.CancelFunc
|
||||
runMutex sync.Mutex
|
||||
running atomic.Bool
|
||||
runDevice atomic.Bool
|
||||
|
||||
option MasqueOption
|
||||
}
|
||||
|
||||
type MasqueOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
PrivateKey string `proxy:"private-key"`
|
||||
PublicKey string `proxy:"public-key"`
|
||||
Ip string `proxy:"ip,omitempty"`
|
||||
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||
URI string `proxy:"uri,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
MTU int `proxy:"mtu,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
|
||||
CongestionController string `proxy:"congestion-controller,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
|
||||
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
||||
Dns []string `proxy:"dns,omitempty"`
|
||||
}
|
||||
|
||||
func (option MasqueOption) Prefixes() ([]netip.Prefix, error) {
|
||||
localPrefixes := make([]netip.Prefix, 0, 2)
|
||||
if len(option.Ip) > 0 {
|
||||
if !strings.Contains(option.Ip, "/") {
|
||||
option.Ip = option.Ip + "/32"
|
||||
}
|
||||
if prefix, err := netip.ParsePrefix(option.Ip); err == nil {
|
||||
localPrefixes = append(localPrefixes, prefix)
|
||||
} else {
|
||||
return nil, fmt.Errorf("ip address parse error: %w", err)
|
||||
}
|
||||
}
|
||||
if len(option.Ipv6) > 0 {
|
||||
if !strings.Contains(option.Ipv6, "/") {
|
||||
option.Ipv6 = option.Ipv6 + "/128"
|
||||
}
|
||||
if prefix, err := netip.ParsePrefix(option.Ipv6); err == nil {
|
||||
localPrefixes = append(localPrefixes, prefix)
|
||||
} else {
|
||||
return nil, fmt.Errorf("ipv6 address parse error: %w", err)
|
||||
}
|
||||
}
|
||||
if len(localPrefixes) == 0 {
|
||||
return nil, errors.New("missing local address")
|
||||
}
|
||||
return localPrefixes, nil
|
||||
}
|
||||
|
||||
func NewMasque(option MasqueOption) (*Masque, error) {
|
||||
outbound := &Masque{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Masque,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
outbound.runCtx = ctx
|
||||
outbound.runCancel = cancel
|
||||
|
||||
privKeyB64, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode private key: %v", err)
|
||||
}
|
||||
privKey, err := x509.ParseECPrivateKey(privKeyB64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse private key: %v", err)
|
||||
}
|
||||
|
||||
endpointPubKeyB64, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode public key: %v", err)
|
||||
}
|
||||
pubKey, err := x509.ParsePKIXPublicKey(endpointPubKeyB64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse public key: %v", err)
|
||||
}
|
||||
ecPubKey, ok := pubKey.(*ecdsa.PublicKey)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("failed to assert public key as ECDSA")
|
||||
}
|
||||
|
||||
uri := option.URI
|
||||
if uri == "" {
|
||||
uri = masque.ConnectURI
|
||||
}
|
||||
outbound.uri = uri
|
||||
|
||||
sni := option.SNI
|
||||
if sni == "" {
|
||||
sni = masque.ConnectSNI
|
||||
}
|
||||
|
||||
tlsConfig, err := masque.PrepareTlsConfig(privKey, ecPubKey, sni)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to prepare TLS config: %v\n", err)
|
||||
}
|
||||
outbound.tlsConfig = tlsConfig
|
||||
|
||||
outbound.quicConfig = &quic.Config{
|
||||
EnableDatagrams: true,
|
||||
InitialPacketSize: 1242,
|
||||
KeepAlivePeriod: 30 * time.Second,
|
||||
}
|
||||
|
||||
prefixes, err := option.Prefixes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outbound.option = option
|
||||
|
||||
mtu := option.MTU
|
||||
if mtu == 0 {
|
||||
mtu = 1280
|
||||
}
|
||||
if len(prefixes) == 0 {
|
||||
return nil, errors.New("missing local address")
|
||||
}
|
||||
outbound.tunDevice, err = wireguard.NewStackDevice(prefixes, uint32(mtu))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create device: %w", err)
|
||||
}
|
||||
|
||||
var has6 bool
|
||||
for _, address := range prefixes {
|
||||
if !address.Addr().Unmap().Is4() {
|
||||
has6 = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if option.RemoteDnsResolve && len(option.Dns) > 0 {
|
||||
nss, err := dns.ParseNameServer(option.Dns)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range nss {
|
||||
nss[i].ProxyAdapter = outbound
|
||||
}
|
||||
outbound.resolver = dns.NewResolver(dns.Config{
|
||||
Main: nss,
|
||||
IPv6: has6,
|
||||
})
|
||||
}
|
||||
|
||||
return outbound, nil
|
||||
}
|
||||
|
||||
func (w *Masque) run(ctx context.Context) error {
|
||||
if w.running.Load() {
|
||||
return nil
|
||||
}
|
||||
w.runMutex.Lock()
|
||||
defer w.runMutex.Unlock()
|
||||
// double-check like sync.Once
|
||||
if w.running.Load() {
|
||||
return nil
|
||||
}
|
||||
|
||||
if w.runCtx.Err() != nil {
|
||||
return w.runCtx.Err()
|
||||
}
|
||||
|
||||
if !w.runDevice.Load() {
|
||||
err := w.tunDevice.Start()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.runDevice.Store(true)
|
||||
}
|
||||
|
||||
udpAddr, err := resolveUDPAddr(ctx, "udp", w.addr, w.prefer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
pc, err := w.dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
quicConn, err := quic.Dial(ctx, pc, udpAddr, w.tlsConfig, w.quicConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
common.SetCongestionController(quicConn, w.option.CongestionController, w.option.CWND)
|
||||
|
||||
tr, ipConn, err := masque.ConnectTunnel(ctx, quicConn, w.uri)
|
||||
if err != nil {
|
||||
_ = pc.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
w.running.Store(true)
|
||||
|
||||
runCtx, runCancel := context.WithCancel(w.runCtx)
|
||||
contextutils.AfterFunc(runCtx, func() {
|
||||
w.running.Store(false)
|
||||
_ = ipConn.Close()
|
||||
_ = tr.Close()
|
||||
_ = pc.Close()
|
||||
})
|
||||
|
||||
go func() {
|
||||
defer runCancel()
|
||||
buf := pool.Get(pool.UDPBufferSize)
|
||||
defer pool.Put(buf)
|
||||
bufs := [][]byte{buf}
|
||||
sizes := []int{0}
|
||||
for runCtx.Err() == nil {
|
||||
_, err := w.tunDevice.Read(bufs, sizes, 0)
|
||||
if err != nil {
|
||||
log.Errorln("[Masque](%s) error reading from TUN device: %v", w.name, err)
|
||||
return
|
||||
}
|
||||
icmp, err := ipConn.WritePacket(buf[:sizes[0]])
|
||||
if err != nil {
|
||||
if errors.As(err, new(*connectip.CloseError)) {
|
||||
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
|
||||
return
|
||||
}
|
||||
log.Warnln("[Masque](%s) error writing to IP connection: %v, continuing...", w.name, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(icmp) > 0 {
|
||||
if _, err := w.tunDevice.Write([][]byte{icmp}, 0); err != nil {
|
||||
log.Warnln("[Masque](%s) error writing ICMP to TUN device: %v, continuing...", w.name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer runCancel()
|
||||
buf := pool.Get(pool.UDPBufferSize)
|
||||
defer pool.Put(buf)
|
||||
for runCtx.Err() == nil {
|
||||
n, err := ipConn.ReadPacket(buf)
|
||||
if err != nil {
|
||||
if errors.As(err, new(*connectip.CloseError)) {
|
||||
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
|
||||
return
|
||||
}
|
||||
log.Warnln("[Masque](%s) error reading from IP connection: %v, continuing...", w.name, err)
|
||||
continue
|
||||
}
|
||||
if _, err := w.tunDevice.Write([][]byte{buf[:n]}, 0); err != nil {
|
||||
log.Errorln("[Masque](%s) error writing to TUN device: %v", w.name, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close implements C.ProxyAdapter
|
||||
func (w *Masque) Close() error {
|
||||
w.runCancel()
|
||||
if w.tunDevice != nil {
|
||||
w.tunDevice.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Masque) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||
var conn net.Conn
|
||||
if err = w.run(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !metadata.Resolved() || w.resolver != nil {
|
||||
r := resolver.DefaultResolver
|
||||
if w.resolver != nil {
|
||||
r = w.resolver
|
||||
}
|
||||
options := w.DialOptions()
|
||||
options = append(options, dialer.WithResolver(r))
|
||||
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: w.tunDevice}))
|
||||
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||
} else {
|
||||
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if conn == nil {
|
||||
return nil, errors.New("conn is nil")
|
||||
}
|
||||
return NewConn(conn, w), nil
|
||||
}
|
||||
|
||||
func (w *Masque) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||
var pc net.PacketConn
|
||||
if err = w.run(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = w.ResolveUDP(ctx, metadata); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if pc == nil {
|
||||
return nil, errors.New("packetConn is nil")
|
||||
}
|
||||
return newPacketConn(pc, w), nil
|
||||
}
|
||||
|
||||
func (w *Masque) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||
if (!metadata.Resolved() || w.resolver != nil) && metadata.Host != "" {
|
||||
r := resolver.DefaultResolver
|
||||
if w.resolver != nil {
|
||||
r = w.resolver
|
||||
}
|
||||
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, r)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't resolve ip: %w", err)
|
||||
}
|
||||
metadata.DstIP = ip
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProxyInfo implements C.ProxyAdapter
|
||||
func (w *Masque) ProxyInfo() C.ProxyInfo {
|
||||
info := w.Base.ProxyInfo()
|
||||
info.DialerProxy = w.option.DialerProxy
|
||||
return info
|
||||
}
|
||||
|
||||
// IsL3Protocol implements C.ProxyAdapter
|
||||
func (w *Masque) IsL3Protocol(metadata *C.Metadata) bool {
|
||||
return true
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
@@ -22,10 +21,8 @@ type Sudoku struct {
|
||||
httpMaskMu sync.Mutex
|
||||
httpMaskClient *sudoku.HTTPMaskTunnelClient
|
||||
|
||||
muxMu sync.Mutex
|
||||
muxClient *sudoku.MultiplexClient
|
||||
muxBackoffUntil time.Time
|
||||
muxLastErr error
|
||||
muxMu sync.Mutex
|
||||
muxClient *sudoku.MultiplexClient
|
||||
}
|
||||
|
||||
type SudokuOption struct {
|
||||
@@ -58,7 +55,7 @@ func (s *Sudoku) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Con
|
||||
|
||||
muxMode := normalizeHTTPMaskMultiplex(cfg.HTTPMaskMultiplex)
|
||||
if muxMode == "on" && !cfg.DisableHTTPMask && httpTunnelModeEnabled(cfg.HTTPMaskMode) {
|
||||
stream, muxErr := s.dialMultiplex(ctx, cfg.TargetAddress, muxMode)
|
||||
stream, muxErr := s.dialMultiplex(ctx, cfg.TargetAddress)
|
||||
if muxErr == nil {
|
||||
return NewConn(stream, s), nil
|
||||
}
|
||||
@@ -265,7 +262,7 @@ func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfi
|
||||
}
|
||||
|
||||
upgrade := func(raw net.Conn) (net.Conn, error) {
|
||||
return sudoku.ClientHandshakeWithOptions(raw, &handshakeCfg, sudoku.ClientHandshakeOptions{})
|
||||
return sudoku.ClientHandshake(raw, &handshakeCfg)
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -303,7 +300,7 @@ func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfi
|
||||
}
|
||||
|
||||
if !handshakeDone {
|
||||
c, err = sudoku.ClientHandshakeWithOptions(c, &handshakeCfg, sudoku.ClientHandshakeOptions{})
|
||||
c, err = sudoku.ClientHandshake(c, &handshakeCfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -312,9 +309,9 @@ func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfi
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Sudoku) dialMultiplex(ctx context.Context, targetAddress string, mode string) (net.Conn, error) {
|
||||
func (s *Sudoku) dialMultiplex(ctx context.Context, targetAddress string) (net.Conn, error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
client, err := s.getOrCreateMuxClient(ctx, mode)
|
||||
client, err := s.getOrCreateMuxClient(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -330,21 +327,11 @@ func (s *Sudoku) dialMultiplex(ctx context.Context, targetAddress string, mode s
|
||||
return nil, fmt.Errorf("multiplex open stream failed")
|
||||
}
|
||||
|
||||
func (s *Sudoku) getOrCreateMuxClient(ctx context.Context, mode string) (*sudoku.MultiplexClient, error) {
|
||||
func (s *Sudoku) getOrCreateMuxClient(ctx context.Context) (*sudoku.MultiplexClient, error) {
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("nil adapter")
|
||||
}
|
||||
|
||||
if mode == "auto" {
|
||||
s.muxMu.Lock()
|
||||
backoffUntil := s.muxBackoffUntil
|
||||
lastErr := s.muxLastErr
|
||||
s.muxMu.Unlock()
|
||||
if time.Now().Before(backoffUntil) {
|
||||
return nil, fmt.Errorf("multiplex temporarily disabled: %v", lastErr)
|
||||
}
|
||||
}
|
||||
|
||||
s.muxMu.Lock()
|
||||
if s.muxClient != nil && !s.muxClient.IsClosed() {
|
||||
client := s.muxClient
|
||||
@@ -363,20 +350,12 @@ func (s *Sudoku) getOrCreateMuxClient(ctx context.Context, mode string) (*sudoku
|
||||
baseCfg := s.baseConf
|
||||
baseConn, err := s.dialAndHandshake(ctx, &baseCfg)
|
||||
if err != nil {
|
||||
if mode == "auto" {
|
||||
s.muxLastErr = err
|
||||
s.muxBackoffUntil = time.Now().Add(45 * time.Second)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client, err := sudoku.StartMultiplexClient(baseConn)
|
||||
if err != nil {
|
||||
_ = baseConn.Close()
|
||||
if mode == "auto" {
|
||||
s.muxLastErr = err
|
||||
s.muxBackoffUntil = time.Now().Add(45 * time.Second)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -384,16 +363,6 @@ func (s *Sudoku) getOrCreateMuxClient(ctx context.Context, mode string) (*sudoku
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (s *Sudoku) noteMuxFailure(mode string, err error) {
|
||||
if mode != "auto" {
|
||||
return
|
||||
}
|
||||
s.muxMu.Lock()
|
||||
s.muxLastErr = err
|
||||
s.muxBackoffUntil = time.Now().Add(45 * time.Second)
|
||||
s.muxMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Sudoku) resetMuxClient() {
|
||||
s.muxMu.Lock()
|
||||
defer s.muxMu.Unlock()
|
||||
|
||||
@@ -178,7 +178,7 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
||||
},
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
singDialer := proxydialer.NewSlowDownSingDialer(proxydialer.NewSingDialer(outbound.dialer), slowdown.New())
|
||||
singDialer := proxydialer.NewSingDialer(proxydialer.NewSlowDownDialer(outbound.dialer, slowdown.New()))
|
||||
|
||||
var reserved [3]uint8
|
||||
if len(option.Reserved) > 0 {
|
||||
|
||||
@@ -159,6 +159,13 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error)
|
||||
break
|
||||
}
|
||||
proxy, err = outbound.NewSudoku(*sudokuOption)
|
||||
case "masque":
|
||||
masqueOption := &outbound.MasqueOption{BasicOption: basicOption}
|
||||
err = decoder.Decode(mapping, masqueOption)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
proxy, err = outbound.NewMasque(*masqueOption)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding"
|
||||
"fmt"
|
||||
|
||||
"github.com/dlclark/regexp2"
|
||||
)
|
||||
|
||||
type overrideSchema struct {
|
||||
TFO *bool `provider:"tfo,omitempty"`
|
||||
MPTcp *bool `provider:"mptcp,omitempty"`
|
||||
UDP *bool `provider:"udp,omitempty"`
|
||||
UDPOverTCP *bool `provider:"udp-over-tcp,omitempty"`
|
||||
Up *string `provider:"up,omitempty"`
|
||||
Down *string `provider:"down,omitempty"`
|
||||
DialerProxy *string `provider:"dialer-proxy,omitempty"`
|
||||
SkipCertVerify *bool `provider:"skip-cert-verify,omitempty"`
|
||||
Interface *string `provider:"interface-name,omitempty"`
|
||||
RoutingMark *int `provider:"routing-mark,omitempty"`
|
||||
IPVersion *string `provider:"ip-version,omitempty"`
|
||||
|
||||
AdditionalPrefix *string `provider:"additional-prefix,omitempty"`
|
||||
AdditionalSuffix *string `provider:"additional-suffix,omitempty"`
|
||||
ProxyName []overrideProxyNameSchema `provider:"proxy-name,omitempty"`
|
||||
}
|
||||
|
||||
type overrideProxyNameSchema struct {
|
||||
// matching expression for regex replacement
|
||||
Pattern *regexp2.Regexp `provider:"pattern"`
|
||||
// the new content after regex matching
|
||||
Target string `provider:"target"`
|
||||
}
|
||||
|
||||
var _ encoding.TextUnmarshaler = (*regexp2.Regexp)(nil) // ensure *regexp2.Regexp can decode direct by structure package
|
||||
|
||||
func (o *overrideSchema) Apply(mapping map[string]any) error {
|
||||
if o.TFO != nil {
|
||||
mapping["tfo"] = *o.TFO
|
||||
}
|
||||
if o.MPTcp != nil {
|
||||
mapping["mptcp"] = *o.MPTcp
|
||||
}
|
||||
if o.UDP != nil {
|
||||
mapping["udp"] = *o.UDP
|
||||
}
|
||||
if o.UDPOverTCP != nil {
|
||||
mapping["udp-over-tcp"] = *o.UDPOverTCP
|
||||
}
|
||||
if o.Up != nil {
|
||||
mapping["up"] = *o.Up
|
||||
}
|
||||
if o.Down != nil {
|
||||
mapping["down"] = *o.Down
|
||||
}
|
||||
if o.DialerProxy != nil {
|
||||
mapping["dialer-proxy"] = *o.DialerProxy
|
||||
}
|
||||
if o.SkipCertVerify != nil {
|
||||
mapping["skip-cert-verify"] = *o.SkipCertVerify
|
||||
}
|
||||
if o.Interface != nil {
|
||||
mapping["interface"] = *o.Interface
|
||||
}
|
||||
if o.RoutingMark != nil {
|
||||
mapping["routing-mark"] = *o.RoutingMark
|
||||
}
|
||||
if o.IPVersion != nil {
|
||||
mapping["ip-version"] = *o.IPVersion
|
||||
}
|
||||
|
||||
for _, expr := range o.ProxyName {
|
||||
name := mapping["name"].(string)
|
||||
newName, err := expr.Pattern.Replace(name, expr.Target, 0, -1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("proxy name replace error: %w", err)
|
||||
}
|
||||
mapping["name"] = newName
|
||||
}
|
||||
if o.AdditionalPrefix != nil {
|
||||
mapping["name"] = fmt.Sprintf("%s%s", *o.AdditionalPrefix, mapping["name"])
|
||||
}
|
||||
if o.AdditionalSuffix != nil {
|
||||
mapping["name"] = fmt.Sprintf("%s%s", mapping["name"], *o.AdditionalSuffix)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
@@ -11,8 +10,6 @@ import (
|
||||
"github.com/metacubex/mihomo/component/resource"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
P "github.com/metacubex/mihomo/constant/provider"
|
||||
|
||||
"github.com/dlclark/regexp2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -28,33 +25,6 @@ type healthCheckSchema struct {
|
||||
ExpectedStatus string `provider:"expected-status,omitempty"`
|
||||
}
|
||||
|
||||
type OverrideProxyNameSchema struct {
|
||||
// matching expression for regex replacement
|
||||
Pattern *regexp2.Regexp `provider:"pattern"`
|
||||
// the new content after regex matching
|
||||
Target string `provider:"target"`
|
||||
}
|
||||
|
||||
var _ encoding.TextUnmarshaler = (*regexp2.Regexp)(nil) // ensure *regexp2.Regexp can decode direct by structure package
|
||||
|
||||
type OverrideSchema struct {
|
||||
TFO *bool `provider:"tfo,omitempty"`
|
||||
MPTcp *bool `provider:"mptcp,omitempty"`
|
||||
UDP *bool `provider:"udp,omitempty"`
|
||||
UDPOverTCP *bool `provider:"udp-over-tcp,omitempty"`
|
||||
Up *string `provider:"up,omitempty"`
|
||||
Down *string `provider:"down,omitempty"`
|
||||
DialerProxy *string `provider:"dialer-proxy,omitempty"`
|
||||
SkipCertVerify *bool `provider:"skip-cert-verify,omitempty"`
|
||||
Interface *string `provider:"interface-name,omitempty"`
|
||||
RoutingMark *int `provider:"routing-mark,omitempty"`
|
||||
IPVersion *string `provider:"ip-version,omitempty"`
|
||||
AdditionalPrefix *string `provider:"additional-prefix,omitempty"`
|
||||
AdditionalSuffix *string `provider:"additional-suffix,omitempty"`
|
||||
|
||||
ProxyName []OverrideProxyNameSchema `provider:"proxy-name,omitempty"`
|
||||
}
|
||||
|
||||
type proxyProviderSchema struct {
|
||||
Type string `provider:"type"`
|
||||
Path string `provider:"path,omitempty"`
|
||||
@@ -69,7 +39,7 @@ type proxyProviderSchema struct {
|
||||
Payload []map[string]any `provider:"payload,omitempty"`
|
||||
|
||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||
Override OverrideSchema `provider:"override,omitempty"`
|
||||
Override overrideSchema `provider:"override,omitempty"`
|
||||
Header map[string][]string `provider:"header,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -340,7 +339,7 @@ func (cp *CompatibleProvider) Close() error {
|
||||
return cp.compatibleProvider.Close()
|
||||
}
|
||||
|
||||
func NewProxiesParser(pdName string, filter string, excludeFilter string, excludeType string, dialerProxy string, override OverrideSchema) (resource.Parser[[]C.Proxy], error) {
|
||||
func NewProxiesParser(pdName string, filter string, excludeFilter string, excludeType string, dialerProxy string, override overrideSchema) (resource.Parser[[]C.Proxy], error) {
|
||||
var excludeTypeArray []string
|
||||
if excludeType != "" {
|
||||
excludeTypeArray = strings.Split(excludeType, "|")
|
||||
@@ -429,33 +428,9 @@ func NewProxiesParser(pdName string, filter string, excludeFilter string, exclud
|
||||
mapping["dialer-proxy"] = dialerProxy
|
||||
}
|
||||
|
||||
val := reflect.ValueOf(override)
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
field := val.Field(i)
|
||||
if field.IsNil() {
|
||||
continue
|
||||
}
|
||||
fieldName := strings.Split(val.Type().Field(i).Tag.Get("provider"), ",")[0]
|
||||
switch fieldName {
|
||||
case "additional-prefix":
|
||||
name := mapping["name"].(string)
|
||||
mapping["name"] = *field.Interface().(*string) + name
|
||||
case "additional-suffix":
|
||||
name := mapping["name"].(string)
|
||||
mapping["name"] = name + *field.Interface().(*string)
|
||||
case "proxy-name":
|
||||
// Iterate through all naming replacement rules and perform the replacements.
|
||||
for _, expr := range override.ProxyName {
|
||||
name := mapping["name"].(string)
|
||||
newName, err := expr.Pattern.Replace(name, expr.Target, 0, -1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("proxy name replace error: %w", err)
|
||||
}
|
||||
mapping["name"] = newName
|
||||
}
|
||||
default:
|
||||
mapping[fieldName] = field.Elem().Interface()
|
||||
}
|
||||
err := override.Apply(mapping)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("proxy %d override error: %w", idx, err)
|
||||
}
|
||||
|
||||
proxy, err := adapter.ParseProxy(mapping, adapter.WithProviderName(pdName))
|
||||
|
||||
@@ -201,6 +201,10 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||
trojan["client-fingerprint"] = fingerprint
|
||||
}
|
||||
|
||||
if pcs := query.Get("pcs"); pcs != "" {
|
||||
trojan["fingerprint"] = pcs
|
||||
}
|
||||
|
||||
proxies = append(proxies, trojan)
|
||||
|
||||
case "vless":
|
||||
|
||||
@@ -35,6 +35,9 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
||||
if alpn := query.Get("alpn"); alpn != "" {
|
||||
proxy["alpn"] = strings.Split(alpn, ",")
|
||||
}
|
||||
if pcs := query.Get("pcs"); pcs != "" {
|
||||
proxy["fingerprint"] = pcs
|
||||
}
|
||||
}
|
||||
if sni := query.Get("sni"); sni != "" {
|
||||
proxy["servername"] = sni
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package orderedmap
|
||||
|
||||
// copy and modified from https://github.com/wk8/go-ordered-map/tree/v2.1.8
|
||||
// which is licensed under Apache v2.
|
||||
//
|
||||
// mihomo modified:
|
||||
// 1. remove dependence of mailru/easyjson for MarshalJSON
|
||||
// 2. remove dependence of buger/jsonparser for UnmarshalJSON
|
||||
@@ -0,0 +1,139 @@
|
||||
package orderedmap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
var (
|
||||
_ json.Marshaler = &OrderedMap[int, any]{}
|
||||
_ json.Unmarshaler = &OrderedMap[int, any]{}
|
||||
)
|
||||
|
||||
// MarshalJSON implements the json.Marshaler interface.
|
||||
func (om *OrderedMap[K, V]) MarshalJSON() ([]byte, error) { //nolint:funlen
|
||||
if om == nil || om.list == nil {
|
||||
return []byte("null"), nil
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
buf.WriteByte('{')
|
||||
enc := json.NewEncoder(&buf)
|
||||
for pair, firstIteration := om.Oldest(), true; pair != nil; pair = pair.Next() {
|
||||
if firstIteration {
|
||||
firstIteration = false
|
||||
} else {
|
||||
buf.WriteByte(',')
|
||||
}
|
||||
|
||||
switch key := any(pair.Key).(type) {
|
||||
case string, encoding.TextMarshaler:
|
||||
if err := enc.Encode(pair.Key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
|
||||
buf.WriteByte('"')
|
||||
buf.WriteString(fmt.Sprint(key))
|
||||
buf.WriteByte('"')
|
||||
default:
|
||||
// this switch takes care of wrapper types around primitive types, such as
|
||||
// type myType string
|
||||
switch keyValue := reflect.ValueOf(key); keyValue.Type().Kind() {
|
||||
case reflect.String:
|
||||
if err := enc.Encode(pair.Key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
|
||||
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
buf.WriteByte('"')
|
||||
buf.WriteString(fmt.Sprint(key))
|
||||
buf.WriteByte('"')
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported key type: %T", key)
|
||||
}
|
||||
}
|
||||
|
||||
buf.WriteByte(':')
|
||||
if err := enc.Encode(pair.Value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
buf.WriteByte('}')
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements the json.Unmarshaler interface.
|
||||
func (om *OrderedMap[K, V]) UnmarshalJSON(data []byte) error {
|
||||
if om.list == nil {
|
||||
om.initialize(0)
|
||||
}
|
||||
|
||||
d := json.NewDecoder(bytes.NewReader(data))
|
||||
tok, err := d.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tok != json.Delim('{') {
|
||||
return errors.New("expect JSON object open with '{'")
|
||||
}
|
||||
|
||||
for d.More() {
|
||||
// key
|
||||
tok, err = d.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
keyStr, ok := tok.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("key must be a string, got %T\n", tok)
|
||||
}
|
||||
|
||||
var key K
|
||||
switch typedKey := any(&key).(type) {
|
||||
case *string:
|
||||
*typedKey = keyStr
|
||||
case encoding.TextUnmarshaler:
|
||||
err = typedKey.UnmarshalText([]byte(keyStr))
|
||||
case *int, *int8, *int16, *int32, *int64, *uint, *uint8, *uint16, *uint32, *uint64:
|
||||
err = json.Unmarshal([]byte(keyStr), typedKey)
|
||||
default:
|
||||
// this switch takes care of wrapper types around primitive types, such as
|
||||
// type myType string
|
||||
switch reflect.TypeOf(key).Kind() {
|
||||
case reflect.String:
|
||||
convertedKeyData := reflect.ValueOf(keyStr).Convert(reflect.TypeOf(key))
|
||||
reflect.ValueOf(&key).Elem().Set(convertedKeyData)
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
|
||||
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
err = json.Unmarshal([]byte(keyStr), &key)
|
||||
default:
|
||||
err = fmt.Errorf("unsupported key type: %T", key)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// value
|
||||
value, _ := om.Get(key)
|
||||
err = d.Decode(&value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
om.Set(key, value)
|
||||
}
|
||||
|
||||
tok, err = d.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tok != json.Delim('}') {
|
||||
return errors.New("expect JSON object close with '}'")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package orderedmap
|
||||
|
||||
// Adapted from https://github.com/dvyukov/go-fuzz-corpus/blob/c42c1b2/json/json.go
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func FuzzRoundTripJSON(f *testing.F) {
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
constructor func() any
|
||||
// should be a function that asserts that 2 objects of the type returned by constructor are equal
|
||||
equalityAssertion func(*testing.T, any, any) bool
|
||||
}{
|
||||
{
|
||||
name: "with a string -> string map",
|
||||
constructor: func() any { return &OrderedMap[string, string]{} },
|
||||
equalityAssertion: assertOrderedMapsEqual[string, string],
|
||||
},
|
||||
{
|
||||
name: "with a string -> int map",
|
||||
constructor: func() any { return &OrderedMap[string, int]{} },
|
||||
equalityAssertion: assertOrderedMapsEqual[string, int],
|
||||
},
|
||||
{
|
||||
name: "with a string -> any map",
|
||||
constructor: func() any { return &OrderedMap[string, any]{} },
|
||||
equalityAssertion: assertOrderedMapsEqual[string, any],
|
||||
},
|
||||
{
|
||||
name: "with a struct with map fields",
|
||||
constructor: func() any { return new(testFuzzStruct) },
|
||||
equalityAssertion: assertTestFuzzStructEqual,
|
||||
},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
v1 := testCase.constructor()
|
||||
if json.Unmarshal(data, v1) != nil {
|
||||
return
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(v1)
|
||||
require.NoError(t, err)
|
||||
|
||||
v2 := testCase.constructor()
|
||||
require.NoError(t, json.Unmarshal(jsonData, v2))
|
||||
|
||||
if !assert.True(t, testCase.equalityAssertion(t, v1, v2), "failed with input data %q", string(data)) {
|
||||
// look at that what the standard lib does with regular map, to help with debugging
|
||||
|
||||
var m1 map[string]any
|
||||
require.NoError(t, json.Unmarshal(data, &m1))
|
||||
|
||||
mapJsonData, err := json.Marshal(m1)
|
||||
require.NoError(t, err)
|
||||
|
||||
var m2 map[string]any
|
||||
require.NoError(t, json.Unmarshal(mapJsonData, &m2))
|
||||
|
||||
t.Logf("initial data = %s", string(data))
|
||||
t.Logf("unmarshalled map = %v", m1)
|
||||
t.Logf("re-marshalled from map = %s", string(mapJsonData))
|
||||
t.Logf("re-marshalled from test obj = %s", string(jsonData))
|
||||
t.Logf("re-unmarshalled map = %s", m2)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// only works for fairly basic maps, that's why it's just in this file
|
||||
func assertOrderedMapsEqual[K comparable, V any](t *testing.T, v1, v2 any) bool {
|
||||
om1, ok1 := v1.(*OrderedMap[K, V])
|
||||
om2, ok2 := v2.(*OrderedMap[K, V])
|
||||
|
||||
if !assert.True(t, ok1, "v1 not an orderedmap") ||
|
||||
!assert.True(t, ok2, "v2 not an orderedmap") {
|
||||
return false
|
||||
}
|
||||
|
||||
success := assert.Equal(t, om1.Len(), om2.Len(), "om1 and om2 have different lengths: %d vs %d", om1.Len(), om2.Len())
|
||||
|
||||
for i, pair1, pair2 := 0, om1.Oldest(), om2.Oldest(); pair1 != nil && pair2 != nil; i, pair1, pair2 = i+1, pair1.Next(), pair2.Next() {
|
||||
success = assert.Equal(t, pair1.Key, pair2.Key, "different keys at position %d: %v vs %v", i, pair1.Key, pair2.Key) && success
|
||||
success = assert.Equal(t, pair1.Value, pair2.Value, "different values at position %d: %v vs %v", i, pair1.Value, pair2.Value) && success
|
||||
}
|
||||
|
||||
return success
|
||||
}
|
||||
|
||||
type testFuzzStruct struct {
|
||||
M1 *OrderedMap[int, any]
|
||||
M2 *OrderedMap[int, string]
|
||||
M3 *OrderedMap[string, string]
|
||||
}
|
||||
|
||||
func assertTestFuzzStructEqual(t *testing.T, v1, v2 any) bool {
|
||||
s1, ok := v1.(*testFuzzStruct)
|
||||
s2, ok := v2.(*testFuzzStruct)
|
||||
|
||||
if !assert.True(t, ok, "v1 not an testFuzzStruct") ||
|
||||
!assert.True(t, ok, "v2 not an testFuzzStruct") {
|
||||
return false
|
||||
}
|
||||
|
||||
success := assertOrderedMapsEqual[int, any](t, s1.M1, s2.M1)
|
||||
success = assertOrderedMapsEqual[int, string](t, s1.M2, s2.M2) && success
|
||||
success = assertOrderedMapsEqual[string, string](t, s1.M3, s2.M3) && success
|
||||
|
||||
return success
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
package orderedmap
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// to test marshalling TextMarshalers and unmarshalling TextUnmarshalers
|
||||
type marshallable int
|
||||
|
||||
func (m marshallable) MarshalText() ([]byte, error) {
|
||||
return []byte(fmt.Sprintf("#%d#", m)), nil
|
||||
}
|
||||
|
||||
func (m *marshallable) UnmarshalText(text []byte) error {
|
||||
if len(text) < 3 {
|
||||
return errors.New("too short")
|
||||
}
|
||||
if text[0] != '#' || text[len(text)-1] != '#' {
|
||||
return errors.New("missing prefix or suffix")
|
||||
}
|
||||
|
||||
value, err := strconv.Atoi(string(text[1 : len(text)-1]))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*m = marshallable(value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestMarshalJSON(t *testing.T) {
|
||||
t.Run("int key", func(t *testing.T) {
|
||||
om := New[int, any]()
|
||||
om.Set(1, "bar")
|
||||
om.Set(7, "baz")
|
||||
om.Set(2, 28)
|
||||
om.Set(3, 100)
|
||||
om.Set(4, "baz")
|
||||
om.Set(5, "28")
|
||||
om.Set(6, "100")
|
||||
om.Set(8, "baz")
|
||||
om.Set(8, "baz")
|
||||
om.Set(9, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque auctor augue accumsan mi maximus, quis viverra massa pretium. Phasellus imperdiet sapien a interdum sollicitudin. Duis at commodo lectus, a lacinia sem.")
|
||||
|
||||
b, err := json.Marshal(om)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `{"1":"bar","7":"baz","2":28,"3":100,"4":"baz","5":"28","6":"100","8":"baz","9":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque auctor augue accumsan mi maximus, quis viverra massa pretium. Phasellus imperdiet sapien a interdum sollicitudin. Duis at commodo lectus, a lacinia sem."}`, string(b))
|
||||
})
|
||||
|
||||
t.Run("string key", func(t *testing.T) {
|
||||
om := New[string, any]()
|
||||
om.Set("test", "bar")
|
||||
om.Set("abc", true)
|
||||
|
||||
b, err := json.Marshal(om)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `{"test":"bar","abc":true}`, string(b))
|
||||
})
|
||||
|
||||
t.Run("typed string key", func(t *testing.T) {
|
||||
type myString string
|
||||
om := New[myString, any]()
|
||||
om.Set("test", "bar")
|
||||
om.Set("abc", true)
|
||||
|
||||
b, err := json.Marshal(om)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `{"test":"bar","abc":true}`, string(b))
|
||||
})
|
||||
|
||||
t.Run("typed int key", func(t *testing.T) {
|
||||
type myInt uint32
|
||||
om := New[myInt, any]()
|
||||
om.Set(1, "bar")
|
||||
om.Set(7, "baz")
|
||||
om.Set(2, 28)
|
||||
om.Set(3, 100)
|
||||
om.Set(4, "baz")
|
||||
|
||||
b, err := json.Marshal(om)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `{"1":"bar","7":"baz","2":28,"3":100,"4":"baz"}`, string(b))
|
||||
})
|
||||
|
||||
t.Run("TextMarshaller key", func(t *testing.T) {
|
||||
om := New[marshallable, any]()
|
||||
om.Set(marshallable(1), "bar")
|
||||
om.Set(marshallable(28), true)
|
||||
|
||||
b, err := json.Marshal(om)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `{"#1#":"bar","#28#":true}`, string(b))
|
||||
})
|
||||
|
||||
t.Run("empty map", func(t *testing.T) {
|
||||
om := New[string, any]()
|
||||
|
||||
b, err := json.Marshal(om)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `{}`, string(b))
|
||||
})
|
||||
}
|
||||
|
||||
func TestUnmarshallJSON(t *testing.T) {
|
||||
t.Run("int key", func(t *testing.T) {
|
||||
data := `{"1":"bar","7":"baz","2":28,"3":100,"4":"baz","5":"28","6":"100","8":"baz"}`
|
||||
|
||||
om := New[int, any]()
|
||||
require.NoError(t, json.Unmarshal([]byte(data), &om))
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]int{1, 7, 2, 3, 4, 5, 6, 8},
|
||||
[]any{"bar", "baz", float64(28), float64(100), "baz", "28", "100", "baz"})
|
||||
})
|
||||
|
||||
t.Run("string key", func(t *testing.T) {
|
||||
data := `{"test":"bar","abc":true}`
|
||||
|
||||
om := New[string, any]()
|
||||
require.NoError(t, json.Unmarshal([]byte(data), &om))
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]string{"test", "abc"},
|
||||
[]any{"bar", true})
|
||||
})
|
||||
|
||||
t.Run("typed string key", func(t *testing.T) {
|
||||
data := `{"test":"bar","abc":true}`
|
||||
|
||||
type myString string
|
||||
om := New[myString, any]()
|
||||
require.NoError(t, json.Unmarshal([]byte(data), &om))
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]myString{"test", "abc"},
|
||||
[]any{"bar", true})
|
||||
})
|
||||
|
||||
t.Run("typed int key", func(t *testing.T) {
|
||||
data := `{"1":"bar","7":"baz","2":28,"3":100,"4":"baz","5":"28","6":"100","8":"baz"}`
|
||||
|
||||
type myInt uint32
|
||||
om := New[myInt, any]()
|
||||
require.NoError(t, json.Unmarshal([]byte(data), &om))
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]myInt{1, 7, 2, 3, 4, 5, 6, 8},
|
||||
[]any{"bar", "baz", float64(28), float64(100), "baz", "28", "100", "baz"})
|
||||
})
|
||||
|
||||
t.Run("TextUnmarshaler key", func(t *testing.T) {
|
||||
data := `{"#1#":"bar","#28#":true}`
|
||||
|
||||
om := New[marshallable, any]()
|
||||
require.NoError(t, json.Unmarshal([]byte(data), &om))
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]marshallable{1, 28},
|
||||
[]any{"bar", true})
|
||||
})
|
||||
|
||||
t.Run("when fed with an input that's not an object", func(t *testing.T) {
|
||||
for _, data := range []string{"true", `["foo"]`, "42", `"foo"`} {
|
||||
om := New[int, any]()
|
||||
require.Error(t, json.Unmarshal([]byte(data), &om))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty map", func(t *testing.T) {
|
||||
data := `{}`
|
||||
|
||||
om := New[int, any]()
|
||||
require.NoError(t, json.Unmarshal([]byte(data), &om))
|
||||
|
||||
assertLenEqual(t, om, 0)
|
||||
})
|
||||
}
|
||||
|
||||
// const specialCharacters = "\\\\/\"\b\f\n\r\t\x00\uffff\ufffd世界\u007f\u00ff\U0010FFFF"
|
||||
const specialCharacters = "\uffff\ufffd世界\u007f\u00ff\U0010FFFF"
|
||||
|
||||
func TestJSONSpecialCharacters(t *testing.T) {
|
||||
baselineMap := map[string]any{specialCharacters: specialCharacters}
|
||||
baselineData, err := json.Marshal(baselineMap)
|
||||
require.NoError(t, err) // baseline proves this key is supported by official json library
|
||||
t.Logf("specialCharacters: %#v as []rune:%v", specialCharacters, []rune(specialCharacters))
|
||||
t.Logf("baseline json data: %s", baselineData)
|
||||
|
||||
t.Run("marshal special characters", func(t *testing.T) {
|
||||
om := New[string, any]()
|
||||
om.Set(specialCharacters, specialCharacters)
|
||||
b, err := json.Marshal(om)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, baselineData, b)
|
||||
|
||||
type myString string
|
||||
om2 := New[myString, myString]()
|
||||
om2.Set(specialCharacters, specialCharacters)
|
||||
b, err = json.Marshal(om2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, baselineData, b)
|
||||
})
|
||||
|
||||
t.Run("unmarshall special characters", func(t *testing.T) {
|
||||
om := New[string, any]()
|
||||
require.NoError(t, json.Unmarshal(baselineData, &om))
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]string{specialCharacters},
|
||||
[]any{specialCharacters})
|
||||
|
||||
type myString string
|
||||
om2 := New[myString, myString]()
|
||||
require.NoError(t, json.Unmarshal(baselineData, &om2))
|
||||
assertOrderedPairsEqual(t, om2,
|
||||
[]myString{specialCharacters},
|
||||
[]myString{specialCharacters})
|
||||
})
|
||||
}
|
||||
|
||||
// to test structs that have nested map fields
|
||||
type nestedMaps struct {
|
||||
X int `json:"x" yaml:"x"`
|
||||
M *OrderedMap[string, []*OrderedMap[int, *OrderedMap[string, any]]] `json:"m" yaml:"m"`
|
||||
}
|
||||
|
||||
func TestJSONRoundTrip(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
input string
|
||||
targetFactory func() any
|
||||
isPrettyPrinted bool
|
||||
}{
|
||||
{
|
||||
name: "",
|
||||
input: `{
|
||||
"x": 28,
|
||||
"m": {
|
||||
"foo": [
|
||||
{
|
||||
"12": {
|
||||
"i": 12,
|
||||
"b": true,
|
||||
"n": null,
|
||||
"m": {
|
||||
"a": "b",
|
||||
"c": 28
|
||||
}
|
||||
},
|
||||
"28": {
|
||||
"a": false,
|
||||
"b": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"3": {
|
||||
"c": null,
|
||||
"d": 87
|
||||
},
|
||||
"4": {
|
||||
"e": true
|
||||
},
|
||||
"5": {
|
||||
"f": 4,
|
||||
"g": 5,
|
||||
"h": 6
|
||||
}
|
||||
}
|
||||
],
|
||||
"bar": [
|
||||
{
|
||||
"5": {
|
||||
"foo": "bar"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}`,
|
||||
targetFactory: func() any { return &nestedMaps{} },
|
||||
isPrettyPrinted: true,
|
||||
},
|
||||
{
|
||||
name: "with UTF-8 special chars in key",
|
||||
input: `{"�":0}`,
|
||||
targetFactory: func() any { return &OrderedMap[string, int]{} },
|
||||
},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
target := testCase.targetFactory()
|
||||
|
||||
require.NoError(t, json.Unmarshal([]byte(testCase.input), target))
|
||||
|
||||
var (
|
||||
out []byte
|
||||
err error
|
||||
)
|
||||
if testCase.isPrettyPrinted {
|
||||
out, err = json.MarshalIndent(target, "", " ")
|
||||
} else {
|
||||
out, err = json.Marshal(target)
|
||||
}
|
||||
|
||||
if assert.NoError(t, err) {
|
||||
assert.Equal(t, strings.TrimSpace(testCase.input), string(out))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMarshalJSON(b *testing.B) {
|
||||
om := New[int, any]()
|
||||
om.Set(1, "bar")
|
||||
om.Set(7, "baz")
|
||||
om.Set(2, 28)
|
||||
om.Set(3, 100)
|
||||
om.Set(4, "baz")
|
||||
om.Set(5, "28")
|
||||
om.Set(6, "100")
|
||||
om.Set(8, "baz")
|
||||
om.Set(8, "baz")
|
||||
|
||||
b.ResetTimer()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = json.Marshal(om)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
// Package orderedmap implements an ordered map, i.e. a map that also keeps track of
|
||||
// the order in which keys were inserted.
|
||||
//
|
||||
// All operations are constant-time.
|
||||
//
|
||||
// Github repo: https://github.com/wk8/go-ordered-map
|
||||
package orderedmap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
list "github.com/bahlo/generic-list-go"
|
||||
)
|
||||
|
||||
type Pair[K comparable, V any] struct {
|
||||
Key K
|
||||
Value V
|
||||
|
||||
element *list.Element[*Pair[K, V]]
|
||||
}
|
||||
|
||||
type OrderedMap[K comparable, V any] struct {
|
||||
pairs map[K]*Pair[K, V]
|
||||
list *list.List[*Pair[K, V]]
|
||||
}
|
||||
|
||||
type initConfig[K comparable, V any] struct {
|
||||
capacity int
|
||||
initialData []Pair[K, V]
|
||||
}
|
||||
|
||||
type InitOption[K comparable, V any] func(config *initConfig[K, V])
|
||||
|
||||
// WithCapacity allows giving a capacity hint for the map, akin to the standard make(map[K]V, capacity).
|
||||
func WithCapacity[K comparable, V any](capacity int) InitOption[K, V] {
|
||||
return func(c *initConfig[K, V]) {
|
||||
c.capacity = capacity
|
||||
}
|
||||
}
|
||||
|
||||
// WithInitialData allows passing in initial data for the map.
|
||||
func WithInitialData[K comparable, V any](initialData ...Pair[K, V]) InitOption[K, V] {
|
||||
return func(c *initConfig[K, V]) {
|
||||
c.initialData = initialData
|
||||
if c.capacity < len(initialData) {
|
||||
c.capacity = len(initialData)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// New creates a new OrderedMap.
|
||||
// options can either be one or several InitOption[K, V], or a single integer,
|
||||
// which is then interpreted as a capacity hint, à la make(map[K]V, capacity).
|
||||
func New[K comparable, V any](options ...any) *OrderedMap[K, V] { //nolint:varnamelen
|
||||
orderedMap := &OrderedMap[K, V]{}
|
||||
|
||||
var config initConfig[K, V]
|
||||
for _, untypedOption := range options {
|
||||
switch option := untypedOption.(type) {
|
||||
case int:
|
||||
if len(options) != 1 {
|
||||
invalidOption()
|
||||
}
|
||||
config.capacity = option
|
||||
|
||||
case InitOption[K, V]:
|
||||
option(&config)
|
||||
|
||||
default:
|
||||
invalidOption()
|
||||
}
|
||||
}
|
||||
|
||||
orderedMap.initialize(config.capacity)
|
||||
orderedMap.AddPairs(config.initialData...)
|
||||
|
||||
return orderedMap
|
||||
}
|
||||
|
||||
const invalidOptionMessage = `when using orderedmap.New[K,V]() with options, either provide one or several InitOption[K, V]; or a single integer which is then interpreted as a capacity hint, à la make(map[K]V, capacity).` //nolint:lll
|
||||
|
||||
func invalidOption() { panic(invalidOptionMessage) }
|
||||
|
||||
func (om *OrderedMap[K, V]) initialize(capacity int) {
|
||||
om.pairs = make(map[K]*Pair[K, V], capacity)
|
||||
om.list = list.New[*Pair[K, V]]()
|
||||
}
|
||||
|
||||
// Get looks for the given key, and returns the value associated with it,
|
||||
// or V's nil value if not found. The boolean it returns says whether the key is present in the map.
|
||||
func (om *OrderedMap[K, V]) Get(key K) (val V, present bool) {
|
||||
if pair, present := om.pairs[key]; present {
|
||||
return pair.Value, true
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Load is an alias for Get, mostly to present an API similar to `sync.Map`'s.
|
||||
func (om *OrderedMap[K, V]) Load(key K) (V, bool) {
|
||||
return om.Get(key)
|
||||
}
|
||||
|
||||
// Value returns the value associated with the given key or the zero value.
|
||||
func (om *OrderedMap[K, V]) Value(key K) (val V) {
|
||||
if pair, present := om.pairs[key]; present {
|
||||
val = pair.Value
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GetPair looks for the given key, and returns the pair associated with it,
|
||||
// or nil if not found. The Pair struct can then be used to iterate over the ordered map
|
||||
// from that point, either forward or backward.
|
||||
func (om *OrderedMap[K, V]) GetPair(key K) *Pair[K, V] {
|
||||
return om.pairs[key]
|
||||
}
|
||||
|
||||
// Set sets the key-value pair, and returns what `Get` would have returned
|
||||
// on that key prior to the call to `Set`.
|
||||
func (om *OrderedMap[K, V]) Set(key K, value V) (val V, present bool) {
|
||||
if pair, present := om.pairs[key]; present {
|
||||
oldValue := pair.Value
|
||||
pair.Value = value
|
||||
return oldValue, true
|
||||
}
|
||||
|
||||
pair := &Pair[K, V]{
|
||||
Key: key,
|
||||
Value: value,
|
||||
}
|
||||
pair.element = om.list.PushBack(pair)
|
||||
om.pairs[key] = pair
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// AddPairs allows setting multiple pairs at a time. It's equivalent to calling
|
||||
// Set on each pair sequentially.
|
||||
func (om *OrderedMap[K, V]) AddPairs(pairs ...Pair[K, V]) {
|
||||
for _, pair := range pairs {
|
||||
om.Set(pair.Key, pair.Value)
|
||||
}
|
||||
}
|
||||
|
||||
// Store is an alias for Set, mostly to present an API similar to `sync.Map`'s.
|
||||
func (om *OrderedMap[K, V]) Store(key K, value V) (V, bool) {
|
||||
return om.Set(key, value)
|
||||
}
|
||||
|
||||
// Delete removes the key-value pair, and returns what `Get` would have returned
|
||||
// on that key prior to the call to `Delete`.
|
||||
func (om *OrderedMap[K, V]) Delete(key K) (val V, present bool) {
|
||||
if pair, present := om.pairs[key]; present {
|
||||
om.list.Remove(pair.element)
|
||||
delete(om.pairs, key)
|
||||
return pair.Value, true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Len returns the length of the ordered map.
|
||||
func (om *OrderedMap[K, V]) Len() int {
|
||||
if om == nil || om.pairs == nil {
|
||||
return 0
|
||||
}
|
||||
return len(om.pairs)
|
||||
}
|
||||
|
||||
// Oldest returns a pointer to the oldest pair. It's meant to be used to iterate on the ordered map's
|
||||
// pairs from the oldest to the newest, e.g.:
|
||||
// for pair := orderedMap.Oldest(); pair != nil; pair = pair.Next() { fmt.Printf("%v => %v\n", pair.Key, pair.Value) }
|
||||
func (om *OrderedMap[K, V]) Oldest() *Pair[K, V] {
|
||||
if om == nil || om.list == nil {
|
||||
return nil
|
||||
}
|
||||
return listElementToPair(om.list.Front())
|
||||
}
|
||||
|
||||
// Newest returns a pointer to the newest pair. It's meant to be used to iterate on the ordered map's
|
||||
// pairs from the newest to the oldest, e.g.:
|
||||
// for pair := orderedMap.Oldest(); pair != nil; pair = pair.Next() { fmt.Printf("%v => %v\n", pair.Key, pair.Value) }
|
||||
func (om *OrderedMap[K, V]) Newest() *Pair[K, V] {
|
||||
if om == nil || om.list == nil {
|
||||
return nil
|
||||
}
|
||||
return listElementToPair(om.list.Back())
|
||||
}
|
||||
|
||||
// Next returns a pointer to the next pair.
|
||||
func (p *Pair[K, V]) Next() *Pair[K, V] {
|
||||
return listElementToPair(p.element.Next())
|
||||
}
|
||||
|
||||
// Prev returns a pointer to the previous pair.
|
||||
func (p *Pair[K, V]) Prev() *Pair[K, V] {
|
||||
return listElementToPair(p.element.Prev())
|
||||
}
|
||||
|
||||
func listElementToPair[K comparable, V any](element *list.Element[*Pair[K, V]]) *Pair[K, V] {
|
||||
if element == nil {
|
||||
return nil
|
||||
}
|
||||
return element.Value
|
||||
}
|
||||
|
||||
// KeyNotFoundError may be returned by functions in this package when they're called with keys that are not present
|
||||
// in the map.
|
||||
type KeyNotFoundError[K comparable] struct {
|
||||
MissingKey K
|
||||
}
|
||||
|
||||
func (e *KeyNotFoundError[K]) Error() string {
|
||||
return fmt.Sprintf("missing key: %v", e.MissingKey)
|
||||
}
|
||||
|
||||
// MoveAfter moves the value associated with key to its new position after the one associated with markKey.
|
||||
// Returns an error iff key or markKey are not present in the map. If an error is returned,
|
||||
// it will be a KeyNotFoundError.
|
||||
func (om *OrderedMap[K, V]) MoveAfter(key, markKey K) error {
|
||||
elements, err := om.getElements(key, markKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
om.list.MoveAfter(elements[0], elements[1])
|
||||
return nil
|
||||
}
|
||||
|
||||
// MoveBefore moves the value associated with key to its new position before the one associated with markKey.
|
||||
// Returns an error iff key or markKey are not present in the map. If an error is returned,
|
||||
// it will be a KeyNotFoundError.
|
||||
func (om *OrderedMap[K, V]) MoveBefore(key, markKey K) error {
|
||||
elements, err := om.getElements(key, markKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
om.list.MoveBefore(elements[0], elements[1])
|
||||
return nil
|
||||
}
|
||||
|
||||
func (om *OrderedMap[K, V]) getElements(keys ...K) ([]*list.Element[*Pair[K, V]], error) {
|
||||
elements := make([]*list.Element[*Pair[K, V]], len(keys))
|
||||
for i, k := range keys {
|
||||
pair, present := om.pairs[k]
|
||||
if !present {
|
||||
return nil, &KeyNotFoundError[K]{k}
|
||||
}
|
||||
elements[i] = pair.element
|
||||
}
|
||||
return elements, nil
|
||||
}
|
||||
|
||||
// MoveToBack moves the value associated with key to the back of the ordered map,
|
||||
// i.e. makes it the newest pair in the map.
|
||||
// Returns an error iff key is not present in the map. If an error is returned,
|
||||
// it will be a KeyNotFoundError.
|
||||
func (om *OrderedMap[K, V]) MoveToBack(key K) error {
|
||||
_, err := om.GetAndMoveToBack(key)
|
||||
return err
|
||||
}
|
||||
|
||||
// MoveToFront moves the value associated with key to the front of the ordered map,
|
||||
// i.e. makes it the oldest pair in the map.
|
||||
// Returns an error iff key is not present in the map. If an error is returned,
|
||||
// it will be a KeyNotFoundError.
|
||||
func (om *OrderedMap[K, V]) MoveToFront(key K) error {
|
||||
_, err := om.GetAndMoveToFront(key)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetAndMoveToBack combines Get and MoveToBack in the same call. If an error is returned,
|
||||
// it will be a KeyNotFoundError.
|
||||
func (om *OrderedMap[K, V]) GetAndMoveToBack(key K) (val V, err error) {
|
||||
if pair, present := om.pairs[key]; present {
|
||||
val = pair.Value
|
||||
om.list.MoveToBack(pair.element)
|
||||
} else {
|
||||
err = &KeyNotFoundError[K]{key}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetAndMoveToFront combines Get and MoveToFront in the same call. If an error is returned,
|
||||
// it will be a KeyNotFoundError.
|
||||
func (om *OrderedMap[K, V]) GetAndMoveToFront(key K) (val V, err error) {
|
||||
if pair, present := om.pairs[key]; present {
|
||||
val = pair.Value
|
||||
om.list.MoveToFront(pair.element)
|
||||
} else {
|
||||
err = &KeyNotFoundError[K]{key}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
package orderedmap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestBasicFeatures(t *testing.T) {
|
||||
n := 100
|
||||
om := New[int, int]()
|
||||
|
||||
// set(i, 2 * i)
|
||||
for i := 0; i < n; i++ {
|
||||
assertLenEqual(t, om, i)
|
||||
oldValue, present := om.Set(i, 2*i)
|
||||
assertLenEqual(t, om, i+1)
|
||||
|
||||
assert.Equal(t, 0, oldValue)
|
||||
assert.False(t, present)
|
||||
}
|
||||
|
||||
// get what we just set
|
||||
for i := 0; i < n; i++ {
|
||||
value, present := om.Get(i)
|
||||
|
||||
assert.Equal(t, 2*i, value)
|
||||
assert.Equal(t, value, om.Value(i))
|
||||
assert.True(t, present)
|
||||
}
|
||||
|
||||
// get pairs of what we just set
|
||||
for i := 0; i < n; i++ {
|
||||
pair := om.GetPair(i)
|
||||
|
||||
assert.NotNil(t, pair)
|
||||
assert.Equal(t, 2*i, pair.Value)
|
||||
}
|
||||
|
||||
// forward iteration
|
||||
i := 0
|
||||
for pair := om.Oldest(); pair != nil; pair = pair.Next() {
|
||||
assert.Equal(t, i, pair.Key)
|
||||
assert.Equal(t, 2*i, pair.Value)
|
||||
i++
|
||||
}
|
||||
// backward iteration
|
||||
i = n - 1
|
||||
for pair := om.Newest(); pair != nil; pair = pair.Prev() {
|
||||
assert.Equal(t, i, pair.Key)
|
||||
assert.Equal(t, 2*i, pair.Value)
|
||||
i--
|
||||
}
|
||||
|
||||
// forward iteration starting from known key
|
||||
i = 42
|
||||
for pair := om.GetPair(i); pair != nil; pair = pair.Next() {
|
||||
assert.Equal(t, i, pair.Key)
|
||||
assert.Equal(t, 2*i, pair.Value)
|
||||
i++
|
||||
}
|
||||
|
||||
// double values for pairs with even keys
|
||||
for j := 0; j < n/2; j++ {
|
||||
i = 2 * j
|
||||
oldValue, present := om.Set(i, 4*i)
|
||||
|
||||
assert.Equal(t, 2*i, oldValue)
|
||||
assert.True(t, present)
|
||||
}
|
||||
// and delete pairs with odd keys
|
||||
for j := 0; j < n/2; j++ {
|
||||
i = 2*j + 1
|
||||
assertLenEqual(t, om, n-j)
|
||||
value, present := om.Delete(i)
|
||||
assertLenEqual(t, om, n-j-1)
|
||||
|
||||
assert.Equal(t, 2*i, value)
|
||||
assert.True(t, present)
|
||||
|
||||
// deleting again shouldn't change anything
|
||||
value, present = om.Delete(i)
|
||||
assertLenEqual(t, om, n-j-1)
|
||||
assert.Equal(t, 0, value)
|
||||
assert.False(t, present)
|
||||
}
|
||||
|
||||
// get the whole range
|
||||
for j := 0; j < n/2; j++ {
|
||||
i = 2 * j
|
||||
value, present := om.Get(i)
|
||||
assert.Equal(t, 4*i, value)
|
||||
assert.Equal(t, value, om.Value(i))
|
||||
assert.True(t, present)
|
||||
|
||||
i = 2*j + 1
|
||||
value, present = om.Get(i)
|
||||
assert.Equal(t, 0, value)
|
||||
assert.Equal(t, value, om.Value(i))
|
||||
assert.False(t, present)
|
||||
}
|
||||
|
||||
// check iterations again
|
||||
i = 0
|
||||
for pair := om.Oldest(); pair != nil; pair = pair.Next() {
|
||||
assert.Equal(t, i, pair.Key)
|
||||
assert.Equal(t, 4*i, pair.Value)
|
||||
i += 2
|
||||
}
|
||||
i = 2 * ((n - 1) / 2)
|
||||
for pair := om.Newest(); pair != nil; pair = pair.Prev() {
|
||||
assert.Equal(t, i, pair.Key)
|
||||
assert.Equal(t, 4*i, pair.Value)
|
||||
i -= 2
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdatingDoesntChangePairsOrder(t *testing.T) {
|
||||
om := New[string, any]()
|
||||
om.Set("foo", "bar")
|
||||
om.Set("wk", 28)
|
||||
om.Set("po", 100)
|
||||
om.Set("bar", "baz")
|
||||
|
||||
oldValue, present := om.Set("po", 102)
|
||||
assert.Equal(t, 100, oldValue)
|
||||
assert.True(t, present)
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]string{"foo", "wk", "po", "bar"},
|
||||
[]any{"bar", 28, 102, "baz"})
|
||||
}
|
||||
|
||||
func TestDeletingAndReinsertingChangesPairsOrder(t *testing.T) {
|
||||
om := New[string, any]()
|
||||
om.Set("foo", "bar")
|
||||
om.Set("wk", 28)
|
||||
om.Set("po", 100)
|
||||
om.Set("bar", "baz")
|
||||
|
||||
// delete a pair
|
||||
oldValue, present := om.Delete("po")
|
||||
assert.Equal(t, 100, oldValue)
|
||||
assert.True(t, present)
|
||||
|
||||
// re-insert the same pair
|
||||
oldValue, present = om.Set("po", 100)
|
||||
assert.Nil(t, oldValue)
|
||||
assert.False(t, present)
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]string{"foo", "wk", "bar", "po"},
|
||||
[]any{"bar", 28, "baz", 100})
|
||||
}
|
||||
|
||||
func TestEmptyMapOperations(t *testing.T) {
|
||||
om := New[string, any]()
|
||||
|
||||
oldValue, present := om.Get("foo")
|
||||
assert.Nil(t, oldValue)
|
||||
assert.Nil(t, om.Value("foo"))
|
||||
assert.False(t, present)
|
||||
|
||||
oldValue, present = om.Delete("bar")
|
||||
assert.Nil(t, oldValue)
|
||||
assert.False(t, present)
|
||||
|
||||
assertLenEqual(t, om, 0)
|
||||
|
||||
assert.Nil(t, om.Oldest())
|
||||
assert.Nil(t, om.Newest())
|
||||
}
|
||||
|
||||
type dummyTestStruct struct {
|
||||
value string
|
||||
}
|
||||
|
||||
func TestPackUnpackStructs(t *testing.T) {
|
||||
om := New[string, dummyTestStruct]()
|
||||
om.Set("foo", dummyTestStruct{"foo!"})
|
||||
om.Set("bar", dummyTestStruct{"bar!"})
|
||||
|
||||
value, present := om.Get("foo")
|
||||
assert.True(t, present)
|
||||
assert.Equal(t, value, om.Value("foo"))
|
||||
if assert.NotNil(t, value) {
|
||||
assert.Equal(t, "foo!", value.value)
|
||||
}
|
||||
|
||||
value, present = om.Set("bar", dummyTestStruct{"baz!"})
|
||||
assert.True(t, present)
|
||||
if assert.NotNil(t, value) {
|
||||
assert.Equal(t, "bar!", value.value)
|
||||
}
|
||||
|
||||
value, present = om.Get("bar")
|
||||
assert.Equal(t, value, om.Value("bar"))
|
||||
assert.True(t, present)
|
||||
if assert.NotNil(t, value) {
|
||||
assert.Equal(t, "baz!", value.value)
|
||||
}
|
||||
}
|
||||
|
||||
// shamelessly stolen from https://github.com/python/cpython/blob/e19a91e45fd54a56e39c2d12e6aaf4757030507f/Lib/test/test_ordered_dict.py#L55-L61
|
||||
func TestShuffle(t *testing.T) {
|
||||
ranLen := 100
|
||||
|
||||
for _, n := range []int{0, 10, 20, 100, 1000, 10000} {
|
||||
t.Run(fmt.Sprintf("shuffle test with %d items", n), func(t *testing.T) {
|
||||
om := New[string, string]()
|
||||
|
||||
keys := make([]string, n)
|
||||
values := make([]string, n)
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
// we prefix with the number to ensure that we don't get any duplicates
|
||||
keys[i] = fmt.Sprintf("%d_%s", i, randomHexString(t, ranLen))
|
||||
values[i] = randomHexString(t, ranLen)
|
||||
|
||||
value, present := om.Set(keys[i], values[i])
|
||||
assert.Equal(t, "", value)
|
||||
assert.False(t, present)
|
||||
}
|
||||
|
||||
assertOrderedPairsEqual(t, om, keys, values)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMove(t *testing.T) {
|
||||
om := New[int, any]()
|
||||
om.Set(1, "bar")
|
||||
om.Set(2, 28)
|
||||
om.Set(3, 100)
|
||||
om.Set(4, "baz")
|
||||
om.Set(5, "28")
|
||||
om.Set(6, "100")
|
||||
om.Set(7, "baz")
|
||||
om.Set(8, "baz")
|
||||
|
||||
err := om.MoveAfter(2, 3)
|
||||
assert.Nil(t, err)
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]int{1, 3, 2, 4, 5, 6, 7, 8},
|
||||
[]any{"bar", 100, 28, "baz", "28", "100", "baz", "baz"})
|
||||
|
||||
err = om.MoveBefore(6, 4)
|
||||
assert.Nil(t, err)
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]int{1, 3, 2, 6, 4, 5, 7, 8},
|
||||
[]any{"bar", 100, 28, "100", "baz", "28", "baz", "baz"})
|
||||
|
||||
err = om.MoveToBack(3)
|
||||
assert.Nil(t, err)
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]int{1, 2, 6, 4, 5, 7, 8, 3},
|
||||
[]any{"bar", 28, "100", "baz", "28", "baz", "baz", 100})
|
||||
|
||||
err = om.MoveToFront(5)
|
||||
assert.Nil(t, err)
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]int{5, 1, 2, 6, 4, 7, 8, 3},
|
||||
[]any{"28", "bar", 28, "100", "baz", "baz", "baz", 100})
|
||||
|
||||
err = om.MoveToFront(100)
|
||||
assert.Equal(t, &KeyNotFoundError[int]{100}, err)
|
||||
}
|
||||
|
||||
func TestGetAndMove(t *testing.T) {
|
||||
om := New[int, any]()
|
||||
om.Set(1, "bar")
|
||||
om.Set(2, 28)
|
||||
om.Set(3, 100)
|
||||
om.Set(4, "baz")
|
||||
om.Set(5, "28")
|
||||
om.Set(6, "100")
|
||||
om.Set(7, "baz")
|
||||
om.Set(8, "baz")
|
||||
|
||||
value, err := om.GetAndMoveToBack(3)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 100, value)
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]int{1, 2, 4, 5, 6, 7, 8, 3},
|
||||
[]any{"bar", 28, "baz", "28", "100", "baz", "baz", 100})
|
||||
|
||||
value, err = om.GetAndMoveToFront(5)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, "28", value)
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]int{5, 1, 2, 4, 6, 7, 8, 3},
|
||||
[]any{"28", "bar", 28, "baz", "100", "baz", "baz", 100})
|
||||
|
||||
value, err = om.GetAndMoveToBack(100)
|
||||
assert.Equal(t, &KeyNotFoundError[int]{100}, err)
|
||||
}
|
||||
|
||||
func TestAddPairs(t *testing.T) {
|
||||
om := New[int, any]()
|
||||
om.AddPairs(
|
||||
Pair[int, any]{
|
||||
Key: 28,
|
||||
Value: "foo",
|
||||
},
|
||||
Pair[int, any]{
|
||||
Key: 12,
|
||||
Value: "bar",
|
||||
},
|
||||
Pair[int, any]{
|
||||
Key: 28,
|
||||
Value: "baz",
|
||||
},
|
||||
)
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]int{28, 12},
|
||||
[]any{"baz", "bar"})
|
||||
}
|
||||
|
||||
// sadly, we can't test the "actual" capacity here, see https://github.com/golang/go/issues/52157
|
||||
func TestNewWithCapacity(t *testing.T) {
|
||||
zero := New[int, string](0)
|
||||
assert.Empty(t, zero.Len())
|
||||
|
||||
assert.PanicsWithValue(t, invalidOptionMessage, func() {
|
||||
_ = New[int, string](1, 2)
|
||||
})
|
||||
assert.PanicsWithValue(t, invalidOptionMessage, func() {
|
||||
_ = New[int, string](1, 2, 3)
|
||||
})
|
||||
|
||||
om := New[int, string](-1)
|
||||
om.Set(1337, "quarante-deux")
|
||||
assert.Equal(t, 1, om.Len())
|
||||
}
|
||||
|
||||
func TestNewWithOptions(t *testing.T) {
|
||||
t.Run("wih capacity", func(t *testing.T) {
|
||||
om := New[string, any](WithCapacity[string, any](98))
|
||||
assert.Equal(t, 0, om.Len())
|
||||
})
|
||||
|
||||
t.Run("with initial data", func(t *testing.T) {
|
||||
om := New[string, int](WithInitialData(
|
||||
Pair[string, int]{
|
||||
Key: "a",
|
||||
Value: 1,
|
||||
},
|
||||
Pair[string, int]{
|
||||
Key: "b",
|
||||
Value: 2,
|
||||
},
|
||||
Pair[string, int]{
|
||||
Key: "c",
|
||||
Value: 3,
|
||||
},
|
||||
))
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]string{"a", "b", "c"},
|
||||
[]int{1, 2, 3})
|
||||
})
|
||||
|
||||
t.Run("with an invalid option type", func(t *testing.T) {
|
||||
assert.PanicsWithValue(t, invalidOptionMessage, func() {
|
||||
_ = New[int, string]("foo")
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestNilMap(t *testing.T) {
|
||||
// we want certain behaviors of a nil ordered map to be the same as they are for standard nil maps
|
||||
var om *OrderedMap[int, any]
|
||||
|
||||
t.Run("len", func(t *testing.T) {
|
||||
assert.Equal(t, 0, om.Len())
|
||||
})
|
||||
|
||||
t.Run("iterating - akin to range", func(t *testing.T) {
|
||||
assert.Nil(t, om.Oldest())
|
||||
assert.Nil(t, om.Newest())
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package orderedmap
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// assertOrderedPairsEqual asserts that the map contains the given keys and values
|
||||
// from oldest to newest.
|
||||
func assertOrderedPairsEqual[K comparable, V any](
|
||||
t *testing.T, orderedMap *OrderedMap[K, V], expectedKeys []K, expectedValues []V,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
assertOrderedPairsEqualFromNewest(t, orderedMap, expectedKeys, expectedValues)
|
||||
assertOrderedPairsEqualFromOldest(t, orderedMap, expectedKeys, expectedValues)
|
||||
}
|
||||
|
||||
func assertOrderedPairsEqualFromNewest[K comparable, V any](
|
||||
t *testing.T, orderedMap *OrderedMap[K, V], expectedKeys []K, expectedValues []V,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
if assert.Equal(t, len(expectedKeys), len(expectedValues)) && assert.Equal(t, len(expectedKeys), orderedMap.Len()) {
|
||||
i := orderedMap.Len() - 1
|
||||
for pair := orderedMap.Newest(); pair != nil; pair = pair.Prev() {
|
||||
assert.Equal(t, expectedKeys[i], pair.Key, "from newest index=%d on key", i)
|
||||
assert.Equal(t, expectedValues[i], pair.Value, "from newest index=%d on value", i)
|
||||
i--
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertOrderedPairsEqualFromOldest[K comparable, V any](
|
||||
t *testing.T, orderedMap *OrderedMap[K, V], expectedKeys []K, expectedValues []V,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
if assert.Equal(t, len(expectedKeys), len(expectedValues)) && assert.Equal(t, len(expectedKeys), orderedMap.Len()) {
|
||||
i := 0
|
||||
for pair := orderedMap.Oldest(); pair != nil; pair = pair.Next() {
|
||||
assert.Equal(t, expectedKeys[i], pair.Key, "from oldest index=%d on key", i)
|
||||
assert.Equal(t, expectedValues[i], pair.Value, "from oldest index=%d on value", i)
|
||||
i++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertLenEqual[K comparable, V any](t *testing.T, orderedMap *OrderedMap[K, V], expectedLen int) {
|
||||
t.Helper()
|
||||
|
||||
assert.Equal(t, expectedLen, orderedMap.Len())
|
||||
|
||||
// also check the list length, for good measure
|
||||
assert.Equal(t, expectedLen, orderedMap.list.Len())
|
||||
}
|
||||
|
||||
func randomHexString(t *testing.T, length int) string {
|
||||
t.Helper()
|
||||
|
||||
b := length / 2 //nolint:gomnd
|
||||
randBytes := make([]byte, b)
|
||||
|
||||
if n, err := rand.Read(randBytes); err != nil || n != b {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("only got %v random bytes, expected %v", n, b)
|
||||
}
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return hex.EncodeToString(randBytes)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package orderedmap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
var (
|
||||
_ yaml.Marshaler = &OrderedMap[int, any]{}
|
||||
_ yaml.Unmarshaler = &OrderedMap[int, any]{}
|
||||
)
|
||||
|
||||
// MarshalYAML implements the yaml.Marshaler interface.
|
||||
func (om *OrderedMap[K, V]) MarshalYAML() (interface{}, error) {
|
||||
if om == nil {
|
||||
return []byte("null"), nil
|
||||
}
|
||||
|
||||
node := yaml.Node{
|
||||
Kind: yaml.MappingNode,
|
||||
}
|
||||
|
||||
for pair := om.Oldest(); pair != nil; pair = pair.Next() {
|
||||
key, value := pair.Key, pair.Value
|
||||
|
||||
keyNode := &yaml.Node{}
|
||||
|
||||
// serialize key to yaml, then deserialize it back into the node
|
||||
// this is a hack to get the correct tag for the key
|
||||
if err := keyNode.Encode(key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
valueNode := &yaml.Node{}
|
||||
if err := valueNode.Encode(value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
node.Content = append(node.Content, keyNode, valueNode)
|
||||
}
|
||||
|
||||
return &node, nil
|
||||
}
|
||||
|
||||
// UnmarshalYAML implements the yaml.Unmarshaler interface.
|
||||
func (om *OrderedMap[K, V]) UnmarshalYAML(value *yaml.Node) error {
|
||||
if value.Kind != yaml.MappingNode {
|
||||
return fmt.Errorf("pipeline must contain YAML mapping, has %v", value.Kind)
|
||||
}
|
||||
|
||||
if om.list == nil {
|
||||
om.initialize(0)
|
||||
}
|
||||
|
||||
for index := 0; index < len(value.Content); index += 2 {
|
||||
var key K
|
||||
var val V
|
||||
|
||||
if err := value.Content[index].Decode(&key); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := value.Content[index+1].Decode(&val); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
om.Set(key, val)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package orderedmap
|
||||
|
||||
// Adapted from https://github.com/dvyukov/go-fuzz-corpus/blob/c42c1b2/json/json.go
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func FuzzRoundTripYAML(f *testing.F) {
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
constructor func() any
|
||||
// should be a function that asserts that 2 objects of the type returned by constructor are equal
|
||||
equalityAssertion func(*testing.T, any, any) bool
|
||||
}{
|
||||
{
|
||||
name: "with a string -> string map",
|
||||
constructor: func() any { return &OrderedMap[string, string]{} },
|
||||
equalityAssertion: assertOrderedMapsEqual[string, string],
|
||||
},
|
||||
{
|
||||
name: "with a string -> int map",
|
||||
constructor: func() any { return &OrderedMap[string, int]{} },
|
||||
equalityAssertion: assertOrderedMapsEqual[string, int],
|
||||
},
|
||||
{
|
||||
name: "with a string -> any map",
|
||||
constructor: func() any { return &OrderedMap[string, any]{} },
|
||||
equalityAssertion: assertOrderedMapsEqual[string, any],
|
||||
},
|
||||
{
|
||||
name: "with a struct with map fields",
|
||||
constructor: func() any { return new(testFuzzStruct) },
|
||||
equalityAssertion: assertTestFuzzStructEqual,
|
||||
},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
v1 := testCase.constructor()
|
||||
if yaml.Unmarshal(data, v1) != nil {
|
||||
return
|
||||
}
|
||||
t.Log(data)
|
||||
t.Log(v1)
|
||||
|
||||
yamlData, err := yaml.Marshal(v1)
|
||||
require.NoError(t, err)
|
||||
t.Log(string(yamlData))
|
||||
|
||||
v2 := testCase.constructor()
|
||||
err = yaml.Unmarshal(yamlData, v2)
|
||||
if err != nil {
|
||||
t.Log(string(yamlData))
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !assert.True(t, testCase.equalityAssertion(t, v1, v2), "failed with input data %q", string(data)) {
|
||||
// look at that what the standard lib does with regular map, to help with debugging
|
||||
|
||||
var m1 map[string]any
|
||||
require.NoError(t, yaml.Unmarshal(data, &m1))
|
||||
|
||||
mapJsonData, err := yaml.Marshal(m1)
|
||||
require.NoError(t, err)
|
||||
|
||||
var m2 map[string]any
|
||||
require.NoError(t, yaml.Unmarshal(mapJsonData, &m2))
|
||||
|
||||
t.Logf("initial data = %s", string(data))
|
||||
t.Logf("unmarshalled map = %v", m1)
|
||||
t.Logf("re-marshalled from map = %s", string(mapJsonData))
|
||||
t.Logf("re-marshalled from test obj = %s", string(yamlData))
|
||||
t.Logf("re-unmarshalled map = %s", m2)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
package orderedmap
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func TestMarshalYAML(t *testing.T) {
|
||||
t.Run("int key", func(t *testing.T) {
|
||||
om := New[int, any]()
|
||||
om.Set(1, "bar")
|
||||
om.Set(7, "baz")
|
||||
om.Set(2, 28)
|
||||
om.Set(3, 100)
|
||||
om.Set(4, "baz")
|
||||
om.Set(5, "28")
|
||||
om.Set(6, "100")
|
||||
om.Set(8, "baz")
|
||||
om.Set(8, "baz")
|
||||
om.Set(9, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque auctor augue accumsan mi maximus, quis viverra massa pretium. Phasellus imperdiet sapien a interdum sollicitudin. Duis at commodo lectus, a lacinia sem.")
|
||||
|
||||
b, err := yaml.Marshal(om)
|
||||
|
||||
expected := `1: bar
|
||||
7: baz
|
||||
2: 28
|
||||
3: 100
|
||||
4: baz
|
||||
5: "28"
|
||||
6: "100"
|
||||
8: baz
|
||||
9: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque auctor augue accumsan mi maximus, quis viverra massa pretium. Phasellus imperdiet sapien a interdum sollicitudin. Duis at commodo lectus, a lacinia sem.
|
||||
`
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, string(b))
|
||||
})
|
||||
|
||||
t.Run("string key", func(t *testing.T) {
|
||||
om := New[string, any]()
|
||||
om.Set("test", "bar")
|
||||
om.Set("abc", true)
|
||||
|
||||
b, err := yaml.Marshal(om)
|
||||
assert.NoError(t, err)
|
||||
expected := `test: bar
|
||||
abc: true
|
||||
`
|
||||
assert.Equal(t, expected, string(b))
|
||||
})
|
||||
|
||||
t.Run("typed string key", func(t *testing.T) {
|
||||
type myString string
|
||||
om := New[myString, any]()
|
||||
om.Set("test", "bar")
|
||||
om.Set("abc", true)
|
||||
|
||||
b, err := yaml.Marshal(om)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `test: bar
|
||||
abc: true
|
||||
`, string(b))
|
||||
})
|
||||
|
||||
t.Run("typed int key", func(t *testing.T) {
|
||||
type myInt uint32
|
||||
om := New[myInt, any]()
|
||||
om.Set(1, "bar")
|
||||
om.Set(7, "baz")
|
||||
om.Set(2, 28)
|
||||
om.Set(3, 100)
|
||||
om.Set(4, "baz")
|
||||
|
||||
b, err := yaml.Marshal(om)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `1: bar
|
||||
7: baz
|
||||
2: 28
|
||||
3: 100
|
||||
4: baz
|
||||
`, string(b))
|
||||
})
|
||||
|
||||
t.Run("TextMarshaller key", func(t *testing.T) {
|
||||
om := New[marshallable, any]()
|
||||
om.Set(marshallable(1), "bar")
|
||||
om.Set(marshallable(28), true)
|
||||
|
||||
b, err := yaml.Marshal(om)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `'#1#': bar
|
||||
'#28#': true
|
||||
`, string(b))
|
||||
})
|
||||
|
||||
t.Run("empty map with 0 elements", func(t *testing.T) {
|
||||
om := New[string, any]()
|
||||
|
||||
b, err := yaml.Marshal(om)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "{}\n", string(b))
|
||||
})
|
||||
|
||||
t.Run("empty map with no elements (null)", func(t *testing.T) {
|
||||
om := &OrderedMap[string, string]{}
|
||||
|
||||
b, err := yaml.Marshal(om)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "{}\n", string(b))
|
||||
})
|
||||
}
|
||||
|
||||
func TestUnmarshallYAML(t *testing.T) {
|
||||
t.Run("int key", func(t *testing.T) {
|
||||
data := `
|
||||
1: bar
|
||||
7: baz
|
||||
2: 28
|
||||
3: 100
|
||||
4: baz
|
||||
5: "28"
|
||||
6: "100"
|
||||
8: baz
|
||||
`
|
||||
om := New[int, any]()
|
||||
require.NoError(t, yaml.Unmarshal([]byte(data), &om))
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]int{1, 7, 2, 3, 4, 5, 6, 8},
|
||||
[]any{"bar", "baz", 28, 100, "baz", "28", "100", "baz"})
|
||||
|
||||
// serialize back to yaml to make sure things are equal
|
||||
})
|
||||
|
||||
t.Run("string key", func(t *testing.T) {
|
||||
data := `{"test":"bar","abc":true}`
|
||||
|
||||
om := New[string, any]()
|
||||
require.NoError(t, yaml.Unmarshal([]byte(data), &om))
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]string{"test", "abc"},
|
||||
[]any{"bar", true})
|
||||
})
|
||||
|
||||
t.Run("typed string key", func(t *testing.T) {
|
||||
data := `{"test":"bar","abc":true}`
|
||||
|
||||
type myString string
|
||||
om := New[myString, any]()
|
||||
require.NoError(t, yaml.Unmarshal([]byte(data), &om))
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]myString{"test", "abc"},
|
||||
[]any{"bar", true})
|
||||
})
|
||||
|
||||
t.Run("typed int key", func(t *testing.T) {
|
||||
data := `
|
||||
1: bar
|
||||
7: baz
|
||||
2: 28
|
||||
3: 100
|
||||
4: baz
|
||||
5: "28"
|
||||
6: "100"
|
||||
8: baz
|
||||
`
|
||||
type myInt uint32
|
||||
om := New[myInt, any]()
|
||||
require.NoError(t, yaml.Unmarshal([]byte(data), &om))
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]myInt{1, 7, 2, 3, 4, 5, 6, 8},
|
||||
[]any{"bar", "baz", 28, 100, "baz", "28", "100", "baz"})
|
||||
})
|
||||
|
||||
t.Run("TextUnmarshaler key", func(t *testing.T) {
|
||||
data := `{"#1#":"bar","#28#":true}`
|
||||
|
||||
om := New[marshallable, any]()
|
||||
require.NoError(t, yaml.Unmarshal([]byte(data), &om))
|
||||
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]marshallable{1, 28},
|
||||
[]any{"bar", true})
|
||||
})
|
||||
|
||||
t.Run("when fed with an input that's not an object", func(t *testing.T) {
|
||||
for _, data := range []string{"true", `["foo"]`, "42", `"foo"`} {
|
||||
om := New[int, any]()
|
||||
require.Error(t, yaml.Unmarshal([]byte(data), &om))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty map", func(t *testing.T) {
|
||||
data := `{}`
|
||||
|
||||
om := New[int, any]()
|
||||
require.NoError(t, yaml.Unmarshal([]byte(data), &om))
|
||||
|
||||
assertLenEqual(t, om, 0)
|
||||
})
|
||||
}
|
||||
|
||||
func TestYAMLSpecialCharacters(t *testing.T) {
|
||||
baselineMap := map[string]any{specialCharacters: specialCharacters}
|
||||
baselineData, err := yaml.Marshal(baselineMap)
|
||||
require.NoError(t, err) // baseline proves this key is supported by official yaml library
|
||||
t.Logf("specialCharacters: %#v as []rune:%v", specialCharacters, []rune(specialCharacters))
|
||||
t.Logf("baseline yaml data: %s", baselineData)
|
||||
|
||||
t.Run("marshal special characters", func(t *testing.T) {
|
||||
om := New[string, any]()
|
||||
om.Set(specialCharacters, specialCharacters)
|
||||
b, err := yaml.Marshal(om)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, baselineData, b)
|
||||
|
||||
type myString string
|
||||
om2 := New[myString, myString]()
|
||||
om2.Set(specialCharacters, specialCharacters)
|
||||
b, err = yaml.Marshal(om2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, baselineData, b)
|
||||
})
|
||||
|
||||
t.Run("unmarshall special characters", func(t *testing.T) {
|
||||
om := New[string, any]()
|
||||
require.NoError(t, yaml.Unmarshal(baselineData, &om))
|
||||
assertOrderedPairsEqual(t, om,
|
||||
[]string{specialCharacters},
|
||||
[]any{specialCharacters})
|
||||
|
||||
type myString string
|
||||
om2 := New[myString, myString]()
|
||||
require.NoError(t, yaml.Unmarshal(baselineData, &om2))
|
||||
assertOrderedPairsEqual(t, om2,
|
||||
[]myString{specialCharacters},
|
||||
[]myString{specialCharacters})
|
||||
})
|
||||
}
|
||||
|
||||
func TestYAMLRoundTrip(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
input string
|
||||
targetFactory func() any
|
||||
}{
|
||||
{
|
||||
name: "empty map",
|
||||
input: "{}\n",
|
||||
targetFactory: func() any {
|
||||
return &OrderedMap[string, any]{}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "",
|
||||
input: `x: 28
|
||||
m:
|
||||
bar:
|
||||
- 5:
|
||||
foo: bar
|
||||
foo:
|
||||
- 12:
|
||||
b: true
|
||||
i: 12
|
||||
m:
|
||||
a: b
|
||||
c: 28
|
||||
"n": null
|
||||
28:
|
||||
a: false
|
||||
b:
|
||||
- 1
|
||||
- 2
|
||||
- 3
|
||||
- 3:
|
||||
c: null
|
||||
d: 87
|
||||
4:
|
||||
e: true
|
||||
5:
|
||||
f: 4
|
||||
g: 5
|
||||
h: 6
|
||||
`,
|
||||
targetFactory: func() any { return &nestedMaps{} },
|
||||
},
|
||||
{
|
||||
name: "with UTF-8 special chars in key",
|
||||
input: "�: 0\n",
|
||||
targetFactory: func() any { return &OrderedMap[string, int]{} },
|
||||
},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
target := testCase.targetFactory()
|
||||
|
||||
require.NoError(t, yaml.Unmarshal([]byte(testCase.input), target))
|
||||
|
||||
var (
|
||||
out []byte
|
||||
err error
|
||||
)
|
||||
|
||||
out, err = yaml.Marshal(target)
|
||||
|
||||
if assert.NoError(t, err) {
|
||||
assert.Equal(t, testCase.input, string(out))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMarshalYAML(b *testing.B) {
|
||||
om := New[int, any]()
|
||||
om.Set(1, "bar")
|
||||
om.Set(7, "baz")
|
||||
om.Set(2, 28)
|
||||
om.Set(3, 100)
|
||||
om.Set(4, "baz")
|
||||
om.Set(5, "28")
|
||||
om.Set(6, "100")
|
||||
om.Set(8, "baz")
|
||||
om.Set(8, "baz")
|
||||
|
||||
b.ResetTimer()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = yaml.Marshal(om)
|
||||
}
|
||||
}
|
||||
@@ -98,10 +98,16 @@ func GetTLSConfig(opt Option) (tlsConfig *tls.Config, err error) {
|
||||
}
|
||||
|
||||
if len(opt.Fingerprint) > 0 {
|
||||
tlsConfig.VerifyPeerCertificate, err = NewFingerprintVerifier(opt.Fingerprint, tlsConfig.Time)
|
||||
verifier, err := NewFingerprintVerifier(opt.Fingerprint, tlsConfig.Time)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConfig.VerifyConnection = func(state tls.ConnectionState) error {
|
||||
// [ConnectionState.ServerName] can return the actual ServerName needed for verification,
|
||||
// avoiding inconsistencies caused by [tlsConfig.ServerName] being modified after the [NewFingerprintVerifier] call.
|
||||
// https://github.com/golang/go/issues/36736#issuecomment-587925536
|
||||
return verifier(state.PeerCertificates, state.ServerName)
|
||||
}
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
// NewFingerprintVerifier returns a function that verifies whether a certificate's SHA-256 fingerprint matches the given one.
|
||||
func NewFingerprintVerifier(fingerprint string, time func() time.Time) (func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error, error) {
|
||||
func NewFingerprintVerifier(fingerprint string, time func() time.Time) (func(certs []*x509.Certificate, serverName string) error, error) {
|
||||
switch fingerprint {
|
||||
case "chrome", "firefox", "safari", "ios", "android", "edge", "360", "qq", "random", "randomized": // WTF???
|
||||
return nil, fmt.Errorf("`fingerprint` is used for TLS certificate pinning. If you need to specify the browser fingerprint, use `client-fingerprint`")
|
||||
@@ -26,37 +26,24 @@ func NewFingerprintVerifier(fingerprint string, time func() time.Time) (func(raw
|
||||
return nil, fmt.Errorf("fingerprint string length error,need sha256 fingerprint")
|
||||
}
|
||||
|
||||
return func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||
return func(certs []*x509.Certificate, serverName string) error {
|
||||
// ssl pining
|
||||
for i, rawCert := range rawCerts {
|
||||
hash := sha256.Sum256(rawCert)
|
||||
for i, cert := range certs {
|
||||
hash := sha256.Sum256(cert.Raw)
|
||||
if bytes.Equal(fpByte, hash[:]) {
|
||||
if i > 0 {
|
||||
|
||||
// When the fingerprint matches a non-leaf certificate,
|
||||
// the certificate chain validity is verified using the certificate as the trusted root certificate.
|
||||
//
|
||||
// Currently, we do not verify that the SNI matches the certificate's DNS name,
|
||||
// but we do verify the validity of the child certificate,
|
||||
// including the issuance time and whether the child certificate was issued by the parent certificate.
|
||||
|
||||
certs := make([]*x509.Certificate, i+1) // stop at i
|
||||
for j := range certs {
|
||||
cert, err := x509.ParseCertificate(rawCerts[j])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
certs[j] = cert
|
||||
}
|
||||
opts := x509.VerifyOptions{
|
||||
Roots: x509.NewCertPool(),
|
||||
Intermediates: x509.NewCertPool(),
|
||||
DNSName: serverName,
|
||||
}
|
||||
if time != nil {
|
||||
opts.CurrentTime = time()
|
||||
}
|
||||
opts.Roots.AddCert(certs[i])
|
||||
for _, cert := range certs[1:] {
|
||||
for _, cert := range certs[1 : i+1] { // stop at i
|
||||
opts.Intermediates.AddCert(cert)
|
||||
}
|
||||
_, err := certs[0].Verify(opts)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package ca
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -10,90 +11,203 @@ import (
|
||||
)
|
||||
|
||||
func TestFingerprintVerifierLeaf(t *testing.T) {
|
||||
leafFingerprint := CalculateFingerprint(leafPEM.Bytes)
|
||||
verifier, err := NewFingerprintVerifier(leafFingerprint, func() time.Time {
|
||||
return time.Unix(1677615892, 0)
|
||||
})
|
||||
leafFingerprint := CalculateFingerprint(leafCert.Raw)
|
||||
verifier, err := NewFingerprintVerifier(leafFingerprint, certTime)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = verifier([][]byte{leafPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, rootCert}, "")
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([][]byte{leafPEM.Bytes, smimeIntermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, rootCert}, leafServerName)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([][]byte{leafPEM.Bytes, intermediatePEM.Bytes, smimeRootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, rootCert}, wrongLeafServerName)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([][]byte{leafWithInvalidHashPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, smimeIntermediateCert, rootCert}, "")
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafCert, smimeIntermediateCert, rootCert}, leafServerName)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafCert, smimeIntermediateCert, rootCert}, wrongLeafServerName)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, smimeRootCert}, "")
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, smimeRootCert}, leafServerName)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, smimeRootCert}, wrongLeafServerName)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafWithInvalidHashCert, intermediateCert, rootCert}, "")
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([][]byte{smimeLeafPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafWithInvalidHashCert, intermediateCert, rootCert}, leafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([][]byte{smimeLeafPEM.Bytes, intermediatePEM.Bytes, smimeRootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafWithInvalidHashCert, intermediateCert, rootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, rootCert}, "")
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, rootCert}, leafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, rootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, smimeRootCert}, "")
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, smimeRootCert}, leafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, smimeRootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestFingerprintVerifierIntermediate(t *testing.T) {
|
||||
intermediateFingerprint := CalculateFingerprint(intermediatePEM.Bytes)
|
||||
verifier, err := NewFingerprintVerifier(intermediateFingerprint, func() time.Time {
|
||||
return time.Unix(1677615892, 0)
|
||||
})
|
||||
intermediateFingerprint := CalculateFingerprint(intermediateCert.Raw)
|
||||
verifier, err := NewFingerprintVerifier(intermediateFingerprint, certTime)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = verifier([][]byte{leafPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, rootCert}, "")
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([][]byte{leafPEM.Bytes, smimeIntermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([][]byte{leafPEM.Bytes, intermediatePEM.Bytes, smimeRootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, rootCert}, leafServerName)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([][]byte{leafWithInvalidHashPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, rootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([][]byte{smimeLeafPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, smimeIntermediateCert, rootCert}, "")
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([][]byte{smimeLeafPEM.Bytes, intermediatePEM.Bytes, smimeRootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, smimeIntermediateCert, rootCert}, leafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafCert, smimeIntermediateCert, rootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, smimeRootCert}, "")
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, smimeRootCert}, leafServerName)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, smimeRootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafWithInvalidHashCert, intermediateCert, rootCert}, "")
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafWithInvalidHashCert, intermediateCert, rootCert}, leafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafWithInvalidHashCert, intermediateCert, rootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, rootCert}, "")
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, rootCert}, leafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, rootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, smimeRootCert}, "")
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, smimeRootCert}, leafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, smimeRootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestFingerprintVerifierRoot(t *testing.T) {
|
||||
rootFingerprint := CalculateFingerprint(rootPEM.Bytes)
|
||||
verifier, err := NewFingerprintVerifier(rootFingerprint, func() time.Time {
|
||||
return time.Unix(1677615892, 0)
|
||||
})
|
||||
rootFingerprint := CalculateFingerprint(rootCert.Raw)
|
||||
verifier, err := NewFingerprintVerifier(rootFingerprint, certTime)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = verifier([][]byte{leafPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, rootCert}, "")
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([][]byte{leafPEM.Bytes, smimeIntermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, rootCert}, leafServerName)
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, rootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([][]byte{leafPEM.Bytes, intermediatePEM.Bytes, smimeRootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, smimeIntermediateCert, rootCert}, "")
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([][]byte{leafWithInvalidHashPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, smimeIntermediateCert, rootCert}, leafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([][]byte{smimeLeafPEM.Bytes, intermediatePEM.Bytes, rootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, smimeIntermediateCert, rootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([][]byte{smimeLeafPEM.Bytes, intermediatePEM.Bytes, smimeRootPEM.Bytes}, nil)
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, smimeRootCert}, "")
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, smimeRootCert}, leafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafCert, intermediateCert, smimeRootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafWithInvalidHashCert, intermediateCert, rootCert}, "")
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafWithInvalidHashCert, intermediateCert, rootCert}, leafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{leafWithInvalidHashCert, intermediateCert, rootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, rootCert}, "")
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, rootCert}, leafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, rootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, smimeRootCert}, "")
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, smimeRootCert}, leafServerName)
|
||||
assert.Error(t, err)
|
||||
|
||||
err = verifier([]*x509.Certificate{smimeLeafCert, intermediateCert, smimeRootCert}, wrongLeafServerName)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
var rootPEM, _ = pem.Decode([]byte(gtsRoot))
|
||||
var rootCert, _ = x509.ParseCertificate(rootPEM.Bytes)
|
||||
var intermediatePEM, _ = pem.Decode([]byte(gtsIntermediate))
|
||||
var intermediateCert, _ = x509.ParseCertificate(intermediatePEM.Bytes)
|
||||
var leafPEM, _ = pem.Decode([]byte(googleLeaf))
|
||||
var leafCert, _ = x509.ParseCertificate(leafPEM.Bytes)
|
||||
var leafWithInvalidHashPEM, _ = pem.Decode([]byte(googleLeafWithInvalidHash))
|
||||
var leafWithInvalidHashCert, _ = x509.ParseCertificate(leafWithInvalidHashPEM.Bytes)
|
||||
var smimeRootPEM, _ = pem.Decode([]byte(smimeRoot))
|
||||
var smimeRootCert, _ = x509.ParseCertificate(smimeRootPEM.Bytes)
|
||||
var smimeIntermediatePEM, _ = pem.Decode([]byte(smimeIntermediate))
|
||||
var smimeIntermediateCert, _ = x509.ParseCertificate(smimeIntermediatePEM.Bytes)
|
||||
var smimeLeafPEM, _ = pem.Decode([]byte(smimeLeaf))
|
||||
var smimeLeafCert, _ = x509.ParseCertificate(smimeLeafPEM.Bytes)
|
||||
var certTime = func() time.Time { return time.Unix(1677615892, 0) }
|
||||
|
||||
const leafServerName = "www.google.com"
|
||||
const wrongLeafServerName = "www.google.com.cn"
|
||||
|
||||
const gtsIntermediate = `-----BEGIN CERTIFICATE-----
|
||||
MIIFljCCA36gAwIBAgINAgO8U1lrNMcY9QFQZjANBgkqhkiG9w0BAQsFADBHMQsw
|
||||
|
||||
+27
-47
@@ -12,6 +12,7 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/atomic"
|
||||
"github.com/metacubex/mihomo/component/keepalive"
|
||||
"github.com/metacubex/mihomo/component/mptcp"
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
@@ -20,18 +21,22 @@ import (
|
||||
const (
|
||||
DefaultTCPTimeout = 5 * time.Second
|
||||
DefaultUDPTimeout = DefaultTCPTimeout
|
||||
)
|
||||
|
||||
type dialFunc func(ctx context.Context, network string, ips []netip.Addr, port string, opt option) (net.Conn, error)
|
||||
dualStackFallbackTimeout = 300 * time.Millisecond
|
||||
)
|
||||
|
||||
var (
|
||||
dialMux sync.Mutex
|
||||
actualSingleStackDialContext = serialSingleStackDialContext
|
||||
actualDualStackDialContext = serialDualStackDialContext
|
||||
tcpConcurrent = false
|
||||
fallbackTimeout = 300 * time.Millisecond
|
||||
tcpConcurrent = atomic.NewBool(false)
|
||||
)
|
||||
|
||||
func SetTcpConcurrent(concurrent bool) {
|
||||
tcpConcurrent.Store(concurrent)
|
||||
}
|
||||
|
||||
func GetTcpConcurrent() bool {
|
||||
return tcpConcurrent.Load()
|
||||
}
|
||||
|
||||
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
||||
opt := applyOptions(options...)
|
||||
|
||||
@@ -50,11 +55,22 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tcpConcurrent := GetTcpConcurrent()
|
||||
|
||||
switch network {
|
||||
case "tcp4", "tcp6", "udp4", "udp6":
|
||||
return actualSingleStackDialContext(ctx, network, ips, port, opt)
|
||||
if tcpConcurrent {
|
||||
return parallelDialContext(ctx, network, ips, port, opt)
|
||||
}
|
||||
return serialDialContext(ctx, network, ips, port, opt)
|
||||
case "tcp", "udp":
|
||||
return actualDualStackDialContext(ctx, network, ips, port, opt)
|
||||
if tcpConcurrent {
|
||||
if opt.prefer != 4 && opt.prefer != 6 {
|
||||
return parallelDialContext(ctx, network, ips, port, opt)
|
||||
}
|
||||
return dualStackDialContext(ctx, parallelDialContext, network, ips, port, opt)
|
||||
}
|
||||
return dualStackDialContext(ctx, serialDialContext, network, ips, port, opt)
|
||||
default:
|
||||
return nil, ErrorInvalidedNetworkStack
|
||||
}
|
||||
@@ -104,25 +120,6 @@ func ListenPacket(ctx context.Context, network, address string, rAddrPort netip.
|
||||
return lc.ListenPacket(ctx, network, address)
|
||||
}
|
||||
|
||||
func SetTcpConcurrent(concurrent bool) {
|
||||
dialMux.Lock()
|
||||
defer dialMux.Unlock()
|
||||
tcpConcurrent = concurrent
|
||||
if concurrent {
|
||||
actualSingleStackDialContext = concurrentSingleStackDialContext
|
||||
actualDualStackDialContext = concurrentDualStackDialContext
|
||||
} else {
|
||||
actualSingleStackDialContext = serialSingleStackDialContext
|
||||
actualDualStackDialContext = serialDualStackDialContext
|
||||
}
|
||||
}
|
||||
|
||||
func GetTcpConcurrent() bool {
|
||||
dialMux.Lock()
|
||||
defer dialMux.Unlock()
|
||||
return tcpConcurrent
|
||||
}
|
||||
|
||||
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt option) (net.Conn, error) {
|
||||
var address string
|
||||
destination, port = resolver.LookupIP4P(destination, port)
|
||||
@@ -205,24 +202,7 @@ func ICMPControl(destination netip.Addr) func(network, address string, conn sysc
|
||||
}
|
||||
}
|
||||
|
||||
func serialSingleStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt option) (net.Conn, error) {
|
||||
return serialDialContext(ctx, network, ips, port, opt)
|
||||
}
|
||||
|
||||
func serialDualStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt option) (net.Conn, error) {
|
||||
return dualStackDialContext(ctx, serialDialContext, network, ips, port, opt)
|
||||
}
|
||||
|
||||
func concurrentSingleStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt option) (net.Conn, error) {
|
||||
return parallelDialContext(ctx, network, ips, port, opt)
|
||||
}
|
||||
|
||||
func concurrentDualStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt option) (net.Conn, error) {
|
||||
if opt.prefer != 4 && opt.prefer != 6 {
|
||||
return parallelDialContext(ctx, network, ips, port, opt)
|
||||
}
|
||||
return dualStackDialContext(ctx, parallelDialContext, network, ips, port, opt)
|
||||
}
|
||||
type dialFunc func(ctx context.Context, network string, ips []netip.Addr, port string, opt option) (net.Conn, error)
|
||||
|
||||
func dualStackDialContext(ctx context.Context, dialFn dialFunc, network string, ips []netip.Addr, port string, opt option) (net.Conn, error) {
|
||||
ipv4s, ipv6s := resolver.SortationAddr(ips)
|
||||
@@ -231,7 +211,7 @@ func dualStackDialContext(ctx context.Context, dialFn dialFunc, network string,
|
||||
}
|
||||
|
||||
preferIPVersion := opt.prefer
|
||||
fallbackTicker := time.NewTicker(fallbackTimeout)
|
||||
fallbackTicker := time.NewTicker(dualStackFallbackTimeout)
|
||||
defer fallbackTicker.Stop()
|
||||
|
||||
results := make(chan dialResult)
|
||||
|
||||
@@ -58,6 +58,11 @@ func Main(args []string) {
|
||||
fmt.Println("Seed: " + seedBase64)
|
||||
fmt.Println("Client: " + clientBase64)
|
||||
fmt.Println("Hash32: " + hash32Base64)
|
||||
fmt.Println("-----------------------")
|
||||
fmt.Println(" Lazy-Config ")
|
||||
fmt.Println("-----------------------")
|
||||
fmt.Printf("[Server] decryption: \"mlkem768x25519plus.native.600s.%s\"\n", seedBase64)
|
||||
fmt.Printf("[Client] encryption: \"mlkem768x25519plus.native.0rtt.%s\"\n", clientBase64)
|
||||
case "vless-x25519":
|
||||
var privateKey string
|
||||
if len(args) > 1 {
|
||||
@@ -70,6 +75,11 @@ func Main(args []string) {
|
||||
fmt.Println("PrivateKey: " + privateKeyBase64)
|
||||
fmt.Println("Password: " + passwordBase64)
|
||||
fmt.Println("Hash32: " + hash32Base64)
|
||||
fmt.Println("-----------------------")
|
||||
fmt.Println(" Lazy-Config ")
|
||||
fmt.Println("-----------------------")
|
||||
fmt.Printf("[Server] decryption: \"mlkem768x25519plus.native.600s.%s\"\n", privateKeyBase64)
|
||||
fmt.Printf("[Client] encryption: \"mlkem768x25519plus.native.0rtt.%s\"\n", passwordBase64)
|
||||
case "sudoku-keypair":
|
||||
privateKey, publicKey, err := sudoku.GenKeyPair()
|
||||
if err != nil {
|
||||
|
||||
+18
-21
@@ -8,7 +8,6 @@ import (
|
||||
"strings"
|
||||
_ "unsafe"
|
||||
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"github.com/metacubex/mihomo/component/resolver/hosts"
|
||||
"github.com/metacubex/mihomo/component/trie"
|
||||
"github.com/metacubex/randv2"
|
||||
@@ -66,37 +65,35 @@ type HostValue struct {
|
||||
Domain string
|
||||
}
|
||||
|
||||
func NewHostValue(value any) (HostValue, error) {
|
||||
func NewHostValue(value []string) (HostValue, error) {
|
||||
isDomain := true
|
||||
ips := make([]netip.Addr, 0)
|
||||
ips := make([]netip.Addr, 0, len(value))
|
||||
domain := ""
|
||||
if valueArr, err := utils.ToStringSlice(value); err != nil {
|
||||
return HostValue{}, err
|
||||
} else {
|
||||
if len(valueArr) > 1 {
|
||||
switch len(value) {
|
||||
case 0:
|
||||
return HostValue{}, errors.New("value is empty")
|
||||
case 1:
|
||||
host := value[0]
|
||||
if ip, err := netip.ParseAddr(host); err == nil {
|
||||
ips = append(ips, ip.Unmap())
|
||||
isDomain = false
|
||||
for _, str := range valueArr {
|
||||
if ip, err := netip.ParseAddr(str); err == nil {
|
||||
ips = append(ips, ip.Unmap())
|
||||
} else {
|
||||
return HostValue{}, err
|
||||
}
|
||||
}
|
||||
} else if len(valueArr) == 1 {
|
||||
host := valueArr[0]
|
||||
if ip, err := netip.ParseAddr(host); err == nil {
|
||||
} else {
|
||||
domain = host
|
||||
}
|
||||
default: // > 1
|
||||
isDomain = false
|
||||
for _, str := range value {
|
||||
if ip, err := netip.ParseAddr(str); err == nil {
|
||||
ips = append(ips, ip.Unmap())
|
||||
isDomain = false
|
||||
} else {
|
||||
domain = host
|
||||
return HostValue{}, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if isDomain {
|
||||
return NewHostValueByDomain(domain)
|
||||
} else {
|
||||
return NewHostValueByIPs(ips)
|
||||
}
|
||||
return NewHostValueByIPs(ips)
|
||||
}
|
||||
|
||||
func NewHostValueByIPs(ips []netip.Addr) (HostValue, error) {
|
||||
|
||||
@@ -127,10 +127,45 @@ func UCertificate(it tls.Certificate) utls.Certificate {
|
||||
|
||||
type EncryptedClientHelloKey = utls.EncryptedClientHelloKey
|
||||
|
||||
func UEncryptedClientHelloKey(it tls.EncryptedClientHelloKey) utls.EncryptedClientHelloKey {
|
||||
return utls.EncryptedClientHelloKey{
|
||||
Config: it.Config,
|
||||
PrivateKey: it.PrivateKey,
|
||||
SendAsRetry: it.SendAsRetry,
|
||||
}
|
||||
}
|
||||
|
||||
type Config = utls.Config
|
||||
|
||||
var tlsCertificateRequestInfoCtxOffset = utils.MustOK(reflect.TypeOf((*tls.CertificateRequestInfo)(nil)).Elem().FieldByName("ctx")).Offset
|
||||
var tlsClientHelloInfoCtxOffset = utils.MustOK(reflect.TypeOf((*tls.ClientHelloInfo)(nil)).Elem().FieldByName("ctx")).Offset
|
||||
var tlsConnectionStateEkmOffset = utils.MustOK(reflect.TypeOf((*tls.ConnectionState)(nil)).Elem().FieldByName("ekm")).Offset
|
||||
var utlsConnectionStateEkmOffset = utils.MustOK(reflect.TypeOf((*utls.ConnectionState)(nil)).Elem().FieldByName("ekm")).Offset
|
||||
|
||||
func tlsConnectionState(state utls.ConnectionState) (tlsState tls.ConnectionState) {
|
||||
tlsState = tls.ConnectionState{
|
||||
Version: state.Version,
|
||||
HandshakeComplete: state.HandshakeComplete,
|
||||
DidResume: state.DidResume,
|
||||
CipherSuite: state.CipherSuite,
|
||||
//CurveID: state.CurveID,
|
||||
NegotiatedProtocol: state.NegotiatedProtocol,
|
||||
NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
|
||||
ServerName: state.ServerName,
|
||||
PeerCertificates: state.PeerCertificates,
|
||||
VerifiedChains: state.VerifiedChains,
|
||||
SignedCertificateTimestamps: state.SignedCertificateTimestamps,
|
||||
OCSPResponse: state.OCSPResponse,
|
||||
TLSUnique: state.TLSUnique,
|
||||
ECHAccepted: state.ECHAccepted,
|
||||
//HelloRetryRequest: state.HelloRetryRequest,
|
||||
}
|
||||
// The layout of map, chan, and func types is equivalent to *T.
|
||||
// state.ekm is a func(label string, context []byte, length int) ([]byte, error)
|
||||
*(*unsafe.Pointer)(unsafe.Add(unsafe.Pointer(&tlsState), tlsConnectionStateEkmOffset)) =
|
||||
*(*unsafe.Pointer)(unsafe.Add(unsafe.Pointer(&state), utlsConnectionStateEkmOffset))
|
||||
return
|
||||
}
|
||||
|
||||
func UConfig(config *tls.Config) *utls.Config {
|
||||
cfg := &utls.Config{
|
||||
@@ -152,6 +187,7 @@ func UConfig(config *tls.Config) *utls.Config {
|
||||
}),
|
||||
SessionTicketsDisabled: config.SessionTicketsDisabled,
|
||||
Renegotiation: utls.RenegotiationSupport(config.Renegotiation),
|
||||
KeyLogWriter: config.KeyLogWriter,
|
||||
}
|
||||
if config.GetClientCertificate != nil {
|
||||
cfg.GetClientCertificate = func(info *utls.CertificateRequestInfo) (*utls.Certificate, error) {
|
||||
@@ -198,6 +234,19 @@ func UConfig(config *tls.Config) *utls.Config {
|
||||
return &uCert, err
|
||||
}
|
||||
}
|
||||
if config.VerifyConnection != nil {
|
||||
cfg.VerifyConnection = func(state utls.ConnectionState) error {
|
||||
return config.VerifyConnection(tlsConnectionState(state))
|
||||
}
|
||||
}
|
||||
config.EncryptedClientHelloConfigList = cfg.EncryptedClientHelloConfigList
|
||||
if config.EncryptedClientHelloRejectionVerify != nil {
|
||||
cfg.EncryptedClientHelloRejectionVerify = func(state utls.ConnectionState) error {
|
||||
return config.EncryptedClientHelloRejectionVerify(tlsConnectionState(state))
|
||||
}
|
||||
}
|
||||
//cfg.GetEncryptedClientHelloKeys =
|
||||
cfg.EncryptedClientHelloKeys = utils.Map(config.EncryptedClientHelloKeys, UEncryptedClientHelloKey)
|
||||
return cfg
|
||||
}
|
||||
|
||||
|
||||
+89
-71
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/metacubex/mihomo/adapter/outbound"
|
||||
"github.com/metacubex/mihomo/adapter/outboundgroup"
|
||||
"github.com/metacubex/mihomo/adapter/provider"
|
||||
"github.com/metacubex/mihomo/common/orderedmap"
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"github.com/metacubex/mihomo/common/yaml"
|
||||
"github.com/metacubex/mihomo/component/auth"
|
||||
@@ -38,7 +39,6 @@ import (
|
||||
RW "github.com/metacubex/mihomo/rules/wrapper"
|
||||
T "github.com/metacubex/mihomo/tunnel"
|
||||
|
||||
orderedmap "github.com/wk8/go-ordered-map/v2"
|
||||
"golang.org/x/exp/slices"
|
||||
)
|
||||
|
||||
@@ -166,6 +166,7 @@ type DNS struct {
|
||||
FakeIPTTL int
|
||||
NameServerPolicy []dns.Policy
|
||||
ProxyServerNameserver []dns.NameServer
|
||||
ProxyServerPolicy []dns.Policy
|
||||
DirectNameServer []dns.NameServer
|
||||
DirectFollowPolicy bool
|
||||
}
|
||||
@@ -236,6 +237,7 @@ type RawDNS struct {
|
||||
CacheMaxSize int `yaml:"cache-max-size" json:"cache-max-size"`
|
||||
NameServerPolicy *orderedmap.OrderedMap[string, any] `yaml:"nameserver-policy" json:"nameserver-policy"`
|
||||
ProxyServerNameserver []string `yaml:"proxy-server-nameserver" json:"proxy-server-nameserver"`
|
||||
ProxyServerNameserverPolicy *orderedmap.OrderedMap[string, any] `yaml:"proxy-server-nameserver-policy" json:"proxy-server-nameserver-policy"`
|
||||
DirectNameServer []string `yaml:"direct-nameserver" json:"direct-nameserver"`
|
||||
DirectNameServerFollowPolicy bool `yaml:"direct-nameserver-follow-policy" json:"direct-nameserver-follow-policy"`
|
||||
}
|
||||
@@ -274,35 +276,36 @@ type RawTun struct {
|
||||
GSO bool `yaml:"gso" json:"gso,omitempty"`
|
||||
GSOMaxSize uint32 `yaml:"gso-max-size" json:"gso-max-size,omitempty"`
|
||||
//Inet4Address []netip.Prefix `yaml:"inet4-address" json:"inet4-address,omitempty"`
|
||||
Inet6Address []netip.Prefix `yaml:"inet6-address" json:"inet6-address,omitempty"`
|
||||
IPRoute2TableIndex int `yaml:"iproute2-table-index" json:"iproute2-table-index,omitempty"`
|
||||
IPRoute2RuleIndex int `yaml:"iproute2-rule-index" json:"iproute2-rule-index,omitempty"`
|
||||
AutoRedirect bool `yaml:"auto-redirect" json:"auto-redirect,omitempty"`
|
||||
AutoRedirectInputMark uint32 `yaml:"auto-redirect-input-mark" json:"auto-redirect-input-mark,omitempty"`
|
||||
AutoRedirectOutputMark uint32 `yaml:"auto-redirect-output-mark" json:"auto-redirect-output-mark,omitempty"`
|
||||
LoopbackAddress []netip.Addr `yaml:"loopback-address" json:"loopback-address,omitempty"`
|
||||
StrictRoute bool `yaml:"strict-route" json:"strict-route,omitempty"`
|
||||
RouteAddress []netip.Prefix `yaml:"route-address" json:"route-address,omitempty"`
|
||||
RouteAddressSet []string `yaml:"route-address-set" json:"route-address-set,omitempty"`
|
||||
RouteExcludeAddress []netip.Prefix `yaml:"route-exclude-address" json:"route-exclude-address,omitempty"`
|
||||
RouteExcludeAddressSet []string `yaml:"route-exclude-address-set" json:"route-exclude-address-set,omitempty"`
|
||||
IncludeInterface []string `yaml:"include-interface" json:"include-interface,omitempty"`
|
||||
ExcludeInterface []string `yaml:"exclude-interface" json:"exclude-interface,omitempty"`
|
||||
IncludeUID []uint32 `yaml:"include-uid" json:"include-uid,omitempty"`
|
||||
IncludeUIDRange []string `yaml:"include-uid-range" json:"include-uid-range,omitempty"`
|
||||
ExcludeUID []uint32 `yaml:"exclude-uid" json:"exclude-uid,omitempty"`
|
||||
ExcludeUIDRange []string `yaml:"exclude-uid-range" json:"exclude-uid-range,omitempty"`
|
||||
ExcludeSrcPort []uint16 `yaml:"exclude-src-port" json:"exclude-src-port,omitempty"`
|
||||
ExcludeSrcPortRange []string `yaml:"exclude-src-port-range" json:"exclude-src-port-range,omitempty"`
|
||||
ExcludeDstPort []uint16 `yaml:"exclude-dst-port" json:"exclude-dst-port,omitempty"`
|
||||
ExcludeDstPortRange []string `yaml:"exclude-dst-port-range" json:"exclude-dst-port-range,omitempty"`
|
||||
IncludeAndroidUser []int `yaml:"include-android-user" json:"include-android-user,omitempty"`
|
||||
IncludePackage []string `yaml:"include-package" json:"include-package,omitempty"`
|
||||
ExcludePackage []string `yaml:"exclude-package" json:"exclude-package,omitempty"`
|
||||
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
|
||||
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
|
||||
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
|
||||
Inet6Address []netip.Prefix `yaml:"inet6-address" json:"inet6-address,omitempty"`
|
||||
IPRoute2TableIndex int `yaml:"iproute2-table-index" json:"iproute2-table-index,omitempty"`
|
||||
IPRoute2RuleIndex int `yaml:"iproute2-rule-index" json:"iproute2-rule-index,omitempty"`
|
||||
AutoRedirect bool `yaml:"auto-redirect" json:"auto-redirect,omitempty"`
|
||||
AutoRedirectInputMark uint32 `yaml:"auto-redirect-input-mark" json:"auto-redirect-input-mark,omitempty"`
|
||||
AutoRedirectOutputMark uint32 `yaml:"auto-redirect-output-mark" json:"auto-redirect-output-mark,omitempty"`
|
||||
AutoRedirectIPRoute2FallbackRuleIndex int `yaml:"auto-redirect-iproute2-fallback-rule-index" json:"auto-redirect-iproute2-fallback-rule-index,omitempty"`
|
||||
LoopbackAddress []netip.Addr `yaml:"loopback-address" json:"loopback-address,omitempty"`
|
||||
StrictRoute bool `yaml:"strict-route" json:"strict-route,omitempty"`
|
||||
RouteAddress []netip.Prefix `yaml:"route-address" json:"route-address,omitempty"`
|
||||
RouteAddressSet []string `yaml:"route-address-set" json:"route-address-set,omitempty"`
|
||||
RouteExcludeAddress []netip.Prefix `yaml:"route-exclude-address" json:"route-exclude-address,omitempty"`
|
||||
RouteExcludeAddressSet []string `yaml:"route-exclude-address-set" json:"route-exclude-address-set,omitempty"`
|
||||
IncludeInterface []string `yaml:"include-interface" json:"include-interface,omitempty"`
|
||||
ExcludeInterface []string `yaml:"exclude-interface" json:"exclude-interface,omitempty"`
|
||||
IncludeUID []uint32 `yaml:"include-uid" json:"include-uid,omitempty"`
|
||||
IncludeUIDRange []string `yaml:"include-uid-range" json:"include-uid-range,omitempty"`
|
||||
ExcludeUID []uint32 `yaml:"exclude-uid" json:"exclude-uid,omitempty"`
|
||||
ExcludeUIDRange []string `yaml:"exclude-uid-range" json:"exclude-uid-range,omitempty"`
|
||||
ExcludeSrcPort []uint16 `yaml:"exclude-src-port" json:"exclude-src-port,omitempty"`
|
||||
ExcludeSrcPortRange []string `yaml:"exclude-src-port-range" json:"exclude-src-port-range,omitempty"`
|
||||
ExcludeDstPort []uint16 `yaml:"exclude-dst-port" json:"exclude-dst-port,omitempty"`
|
||||
ExcludeDstPortRange []string `yaml:"exclude-dst-port-range" json:"exclude-dst-port-range,omitempty"`
|
||||
IncludeAndroidUser []int `yaml:"include-android-user" json:"include-android-user,omitempty"`
|
||||
IncludePackage []string `yaml:"include-package" json:"include-package,omitempty"`
|
||||
ExcludePackage []string `yaml:"exclude-package" json:"exclude-package,omitempty"`
|
||||
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
|
||||
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
|
||||
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
|
||||
|
||||
Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
|
||||
Inet6RouteAddress []netip.Prefix `yaml:"inet6-route-address" json:"inet6-route-address,omitempty"`
|
||||
@@ -955,6 +958,12 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
||||
)
|
||||
proxies["GLOBAL"] = adapter.NewProxy(global)
|
||||
}
|
||||
|
||||
// validate dialer-proxy references
|
||||
if err := validateDialerProxies(proxies); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return proxies, providersMap, nil
|
||||
}
|
||||
|
||||
@@ -1106,22 +1115,23 @@ func parseHosts(cfg *RawConfig) (*trie.DomainTrie[resolver.HostValue], error) {
|
||||
|
||||
if len(cfg.Hosts) != 0 {
|
||||
for domain, anyValue := range cfg.Hosts {
|
||||
if str, ok := anyValue.(string); ok && str == "lan" {
|
||||
hosts, err := utils.ToStringSlice(anyValue)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(hosts) == 1 && hosts[0] == "lan" {
|
||||
if addrs, err := net.InterfaceAddrs(); err != nil {
|
||||
log.Errorln("insert lan to host error: %s", err)
|
||||
} else {
|
||||
ips := make([]netip.Addr, 0)
|
||||
hosts = make([]string, 0, len(addrs))
|
||||
for _, addr := range addrs {
|
||||
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && !ipnet.IP.IsLinkLocalUnicast() {
|
||||
if ip, err := netip.ParseAddr(ipnet.IP.String()); err == nil {
|
||||
ips = append(ips, ip)
|
||||
}
|
||||
hosts = append(hosts, ipnet.IP.String())
|
||||
}
|
||||
}
|
||||
anyValue = ips
|
||||
}
|
||||
}
|
||||
value, err := resolver.NewHostValue(anyValue)
|
||||
value, err := resolver.NewHostValue(hosts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s is not a valid value", anyValue)
|
||||
}
|
||||
@@ -1189,7 +1199,7 @@ func parseNameServer(servers []string, respectRules bool, preferH3 bool) ([]dns.
|
||||
dnsNetType = "tcp" // TCP
|
||||
case "tls":
|
||||
addr, err = hostWithDefaultPort(u.Host, "853")
|
||||
dnsNetType = "tcp-tls" // DNS over TLS
|
||||
dnsNetType = "tls" // DNS over TLS
|
||||
case "http", "https":
|
||||
addr, err = hostWithDefaultPort(u.Host, "443")
|
||||
dnsNetType = "https" // DNS over HTTPS
|
||||
@@ -1396,6 +1406,13 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if dnsCfg.ProxyServerPolicy, err = parseNameServerPolicy(cfg.ProxyServerNameserverPolicy, ruleProviders, false, cfg.PreferH3); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(dnsCfg.ProxyServerPolicy) != 0 && len(dnsCfg.ProxyServerNameserver) == 0 {
|
||||
return nil, errors.New("disallow empty `proxy-server-nameserver` when `proxy-server-nameserver-policy` is set")
|
||||
}
|
||||
|
||||
if dnsCfg.DirectNameServer, err = parseNameServer(cfg.DirectNameServer, false, cfg.PreferH3); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1633,39 +1650,40 @@ func parseTun(rawTun RawTun, dns *DNS, general *General) error {
|
||||
AutoRoute: rawTun.AutoRoute,
|
||||
AutoDetectInterface: rawTun.AutoDetectInterface,
|
||||
|
||||
MTU: rawTun.MTU,
|
||||
GSO: rawTun.GSO,
|
||||
GSOMaxSize: rawTun.GSOMaxSize,
|
||||
Inet4Address: []netip.Prefix{tunAddressPrefix},
|
||||
Inet6Address: rawTun.Inet6Address,
|
||||
IPRoute2TableIndex: rawTun.IPRoute2TableIndex,
|
||||
IPRoute2RuleIndex: rawTun.IPRoute2RuleIndex,
|
||||
AutoRedirect: rawTun.AutoRedirect,
|
||||
AutoRedirectInputMark: rawTun.AutoRedirectInputMark,
|
||||
AutoRedirectOutputMark: rawTun.AutoRedirectOutputMark,
|
||||
LoopbackAddress: rawTun.LoopbackAddress,
|
||||
StrictRoute: rawTun.StrictRoute,
|
||||
RouteAddress: rawTun.RouteAddress,
|
||||
RouteAddressSet: rawTun.RouteAddressSet,
|
||||
RouteExcludeAddress: rawTun.RouteExcludeAddress,
|
||||
RouteExcludeAddressSet: rawTun.RouteExcludeAddressSet,
|
||||
IncludeInterface: rawTun.IncludeInterface,
|
||||
ExcludeInterface: rawTun.ExcludeInterface,
|
||||
IncludeUID: rawTun.IncludeUID,
|
||||
IncludeUIDRange: rawTun.IncludeUIDRange,
|
||||
ExcludeUID: rawTun.ExcludeUID,
|
||||
ExcludeUIDRange: rawTun.ExcludeUIDRange,
|
||||
ExcludeSrcPort: rawTun.ExcludeSrcPort,
|
||||
ExcludeSrcPortRange: rawTun.ExcludeSrcPortRange,
|
||||
ExcludeDstPort: rawTun.ExcludeDstPort,
|
||||
ExcludeDstPortRange: rawTun.ExcludeDstPortRange,
|
||||
IncludeAndroidUser: rawTun.IncludeAndroidUser,
|
||||
IncludePackage: rawTun.IncludePackage,
|
||||
ExcludePackage: rawTun.ExcludePackage,
|
||||
EndpointIndependentNat: rawTun.EndpointIndependentNat,
|
||||
UDPTimeout: rawTun.UDPTimeout,
|
||||
DisableICMPForwarding: rawTun.DisableICMPForwarding,
|
||||
FileDescriptor: rawTun.FileDescriptor,
|
||||
MTU: rawTun.MTU,
|
||||
GSO: rawTun.GSO,
|
||||
GSOMaxSize: rawTun.GSOMaxSize,
|
||||
Inet4Address: []netip.Prefix{tunAddressPrefix},
|
||||
Inet6Address: rawTun.Inet6Address,
|
||||
IPRoute2TableIndex: rawTun.IPRoute2TableIndex,
|
||||
IPRoute2RuleIndex: rawTun.IPRoute2RuleIndex,
|
||||
AutoRedirect: rawTun.AutoRedirect,
|
||||
AutoRedirectInputMark: rawTun.AutoRedirectInputMark,
|
||||
AutoRedirectOutputMark: rawTun.AutoRedirectOutputMark,
|
||||
AutoRedirectIPRoute2FallbackRuleIndex: rawTun.AutoRedirectIPRoute2FallbackRuleIndex,
|
||||
LoopbackAddress: rawTun.LoopbackAddress,
|
||||
StrictRoute: rawTun.StrictRoute,
|
||||
RouteAddress: rawTun.RouteAddress,
|
||||
RouteAddressSet: rawTun.RouteAddressSet,
|
||||
RouteExcludeAddress: rawTun.RouteExcludeAddress,
|
||||
RouteExcludeAddressSet: rawTun.RouteExcludeAddressSet,
|
||||
IncludeInterface: rawTun.IncludeInterface,
|
||||
ExcludeInterface: rawTun.ExcludeInterface,
|
||||
IncludeUID: rawTun.IncludeUID,
|
||||
IncludeUIDRange: rawTun.IncludeUIDRange,
|
||||
ExcludeUID: rawTun.ExcludeUID,
|
||||
ExcludeUIDRange: rawTun.ExcludeUIDRange,
|
||||
ExcludeSrcPort: rawTun.ExcludeSrcPort,
|
||||
ExcludeSrcPortRange: rawTun.ExcludeSrcPortRange,
|
||||
ExcludeDstPort: rawTun.ExcludeDstPort,
|
||||
ExcludeDstPortRange: rawTun.ExcludeDstPortRange,
|
||||
IncludeAndroidUser: rawTun.IncludeAndroidUser,
|
||||
IncludePackage: rawTun.IncludePackage,
|
||||
ExcludePackage: rawTun.ExcludePackage,
|
||||
EndpointIndependentNat: rawTun.EndpointIndependentNat,
|
||||
UDPTimeout: rawTun.UDPTimeout,
|
||||
DisableICMPForwarding: rawTun.DisableICMPForwarding,
|
||||
FileDescriptor: rawTun.FileDescriptor,
|
||||
|
||||
Inet4RouteAddress: rawTun.Inet4RouteAddress,
|
||||
Inet6RouteAddress: rawTun.Inet6RouteAddress,
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/metacubex/mihomo/adapter/outboundgroup"
|
||||
"github.com/metacubex/mihomo/common/structure"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
)
|
||||
|
||||
// Check if ProxyGroups form DAG(Directed Acyclic Graph), and sort all ProxyGroups by dependency order.
|
||||
@@ -143,6 +144,64 @@ func proxyGroupsDagSort(groupsConfig []map[string]any) error {
|
||||
return fmt.Errorf("loop is detected in ProxyGroup, please check following ProxyGroups: %v", loopElements)
|
||||
}
|
||||
|
||||
// validateDialerProxies checks if all dialer-proxy references are valid
|
||||
func validateDialerProxies(proxies map[string]C.Proxy) error {
|
||||
graph := make(map[string]string) // proxy name -> dialer-proxy name
|
||||
|
||||
// collect all proxies with dialer-proxy configured
|
||||
for name, proxy := range proxies {
|
||||
dialerProxy := proxy.ProxyInfo().DialerProxy
|
||||
if dialerProxy != "" {
|
||||
// validate each dialer-proxy reference
|
||||
_, exist := proxies[dialerProxy]
|
||||
if !exist {
|
||||
return fmt.Errorf("proxy [%s] dialer-proxy [%s] not found", name, dialerProxy)
|
||||
}
|
||||
|
||||
// build dependency graph
|
||||
graph[name] = dialerProxy
|
||||
}
|
||||
}
|
||||
|
||||
// perform depth-first search to detect cycles for each proxy
|
||||
for name := range graph {
|
||||
visited := make(map[string]bool, len(graph))
|
||||
path := make([]string, 0, len(graph))
|
||||
if validateDialerProxiesHasCycle(name, graph, visited, path) {
|
||||
return fmt.Errorf("proxy [%s] has circular dialer-proxy dependency", name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateDialerProxiesHasCycle performs DFS to detect if there's a cycle starting from current proxy
|
||||
func validateDialerProxiesHasCycle(current string, graph map[string]string, visited map[string]bool, path []string) bool {
|
||||
// check if current is already in path (cycle detected)
|
||||
for _, p := range path {
|
||||
if p == current {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// already visited and no cycle
|
||||
if visited[current] {
|
||||
return false
|
||||
}
|
||||
|
||||
visited[current] = true
|
||||
path = append(path, current)
|
||||
|
||||
// check dialer-proxy of current proxy
|
||||
if dialerProxy, exists := graph[current]; exists {
|
||||
if validateDialerProxiesHasCycle(dialerProxy, graph, visited, path) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func verifyIP6() bool {
|
||||
if skip, _ := strconv.ParseBool(os.Getenv("SKIP_SYSTEM_IPV6_CHECK")); skip {
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestValidateDialerProxies(t *testing.T) {
|
||||
testCases := []struct {
|
||||
testName string
|
||||
proxy []map[string]any
|
||||
errContains string
|
||||
}{
|
||||
{
|
||||
testName: "ValidReference",
|
||||
proxy: []map[string]any{ // create proxy with valid dialer-proxy reference
|
||||
{"name": "base-proxy", "type": "socks5", "server": "127.0.0.1", "port": 1080},
|
||||
{"name": "proxy-with-dialer", "type": "socks5", "server": "127.0.0.1", "port": 1081, "dialer-proxy": "base-proxy"},
|
||||
},
|
||||
errContains: "",
|
||||
},
|
||||
{
|
||||
testName: "NotFoundReference",
|
||||
proxy: []map[string]any{ // create proxy with non-existent dialer-proxy reference
|
||||
{"name": "proxy-with-dialer", "type": "socks5", "server": "127.0.0.1", "port": 1081, "dialer-proxy": "non-existent-proxy"},
|
||||
},
|
||||
errContains: "not found",
|
||||
},
|
||||
{
|
||||
testName: "CircularDependency",
|
||||
proxy: []map[string]any{
|
||||
// create proxy A that references B
|
||||
{"name": "proxy-a", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "proxy-c"},
|
||||
// create proxy B that references C
|
||||
{"name": "proxy-b", "type": "socks5", "server": "127.0.0.1", "port": 1081, "dialer-proxy": "proxy-a"},
|
||||
// create proxy C that references A (creates cycle)
|
||||
{"name": "proxy-c", "type": "socks5", "server": "127.0.0.1", "port": 1082, "dialer-proxy": "proxy-a"},
|
||||
},
|
||||
errContains: "circular",
|
||||
},
|
||||
{
|
||||
testName: "ComplexChain",
|
||||
proxy: []map[string]any{ // create a valid chain: proxy-d -> proxy-c -> proxy-b -> proxy-a
|
||||
{"name": "proxy-a", "type": "socks5", "server": "127.0.0.1", "port": 1080},
|
||||
{"name": "proxy-b", "type": "socks5", "server": "127.0.0.1", "port": 1081, "dialer-proxy": "proxy-a"},
|
||||
{"name": "proxy-c", "type": "socks5", "server": "127.0.0.1", "port": 1082, "dialer-proxy": "proxy-b"},
|
||||
{"name": "proxy-d", "type": "socks5", "server": "127.0.0.1", "port": 1083, "dialer-proxy": "proxy-c"},
|
||||
},
|
||||
errContains: "",
|
||||
},
|
||||
{
|
||||
testName: "EmptyDialerProxy",
|
||||
proxy: []map[string]any{ // create proxy without dialer-proxy
|
||||
{"name": "simple-proxy", "type": "socks5", "server": "127.0.0.1", "port": 1080},
|
||||
},
|
||||
errContains: "",
|
||||
},
|
||||
{
|
||||
testName: "SelfReference",
|
||||
proxy: []map[string]any{ // create proxy that references itself
|
||||
{"name": "self-proxy", "type": "socks5", "server": "127.0.0.1", "port": 1080, "dialer-proxy": "self-proxy"},
|
||||
},
|
||||
errContains: "circular",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.testName, func(t *testing.T) {
|
||||
config := RawConfig{Proxy: testCase.proxy}
|
||||
_, _, err := parseProxies(&config)
|
||||
if testCase.errContains == "" {
|
||||
assert.NoError(t, err, testCase.testName)
|
||||
} else {
|
||||
assert.ErrorContains(t, err, testCase.errContains, testCase.testName)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,7 @@ const (
|
||||
Mieru
|
||||
AnyTLS
|
||||
Sudoku
|
||||
Masque
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -212,6 +213,8 @@ func (at AdapterType) String() string {
|
||||
return "AnyTLS"
|
||||
case Sudoku:
|
||||
return "Sudoku"
|
||||
case Masque:
|
||||
return "Masque"
|
||||
case Relay:
|
||||
return "Relay"
|
||||
case Selector:
|
||||
|
||||
+4
-30
@@ -7,20 +7,17 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/component/ca"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
"github.com/metacubex/tls"
|
||||
D "github.com/miekg/dns"
|
||||
)
|
||||
|
||||
type client struct {
|
||||
port string
|
||||
host string
|
||||
dialer *dnsDialer
|
||||
schema string
|
||||
skipCertVerify bool
|
||||
port string
|
||||
host string
|
||||
dialer *dnsDialer
|
||||
schema string
|
||||
}
|
||||
|
||||
var _ dnsClient = (*client)(nil)
|
||||
@@ -43,23 +40,6 @@ func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
if c.schema == "tls" {
|
||||
tlsConfig, err := ca.GetTLSConfig(ca.Option{
|
||||
TLSConfig: &tls.Config{
|
||||
ServerName: c.host,
|
||||
InsecureSkipVerify: c.skipCertVerify,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConn := tls.Client(conn, tlsConfig)
|
||||
if err := tlsConn.HandshakeContext(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn = tlsConn
|
||||
}
|
||||
|
||||
// miekg/dns ExchangeContext doesn't respond to context cancel.
|
||||
// this is a workaround
|
||||
type result struct {
|
||||
@@ -117,12 +97,6 @@ func newClient(addr string, resolver *Resolver, netType string, params map[strin
|
||||
}
|
||||
if strings.HasPrefix(netType, "tcp") {
|
||||
c.schema = "tcp"
|
||||
if strings.HasSuffix(netType, "tls") {
|
||||
c.schema = "tls"
|
||||
}
|
||||
}
|
||||
if params["skip-cert-verify"] == "true" {
|
||||
c.skipCertVerify = true
|
||||
}
|
||||
return c
|
||||
}
|
||||
+3
-7
@@ -725,14 +725,10 @@ func (doh *dnsOverHTTPS) tlsDial(ctx context.Context, network string, config *tl
|
||||
// TLS handshake dialTimeout will be used as connection deadLine.
|
||||
conn := tls.Client(rawConn, config)
|
||||
|
||||
err = conn.SetDeadline(time.Now().Add(dialTimeout))
|
||||
if err != nil {
|
||||
// Must not happen in normal circumstances.
|
||||
log.Errorln("cannot set deadline: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, dialTimeout)
|
||||
defer cancel()
|
||||
|
||||
err = conn.Handshake()
|
||||
err = conn.HandshakeContext(ctx)
|
||||
if err != nil {
|
||||
defer conn.Close()
|
||||
return nil, err
|
||||
|
||||
+3
-28
@@ -11,6 +11,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/pool"
|
||||
"github.com/metacubex/mihomo/component/ca"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
@@ -55,11 +56,6 @@ type dnsOverQUIC struct {
|
||||
conn *quic.Conn
|
||||
connMu sync.RWMutex
|
||||
|
||||
// bytesPool is a *sync.Pool we use to store byte buffers in. These byte
|
||||
// buffers are used to read responses from the upstream.
|
||||
bytesPool *sync.Pool
|
||||
bytesPoolGuard sync.Mutex
|
||||
|
||||
addr string
|
||||
dialer *dnsDialer
|
||||
skipCertVerify bool
|
||||
@@ -203,24 +199,6 @@ func (doq *dnsOverQUIC) shouldRetry(err error) (ok bool) {
|
||||
return isQUICRetryError(err)
|
||||
}
|
||||
|
||||
// getBytesPool returns (creates if needed) a pool we store byte buffers in.
|
||||
func (doq *dnsOverQUIC) getBytesPool() (pool *sync.Pool) {
|
||||
doq.bytesPoolGuard.Lock()
|
||||
defer doq.bytesPoolGuard.Unlock()
|
||||
|
||||
if doq.bytesPool == nil {
|
||||
doq.bytesPool = &sync.Pool{
|
||||
New: func() interface{} {
|
||||
b := make([]byte, MaxMsgSize)
|
||||
|
||||
return &b
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return doq.bytesPool
|
||||
}
|
||||
|
||||
// getConnection opens or returns an existing *quic.Conn. useCached
|
||||
// argument controls whether we should try to use the existing cached
|
||||
// connection. If it is false, we will forcibly create a new connection and
|
||||
@@ -386,12 +364,9 @@ func (doq *dnsOverQUIC) closeConnWithError(err error) {
|
||||
|
||||
// readMsg reads the incoming DNS message from the QUIC stream.
|
||||
func (doq *dnsOverQUIC) readMsg(stream *quic.Stream) (m *D.Msg, err error) {
|
||||
pool := doq.getBytesPool()
|
||||
bufPtr := pool.Get().(*[]byte)
|
||||
respBuf := pool.Get(MaxMsgSize)
|
||||
defer pool.Put(respBuf)
|
||||
|
||||
defer pool.Put(bufPtr)
|
||||
|
||||
respBuf := *bufPtr
|
||||
n, err := stream.Read(respBuf)
|
||||
if err != nil && n == 0 {
|
||||
return nil, fmt.Errorf("reading response from %s: %w", doq.Address(), err)
|
||||
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/deque"
|
||||
"github.com/metacubex/mihomo/component/ca"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
|
||||
"github.com/metacubex/tls"
|
||||
D "github.com/miekg/dns"
|
||||
)
|
||||
|
||||
const maxOldDotConns = 8
|
||||
|
||||
type dnsOverTLS struct {
|
||||
port string
|
||||
host string
|
||||
dialer *dnsDialer
|
||||
skipCertVerify bool
|
||||
|
||||
access sync.Mutex
|
||||
connections deque.Deque[net.Conn] // LIFO
|
||||
}
|
||||
|
||||
var _ dnsClient = (*dnsOverTLS)(nil)
|
||||
|
||||
// Address implements dnsClient
|
||||
func (t *dnsOverTLS) Address() string {
|
||||
return fmt.Sprintf("tls://%s", net.JoinHostPort(t.host, t.port))
|
||||
}
|
||||
|
||||
func (t *dnsOverTLS) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error) {
|
||||
// miekg/dns ExchangeContext doesn't respond to context cancel.
|
||||
// this is a workaround
|
||||
type result struct {
|
||||
msg *D.Msg
|
||||
err error
|
||||
}
|
||||
ch := make(chan result, 1)
|
||||
|
||||
go func() {
|
||||
var msg *D.Msg
|
||||
var err error
|
||||
defer func() { ch <- result{msg, err} }()
|
||||
for { // retry loop; only retry when reusing old conn
|
||||
err = ctx.Err() // check context first
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var conn net.Conn
|
||||
isOldConn := true
|
||||
|
||||
t.access.Lock()
|
||||
if t.connections.Len() > 0 {
|
||||
conn = t.connections.PopBack()
|
||||
}
|
||||
t.access.Unlock()
|
||||
|
||||
if conn == nil {
|
||||
conn, err = t.dialContext(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
isOldConn = false
|
||||
}
|
||||
|
||||
dClient := &D.Client{
|
||||
UDPSize: 4096,
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
dConn := &D.Conn{
|
||||
Conn: conn,
|
||||
UDPSize: dClient.UDPSize,
|
||||
}
|
||||
|
||||
msg, _, err = dClient.ExchangeWithConn(m, dConn)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
conn = nil
|
||||
if isOldConn { // retry
|
||||
continue
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
t.access.Lock()
|
||||
if t.connections.Len() >= maxOldDotConns {
|
||||
oldConn := t.connections.PopFront()
|
||||
go oldConn.Close() // close in a new goroutine, not blocking the current task
|
||||
}
|
||||
t.connections.PushBack(conn)
|
||||
t.access.Unlock()
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case ret := <-ch:
|
||||
return ret.msg, ret.err
|
||||
}
|
||||
}
|
||||
|
||||
func (t *dnsOverTLS) dialContext(ctx context.Context) (net.Conn, error) {
|
||||
conn, err := t.dialer.DialContext(ctx, "tcp", net.JoinHostPort(t.host, t.port))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tlsConfig, err := ca.GetTLSConfig(ca.Option{
|
||||
TLSConfig: &tls.Config{
|
||||
ServerName: t.host,
|
||||
InsecureSkipVerify: t.skipCertVerify,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConn := tls.Client(conn, tlsConfig)
|
||||
if err = tlsConn.HandshakeContext(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn = tlsConn
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (t *dnsOverTLS) ResetConnection() {
|
||||
t.access.Lock()
|
||||
for t.connections.Len() > 0 {
|
||||
oldConn := t.connections.PopFront()
|
||||
go oldConn.Close() // close in a new goroutine, not blocking the current task
|
||||
}
|
||||
t.access.Unlock()
|
||||
}
|
||||
|
||||
func (t *dnsOverTLS) Close() error {
|
||||
runtime.SetFinalizer(t, nil)
|
||||
t.ResetConnection()
|
||||
return nil
|
||||
}
|
||||
|
||||
func newDoTClient(addr string, resolver *Resolver, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *dnsOverTLS {
|
||||
host, port, _ := net.SplitHostPort(addr)
|
||||
c := &dnsOverTLS{
|
||||
port: port,
|
||||
host: host,
|
||||
dialer: newDNSDialer(resolver, proxyAdapter, proxyName),
|
||||
}
|
||||
c.connections.SetBaseCap(maxOldDotConns)
|
||||
if params["skip-cert-verify"] == "true" {
|
||||
c.skipCertVerify = true
|
||||
}
|
||||
runtime.SetFinalizer(c, (*dnsOverTLS).Close)
|
||||
return c
|
||||
}
|
||||
+41
-40
@@ -451,6 +451,7 @@ type Config struct {
|
||||
FallbackIPFilter []C.IpMatcher
|
||||
FallbackDomainFilter []C.DomainMatcher
|
||||
Policy []Policy
|
||||
ProxyServerPolicy []Policy
|
||||
CacheAlgorithm string
|
||||
CacheMaxSize int
|
||||
}
|
||||
@@ -519,55 +520,20 @@ func NewResolver(config Config) (rs Resolvers) {
|
||||
return
|
||||
}
|
||||
|
||||
r := &Resolver{
|
||||
ipv6: config.IPv6,
|
||||
main: cacheTransform(config.Main),
|
||||
cache: config.newCache(),
|
||||
ipv6Timeout: time.Duration(config.IPv6Timeout) * time.Millisecond,
|
||||
}
|
||||
r.defaultResolver = defaultResolver
|
||||
rs.Resolver = r
|
||||
|
||||
if len(config.ProxyServer) != 0 {
|
||||
rs.ProxyResolver = &Resolver{
|
||||
ipv6: config.IPv6,
|
||||
main: cacheTransform(config.ProxyServer),
|
||||
cache: config.newCache(),
|
||||
ipv6Timeout: time.Duration(config.IPv6Timeout) * time.Millisecond,
|
||||
}
|
||||
}
|
||||
|
||||
if len(config.DirectServer) != 0 {
|
||||
rs.DirectResolver = &Resolver{
|
||||
ipv6: config.IPv6,
|
||||
main: cacheTransform(config.DirectServer),
|
||||
cache: config.newCache(),
|
||||
ipv6Timeout: time.Duration(config.IPv6Timeout) * time.Millisecond,
|
||||
}
|
||||
}
|
||||
|
||||
if len(config.Fallback) != 0 {
|
||||
r.fallback = cacheTransform(config.Fallback)
|
||||
r.fallbackIPFilters = config.FallbackIPFilter
|
||||
r.fallbackDomainFilters = config.FallbackDomainFilter
|
||||
}
|
||||
|
||||
if len(config.Policy) != 0 {
|
||||
r.policy = make([]dnsPolicy, 0)
|
||||
|
||||
makePolicy := func(policies []Policy) (dnsPolicies []dnsPolicy) {
|
||||
var triePolicy *trie.DomainTrie[[]dnsClient]
|
||||
insertPolicy := func(policy dnsPolicy) {
|
||||
if triePolicy != nil {
|
||||
triePolicy.Optimize()
|
||||
r.policy = append(r.policy, domainTriePolicy{triePolicy})
|
||||
dnsPolicies = append(dnsPolicies, domainTriePolicy{triePolicy})
|
||||
triePolicy = nil
|
||||
}
|
||||
if policy != nil {
|
||||
r.policy = append(r.policy, policy)
|
||||
dnsPolicies = append(dnsPolicies, policy)
|
||||
}
|
||||
}
|
||||
|
||||
for _, policy := range config.Policy {
|
||||
for _, policy := range policies {
|
||||
if policy.Matcher != nil {
|
||||
insertPolicy(domainMatcherPolicy{matcher: policy.Matcher, dnsClients: cacheTransform(policy.NameServers)})
|
||||
} else {
|
||||
@@ -578,12 +544,47 @@ func NewResolver(config Config) (rs Resolvers) {
|
||||
}
|
||||
}
|
||||
insertPolicy(nil)
|
||||
return
|
||||
}
|
||||
|
||||
if rs.DirectResolver != nil && config.DirectFollowPolicy {
|
||||
r := &Resolver{
|
||||
ipv6: config.IPv6,
|
||||
main: cacheTransform(config.Main),
|
||||
cache: config.newCache(),
|
||||
ipv6Timeout: time.Duration(config.IPv6Timeout) * time.Millisecond,
|
||||
policy: makePolicy(config.Policy),
|
||||
}
|
||||
r.defaultResolver = defaultResolver
|
||||
rs.Resolver = r
|
||||
|
||||
if len(config.ProxyServer) != 0 {
|
||||
rs.ProxyResolver = &Resolver{
|
||||
ipv6: config.IPv6,
|
||||
main: cacheTransform(config.ProxyServer),
|
||||
cache: config.newCache(),
|
||||
ipv6Timeout: time.Duration(config.IPv6Timeout) * time.Millisecond,
|
||||
policy: makePolicy(config.ProxyServerPolicy),
|
||||
}
|
||||
}
|
||||
|
||||
if len(config.DirectServer) != 0 {
|
||||
rs.DirectResolver = &Resolver{
|
||||
ipv6: config.IPv6,
|
||||
main: cacheTransform(config.DirectServer),
|
||||
cache: config.newCache(),
|
||||
ipv6Timeout: time.Duration(config.IPv6Timeout) * time.Millisecond,
|
||||
}
|
||||
if config.DirectFollowPolicy {
|
||||
rs.DirectResolver.policy = r.policy
|
||||
}
|
||||
}
|
||||
|
||||
if len(config.Fallback) != 0 {
|
||||
r.fallback = cacheTransform(config.Fallback)
|
||||
r.fallbackIPFilters = config.FallbackIPFilter
|
||||
r.fallbackDomainFilters = config.FallbackDomainFilter
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -95,6 +95,8 @@ func transform(servers []NameServer, resolver *Resolver) []dnsClient {
|
||||
for _, s := range servers {
|
||||
var c dnsClient
|
||||
switch s.Net {
|
||||
case "tls":
|
||||
c = newDoTClient(s.Addr, resolver, s.Params, s.ProxyAdapter, s.ProxyName)
|
||||
case "https":
|
||||
c = newDoHClient(s.Addr, resolver, s.PreferH3, s.Params, s.ProxyAdapter, s.ProxyName)
|
||||
case "dhcp":
|
||||
|
||||
+43
-21
@@ -97,11 +97,6 @@ external-doh-server: /dns-query
|
||||
|
||||
# interface-name: en0 # 设置出口网卡
|
||||
|
||||
# 全局 TLS 指纹,优先低于 proxy 内的 client-fingerprint
|
||||
# 可选: "chrome","firefox","safari","ios","random","none" options.
|
||||
# Utls is currently support TLS transport in TCP/grpc/WS/HTTP for VLESS/Vmess and trojan.
|
||||
global-client-fingerprint: chrome
|
||||
|
||||
# TCP keep alive interval
|
||||
# disable-keep-alive: false #目前在android端强制为true
|
||||
# keep-alive-idle: 15
|
||||
@@ -323,8 +318,10 @@ dns:
|
||||
|
||||
# 专用于节点域名解析的 DNS 服务器,非必要配置项,如果不填则遵循nameserver-policy、nameserver和fallback的配置
|
||||
# proxy-server-nameserver:
|
||||
# - https://dns.google/dns-query
|
||||
# - tls://one.one.one.one
|
||||
# - https://doh.pub/dns-query
|
||||
# - tls://223.5.5.5:853
|
||||
# proxy-server-nameserver-policy: # 格式同nameserver-policy,仅用于节点域名解析,当且仅当proxy-server-nameserver不为空时生效
|
||||
# 'www.yournode.com': '114.114.114.114'
|
||||
|
||||
# 专用于direct出口域名解析的 DNS 服务器,非必要配置项,如果不填则遵循nameserver-policy、nameserver和fallback的配置
|
||||
# direct-nameserver:
|
||||
@@ -464,6 +461,7 @@ proxies: # socks5
|
||||
# enable: true # 必须手动开启
|
||||
# # 如果config为空则通过dns解析,不为空则通过该值指定,格式为经过base64编码的ech参数(dig +short TYPE65 tls-ech.dev)
|
||||
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
|
||||
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
|
||||
# skip-cert-verify: true
|
||||
# host: bing.com
|
||||
# path: "/"
|
||||
@@ -605,6 +603,7 @@ proxies: # socks5
|
||||
# enable: true # 必须手动开启
|
||||
# # 如果config为空则通过dns解析,不为空则通过该值指定,格式为经过base64编码的ech参数(dig +short TYPE65 tls-ech.dev)
|
||||
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
|
||||
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
|
||||
# ws-opts:
|
||||
# path: /path
|
||||
# headers:
|
||||
@@ -690,6 +689,7 @@ proxies: # socks5
|
||||
# enable: true # 必须手动开启
|
||||
# # 如果config为空则通过dns解析,不为空则通过该值指定,格式为经过base64编码的ech参数(dig +short TYPE65 tls-ech.dev)
|
||||
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
|
||||
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
|
||||
|
||||
- name: "vless-vision"
|
||||
type: vless
|
||||
@@ -812,6 +812,7 @@ proxies: # socks5
|
||||
# enable: true # 必须手动开启
|
||||
# # 如果config为空则通过dns解析,不为空则通过该值指定,格式为经过base64编码的ech参数(dig +short TYPE65 tls-ech.dev)
|
||||
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
|
||||
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
|
||||
|
||||
- name: trojan-grpc
|
||||
server: server
|
||||
@@ -883,6 +884,7 @@ proxies: # socks5
|
||||
# enable: true # 必须手动开启
|
||||
# # 如果config为空则通过dns解析,不为空则通过该值指定,格式为经过base64编码的ech参数(dig +short TYPE65 tls-ech.dev)
|
||||
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
|
||||
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
|
||||
# skip-cert-verify: false
|
||||
# recv-window-conn: 12582912
|
||||
# recv-window: 52428800
|
||||
@@ -911,6 +913,7 @@ proxies: # socks5
|
||||
# enable: true # 必须手动开启
|
||||
# # 如果config为空则通过dns解析,不为空则通过该值指定,格式为经过base64编码的ech参数(dig +short TYPE65 tls-ech.dev)
|
||||
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
|
||||
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
|
||||
# skip-cert-verify: false
|
||||
# fingerprint: xxxx # 配置指纹将实现 SSL Pining 效果, 可使用 openssl x509 -noout -fingerprint -sha256 -inform pem -in yourcert.pem 获取
|
||||
# 下面两项如果填写则开启 mTLS(需要同时填写)
|
||||
@@ -938,6 +941,7 @@ proxies: # socks5
|
||||
reserved: "U4An"
|
||||
# 数组格式也是合法的
|
||||
# reserved: [209,98,59]
|
||||
# persistent-keepalive: 0
|
||||
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
|
||||
# dialer-proxy: "ss1"
|
||||
# remote-dns-resolve: true # 强制 dns 远程解析,默认值为 false
|
||||
@@ -978,6 +982,23 @@ proxies: # socks5
|
||||
# j3: <t><b 0xf6ab><c><r 10> # AmneziaWG v1.5 only (removed in v2)
|
||||
# itime: 60 # AmneziaWG v1.5 only (removed in v2)
|
||||
|
||||
# masque
|
||||
- name: "masque"
|
||||
type: masque
|
||||
server: 162.159.198.1
|
||||
port: 443
|
||||
private-key: MHcCAQEEILI1eOtnbEIh89Fj4yNDuFR6UjayCKI3NdLl3DhetimWoAoGCCqGSM49AwEHoUQDQgAEgyXrE8v+hHsHy3ewSb3WcRjYgCrM9T9hiE0Uv6k2DZ1+4kefrDT9v1Q/8wdRigTf6t6gGNUV8W+IUMdrfUt+9g==
|
||||
public-key: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIaU7MToJm9NKp8YfGxR6r+/h4mcG7SxI8tsW8OR1A5tv/zCzVbCRRh2t87/kxnP6lAy0lkr7qYwu+ox+k3dr6w==
|
||||
ip: 172.16.0.2
|
||||
ipv6: 2606:4700:110:84c0:163a:4914:a0ad:3342
|
||||
mtu: 1280
|
||||
udp: true
|
||||
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
|
||||
# dialer-proxy: "ss1"
|
||||
# remote-dns-resolve: true # 强制 dns 远程解析,默认值为 false
|
||||
# dns: [ 1.1.1.1, 8.8.8.8 ] # 仅在 remote-dns-resolve 为 true 时生效
|
||||
# congestion-controller: bbr # 默认不开启
|
||||
|
||||
# tuic
|
||||
- name: tuic
|
||||
server: www.example.com
|
||||
@@ -1006,6 +1027,7 @@ proxies: # socks5
|
||||
# enable: true # 必须手动开启
|
||||
# # 如果config为空则通过dns解析,不为空则通过该值指定,格式为经过base64编码的ech参数(dig +short TYPE65 tls-ech.dev)
|
||||
# config: AEn+DQBFKwAgACABWIHUGj4u+PIggYXcR5JF0gYk3dCRioBW8uJq9H4mKAAIAAEAAQABAANAEnB1YmxpYy50bHMtZWNoLmRldgAA
|
||||
# # query-server-name: xxx.com # 可选项,不为空时用于指定通过dns解析时的域名
|
||||
#
|
||||
# meta 和 sing-box 私有扩展,将 ss-uot 用于 udp 中继,开启此选项后 udp-relay-mode 将失效
|
||||
# 警告,与原版 tuic 不兼容!!!
|
||||
@@ -1062,19 +1084,19 @@ proxies: # socks5
|
||||
server: server_ip/domain # 1.2.3.4 or domain
|
||||
port: 443
|
||||
key: "<client_key>" # 如果你使用sudoku生成的ED25519密钥对,请填写密钥对中的私钥,否则填入和服务端相同的uuid
|
||||
aead-method: chacha20-poly1305 # 可选值:chacha20-poly1305、aes-128-gcm、none 我们保证在none的情况下sudoku混淆层仍然确保安全
|
||||
padding-min: 2 # 最小填充字节数
|
||||
padding-max: 7 # 最大填充字节数
|
||||
aead-method: chacha20-poly1305 # 可选:chacha20-poly1305、aes-128-gcm、none(不建议;且 enable-pure-downlink=false 时不可用)
|
||||
padding-min: 2 # 最小填充率(0-100)
|
||||
padding-max: 7 # 最大填充率(0-100,必须 >= padding-min)
|
||||
table-type: prefer_ascii # 可选值:prefer_ascii、prefer_entropy 前者全ascii映射,后者保证熵值(汉明1)低于3
|
||||
# custom-table: xpxvvpvv # 可选,自定义字节布局,必须包含2个x、2个p、4个v,可随意组合。启用此处则需配置`table-type`为`prefer_entropy`
|
||||
# custom-tables: ["xpxvvpvv", "vxpvxvvp"] # 可选,自定义字节布局列表(x/v/p),用于 xvp 模式轮换;非空时覆盖 custom-table
|
||||
http-mask: true # 是否启用http掩码
|
||||
# http-mask-mode: legacy # 可选:legacy(默认)、stream、poll、auto;stream/poll/auto 支持走 CDN/反代
|
||||
# http-mask-mode: legacy # 可选:legacy(默认)、stream(split-stream)、poll、auto(先 stream 再 poll);stream/poll/auto 支持走 CDN/反代
|
||||
# http-mask-tls: true # 可选:仅在 http-mask-mode 为 stream/poll/auto 时生效;true 强制 https;false 强制 http(不会根据端口自动推断)
|
||||
# http-mask-host: "" # 可选:覆盖 Host/SNI(支持 example.com 或 example.com:443);仅在 http-mask-mode 为 stream/poll/auto 时生效
|
||||
# path-root: "" # 可选:HTTP 隧道端点一级路径前缀(双方需一致),例如 "aabbcc" => /aabbcc/session、/aabbcc/stream、/aabbcc/api/v1/upload
|
||||
# http-mask-multiplex: off # 可选:off(默认)、auto(复用 h1.1 keep-alive / h2 连接,减少每次建链 RTT)、on(单条隧道内多路复用多个目标连接;仅在 http-mask-mode=stream/poll/auto 生效)
|
||||
enable-pure-downlink: false # 是否启用混淆下行,false的情况下能在保证数据安全的前提下极大提升下行速度,与服务端端保持相同(如果此处为false,则要求aead不可为none)
|
||||
# path-root: "" # 可选:HTTP 隧道端点一级路径前缀(双方需一致),例如 "aabbcc" 或 "/aabbcc/" => /aabbcc/session、/aabbcc/stream、/aabbcc/api/v1/upload
|
||||
# http-mask-multiplex: off # 可选:off(默认)、auto(复用底层 HTTP 连接,减少建链 RTT)、on(Sudoku mux 单隧道多目标;仅在 http-mask-mode=stream/poll/auto 生效)
|
||||
enable-pure-downlink: false # 可选:false=带宽优化下行(更快,要求 aead-method != none);true=纯 Sudoku 下行
|
||||
|
||||
# anytls
|
||||
- name: anytls
|
||||
@@ -1612,17 +1634,17 @@ listeners:
|
||||
port: 8443 # 仅支持单端口
|
||||
listen: 0.0.0.0
|
||||
key: "<server_key>" # 如果你使用sudoku生成的ED25519密钥对,此处是密钥对中的公钥,当然,你也可以仅仅使用任意uuid充当key
|
||||
aead-method: chacha20-poly1305 # 支持chacha20-poly1305或者aes-128-gcm以及none,sudoku的混淆层可以确保none情况下数据安全
|
||||
padding-min: 1 # 填充最小长度
|
||||
padding-max: 15 # 填充最大长度,均不建议过大
|
||||
aead-method: chacha20-poly1305 # 可选:chacha20-poly1305、aes-128-gcm、none(不建议;且 enable-pure-downlink=false 时不可用)
|
||||
padding-min: 1 # 最小填充率(0-100)
|
||||
padding-max: 15 # 最大填充率(0-100,必须 >= padding-min)
|
||||
table-type: prefer_ascii # 可选值:prefer_ascii、prefer_entropy 前者全ascii映射,后者保证熵值(汉明1)低于3
|
||||
# custom-table: xpxvvpvv # 可选,自定义字节布局,必须包含2个x、2个p、4个v,可随意组合。启用此处则需配置`table-type`为`prefer_entropy`
|
||||
# custom-tables: ["xpxvvpvv", "vxpvxvvp"] # 可选,自定义字节布局列表(x/v/p),用于 xvp 模式轮换;非空时覆盖 custom-table
|
||||
handshake-timeout: 5 # optional
|
||||
enable-pure-downlink: false # 是否启用混淆下行,false的情况下能在保证数据安全的前提下极大提升下行速度,与客户端保持相同(如果此处为false,则要求aead不可为none)
|
||||
handshake-timeout: 5 # 可选(秒)
|
||||
enable-pure-downlink: false # 可选:false=带宽优化下行(更快,要求 aead-method != none);true=纯 Sudoku 下行
|
||||
disable-http-mask: false # 可选:禁用 http 掩码/隧道(默认为 false)
|
||||
# http-mask-mode: legacy # 可选:legacy(默认)、stream、poll、auto;stream/poll/auto 支持走 CDN/反代
|
||||
# path-root: "" # 可选:HTTP 隧道端点一级路径前缀(双方需一致),例如 "aabbcc" => /aabbcc/session、/aabbcc/stream、/aabbcc/api/v1/upload
|
||||
# http-mask-mode: legacy # 可选:legacy(默认)、stream(split-stream)、poll、auto(先 stream 再 poll);stream/poll/auto 支持走 CDN/反代
|
||||
# path-root: "" # 可选:HTTP 隧道端点一级路径前缀(双方需一致),例如 "aabbcc" 或 "/aabbcc/" => /aabbcc/session、/aabbcc/stream、/aabbcc/api/v1/upload
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -11,67 +11,72 @@ require (
|
||||
github.com/gobwas/ws v1.4.0
|
||||
github.com/gofrs/uuid/v5 v5.4.0
|
||||
github.com/golang/snappy v1.0.0
|
||||
github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905
|
||||
github.com/klauspost/compress v1.17.9 // lastest version compatible with golang1.20
|
||||
github.com/mdlayher/netlink v1.7.2
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d
|
||||
github.com/metacubex/bart v0.26.0
|
||||
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b
|
||||
github.com/metacubex/blake3 v0.1.0
|
||||
github.com/metacubex/chacha v0.1.5
|
||||
github.com/metacubex/chi v0.1.0
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260128031117-1cad62060727
|
||||
github.com/metacubex/cpu v0.1.0
|
||||
github.com/metacubex/fswatch v0.1.1
|
||||
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759
|
||||
github.com/metacubex/http v0.1.0
|
||||
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604
|
||||
github.com/metacubex/mlkem v0.1.0
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260112033758-aa29579f2001
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260128071132-0f3233b973af
|
||||
github.com/metacubex/randv2 v0.2.0
|
||||
github.com/metacubex/restls-client-go v0.1.7
|
||||
github.com/metacubex/sing v0.5.6
|
||||
github.com/metacubex/sing-mux v0.3.4
|
||||
github.com/metacubex/sing v0.5.7
|
||||
github.com/metacubex/sing-mux v0.3.5
|
||||
github.com/metacubex/sing-quic v0.0.0-20260112044712-65d17608159e
|
||||
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.11
|
||||
github.com/metacubex/sing-vmess v0.2.4
|
||||
github.com/metacubex/sing-tun v0.4.15
|
||||
github.com/metacubex/sing-vmess v0.2.5
|
||||
github.com/metacubex/sing-wireguard v0.0.0-20250503063753-2dc62acc626f
|
||||
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141
|
||||
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443
|
||||
github.com/metacubex/tls v0.1.1
|
||||
github.com/metacubex/tls v0.1.4
|
||||
github.com/metacubex/utls v1.8.4
|
||||
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f
|
||||
github.com/miekg/dns v1.1.63 // lastest version compatible with golang1.20
|
||||
github.com/mroth/weightedrand/v2 v2.1.0
|
||||
github.com/openacid/low v0.1.21
|
||||
github.com/oschwald/maxminddb-golang v1.12.0 // lastest version compatible with golang1.20
|
||||
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a
|
||||
github.com/samber/lo v1.52.0
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/sirupsen/logrus v1.9.4
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/vmihailenco/msgpack/v5 v5.4.1
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2
|
||||
gitlab.com/go-extension/aes-ccm v0.0.0-20230221065045-e58665ef23c7
|
||||
go.uber.org/automaxprocs v1.6.0
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
|
||||
golang.org/x/crypto v0.33.0 // lastest version compatible with golang1.20
|
||||
golang.org/x/exp v0.0.0-20240904232852-e7e105dedf7e // lastest version compatible with golang1.20
|
||||
golang.org/x/net v0.35.0 // lastest version compatible with golang1.20
|
||||
golang.org/x/sync v0.11.0 // lastest version compatible with golang1.20
|
||||
golang.org/x/sys v0.30.0 // lastest version compatible with golang1.20
|
||||
google.golang.org/protobuf v1.34.2 // lastest version compatible with golang1.20
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
// lastest version compatible with golang1.20
|
||||
require (
|
||||
github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905
|
||||
github.com/klauspost/compress v1.17.9
|
||||
github.com/mdlayher/netlink v1.7.2
|
||||
github.com/miekg/dns v1.1.63
|
||||
github.com/oschwald/maxminddb-golang v1.12.0
|
||||
golang.org/x/crypto v0.33.0
|
||||
golang.org/x/exp v0.0.0-20240904232852-e7e105dedf7e
|
||||
golang.org/x/net v0.35.0
|
||||
golang.org/x/sync v0.11.0
|
||||
golang.org/x/sys v0.30.0
|
||||
google.golang.org/protobuf v1.34.2
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/RyuaNerin/go-krypto v1.3.0 // indirect
|
||||
github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344 // indirect
|
||||
github.com/ajg/form v1.5.1 // indirect
|
||||
github.com/andybalholm/brotli v1.0.6 // indirect
|
||||
github.com/buger/jsonparser v1.1.1 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dunglas/httpsfv v1.0.2 // indirect
|
||||
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 // indirect
|
||||
github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 // indirect
|
||||
github.com/ericlagergren/siv v0.0.0-20220507050439-0b757b3aa5f1 // indirect
|
||||
@@ -88,7 +93,6 @@ require (
|
||||
github.com/klauspost/cpuid/v2 v2.2.6 // indirect
|
||||
github.com/klauspost/reedsolomon v1.12.3 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/mdlayher/socket v0.4.1 // indirect
|
||||
github.com/metacubex/ascon v0.1.0 // indirect
|
||||
github.com/metacubex/gvisor v0.0.0-20251227095601-261ec1326fe8 // indirect
|
||||
|
||||
@@ -12,8 +12,6 @@ github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHG
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk=
|
||||
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
|
||||
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/coreos/go-iptables v0.8.0 h1:MPc2P89IhuVpLI7ETL/2tx3XZ61VeICZjYqDEgNsPRc=
|
||||
github.com/coreos/go-iptables v0.8.0/go.mod h1:Qe8Bv2Xik5FyTXwgIbLAnv2sWSBmvWdFETJConOQ//Q=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
@@ -22,6 +20,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
|
||||
github.com/dlclark/regexp2 v1.11.5/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.26.2 h1:U/2XJc+3vrJD9r815FoFdwToQFEcqSOzzzWIPPhjfEU=
|
||||
github.com/enfein/mieru/v3 v3.26.2/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
|
||||
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 h1:kXYqH/sL8dS/FdoFjr12ePjnLPorPo2FsnrHNuXSDyo=
|
||||
@@ -59,7 +59,6 @@ github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8/go.mod h1:K1liHPHnj73
|
||||
github.com/google/tink/go v1.6.1 h1:t7JHqO8Ath2w2ig5vjwQYJzhGEZymedQc90lQXUBa4I=
|
||||
github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905 h1:q3OEI9RaN/wwcx+qgGo6ZaoJkCiDYe/gjDLfq7lQQF4=
|
||||
github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905/go.mod h1:VvGYjkZoJyKqlmT1yzakUs4mfKMNB0XdODP0+rdml6k=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/josharian/native v1.0.1-0.20221213033349-c1e37c09b531/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
|
||||
github.com/josharian/native v1.1.0 h1:uuaP0hAbW7Y4l0ZRQ6C9zfb7Mg1mbFKry/xzDAfmtLA=
|
||||
github.com/josharian/native v1.1.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
|
||||
@@ -72,8 +71,6 @@ github.com/klauspost/reedsolomon v1.12.3/go.mod h1:3K5rXwABAvzGeR01r6pWZieUALXO/
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/g=
|
||||
github.com/mdlayher/netlink v1.7.2/go.mod h1:xraEF7uJbxLhc5fpHL4cPe221LI2bdttWlU+ZGLfQSw=
|
||||
github.com/mdlayher/socket v0.4.1 h1:eM9y2/jlbs1M615oshPQOHZzj6R6wMT7bX5NPiQvn2U=
|
||||
@@ -92,6 +89,8 @@ github.com/metacubex/chacha v0.1.5 h1:fKWMb/5c7ZrY8Uoqi79PPFxl+qwR7X/q0OrsAubyX2
|
||||
github.com/metacubex/chacha v0.1.5/go.mod h1:Djn9bPZxLTXbJFSeyo0/qzEzQI+gUSSzttuzZM75GH8=
|
||||
github.com/metacubex/chi v0.1.0 h1:rjNDyDj50nRpicG43CNkIw4ssiCbmDL8d7wJXKlUCsg=
|
||||
github.com/metacubex/chi v0.1.0/go.mod h1:zM5u5oMQt8b2DjvDHvzadKrP6B2ztmasL1YHRMbVV+g=
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260128031117-1cad62060727 h1:qbZQ0sO0bDBKPvTd/qNQK6513300WJ5GRsHnw3PO4Ho=
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260128031117-1cad62060727/go.mod h1:xYC8Ik7/rN6no+vTRuWMEziGwm3brA0wNM/zZP9qhOQ=
|
||||
github.com/metacubex/cpu v0.1.0 h1:8PeTdV9j6UKbN1K5Jvtbi/Jock7dknvzyYuLb8Conmk=
|
||||
github.com/metacubex/cpu v0.1.0/go.mod h1:09VEt4dSRLR+bOA8l4w4NDuzGZ8n5dkMv7e8axgEeTU=
|
||||
github.com/metacubex/fswatch v0.1.1 h1:jqU7C/v+g0qc2RUFgmAOPoVvfl2BXXUXEumn6oQuxhU=
|
||||
@@ -114,16 +113,16 @@ github.com/metacubex/nftables v0.0.0-20250503052935-30a69ab87793 h1:1Qpuy+sU3Dmy
|
||||
github.com/metacubex/nftables v0.0.0-20250503052935-30a69ab87793/go.mod h1:RjRNb4G52yAgfR+Oe/kp9G4PJJ97Fnj89eY1BFO3YyA=
|
||||
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.20260112033758-aa29579f2001 h1:RlT3bFCIDM/NR9GWaDbFCrweOwpHRfgaT9c0zuRlPhY=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260112033758-aa29579f2001/go.mod h1:oNzMrmylS897M3zSMuapIdwSwfq6F2qW01Z3NhVRJhk=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260128071132-0f3233b973af h1:do5o1rzn64NEN5oGswo7VruDkbz2055fhVT3rXehA8E=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260128071132-0f3233b973af/go.mod h1:oNzMrmylS897M3zSMuapIdwSwfq6F2qW01Z3NhVRJhk=
|
||||
github.com/metacubex/randv2 v0.2.0 h1:uP38uBvV2SxYfLj53kuvAjbND4RUDfFJjwr4UigMiLs=
|
||||
github.com/metacubex/randv2 v0.2.0/go.mod h1:kFi2SzrQ5WuneuoLLCMkABtiBu6VRrMrWFqSPyj2cxY=
|
||||
github.com/metacubex/restls-client-go v0.1.7 h1:eCwiXCTQb5WJu9IlgYvDBA1OgrINv58dEe7hcN5H15k=
|
||||
github.com/metacubex/restls-client-go v0.1.7/go.mod h1:BN/U52vPw7j8VTSh2vleD/MnmVKCov84mS5VcjVHH4g=
|
||||
github.com/metacubex/sing v0.5.6 h1:mEPDCadsCj3DB8gn+t/EtposlYuALEkExa/LUguw6/c=
|
||||
github.com/metacubex/sing v0.5.6/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w=
|
||||
github.com/metacubex/sing-mux v0.3.4 h1:tf4r27CIkzaxq9kBlAXQkgMXq2HPp5Mta60Kb4RCZF0=
|
||||
github.com/metacubex/sing-mux v0.3.4/go.mod h1:SEJfAuykNj/ozbPqngEYqyggwSr81+L7Nu09NRD5mh4=
|
||||
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.5 h1:UqVN+o62SR8kJaC9/3VfOc5UiVqgVY/ef9WwfGYYkk0=
|
||||
github.com/metacubex/sing-mux v0.3.5/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260112044712-65d17608159e h1:MLxp42z9Jd6LtY2suyawnl24oNzIsFxWc15bNeDIGxA=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260112044712-65d17608159e/go.mod h1:+lgKTd52xAarGtqugALISShyw4KxnoEpYe2u0zJh26w=
|
||||
github.com/metacubex/sing-shadowsocks v0.2.12 h1:Wqzo8bYXrK5aWqxu/TjlTnYZzAKtKsaFQBdr6IHFaBE=
|
||||
@@ -132,18 +131,18 @@ github.com/metacubex/sing-shadowsocks2 v0.2.7 h1:hSuuc0YpsfiqYqt1o+fP4m34BQz4e6w
|
||||
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.11 h1:NG5zpvYPbBXf+9GSUmDaGCDwl3hZXV677tbRAw0QtCM=
|
||||
github.com/metacubex/sing-tun v0.4.11/go.mod h1:L/TjQY5JEGy8nvsuYmy/XgMFMCPiF0+AWSFCYfS6r9w=
|
||||
github.com/metacubex/sing-vmess v0.2.4 h1:Tx6AGgCiEf400E/xyDuYyafsel6sGbR8oF7RkAaus6I=
|
||||
github.com/metacubex/sing-vmess v0.2.4/go.mod h1:21R5R1u90uUvBQF0owoooEu96/SAYYD56nDrwm6nFaM=
|
||||
github.com/metacubex/sing-tun v0.4.15 h1:0uOO8kCpodgs4Op8L7sn+C4J6a/lQagmeRTrzHxn+mo=
|
||||
github.com/metacubex/sing-tun v0.4.15/go.mod h1:L/TjQY5JEGy8nvsuYmy/XgMFMCPiF0+AWSFCYfS6r9w=
|
||||
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-20250503063753-2dc62acc626f h1:Sr/DYKYofKHKc4GF3qkRGNuj6XA6c0eqPgEDN+VAsYU=
|
||||
github.com/metacubex/sing-wireguard v0.0.0-20250503063753-2dc62acc626f/go.mod h1:jpAkVLPnCpGSfNyVmj6Cq4YbuZsFepm/Dc+9BAOcR80=
|
||||
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/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.1 h1:BEcZrsPTTfNf4sKZ02EbZodv4UIj7fgHWa1Eqo12Bc0=
|
||||
github.com/metacubex/tls v0.1.1/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
|
||||
github.com/metacubex/tls v0.1.4 h1:Gm5GrkyMUh52gYOMIAQ1kHIym4v4M3Qb87Wsmd8Kpdc=
|
||||
github.com/metacubex/tls v0.1.4/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=
|
||||
@@ -179,8 +178,8 @@ github.com/sina-ghaderi/rabaead v0.0.0-20220730151906-ab6e06b96e8c h1:DjKMC30y6y
|
||||
github.com/sina-ghaderi/rabaead v0.0.0-20220730151906-ab6e06b96e8c/go.mod h1:NV/a66PhhWYVmUMaotlXJ8fIEFB98u+c8l/CQIEFLrU=
|
||||
github.com/sina-ghaderi/rabbitio v0.0.0-20220730151941-9ce26f4f872e h1:ur8uMsPIFG3i4Gi093BQITvwH9znsz2VUZmnmwHvpIo=
|
||||
github.com/sina-ghaderi/rabbitio v0.0.0-20220730151941-9ce26f4f872e/go.mod h1:+e5fBW3bpPyo+3uLo513gIUblc03egGjMM0+5GKbzK8=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
|
||||
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
@@ -198,9 +197,9 @@ github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IU
|
||||
github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
|
||||
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
gitlab.com/go-extension/aes-ccm v0.0.0-20230221065045-e58665ef23c7 h1:UNrDfkQqiEYzdMlNsVvBYOAJWZjdktqFE9tQh5BT2+4=
|
||||
gitlab.com/go-extension/aes-ccm v0.0.0-20230221065045-e58665ef23c7/go.mod h1:E+rxHvJG9H6PUdzq9NRG6csuLN3XUx98BfGOVWNYnXs=
|
||||
gitlab.com/yawning/bsaes.git v0.0.0-20190805113838-0a714cd429ec h1:FpfFs4EhNehiVfzQttTuxanPIT43FtkkCFypIod8LHo=
|
||||
@@ -233,7 +232,6 @@ golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
|
||||
@@ -258,6 +258,7 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
|
||||
Default: c.DefaultNameserver,
|
||||
Policy: c.NameServerPolicy,
|
||||
ProxyServer: c.ProxyServerNameserver,
|
||||
ProxyServerPolicy: c.ProxyServerPolicy,
|
||||
DirectServer: c.DirectNameServer,
|
||||
DirectFollowPolicy: c.DirectFollowPolicy,
|
||||
CacheAlgorithm: c.CacheAlgorithm,
|
||||
|
||||
+28
-24
@@ -71,30 +71,31 @@ type tunSchema struct {
|
||||
GSO *bool `yaml:"gso" json:"gso,omitempty"`
|
||||
GSOMaxSize *uint32 `yaml:"gso-max-size" json:"gso-max-size,omitempty"`
|
||||
//Inet4Address *[]netip.Prefix `yaml:"inet4-address" json:"inet4-address,omitempty"`
|
||||
Inet6Address *[]netip.Prefix `yaml:"inet6-address" json:"inet6-address,omitempty"`
|
||||
IPRoute2TableIndex *int `yaml:"iproute2-table-index" json:"iproute2-table-index,omitempty"`
|
||||
IPRoute2RuleIndex *int `yaml:"iproute2-rule-index" json:"iproute2-rule-index,omitempty"`
|
||||
AutoRedirect *bool `yaml:"auto-redirect" json:"auto-redirect,omitempty"`
|
||||
AutoRedirectInputMark *uint32 `yaml:"auto-redirect-input-mark" json:"auto-redirect-input-mark,omitempty"`
|
||||
AutoRedirectOutputMark *uint32 `yaml:"auto-redirect-output-mark" json:"auto-redirect-output-mark,omitempty"`
|
||||
LoopbackAddress *[]netip.Addr `yaml:"loopback-address" json:"loopback-address,omitempty"`
|
||||
StrictRoute *bool `yaml:"strict-route" json:"strict-route,omitempty"`
|
||||
RouteAddress *[]netip.Prefix `yaml:"route-address" json:"route-address,omitempty"`
|
||||
RouteAddressSet *[]string `yaml:"route-address-set" json:"route-address-set,omitempty"`
|
||||
RouteExcludeAddress *[]netip.Prefix `yaml:"route-exclude-address" json:"route-exclude-address,omitempty"`
|
||||
RouteExcludeAddressSet *[]string `yaml:"route-exclude-address-set" json:"route-exclude-address-set,omitempty"`
|
||||
IncludeInterface *[]string `yaml:"include-interface" json:"include-interface,omitempty"`
|
||||
ExcludeInterface *[]string `yaml:"exclude-interface" json:"exclude-interface,omitempty"`
|
||||
IncludeUID *[]uint32 `yaml:"include-uid" json:"include-uid,omitempty"`
|
||||
IncludeUIDRange *[]string `yaml:"include-uid-range" json:"include-uid-range,omitempty"`
|
||||
ExcludeUID *[]uint32 `yaml:"exclude-uid" json:"exclude-uid,omitempty"`
|
||||
ExcludeUIDRange *[]string `yaml:"exclude-uid-range" json:"exclude-uid-range,omitempty"`
|
||||
IncludeAndroidUser *[]int `yaml:"include-android-user" json:"include-android-user,omitempty"`
|
||||
IncludePackage *[]string `yaml:"include-package" json:"include-package,omitempty"`
|
||||
ExcludePackage *[]string `yaml:"exclude-package" json:"exclude-package,omitempty"`
|
||||
EndpointIndependentNat *bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout *int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
|
||||
FileDescriptor *int `yaml:"file-descriptor" json:"file-descriptor"`
|
||||
Inet6Address *[]netip.Prefix `yaml:"inet6-address" json:"inet6-address,omitempty"`
|
||||
IPRoute2TableIndex *int `yaml:"iproute2-table-index" json:"iproute2-table-index,omitempty"`
|
||||
IPRoute2RuleIndex *int `yaml:"iproute2-rule-index" json:"iproute2-rule-index,omitempty"`
|
||||
AutoRedirect *bool `yaml:"auto-redirect" json:"auto-redirect,omitempty"`
|
||||
AutoRedirectInputMark *uint32 `yaml:"auto-redirect-input-mark" json:"auto-redirect-input-mark,omitempty"`
|
||||
AutoRedirectOutputMark *uint32 `yaml:"auto-redirect-output-mark" json:"auto-redirect-output-mark,omitempty"`
|
||||
AutoRedirectIPRoute2FallbackRuleIndex *int `yaml:"auto-redirect-iproute2-fallback-rule-index" json:"auto-redirect-iproute2-fallback-rule-index,omitempty"`
|
||||
LoopbackAddress *[]netip.Addr `yaml:"loopback-address" json:"loopback-address,omitempty"`
|
||||
StrictRoute *bool `yaml:"strict-route" json:"strict-route,omitempty"`
|
||||
RouteAddress *[]netip.Prefix `yaml:"route-address" json:"route-address,omitempty"`
|
||||
RouteAddressSet *[]string `yaml:"route-address-set" json:"route-address-set,omitempty"`
|
||||
RouteExcludeAddress *[]netip.Prefix `yaml:"route-exclude-address" json:"route-exclude-address,omitempty"`
|
||||
RouteExcludeAddressSet *[]string `yaml:"route-exclude-address-set" json:"route-exclude-address-set,omitempty"`
|
||||
IncludeInterface *[]string `yaml:"include-interface" json:"include-interface,omitempty"`
|
||||
ExcludeInterface *[]string `yaml:"exclude-interface" json:"exclude-interface,omitempty"`
|
||||
IncludeUID *[]uint32 `yaml:"include-uid" json:"include-uid,omitempty"`
|
||||
IncludeUIDRange *[]string `yaml:"include-uid-range" json:"include-uid-range,omitempty"`
|
||||
ExcludeUID *[]uint32 `yaml:"exclude-uid" json:"exclude-uid,omitempty"`
|
||||
ExcludeUIDRange *[]string `yaml:"exclude-uid-range" json:"exclude-uid-range,omitempty"`
|
||||
IncludeAndroidUser *[]int `yaml:"include-android-user" json:"include-android-user,omitempty"`
|
||||
IncludePackage *[]string `yaml:"include-package" json:"include-package,omitempty"`
|
||||
ExcludePackage *[]string `yaml:"exclude-package" json:"exclude-package,omitempty"`
|
||||
EndpointIndependentNat *bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout *int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
|
||||
FileDescriptor *int `yaml:"file-descriptor" json:"file-descriptor"`
|
||||
|
||||
Inet4RouteAddress *[]netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
|
||||
Inet6RouteAddress *[]netip.Prefix `yaml:"inet6-route-address" json:"inet6-route-address,omitempty"`
|
||||
@@ -181,6 +182,9 @@ func pointerOrDefaultTun(p *tunSchema, def LC.Tun) LC.Tun {
|
||||
if p.AutoRedirectOutputMark != nil {
|
||||
def.AutoRedirectOutputMark = *p.AutoRedirectOutputMark
|
||||
}
|
||||
if p.AutoRedirectIPRoute2FallbackRuleIndex != nil {
|
||||
def.AutoRedirectIPRoute2FallbackRuleIndex = *p.AutoRedirectIPRoute2FallbackRuleIndex
|
||||
}
|
||||
if p.LoopbackAddress != nil {
|
||||
def.LoopbackAddress = *p.LoopbackAddress
|
||||
}
|
||||
|
||||
+20
-2
@@ -46,7 +46,7 @@ func parseProxyName(next http.Handler) http.Handler {
|
||||
func findProxyByName(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.Context().Value(CtxKeyProxyName).(string)
|
||||
proxies := tunnel.ProxiesWithProviders()
|
||||
proxies := proxiesWithProviders()
|
||||
proxy, exist := proxies[name]
|
||||
if !exist {
|
||||
render.Status(r, http.StatusNotFound)
|
||||
@@ -60,7 +60,7 @@ func findProxyByName(next http.Handler) http.Handler {
|
||||
}
|
||||
|
||||
func getProxies(w http.ResponseWriter, r *http.Request) {
|
||||
proxies := tunnel.ProxiesWithProviders()
|
||||
proxies := proxiesWithProviders()
|
||||
render.JSON(w, r, render.M{
|
||||
"proxies": proxies,
|
||||
})
|
||||
@@ -158,3 +158,21 @@ func unfixedProxy(w http.ResponseWriter, r *http.Request) {
|
||||
render.Status(r, http.StatusBadRequest)
|
||||
render.JSON(w, r, ErrBadRequest)
|
||||
}
|
||||
|
||||
// proxiesWithProviders merges all proxies from tunnel
|
||||
//
|
||||
// Deprecated: This function is poorly implemented and should not be called by any new code.
|
||||
// It is left here only to ensure the compatibility of the output of the existing RESTful API.
|
||||
func proxiesWithProviders() map[string]C.Proxy {
|
||||
allProxies := make(map[string]C.Proxy)
|
||||
for name, proxy := range tunnel.Proxies() {
|
||||
allProxies[name] = proxy
|
||||
}
|
||||
for _, p := range tunnel.Providers() {
|
||||
for _, proxy := range p.Proxies() {
|
||||
name := proxy.Name()
|
||||
allProxies[name] = proxy
|
||||
}
|
||||
}
|
||||
return allProxies
|
||||
}
|
||||
+37
-33
@@ -17,39 +17,40 @@ type Tun struct {
|
||||
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
||||
AutoDetectInterface bool `yaml:"auto-detect-interface" json:"auto-detect-interface"`
|
||||
|
||||
MTU uint32 `yaml:"mtu" json:"mtu,omitempty"`
|
||||
GSO bool `yaml:"gso" json:"gso,omitempty"`
|
||||
GSOMaxSize uint32 `yaml:"gso-max-size" json:"gso-max-size,omitempty"`
|
||||
Inet4Address []netip.Prefix `yaml:"inet4-address" json:"inet4-address,omitempty"`
|
||||
Inet6Address []netip.Prefix `yaml:"inet6-address" json:"inet6-address,omitempty"`
|
||||
IPRoute2TableIndex int `yaml:"iproute2-table-index" json:"iproute2-table-index,omitempty"`
|
||||
IPRoute2RuleIndex int `yaml:"iproute2-rule-index" json:"iproute2-rule-index,omitempty"`
|
||||
AutoRedirect bool `yaml:"auto-redirect" json:"auto-redirect,omitempty"`
|
||||
AutoRedirectInputMark uint32 `yaml:"auto-redirect-input-mark" json:"auto-redirect-input-mark,omitempty"`
|
||||
AutoRedirectOutputMark uint32 `yaml:"auto-redirect-output-mark" json:"auto-redirect-output-mark,omitempty"`
|
||||
LoopbackAddress []netip.Addr `yaml:"loopback-address" json:"loopback-address,omitempty"`
|
||||
StrictRoute bool `yaml:"strict-route" json:"strict-route,omitempty"`
|
||||
RouteAddress []netip.Prefix `yaml:"route-address" json:"route-address,omitempty"`
|
||||
RouteAddressSet []string `yaml:"route-address-set" json:"route-address-set,omitempty"`
|
||||
RouteExcludeAddress []netip.Prefix `yaml:"route-exclude-address" json:"route-exclude-address,omitempty"`
|
||||
RouteExcludeAddressSet []string `yaml:"route-exclude-address-set" json:"route-exclude-address-set,omitempty"`
|
||||
IncludeInterface []string `yaml:"include-interface" json:"include-interface,omitempty"`
|
||||
ExcludeInterface []string `yaml:"exclude-interface" json:"exclude-interface,omitempty"`
|
||||
IncludeUID []uint32 `yaml:"include-uid" json:"include-uid,omitempty"`
|
||||
IncludeUIDRange []string `yaml:"include-uid-range" json:"include-uid-range,omitempty"`
|
||||
ExcludeUID []uint32 `yaml:"exclude-uid" json:"exclude-uid,omitempty"`
|
||||
ExcludeUIDRange []string `yaml:"exclude-uid-range" json:"exclude-uid-range,omitempty"`
|
||||
ExcludeSrcPort []uint16 `yaml:"exclude-src-port" json:"exclude-src-port,omitempty"`
|
||||
ExcludeSrcPortRange []string `yaml:"exclude-src-port-range" json:"exclude-src-port-range,omitempty"`
|
||||
ExcludeDstPort []uint16 `yaml:"exclude-dst-port" json:"exclude-dst-port,omitempty"`
|
||||
ExcludeDstPortRange []string `yaml:"exclude-dst-port-range" json:"exclude-dst-port-range,omitempty"`
|
||||
IncludeAndroidUser []int `yaml:"include-android-user" json:"include-android-user,omitempty"`
|
||||
IncludePackage []string `yaml:"include-package" json:"include-package,omitempty"`
|
||||
ExcludePackage []string `yaml:"exclude-package" json:"exclude-package,omitempty"`
|
||||
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
|
||||
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
|
||||
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
|
||||
MTU uint32 `yaml:"mtu" json:"mtu,omitempty"`
|
||||
GSO bool `yaml:"gso" json:"gso,omitempty"`
|
||||
GSOMaxSize uint32 `yaml:"gso-max-size" json:"gso-max-size,omitempty"`
|
||||
Inet4Address []netip.Prefix `yaml:"inet4-address" json:"inet4-address,omitempty"`
|
||||
Inet6Address []netip.Prefix `yaml:"inet6-address" json:"inet6-address,omitempty"`
|
||||
IPRoute2TableIndex int `yaml:"iproute2-table-index" json:"iproute2-table-index,omitempty"`
|
||||
IPRoute2RuleIndex int `yaml:"iproute2-rule-index" json:"iproute2-rule-index,omitempty"`
|
||||
AutoRedirect bool `yaml:"auto-redirect" json:"auto-redirect,omitempty"`
|
||||
AutoRedirectInputMark uint32 `yaml:"auto-redirect-input-mark" json:"auto-redirect-input-mark,omitempty"`
|
||||
AutoRedirectOutputMark uint32 `yaml:"auto-redirect-output-mark" json:"auto-redirect-output-mark,omitempty"`
|
||||
AutoRedirectIPRoute2FallbackRuleIndex int `yaml:"auto-redirect-iproute2-fallback-rule-index" json:"auto-redirect-iproute2-fallback-rule-index,omitempty"`
|
||||
LoopbackAddress []netip.Addr `yaml:"loopback-address" json:"loopback-address,omitempty"`
|
||||
StrictRoute bool `yaml:"strict-route" json:"strict-route,omitempty"`
|
||||
RouteAddress []netip.Prefix `yaml:"route-address" json:"route-address,omitempty"`
|
||||
RouteAddressSet []string `yaml:"route-address-set" json:"route-address-set,omitempty"`
|
||||
RouteExcludeAddress []netip.Prefix `yaml:"route-exclude-address" json:"route-exclude-address,omitempty"`
|
||||
RouteExcludeAddressSet []string `yaml:"route-exclude-address-set" json:"route-exclude-address-set,omitempty"`
|
||||
IncludeInterface []string `yaml:"include-interface" json:"include-interface,omitempty"`
|
||||
ExcludeInterface []string `yaml:"exclude-interface" json:"exclude-interface,omitempty"`
|
||||
IncludeUID []uint32 `yaml:"include-uid" json:"include-uid,omitempty"`
|
||||
IncludeUIDRange []string `yaml:"include-uid-range" json:"include-uid-range,omitempty"`
|
||||
ExcludeUID []uint32 `yaml:"exclude-uid" json:"exclude-uid,omitempty"`
|
||||
ExcludeUIDRange []string `yaml:"exclude-uid-range" json:"exclude-uid-range,omitempty"`
|
||||
ExcludeSrcPort []uint16 `yaml:"exclude-src-port" json:"exclude-src-port,omitempty"`
|
||||
ExcludeSrcPortRange []string `yaml:"exclude-src-port-range" json:"exclude-src-port-range,omitempty"`
|
||||
ExcludeDstPort []uint16 `yaml:"exclude-dst-port" json:"exclude-dst-port,omitempty"`
|
||||
ExcludeDstPortRange []string `yaml:"exclude-dst-port-range" json:"exclude-dst-port-range,omitempty"`
|
||||
IncludeAndroidUser []int `yaml:"include-android-user" json:"include-android-user,omitempty"`
|
||||
IncludePackage []string `yaml:"include-package" json:"include-package,omitempty"`
|
||||
ExcludePackage []string `yaml:"exclude-package" json:"exclude-package,omitempty"`
|
||||
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
|
||||
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
|
||||
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
|
||||
|
||||
Inet4RouteAddress []netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
|
||||
Inet6RouteAddress []netip.Prefix `yaml:"inet6-route-address" json:"inet6-route-address,omitempty"`
|
||||
@@ -136,6 +137,9 @@ func (t *Tun) Equal(other Tun) bool {
|
||||
if t.AutoRedirectOutputMark != other.AutoRedirectOutputMark {
|
||||
return false
|
||||
}
|
||||
if t.AutoRedirectIPRoute2FallbackRuleIndex != other.AutoRedirectIPRoute2FallbackRuleIndex {
|
||||
return false
|
||||
}
|
||||
if !slices.Equal(t.RouteAddress, other.RouteAddress) {
|
||||
return false
|
||||
}
|
||||
|
||||
+74
-72
@@ -18,39 +18,40 @@ type TunOption struct {
|
||||
AutoRoute bool `inbound:"auto-route,omitempty"`
|
||||
AutoDetectInterface bool `inbound:"auto-detect-interface,omitempty"`
|
||||
|
||||
MTU uint32 `inbound:"mtu,omitempty"`
|
||||
GSO bool `inbound:"gso,omitempty"`
|
||||
GSOMaxSize uint32 `inbound:"gso-max-size,omitempty"`
|
||||
Inet4Address []netip.Prefix `inbound:"inet4-address,omitempty"`
|
||||
Inet6Address []netip.Prefix `inbound:"inet6-address,omitempty"`
|
||||
IPRoute2TableIndex int `inbound:"iproute2-table-index,omitempty"`
|
||||
IPRoute2RuleIndex int `inbound:"iproute2-rule-index,omitempty"`
|
||||
AutoRedirect bool `inbound:"auto-redirect,omitempty"`
|
||||
AutoRedirectInputMark uint32 `inbound:"auto-redirect-input-mark,omitempty"`
|
||||
AutoRedirectOutputMark uint32 `inbound:"auto-redirect-output-mark,omitempty"`
|
||||
LoopbackAddress []netip.Addr `inbound:"loopback-address,omitempty"`
|
||||
StrictRoute bool `inbound:"strict-route,omitempty"`
|
||||
RouteAddress []netip.Prefix `inbound:"route-address,omitempty"`
|
||||
RouteAddressSet []string `inbound:"route-address-set,omitempty"`
|
||||
RouteExcludeAddress []netip.Prefix `inbound:"route-exclude-address,omitempty"`
|
||||
RouteExcludeAddressSet []string `inbound:"route-exclude-address-set,omitempty"`
|
||||
IncludeInterface []string `inbound:"include-interface,omitempty"`
|
||||
ExcludeInterface []string `inbound:"exclude-interface,omitempty"`
|
||||
IncludeUID []uint32 `inbound:"include-uid,omitempty"`
|
||||
IncludeUIDRange []string `inbound:"include-uid-range,omitempty"`
|
||||
ExcludeUID []uint32 `inbound:"exclude-uid,omitempty"`
|
||||
ExcludeUIDRange []string `inbound:"exclude-uid-range,omitempty"`
|
||||
ExcludeSrcPort []uint16 `inbound:"exclude-src-port,omitempty"`
|
||||
ExcludeSrcPortRange []string `inbound:"exclude-src-port-range,omitempty"`
|
||||
ExcludeDstPort []uint16 `inbound:"exclude-dst-port,omitempty"`
|
||||
ExcludeDstPortRange []string `inbound:"exclude-dst-port-range,omitempty"`
|
||||
IncludeAndroidUser []int `inbound:"include-android-user,omitempty"`
|
||||
IncludePackage []string `inbound:"include-package,omitempty"`
|
||||
ExcludePackage []string `inbound:"exclude-package,omitempty"`
|
||||
EndpointIndependentNat bool `inbound:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout int64 `inbound:"udp-timeout,omitempty"`
|
||||
DisableICMPForwarding bool `inbound:"disable-icmp-forwarding,omitempty"`
|
||||
FileDescriptor int `inbound:"file-descriptor,omitempty"`
|
||||
MTU uint32 `inbound:"mtu,omitempty"`
|
||||
GSO bool `inbound:"gso,omitempty"`
|
||||
GSOMaxSize uint32 `inbound:"gso-max-size,omitempty"`
|
||||
Inet4Address []netip.Prefix `inbound:"inet4-address,omitempty"`
|
||||
Inet6Address []netip.Prefix `inbound:"inet6-address,omitempty"`
|
||||
IPRoute2TableIndex int `inbound:"iproute2-table-index,omitempty"`
|
||||
IPRoute2RuleIndex int `inbound:"iproute2-rule-index,omitempty"`
|
||||
AutoRedirect bool `inbound:"auto-redirect,omitempty"`
|
||||
AutoRedirectInputMark uint32 `inbound:"auto-redirect-input-mark,omitempty"`
|
||||
AutoRedirectOutputMark uint32 `inbound:"auto-redirect-output-mark,omitempty"`
|
||||
AutoRedirectIPRoute2FallbackRuleIndex int `inbound:"auto-redirect-iproute2-fallback-rule-index,omitempty"`
|
||||
LoopbackAddress []netip.Addr `inbound:"loopback-address,omitempty"`
|
||||
StrictRoute bool `inbound:"strict-route,omitempty"`
|
||||
RouteAddress []netip.Prefix `inbound:"route-address,omitempty"`
|
||||
RouteAddressSet []string `inbound:"route-address-set,omitempty"`
|
||||
RouteExcludeAddress []netip.Prefix `inbound:"route-exclude-address,omitempty"`
|
||||
RouteExcludeAddressSet []string `inbound:"route-exclude-address-set,omitempty"`
|
||||
IncludeInterface []string `inbound:"include-interface,omitempty"`
|
||||
ExcludeInterface []string `inbound:"exclude-interface,omitempty"`
|
||||
IncludeUID []uint32 `inbound:"include-uid,omitempty"`
|
||||
IncludeUIDRange []string `inbound:"include-uid-range,omitempty"`
|
||||
ExcludeUID []uint32 `inbound:"exclude-uid,omitempty"`
|
||||
ExcludeUIDRange []string `inbound:"exclude-uid-range,omitempty"`
|
||||
ExcludeSrcPort []uint16 `inbound:"exclude-src-port,omitempty"`
|
||||
ExcludeSrcPortRange []string `inbound:"exclude-src-port-range,omitempty"`
|
||||
ExcludeDstPort []uint16 `inbound:"exclude-dst-port,omitempty"`
|
||||
ExcludeDstPortRange []string `inbound:"exclude-dst-port-range,omitempty"`
|
||||
IncludeAndroidUser []int `inbound:"include-android-user,omitempty"`
|
||||
IncludePackage []string `inbound:"include-package,omitempty"`
|
||||
ExcludePackage []string `inbound:"exclude-package,omitempty"`
|
||||
EndpointIndependentNat bool `inbound:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout int64 `inbound:"udp-timeout,omitempty"`
|
||||
DisableICMPForwarding bool `inbound:"disable-icmp-forwarding,omitempty"`
|
||||
FileDescriptor int `inbound:"file-descriptor,omitempty"`
|
||||
|
||||
Inet4RouteAddress []netip.Prefix `inbound:"inet4-route-address,omitempty"`
|
||||
Inet6RouteAddress []netip.Prefix `inbound:"inet6-route-address,omitempty"`
|
||||
@@ -86,45 +87,46 @@ func NewTun(options *TunOption) (*Tun, error) {
|
||||
Base: base,
|
||||
config: options,
|
||||
tun: LC.Tun{
|
||||
Enable: true,
|
||||
Device: options.Device,
|
||||
Stack: options.Stack,
|
||||
DNSHijack: options.DNSHijack,
|
||||
AutoRoute: options.AutoRoute,
|
||||
AutoDetectInterface: options.AutoDetectInterface,
|
||||
MTU: options.MTU,
|
||||
GSO: options.GSO,
|
||||
GSOMaxSize: options.GSOMaxSize,
|
||||
Inet4Address: options.Inet4Address,
|
||||
Inet6Address: options.Inet6Address,
|
||||
IPRoute2TableIndex: options.IPRoute2TableIndex,
|
||||
IPRoute2RuleIndex: options.IPRoute2RuleIndex,
|
||||
AutoRedirect: options.AutoRedirect,
|
||||
AutoRedirectInputMark: options.AutoRedirectInputMark,
|
||||
AutoRedirectOutputMark: options.AutoRedirectOutputMark,
|
||||
LoopbackAddress: options.LoopbackAddress,
|
||||
StrictRoute: options.StrictRoute,
|
||||
RouteAddress: options.RouteAddress,
|
||||
RouteAddressSet: options.RouteAddressSet,
|
||||
RouteExcludeAddress: options.RouteExcludeAddress,
|
||||
RouteExcludeAddressSet: options.RouteExcludeAddressSet,
|
||||
IncludeInterface: options.IncludeInterface,
|
||||
ExcludeInterface: options.ExcludeInterface,
|
||||
IncludeUID: options.IncludeUID,
|
||||
IncludeUIDRange: options.IncludeUIDRange,
|
||||
ExcludeUID: options.ExcludeUID,
|
||||
ExcludeUIDRange: options.ExcludeUIDRange,
|
||||
ExcludeSrcPort: options.ExcludeSrcPort,
|
||||
ExcludeSrcPortRange: options.ExcludeSrcPortRange,
|
||||
ExcludeDstPort: options.ExcludeDstPort,
|
||||
ExcludeDstPortRange: options.ExcludeDstPortRange,
|
||||
IncludeAndroidUser: options.IncludeAndroidUser,
|
||||
IncludePackage: options.IncludePackage,
|
||||
ExcludePackage: options.ExcludePackage,
|
||||
EndpointIndependentNat: options.EndpointIndependentNat,
|
||||
UDPTimeout: options.UDPTimeout,
|
||||
DisableICMPForwarding: options.DisableICMPForwarding,
|
||||
FileDescriptor: options.FileDescriptor,
|
||||
Enable: true,
|
||||
Device: options.Device,
|
||||
Stack: options.Stack,
|
||||
DNSHijack: options.DNSHijack,
|
||||
AutoRoute: options.AutoRoute,
|
||||
AutoDetectInterface: options.AutoDetectInterface,
|
||||
MTU: options.MTU,
|
||||
GSO: options.GSO,
|
||||
GSOMaxSize: options.GSOMaxSize,
|
||||
Inet4Address: options.Inet4Address,
|
||||
Inet6Address: options.Inet6Address,
|
||||
IPRoute2TableIndex: options.IPRoute2TableIndex,
|
||||
IPRoute2RuleIndex: options.IPRoute2RuleIndex,
|
||||
AutoRedirect: options.AutoRedirect,
|
||||
AutoRedirectInputMark: options.AutoRedirectInputMark,
|
||||
AutoRedirectOutputMark: options.AutoRedirectOutputMark,
|
||||
AutoRedirectIPRoute2FallbackRuleIndex: options.AutoRedirectIPRoute2FallbackRuleIndex,
|
||||
LoopbackAddress: options.LoopbackAddress,
|
||||
StrictRoute: options.StrictRoute,
|
||||
RouteAddress: options.RouteAddress,
|
||||
RouteAddressSet: options.RouteAddressSet,
|
||||
RouteExcludeAddress: options.RouteExcludeAddress,
|
||||
RouteExcludeAddressSet: options.RouteExcludeAddressSet,
|
||||
IncludeInterface: options.IncludeInterface,
|
||||
ExcludeInterface: options.ExcludeInterface,
|
||||
IncludeUID: options.IncludeUID,
|
||||
IncludeUIDRange: options.IncludeUIDRange,
|
||||
ExcludeUID: options.ExcludeUID,
|
||||
ExcludeUIDRange: options.ExcludeUIDRange,
|
||||
ExcludeSrcPort: options.ExcludeSrcPort,
|
||||
ExcludeSrcPortRange: options.ExcludeSrcPortRange,
|
||||
ExcludeDstPort: options.ExcludeDstPort,
|
||||
ExcludeDstPortRange: options.ExcludeDstPortRange,
|
||||
IncludeAndroidUser: options.IncludeAndroidUser,
|
||||
IncludePackage: options.IncludePackage,
|
||||
ExcludePackage: options.ExcludePackage,
|
||||
EndpointIndependentNat: options.EndpointIndependentNat,
|
||||
UDPTimeout: options.UDPTimeout,
|
||||
DisableICMPForwarding: options.DisableICMPForwarding,
|
||||
FileDescriptor: options.FileDescriptor,
|
||||
|
||||
Inet4RouteAddress: options.Inet4RouteAddress,
|
||||
Inet6RouteAddress: options.Inet6RouteAddress,
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/adapter/inbound"
|
||||
"github.com/metacubex/mihomo/adapter/outbound"
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
"github.com/metacubex/mihomo/component/ech"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
LC "github.com/metacubex/mihomo/listener/config"
|
||||
"github.com/metacubex/mihomo/listener/inner"
|
||||
"github.com/metacubex/mihomo/listener/sing"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
"github.com/metacubex/mihomo/ntp"
|
||||
@@ -123,6 +125,21 @@ func New(config LC.Hysteria2Server, tunnel C.Tunnel, additions ...inbound.Additi
|
||||
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
},
|
||||
Transport: &http.Transport{
|
||||
// fellow hysteria2's code skip verify
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
},
|
||||
// from http.DefaultTransport
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: 100,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
return inner.HandleTcp(tunnel, address, "")
|
||||
},
|
||||
},
|
||||
}
|
||||
default:
|
||||
return nil, E.New("unknown masquerade URL scheme: ", masqueradeURL.Scheme)
|
||||
|
||||
+43
-37
@@ -153,6 +153,13 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
|
||||
tunName = CalculateInterfaceName(InterfaceName)
|
||||
options.Device = tunName
|
||||
}
|
||||
forwarderBindInterface := false
|
||||
if options.FileDescriptor > 0 {
|
||||
if tunnelName, err := getTunnelName(int32(options.FileDescriptor)); err != nil {
|
||||
tunName = tunnelName // sing-tun must have the truth tun interface name even it from a fd
|
||||
forwarderBindInterface = true
|
||||
}
|
||||
}
|
||||
routeAddress := options.RouteAddress
|
||||
if len(options.Inet4RouteAddress) > 0 {
|
||||
routeAddress = append(routeAddress, options.Inet4RouteAddress...)
|
||||
@@ -197,6 +204,10 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
|
||||
if ruleIndex == 0 {
|
||||
ruleIndex = tun.DefaultIPRoute2RuleIndex
|
||||
}
|
||||
autoRedirectFallbackRuleIndex := options.AutoRedirectIPRoute2FallbackRuleIndex
|
||||
if autoRedirectFallbackRuleIndex == 0 {
|
||||
autoRedirectFallbackRuleIndex = tun.DefaultIPRoute2AutoRedirectFallbackRuleIndex
|
||||
}
|
||||
inputMark := options.AutoRedirectInputMark
|
||||
if inputMark == 0 {
|
||||
inputMark = tun.DefaultAutoRedirectInputMark
|
||||
@@ -349,36 +360,37 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
|
||||
}
|
||||
|
||||
tunOptions := tun.Options{
|
||||
Name: tunName,
|
||||
MTU: tunMTU,
|
||||
GSO: options.GSO,
|
||||
Inet4Address: options.Inet4Address,
|
||||
Inet6Address: options.Inet6Address,
|
||||
AutoRoute: options.AutoRoute,
|
||||
IPRoute2TableIndex: tableIndex,
|
||||
IPRoute2RuleIndex: ruleIndex,
|
||||
AutoRedirectInputMark: inputMark,
|
||||
AutoRedirectOutputMark: outputMark,
|
||||
Inet4LoopbackAddress: common.Filter(options.LoopbackAddress, netip.Addr.Is4),
|
||||
Inet6LoopbackAddress: common.Filter(options.LoopbackAddress, netip.Addr.Is6),
|
||||
StrictRoute: options.StrictRoute,
|
||||
Inet4RouteAddress: inet4RouteAddress,
|
||||
Inet6RouteAddress: inet6RouteAddress,
|
||||
Inet4RouteExcludeAddress: inet4RouteExcludeAddress,
|
||||
Inet6RouteExcludeAddress: inet6RouteExcludeAddress,
|
||||
IncludeInterface: options.IncludeInterface,
|
||||
ExcludeInterface: options.ExcludeInterface,
|
||||
IncludeUID: includeUID,
|
||||
ExcludeUID: excludeUID,
|
||||
ExcludeSrcPort: excludeSrcPort,
|
||||
ExcludeDstPort: excludeDstPort,
|
||||
IncludeAndroidUser: options.IncludeAndroidUser,
|
||||
IncludePackage: options.IncludePackage,
|
||||
ExcludePackage: options.ExcludePackage,
|
||||
FileDescriptor: options.FileDescriptor,
|
||||
InterfaceMonitor: defaultInterfaceMonitor,
|
||||
EXP_RecvMsgX: options.RecvMsgX,
|
||||
EXP_SendMsgX: options.SendMsgX,
|
||||
Name: tunName,
|
||||
MTU: tunMTU,
|
||||
GSO: options.GSO,
|
||||
Inet4Address: options.Inet4Address,
|
||||
Inet6Address: options.Inet6Address,
|
||||
AutoRoute: options.AutoRoute,
|
||||
IPRoute2TableIndex: tableIndex,
|
||||
IPRoute2RuleIndex: ruleIndex,
|
||||
IPRoute2AutoRedirectFallbackRuleIndex: autoRedirectFallbackRuleIndex,
|
||||
AutoRedirectInputMark: inputMark,
|
||||
AutoRedirectOutputMark: outputMark,
|
||||
Inet4LoopbackAddress: common.Filter(options.LoopbackAddress, netip.Addr.Is4),
|
||||
Inet6LoopbackAddress: common.Filter(options.LoopbackAddress, netip.Addr.Is6),
|
||||
StrictRoute: options.StrictRoute,
|
||||
Inet4RouteAddress: inet4RouteAddress,
|
||||
Inet6RouteAddress: inet6RouteAddress,
|
||||
Inet4RouteExcludeAddress: inet4RouteExcludeAddress,
|
||||
Inet6RouteExcludeAddress: inet6RouteExcludeAddress,
|
||||
IncludeInterface: options.IncludeInterface,
|
||||
ExcludeInterface: options.ExcludeInterface,
|
||||
IncludeUID: includeUID,
|
||||
ExcludeUID: excludeUID,
|
||||
ExcludeSrcPort: excludeSrcPort,
|
||||
ExcludeDstPort: excludeDstPort,
|
||||
IncludeAndroidUser: options.IncludeAndroidUser,
|
||||
IncludePackage: options.IncludePackage,
|
||||
ExcludePackage: options.ExcludePackage,
|
||||
FileDescriptor: options.FileDescriptor,
|
||||
InterfaceMonitor: defaultInterfaceMonitor,
|
||||
EXP_RecvMsgX: options.RecvMsgX,
|
||||
EXP_SendMsgX: options.SendMsgX,
|
||||
}
|
||||
|
||||
if options.AutoRedirect {
|
||||
@@ -454,16 +466,10 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
|
||||
UDPTimeout: udpTimeout,
|
||||
Handler: handler,
|
||||
Logger: log.SingLogger,
|
||||
ForwarderBindInterface: forwarderBindInterface,
|
||||
InterfaceFinder: interfaceFinder,
|
||||
EnforceBindInterface: EnforceBindInterface,
|
||||
}
|
||||
|
||||
if options.FileDescriptor > 0 {
|
||||
if tunName, err := getTunnelName(int32(options.FileDescriptor)); err != nil {
|
||||
stackOptions.TunOptions.Name = tunName
|
||||
stackOptions.ForwarderBindInterface = true
|
||||
}
|
||||
}
|
||||
l.tunIf = tunIf
|
||||
|
||||
tunStack, err := tun.NewStack(strings.ToLower(options.Stack.String()), stackOptions)
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"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"
|
||||
LC "github.com/metacubex/mihomo/listener/config"
|
||||
"github.com/metacubex/mihomo/listener/sing"
|
||||
@@ -112,6 +114,7 @@ func (l *Listener) handleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbou
|
||||
func (l *Listener) handleUoTSession(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
|
||||
writer := sudoku.NewUoTPacketConn(conn)
|
||||
remoteAddr := conn.RemoteAddr()
|
||||
connID := utils.NewUUIDV4().String() // make a new SNAT key
|
||||
|
||||
for {
|
||||
addrStr, payload, err := sudoku.ReadDatagram(conn)
|
||||
@@ -129,12 +132,13 @@ func (l *Listener) handleUoTSession(conn net.Conn, tunnel C.Tunnel, additions ..
|
||||
continue
|
||||
}
|
||||
|
||||
packet := &uotPacket{
|
||||
cPacket := &uotPacket{
|
||||
payload: payload,
|
||||
writer: writer,
|
||||
rAddr: remoteAddr,
|
||||
}
|
||||
tunnel.HandleUDPPacket(inbound.NewPacket(target, packet, C.SUDOKU, additions...))
|
||||
cPacket.rAddr = N.NewCustomAddr(C.SUDOKU.String(), connID, cPacket.rAddr) // for tunnel's handleUDPConn
|
||||
tunnel.HandleUDPPacket(inbound.NewPacket(target, cPacket, C.SUDOKU, additions...))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/metacubex/mihomo/adapter/inbound"
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"github.com/metacubex/mihomo/component/ca"
|
||||
"github.com/metacubex/mihomo/component/ech"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
@@ -269,20 +271,25 @@ func (l *Listener) handleConn(inMux bool, conn net.Conn, tunnel C.Tunnel, additi
|
||||
l.handler.HandleSocket(target, conn, additions...)
|
||||
case trojan.CommandUDP:
|
||||
pc := trojan.NewPacketConn(conn)
|
||||
remoteAddr := conn.RemoteAddr()
|
||||
connID := utils.NewUUIDV4().String() // make a new SNAT key
|
||||
|
||||
for {
|
||||
data, put, remoteAddr, err := pc.WaitReadFrom()
|
||||
data, put, addr, err := pc.WaitReadFrom()
|
||||
if err != nil {
|
||||
if put != nil {
|
||||
put()
|
||||
}
|
||||
break
|
||||
}
|
||||
target := socks5.ParseAddrToSocksAddr(addr)
|
||||
cPacket := &packet{
|
||||
pc: pc,
|
||||
rAddr: remoteAddr,
|
||||
payload: data,
|
||||
put: put,
|
||||
}
|
||||
cPacket.rAddr = N.NewCustomAddr(C.TROJAN.String(), connID, cPacket.rAddr) // for tunnel's handleUDPConn
|
||||
|
||||
tunnel.HandleUDPPacket(inbound.NewPacket(target, cPacket, C.TROJAN, additions...))
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"strings"
|
||||
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"golang.org/x/net/idna"
|
||||
)
|
||||
|
||||
type Domain struct {
|
||||
@@ -30,10 +29,9 @@ func (d *Domain) Payload() string {
|
||||
}
|
||||
|
||||
func NewDomain(domain string, adapter string) *Domain {
|
||||
punycode, _ := idna.ToASCII(strings.ToLower(domain))
|
||||
return &Domain{
|
||||
Base: Base{},
|
||||
domain: punycode,
|
||||
domain: strings.ToLower(domain),
|
||||
adapter: adapter,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"strings"
|
||||
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"golang.org/x/net/idna"
|
||||
)
|
||||
|
||||
type DomainKeyword struct {
|
||||
@@ -31,10 +30,9 @@ func (dk *DomainKeyword) Payload() string {
|
||||
}
|
||||
|
||||
func NewDomainKeyword(keyword string, adapter string) *DomainKeyword {
|
||||
punycode, _ := idna.ToASCII(strings.ToLower(keyword))
|
||||
return &DomainKeyword{
|
||||
Base: Base{},
|
||||
keyword: punycode,
|
||||
keyword: strings.ToLower(keyword),
|
||||
adapter: adapter,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"strings"
|
||||
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"golang.org/x/net/idna"
|
||||
)
|
||||
|
||||
type DomainSuffix struct {
|
||||
@@ -31,10 +30,9 @@ func (ds *DomainSuffix) Payload() string {
|
||||
}
|
||||
|
||||
func NewDomainSuffix(suffix string, adapter string) *DomainSuffix {
|
||||
punycode, _ := idna.ToASCII(strings.ToLower(suffix))
|
||||
return &DomainSuffix{
|
||||
Base: Base{},
|
||||
suffix: punycode,
|
||||
suffix: strings.ToLower(suffix),
|
||||
adapter: adapter,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
// Package masque
|
||||
// copy and modify from https://github.com/Diniboy1123/usque/blob/d0eb96e7e5c56cce6cf34a7f8d75abbedba58fef/api/masque.go
|
||||
package masque
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
connectip "github.com/metacubex/connect-ip-go"
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/quic-go"
|
||||
"github.com/metacubex/quic-go/http3"
|
||||
"github.com/metacubex/tls"
|
||||
"github.com/yosida95/uritemplate/v3"
|
||||
)
|
||||
|
||||
const (
|
||||
ConnectSNI = "consumer-masque.cloudflareclient.com"
|
||||
ConnectURI = "https://cloudflareaccess.com"
|
||||
)
|
||||
|
||||
// PrepareTlsConfig creates a TLS configuration using the provided certificate and SNI (Server Name Indication).
|
||||
// It also verifies the peer's public key against the provided public key.
|
||||
func PrepareTlsConfig(privKey *ecdsa.PrivateKey, peerPubKey *ecdsa.PublicKey, sni string) (*tls.Config, error) {
|
||||
verfiyCert := func(cert *x509.Certificate) error {
|
||||
if _, ok := cert.PublicKey.(*ecdsa.PublicKey); !ok {
|
||||
// we only support ECDSA
|
||||
// TODO: don't hardcode cert type in the future
|
||||
// as backend can start using different cert types
|
||||
return x509.ErrUnsupportedAlgorithm
|
||||
}
|
||||
|
||||
if !cert.PublicKey.(*ecdsa.PublicKey).Equal(peerPubKey) {
|
||||
// reason is incorrect, but the best I could figure
|
||||
// detail explains the actual reason
|
||||
|
||||
//10 is NoValidChains, but we support go1.22 where it's not defined
|
||||
return x509.CertificateInvalidError{Cert: cert, Reason: 10, Detail: "remote endpoint has a different public key than what we trust"}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
cert, err := GenerateCert(privKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate cert: %v", err)
|
||||
}
|
||||
|
||||
tlsConfig := &tls.Config{
|
||||
Certificates: []tls.Certificate{
|
||||
{
|
||||
Certificate: cert,
|
||||
PrivateKey: privKey,
|
||||
},
|
||||
},
|
||||
ServerName: sni,
|
||||
NextProtos: []string{http3.NextProtoH3},
|
||||
// WARN: SNI is usually not for the endpoint, so we must skip verification
|
||||
InsecureSkipVerify: true,
|
||||
// we pin to the endpoint public key
|
||||
VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||
if len(rawCerts) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var err error
|
||||
for _, v := range rawCerts {
|
||||
cert, er := x509.ParseCertificate(v)
|
||||
if er != nil {
|
||||
err = errors.Join(err, er)
|
||||
continue
|
||||
}
|
||||
|
||||
if er = verfiyCert(cert); er != nil {
|
||||
err = errors.Join(err, er)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
},
|
||||
}
|
||||
|
||||
return tlsConfig, nil
|
||||
}
|
||||
|
||||
func GenerateCert(privKey *ecdsa.PrivateKey) ([][]byte, error) {
|
||||
cert, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{
|
||||
SerialNumber: big.NewInt(0),
|
||||
NotBefore: time.Now(),
|
||||
NotAfter: time.Now().Add(1 * 24 * time.Hour),
|
||||
}, &x509.Certificate{}, &privKey.PublicKey, privKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return [][]byte{cert}, nil
|
||||
}
|
||||
|
||||
// ConnectTunnel establishes a QUIC connection and sets up a Connect-IP tunnel with the provided endpoint.
|
||||
// Endpoint address is used to check whether the authentication/connection is successful or not.
|
||||
// Requires modified connect-ip-go for now to support Cloudflare's non RFC compliant implementation.
|
||||
func ConnectTunnel(ctx context.Context, quicConn *quic.Conn, connectUri string) (*http3.Transport, *connectip.Conn, error) {
|
||||
tr := &http3.Transport{
|
||||
EnableDatagrams: true,
|
||||
AdditionalSettings: map[uint64]uint64{
|
||||
// official client still sends this out as well, even though
|
||||
// it's deprecated, see https://datatracker.ietf.org/doc/draft-ietf-masque-h3-datagram/00/
|
||||
// SETTINGS_H3_DATAGRAM_00 = 0x0000000000000276
|
||||
// https://github.com/cloudflare/quiche/blob/7c66757dbc55b8d0c3653d4b345c6785a181f0b7/quiche/src/h3/frame.rs#L46
|
||||
0x276: 1,
|
||||
},
|
||||
DisableCompression: true,
|
||||
}
|
||||
|
||||
hconn := tr.NewClientConn(quicConn)
|
||||
|
||||
additionalHeaders := http.Header{
|
||||
"User-Agent": []string{""},
|
||||
}
|
||||
|
||||
template := uritemplate.MustNew(connectUri)
|
||||
ipConn, rsp, err := dialEx(ctx, hconn, template, "cf-connect-ip", additionalHeaders, true)
|
||||
if err != nil {
|
||||
_ = tr.Close()
|
||||
if err.Error() == "CRYPTO_ERROR 0x131 (remote): tls: access denied" {
|
||||
return nil, nil, errors.New("login failed! Please double-check if your tls key and cert is enrolled in the Cloudflare Access service")
|
||||
}
|
||||
return nil, nil, fmt.Errorf("failed to dial connect-ip: %v", err)
|
||||
}
|
||||
|
||||
err = ipConn.AdvertiseRoute(ctx, []connectip.IPRoute{
|
||||
{
|
||||
IPProtocol: 0,
|
||||
StartIP: netip.AddrFrom4([4]byte{}),
|
||||
EndIP: netip.AddrFrom4([4]byte{255, 255, 255, 255}),
|
||||
},
|
||||
{
|
||||
IPProtocol: 0,
|
||||
StartIP: netip.AddrFrom16([16]byte{}),
|
||||
EndIP: netip.AddrFrom16([16]byte{
|
||||
255, 255, 255, 255,
|
||||
255, 255, 255, 255,
|
||||
255, 255, 255, 255,
|
||||
255, 255, 255, 255,
|
||||
}),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
_ = ipConn.Close()
|
||||
_ = tr.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if rsp.StatusCode != http.StatusOK {
|
||||
_ = ipConn.Close()
|
||||
_ = tr.Close()
|
||||
return nil, nil, fmt.Errorf("failed to dial connect-ip: %v", rsp.Status)
|
||||
}
|
||||
|
||||
return tr, ipConn, nil
|
||||
}
|
||||
|
||||
// dialEx dials a proxied connection to a target server.
|
||||
func dialEx(ctx context.Context, conn *http3.ClientConn, template *uritemplate.Template, requestProtocol string, additionalHeaders http.Header, ignoreExtendedConnect bool) (*connectip.Conn, *http.Response, error) {
|
||||
if len(template.Varnames()) > 0 {
|
||||
return nil, nil, errors.New("connect-ip: IP flow forwarding not supported")
|
||||
}
|
||||
|
||||
u, err := url.Parse(template.Raw())
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to parse URI: %w", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, nil, context.Cause(ctx)
|
||||
case <-conn.Context().Done():
|
||||
return nil, nil, context.Cause(conn.Context())
|
||||
case <-conn.ReceivedSettings():
|
||||
}
|
||||
settings := conn.Settings()
|
||||
if !ignoreExtendedConnect && !settings.EnableExtendedConnect {
|
||||
return nil, nil, errors.New("connect-ip: server didn't enable Extended CONNECT")
|
||||
}
|
||||
if !settings.EnableDatagrams {
|
||||
return nil, nil, errors.New("connect-ip: server didn't enable datagrams")
|
||||
}
|
||||
|
||||
const capsuleProtocolHeaderValue = "?1"
|
||||
headers := http.Header{http3.CapsuleProtocolHeader: []string{capsuleProtocolHeaderValue}}
|
||||
for k, v := range additionalHeaders {
|
||||
headers[k] = v
|
||||
}
|
||||
|
||||
rstr, err := conn.OpenRequestStream(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to open request stream: %w", err)
|
||||
}
|
||||
if err := rstr.SendRequestHeader(&http.Request{
|
||||
Method: http.MethodConnect,
|
||||
Proto: requestProtocol,
|
||||
Host: u.Host,
|
||||
Header: headers,
|
||||
URL: u,
|
||||
}); err != nil {
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to send request: %w", err)
|
||||
}
|
||||
// TODO: optimistically return the connection
|
||||
rsp, err := rstr.ReadResponse()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to read response: %w", err)
|
||||
}
|
||||
if rsp.StatusCode < 200 || rsp.StatusCode > 299 {
|
||||
return nil, rsp, fmt.Errorf("connect-ip: server responded with %d", rsp.StatusCode)
|
||||
}
|
||||
return connectip.NewProxiedConn(rstr), rsp, nil
|
||||
}
|
||||
@@ -264,7 +264,7 @@ func (pc *packetConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||
pc.wMux.Lock()
|
||||
defer pc.wMux.Unlock()
|
||||
|
||||
return WritePacket(pc, socks5.ParseAddr(addr.String()), b)
|
||||
return WritePacket(pc, socks5.ParseAddrToSocksAddr(addr), b)
|
||||
}
|
||||
|
||||
func (pc *packetConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
|
||||
@@ -32,7 +32,8 @@ type ProtocolConfig struct {
|
||||
PaddingMin int
|
||||
PaddingMax int
|
||||
|
||||
// EnablePureDownlink toggles the bandwidth-optimized downlink mode.
|
||||
// EnablePureDownlink enables the pure Sudoku downlink mode.
|
||||
// When false, the connection uses the bandwidth-optimized packed downlink (requires AEAD).
|
||||
EnablePureDownlink bool
|
||||
|
||||
// Client-only: final target "host:port".
|
||||
@@ -46,7 +47,7 @@ type ProtocolConfig struct {
|
||||
|
||||
// HTTPMaskMode controls how the HTTP layer behaves:
|
||||
// - "legacy": write a fake HTTP/1.1 header then switch to raw stream (default, not CDN-compatible)
|
||||
// - "stream": real HTTP tunnel (stream-one or split), CDN-compatible
|
||||
// - "stream": real HTTP tunnel (split-stream), CDN-compatible
|
||||
// - "poll": plain HTTP tunnel (authorize/push/pull), strong restricted-network pass-through
|
||||
// - "auto": try stream then fall back to poll
|
||||
HTTPMaskMode string
|
||||
@@ -114,7 +115,8 @@ func (c *ProtocolConfig) Validate() error {
|
||||
}
|
||||
|
||||
if v := strings.TrimSpace(c.HTTPMaskPathRoot); v != "" {
|
||||
if strings.Contains(v, "/") {
|
||||
v = strings.Trim(v, "/")
|
||||
if v == "" || strings.Contains(v, "/") {
|
||||
return fmt.Errorf("invalid http-mask-path-root: must be a single path segment")
|
||||
}
|
||||
for i := 0; i < len(v); i++ {
|
||||
|
||||
@@ -22,6 +22,26 @@ type AEADConn struct {
|
||||
nonceSize int
|
||||
}
|
||||
|
||||
func (cc *AEADConn) CloseWrite() error {
|
||||
if cc == nil || cc.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
if cw, ok := cc.Conn.(interface{ CloseWrite() error }); ok {
|
||||
return cw.CloseWrite()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cc *AEADConn) CloseRead() error {
|
||||
if cc == nil || cc.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
if cr, ok := cc.Conn.(interface{ CloseRead() error }); ok {
|
||||
return cr.CloseRead()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewAEADConn(c net.Conn, key string, method string) (*AEADConn, error) {
|
||||
if method == "none" {
|
||||
return &AEADConn{Conn: c, aead: nil}, nil
|
||||
|
||||
@@ -5,113 +5,10 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
sudokuobfs "github.com/metacubex/mihomo/transport/sudoku/obfs/sudoku"
|
||||
)
|
||||
|
||||
type discardConn struct{}
|
||||
|
||||
func (discardConn) Read([]byte) (int, error) { return 0, io.EOF }
|
||||
func (discardConn) Write(p []byte) (int, error) { return len(p), nil }
|
||||
func (discardConn) Close() error { return nil }
|
||||
func (discardConn) LocalAddr() net.Addr { return nil }
|
||||
func (discardConn) RemoteAddr() net.Addr { return nil }
|
||||
func (discardConn) SetDeadline(time.Time) error { return nil }
|
||||
func (discardConn) SetReadDeadline(time.Time) error { return nil }
|
||||
func (discardConn) SetWriteDeadline(time.Time) error { return nil }
|
||||
|
||||
func TestSudokuObfsWriter_ReducesWriteAllocs(t *testing.T) {
|
||||
table := sudokuobfs.NewTable("alloc-seed", "prefer_ascii")
|
||||
w := newSudokuObfsWriter(discardConn{}, table, 0, 0)
|
||||
|
||||
payload := bytes.Repeat([]byte{0x42}, 2048)
|
||||
if _, err := w.Write(payload); err != nil {
|
||||
t.Fatalf("warmup write: %v", err)
|
||||
}
|
||||
|
||||
allocs := testing.AllocsPerRun(100, func() {
|
||||
if _, err := w.Write(payload); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
})
|
||||
if allocs != 0 {
|
||||
t.Fatalf("expected 0 allocs/run, got %.2f", allocs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPMaskStrategy_WebSocketAndPost(t *testing.T) {
|
||||
key := "mask-test-key"
|
||||
target := "1.1.1.1:80"
|
||||
table := sudokuobfs.NewTable("mask-seed", "prefer_ascii")
|
||||
|
||||
base := DefaultConfig()
|
||||
base.Key = key
|
||||
base.AEADMethod = "chacha20-poly1305"
|
||||
base.Table = table
|
||||
base.PaddingMin = 0
|
||||
base.PaddingMax = 0
|
||||
base.EnablePureDownlink = true
|
||||
base.HandshakeTimeoutSeconds = 5
|
||||
base.DisableHTTPMask = false
|
||||
base.ServerAddress = "example.com:443"
|
||||
|
||||
cases := []string{"post", "websocket"}
|
||||
for _, strategy := range cases {
|
||||
t.Run(strategy, func(t *testing.T) {
|
||||
serverConn, clientConn := net.Pipe()
|
||||
defer serverConn.Close()
|
||||
defer clientConn.Close()
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
defer close(errCh)
|
||||
session, err := ServerHandshake(serverConn, base)
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
defer session.Conn.Close()
|
||||
if session.Type != SessionTypeTCP {
|
||||
errCh <- io.ErrUnexpectedEOF
|
||||
return
|
||||
}
|
||||
if session.Target != target {
|
||||
errCh <- io.ErrClosedPipe
|
||||
return
|
||||
}
|
||||
_, _ = session.Conn.Write([]byte("ok"))
|
||||
}()
|
||||
|
||||
cConn, err := ClientHandshakeWithOptions(clientConn, base, ClientHandshakeOptions{HTTPMaskStrategy: strategy})
|
||||
if err != nil {
|
||||
t.Fatalf("client handshake: %v", err)
|
||||
}
|
||||
defer cConn.Close()
|
||||
|
||||
addrBuf, err := EncodeAddress(target)
|
||||
if err != nil {
|
||||
t.Fatalf("encode addr: %v", err)
|
||||
}
|
||||
if _, err := cConn.Write(addrBuf); err != nil {
|
||||
t.Fatalf("write addr: %v", err)
|
||||
}
|
||||
|
||||
buf := make([]byte, 2)
|
||||
if _, err := io.ReadFull(cConn, buf); err != nil {
|
||||
t.Fatalf("read: %v", err)
|
||||
}
|
||||
if string(buf) != "ok" {
|
||||
t.Fatalf("unexpected payload: %q", buf)
|
||||
}
|
||||
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatalf("server: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomTablesRotation_ProbedByServer(t *testing.T) {
|
||||
key := "rotate-test-key"
|
||||
target := "8.8.8.8:53"
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/transport/sudoku/crypto"
|
||||
@@ -69,6 +68,15 @@ type directionalConn struct {
|
||||
closers []func() error
|
||||
}
|
||||
|
||||
func newDirectionalConn(base net.Conn, reader io.Reader, writer io.Writer, closers ...func() error) net.Conn {
|
||||
return &directionalConn{
|
||||
Conn: base,
|
||||
reader: reader,
|
||||
writer: writer,
|
||||
closers: closers,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *directionalConn) Read(p []byte) (int, error) {
|
||||
return c.reader.Read(p)
|
||||
}
|
||||
@@ -113,40 +121,21 @@ func downlinkMode(cfg *ProtocolConfig) byte {
|
||||
}
|
||||
|
||||
func buildClientObfsConn(raw net.Conn, cfg *ProtocolConfig, table *sudoku.Table) net.Conn {
|
||||
baseReader := sudoku.NewConn(raw, table, cfg.PaddingMin, cfg.PaddingMax, false)
|
||||
baseWriter := newSudokuObfsWriter(raw, table, cfg.PaddingMin, cfg.PaddingMax)
|
||||
baseSudoku := sudoku.NewConn(raw, table, cfg.PaddingMin, cfg.PaddingMax, false)
|
||||
if cfg.EnablePureDownlink {
|
||||
return &directionalConn{
|
||||
Conn: raw,
|
||||
reader: baseReader,
|
||||
writer: baseWriter,
|
||||
}
|
||||
return baseSudoku
|
||||
}
|
||||
packed := sudoku.NewPackedConn(raw, table, cfg.PaddingMin, cfg.PaddingMax)
|
||||
return &directionalConn{
|
||||
Conn: raw,
|
||||
reader: packed,
|
||||
writer: baseWriter,
|
||||
}
|
||||
return newDirectionalConn(raw, packed, baseSudoku)
|
||||
}
|
||||
|
||||
func buildServerObfsConn(raw net.Conn, cfg *ProtocolConfig, table *sudoku.Table, record bool) (*sudoku.Conn, net.Conn) {
|
||||
uplink := sudoku.NewConn(raw, table, cfg.PaddingMin, cfg.PaddingMax, record)
|
||||
uplinkSudoku := sudoku.NewConn(raw, table, cfg.PaddingMin, cfg.PaddingMax, record)
|
||||
if cfg.EnablePureDownlink {
|
||||
downlink := &directionalConn{
|
||||
Conn: raw,
|
||||
reader: uplink,
|
||||
writer: newSudokuObfsWriter(raw, table, cfg.PaddingMin, cfg.PaddingMax),
|
||||
}
|
||||
return uplink, downlink
|
||||
return uplinkSudoku, uplinkSudoku
|
||||
}
|
||||
packed := sudoku.NewPackedConn(raw, table, cfg.PaddingMin, cfg.PaddingMax)
|
||||
return uplink, &directionalConn{
|
||||
Conn: raw,
|
||||
reader: uplink,
|
||||
writer: packed,
|
||||
closers: []func() error{packed.Flush},
|
||||
}
|
||||
return uplinkSudoku, newDirectionalConn(raw, uplinkSudoku, packed, packed.Flush)
|
||||
}
|
||||
|
||||
func buildHandshakePayload(key string) [16]byte {
|
||||
@@ -192,19 +181,8 @@ func ClientAEADSeed(key string) string {
|
||||
return key
|
||||
}
|
||||
|
||||
type ClientHandshakeOptions struct {
|
||||
// HTTPMaskStrategy controls how the client generates the HTTP mask header when DisableHTTPMask=false.
|
||||
// Supported: ""/"random" (default), "post", "websocket".
|
||||
HTTPMaskStrategy string
|
||||
}
|
||||
|
||||
// ClientHandshake performs the client-side Sudoku handshake (without sending target address).
|
||||
func ClientHandshake(rawConn net.Conn, cfg *ProtocolConfig) (net.Conn, error) {
|
||||
return ClientHandshakeWithOptions(rawConn, cfg, ClientHandshakeOptions{})
|
||||
}
|
||||
|
||||
// ClientHandshakeWithOptions performs the client-side Sudoku handshake (without sending target address).
|
||||
func ClientHandshakeWithOptions(rawConn net.Conn, cfg *ProtocolConfig, opt ClientHandshakeOptions) (net.Conn, error) {
|
||||
if cfg == nil {
|
||||
return nil, fmt.Errorf("config is required")
|
||||
}
|
||||
@@ -213,7 +191,7 @@ func ClientHandshakeWithOptions(rawConn net.Conn, cfg *ProtocolConfig, opt Clien
|
||||
}
|
||||
|
||||
if !cfg.DisableHTTPMask {
|
||||
if err := WriteHTTPMaskHeader(rawConn, cfg.ServerAddress, cfg.HTTPMaskPathRoot, opt.HTTPMaskStrategy); err != nil {
|
||||
if err := httpmask.WriteRandomRequestHeaderWithPathRoot(rawConn, cfg.ServerAddress, cfg.HTTPMaskPathRoot); err != nil {
|
||||
return nil, fmt.Errorf("write http mask failed: %w", err)
|
||||
}
|
||||
}
|
||||
@@ -363,18 +341,6 @@ func GenKeyPair() (privateKey, publicKey string, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func normalizeHTTPMaskStrategy(strategy string) string {
|
||||
s := strings.TrimSpace(strings.ToLower(strategy))
|
||||
switch s {
|
||||
case "", "random":
|
||||
return "random"
|
||||
case "ws":
|
||||
return "websocket"
|
||||
default:
|
||||
return s
|
||||
}
|
||||
}
|
||||
|
||||
func userHashFromHandshake(handshakeBuf []byte) string {
|
||||
if len(handshakeBuf) < 16 {
|
||||
return ""
|
||||
|
||||
@@ -1,214 +0,0 @@
|
||||
package sudoku
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/transport/sudoku/obfs/httpmask"
|
||||
)
|
||||
|
||||
var (
|
||||
httpMaskUserAgents = []string{
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15",
|
||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
}
|
||||
httpMaskAccepts = []string{
|
||||
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
||||
"application/json, text/plain, */*",
|
||||
"application/octet-stream",
|
||||
"*/*",
|
||||
}
|
||||
httpMaskAcceptLanguages = []string{
|
||||
"en-US,en;q=0.9",
|
||||
"zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
}
|
||||
httpMaskAcceptEncodings = []string{
|
||||
"gzip, deflate, br",
|
||||
"gzip, deflate",
|
||||
}
|
||||
httpMaskPaths = []string{
|
||||
"/api/v1/upload",
|
||||
"/data/sync",
|
||||
"/v1/telemetry",
|
||||
"/session",
|
||||
"/ws",
|
||||
}
|
||||
httpMaskContentTypes = []string{
|
||||
"application/octet-stream",
|
||||
"application/json",
|
||||
}
|
||||
)
|
||||
|
||||
var (
|
||||
httpMaskRngPool = sync.Pool{
|
||||
New: func() any { return rand.New(rand.NewSource(time.Now().UnixNano())) },
|
||||
}
|
||||
httpMaskBufPool = sync.Pool{
|
||||
New: func() any {
|
||||
b := make([]byte, 0, 1024)
|
||||
return &b
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
func trimPortForHost(host string) string {
|
||||
if host == "" {
|
||||
return host
|
||||
}
|
||||
h, _, err := net.SplitHostPort(host)
|
||||
if err == nil && h != "" {
|
||||
return h
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func appendCommonHeaders(buf []byte, host string, r *rand.Rand) []byte {
|
||||
ua := httpMaskUserAgents[r.Intn(len(httpMaskUserAgents))]
|
||||
accept := httpMaskAccepts[r.Intn(len(httpMaskAccepts))]
|
||||
lang := httpMaskAcceptLanguages[r.Intn(len(httpMaskAcceptLanguages))]
|
||||
enc := httpMaskAcceptEncodings[r.Intn(len(httpMaskAcceptEncodings))]
|
||||
|
||||
buf = append(buf, "Host: "...)
|
||||
buf = append(buf, host...)
|
||||
buf = append(buf, "\r\nUser-Agent: "...)
|
||||
buf = append(buf, ua...)
|
||||
buf = append(buf, "\r\nAccept: "...)
|
||||
buf = append(buf, accept...)
|
||||
buf = append(buf, "\r\nAccept-Language: "...)
|
||||
buf = append(buf, lang...)
|
||||
buf = append(buf, "\r\nAccept-Encoding: "...)
|
||||
buf = append(buf, enc...)
|
||||
buf = append(buf, "\r\nConnection: keep-alive\r\n"...)
|
||||
buf = append(buf, "Cache-Control: no-cache\r\nPragma: no-cache\r\n"...)
|
||||
return buf
|
||||
}
|
||||
|
||||
// WriteHTTPMaskHeader writes an HTTP/1.x request header as a mask, according to strategy.
|
||||
// Supported strategies: ""/"random", "post", "websocket".
|
||||
func WriteHTTPMaskHeader(w io.Writer, host string, pathRoot string, strategy string) error {
|
||||
switch normalizeHTTPMaskStrategy(strategy) {
|
||||
case "random":
|
||||
return httpmask.WriteRandomRequestHeaderWithPathRoot(w, host, pathRoot)
|
||||
case "post":
|
||||
return writeHTTPMaskPOST(w, host, pathRoot)
|
||||
case "websocket":
|
||||
return writeHTTPMaskWebSocket(w, host, pathRoot)
|
||||
default:
|
||||
return fmt.Errorf("unsupported http-mask-strategy: %s", strategy)
|
||||
}
|
||||
}
|
||||
|
||||
func writeHTTPMaskPOST(w io.Writer, host string, pathRoot string) error {
|
||||
r := httpMaskRngPool.Get().(*rand.Rand)
|
||||
defer httpMaskRngPool.Put(r)
|
||||
|
||||
path := joinPathRoot(pathRoot, httpMaskPaths[r.Intn(len(httpMaskPaths))])
|
||||
ctype := httpMaskContentTypes[r.Intn(len(httpMaskContentTypes))]
|
||||
|
||||
bufPtr := httpMaskBufPool.Get().(*[]byte)
|
||||
buf := *bufPtr
|
||||
buf = buf[:0]
|
||||
defer func() {
|
||||
if cap(buf) <= 4096 {
|
||||
*bufPtr = buf
|
||||
httpMaskBufPool.Put(bufPtr)
|
||||
}
|
||||
}()
|
||||
|
||||
const minCL = int64(4 * 1024)
|
||||
const maxCL = int64(10 * 1024 * 1024)
|
||||
contentLength := minCL + r.Int63n(maxCL-minCL+1)
|
||||
|
||||
buf = append(buf, "POST "...)
|
||||
buf = append(buf, path...)
|
||||
buf = append(buf, " HTTP/1.1\r\n"...)
|
||||
buf = appendCommonHeaders(buf, host, r)
|
||||
buf = append(buf, "Content-Type: "...)
|
||||
buf = append(buf, ctype...)
|
||||
buf = append(buf, "\r\nContent-Length: "...)
|
||||
buf = strconv.AppendInt(buf, contentLength, 10)
|
||||
buf = append(buf, "\r\n\r\n"...)
|
||||
|
||||
_, err := w.Write(buf)
|
||||
return err
|
||||
}
|
||||
|
||||
func writeHTTPMaskWebSocket(w io.Writer, host string, pathRoot string) error {
|
||||
r := httpMaskRngPool.Get().(*rand.Rand)
|
||||
defer httpMaskRngPool.Put(r)
|
||||
|
||||
path := joinPathRoot(pathRoot, httpMaskPaths[r.Intn(len(httpMaskPaths))])
|
||||
|
||||
bufPtr := httpMaskBufPool.Get().(*[]byte)
|
||||
buf := *bufPtr
|
||||
buf = buf[:0]
|
||||
defer func() {
|
||||
if cap(buf) <= 4096 {
|
||||
*bufPtr = buf
|
||||
httpMaskBufPool.Put(bufPtr)
|
||||
}
|
||||
}()
|
||||
|
||||
hostNoPort := trimPortForHost(host)
|
||||
var keyBytes [16]byte
|
||||
for i := 0; i < len(keyBytes); i++ {
|
||||
keyBytes[i] = byte(r.Intn(256))
|
||||
}
|
||||
var wsKey [24]byte
|
||||
base64.StdEncoding.Encode(wsKey[:], keyBytes[:])
|
||||
|
||||
buf = append(buf, "GET "...)
|
||||
buf = append(buf, path...)
|
||||
buf = append(buf, " HTTP/1.1\r\n"...)
|
||||
buf = appendCommonHeaders(buf, host, r)
|
||||
buf = append(buf, "Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: "...)
|
||||
buf = append(buf, wsKey[:]...)
|
||||
buf = append(buf, "\r\nOrigin: https://"...)
|
||||
buf = append(buf, hostNoPort...)
|
||||
buf = append(buf, "\r\n\r\n"...)
|
||||
|
||||
_, err := w.Write(buf)
|
||||
return err
|
||||
}
|
||||
|
||||
func normalizePathRoot(root string) string {
|
||||
root = strings.TrimSpace(root)
|
||||
root = strings.Trim(root, "/")
|
||||
if root == "" {
|
||||
return ""
|
||||
}
|
||||
for i := 0; i < len(root); i++ {
|
||||
c := root[i]
|
||||
switch {
|
||||
case c >= 'a' && c <= 'z':
|
||||
case c >= 'A' && c <= 'Z':
|
||||
case c >= '0' && c <= '9':
|
||||
case c == '_' || c == '-':
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return "/" + root
|
||||
}
|
||||
|
||||
func joinPathRoot(root, path string) string {
|
||||
root = normalizePathRoot(root)
|
||||
if root == "" {
|
||||
return path
|
||||
}
|
||||
if path == "" {
|
||||
return root
|
||||
}
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
path = "/" + path
|
||||
}
|
||||
return root + path
|
||||
}
|
||||
@@ -383,7 +383,11 @@ func (c *stream) enqueue(payload []byte) {
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
c.queue = append(c.queue, payload)
|
||||
if len(c.readBuf) == 0 && len(c.queue) == 0 {
|
||||
c.readBuf = payload
|
||||
} else {
|
||||
c.queue = append(c.queue, payload)
|
||||
}
|
||||
c.cond.Signal()
|
||||
c.mu.Unlock()
|
||||
}
|
||||
@@ -491,6 +495,9 @@ func (c *stream) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *stream) CloseWrite() error { return c.Close() }
|
||||
func (c *stream) CloseRead() error { return c.Close() }
|
||||
|
||||
func (c *stream) LocalAddr() net.Addr { return c.localAddr }
|
||||
func (c *stream) RemoteAddr() net.Addr { return c.remoteAddr }
|
||||
|
||||
@@ -501,4 +508,3 @@ func (c *stream) SetDeadline(t time.Time) error {
|
||||
}
|
||||
func (c *stream) SetReadDeadline(time.Time) error { return nil }
|
||||
func (c *stream) SetWriteDeadline(time.Time) error { return nil }
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"github.com/metacubex/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
const (
|
||||
tunnelAuthHeaderKey = "Authorization"
|
||||
tunnelAuthHeaderPrefix = "Bearer "
|
||||
tunnelAuthQueryKey = "auth"
|
||||
)
|
||||
|
||||
type tunnelAuth struct {
|
||||
@@ -61,8 +63,15 @@ func (a *tunnelAuth) verify(headers map[string]string, mode TunnelMode, method,
|
||||
if headers == nil {
|
||||
return false
|
||||
}
|
||||
return a.verifyValue(headers["authorization"], mode, method, path, now)
|
||||
}
|
||||
|
||||
val := strings.TrimSpace(headers["authorization"])
|
||||
func (a *tunnelAuth) verifyValue(val string, mode TunnelMode, method, path string, now time.Time) bool {
|
||||
if a == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
val = strings.TrimSpace(val)
|
||||
if val == "" {
|
||||
return false
|
||||
}
|
||||
@@ -121,11 +130,9 @@ func (a *tunnelAuth) sign(mode TunnelMode, method, path string, ts int64) [16]by
|
||||
return out
|
||||
}
|
||||
|
||||
type headerSetter interface {
|
||||
Set(key, value string)
|
||||
}
|
||||
type httpHeaderSetter = http.Header
|
||||
|
||||
func applyTunnelAuthHeader(h headerSetter, auth *tunnelAuth, mode TunnelMode, method, path string) {
|
||||
func applyTunnelAuthHeader(h httpHeaderSetter, auth *tunnelAuth, mode TunnelMode, method, path string) {
|
||||
if auth == nil || h == nil {
|
||||
return
|
||||
}
|
||||
@@ -135,3 +142,19 @@ func applyTunnelAuthHeader(h headerSetter, auth *tunnelAuth, mode TunnelMode, me
|
||||
}
|
||||
h.Set(tunnelAuthHeaderKey, tunnelAuthHeaderPrefix+token)
|
||||
}
|
||||
|
||||
func applyTunnelAuth(req *http.Request, auth *tunnelAuth, mode TunnelMode, method, path string) {
|
||||
if auth == nil || req == nil {
|
||||
return
|
||||
}
|
||||
token := auth.token(mode, method, path, time.Now())
|
||||
if token == "" {
|
||||
return
|
||||
}
|
||||
req.Header.Set(tunnelAuthHeaderKey, tunnelAuthHeaderPrefix+token)
|
||||
if req.URL != nil {
|
||||
q := req.URL.Query()
|
||||
q.Set(tunnelAuthQueryKey, token)
|
||||
req.URL.RawQuery = q.Encode()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package httpmask
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type pipeDeadline struct {
|
||||
mu sync.Mutex
|
||||
timer *time.Timer
|
||||
cancel chan struct{}
|
||||
}
|
||||
|
||||
func makePipeDeadline() pipeDeadline {
|
||||
return pipeDeadline{cancel: make(chan struct{})}
|
||||
}
|
||||
|
||||
func (d *pipeDeadline) set(t time.Time) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
if d.timer != nil && !d.timer.Stop() {
|
||||
<-d.cancel
|
||||
}
|
||||
d.timer = nil
|
||||
|
||||
closed := isClosedPipeChan(d.cancel)
|
||||
if t.IsZero() {
|
||||
if closed {
|
||||
d.cancel = make(chan struct{})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if dur := time.Until(t); dur > 0 {
|
||||
if closed {
|
||||
d.cancel = make(chan struct{})
|
||||
}
|
||||
d.timer = time.AfterFunc(dur, func() {
|
||||
close(d.cancel)
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if !closed {
|
||||
close(d.cancel)
|
||||
}
|
||||
}
|
||||
|
||||
func (d *pipeDeadline) wait() <-chan struct{} {
|
||||
d.mu.Lock()
|
||||
ch := d.cancel
|
||||
d.mu.Unlock()
|
||||
return ch
|
||||
}
|
||||
|
||||
func isClosedPipeChan(ch <-chan struct{}) bool {
|
||||
select {
|
||||
case <-ch:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
type halfPipeAddr struct{}
|
||||
|
||||
func (halfPipeAddr) Network() string { return "pipe" }
|
||||
func (halfPipeAddr) String() string { return "pipe" }
|
||||
|
||||
type halfPipeConn struct {
|
||||
wrMu sync.Mutex
|
||||
|
||||
rdRx <-chan []byte
|
||||
rdTx chan<- int
|
||||
|
||||
wrTx chan<- []byte
|
||||
wrRx <-chan int
|
||||
|
||||
readOnce sync.Once
|
||||
writeOnce sync.Once
|
||||
|
||||
localReadDone chan struct{}
|
||||
localWriteDone chan struct{}
|
||||
|
||||
remoteReadDone <-chan struct{}
|
||||
remoteWriteDone <-chan struct{}
|
||||
|
||||
readDeadline pipeDeadline
|
||||
writeDeadline pipeDeadline
|
||||
}
|
||||
|
||||
func newHalfPipe() (net.Conn, net.Conn) {
|
||||
cb1 := make(chan []byte)
|
||||
cb2 := make(chan []byte)
|
||||
cn1 := make(chan int)
|
||||
cn2 := make(chan int)
|
||||
|
||||
r1 := make(chan struct{})
|
||||
w1 := make(chan struct{})
|
||||
r2 := make(chan struct{})
|
||||
w2 := make(chan struct{})
|
||||
|
||||
c1 := &halfPipeConn{
|
||||
rdRx: cb1,
|
||||
rdTx: cn1,
|
||||
wrTx: cb2,
|
||||
wrRx: cn2,
|
||||
|
||||
localReadDone: r1,
|
||||
localWriteDone: w1,
|
||||
remoteReadDone: r2,
|
||||
remoteWriteDone: w2,
|
||||
|
||||
readDeadline: makePipeDeadline(),
|
||||
writeDeadline: makePipeDeadline(),
|
||||
}
|
||||
c2 := &halfPipeConn{
|
||||
rdRx: cb2,
|
||||
rdTx: cn2,
|
||||
wrTx: cb1,
|
||||
wrRx: cn1,
|
||||
|
||||
localReadDone: r2,
|
||||
localWriteDone: w2,
|
||||
remoteReadDone: r1,
|
||||
remoteWriteDone: w1,
|
||||
|
||||
readDeadline: makePipeDeadline(),
|
||||
writeDeadline: makePipeDeadline(),
|
||||
}
|
||||
return c1, c2
|
||||
}
|
||||
|
||||
func (*halfPipeConn) LocalAddr() net.Addr { return halfPipeAddr{} }
|
||||
func (*halfPipeConn) RemoteAddr() net.Addr { return halfPipeAddr{} }
|
||||
|
||||
func (c *halfPipeConn) Read(p []byte) (int, error) {
|
||||
switch {
|
||||
case isClosedPipeChan(c.localReadDone):
|
||||
return 0, io.ErrClosedPipe
|
||||
case isClosedPipeChan(c.remoteWriteDone):
|
||||
return 0, io.EOF
|
||||
case isClosedPipeChan(c.readDeadline.wait()):
|
||||
return 0, os.ErrDeadlineExceeded
|
||||
}
|
||||
|
||||
select {
|
||||
case b := <-c.rdRx:
|
||||
n := copy(p, b)
|
||||
c.rdTx <- n
|
||||
return n, nil
|
||||
case <-c.localReadDone:
|
||||
return 0, io.ErrClosedPipe
|
||||
case <-c.remoteWriteDone:
|
||||
return 0, io.EOF
|
||||
case <-c.readDeadline.wait():
|
||||
return 0, os.ErrDeadlineExceeded
|
||||
}
|
||||
}
|
||||
|
||||
func (c *halfPipeConn) Write(p []byte) (int, error) {
|
||||
switch {
|
||||
case isClosedPipeChan(c.localWriteDone):
|
||||
return 0, io.ErrClosedPipe
|
||||
case isClosedPipeChan(c.remoteReadDone):
|
||||
return 0, io.ErrClosedPipe
|
||||
case isClosedPipeChan(c.writeDeadline.wait()):
|
||||
return 0, os.ErrDeadlineExceeded
|
||||
}
|
||||
|
||||
c.wrMu.Lock()
|
||||
defer c.wrMu.Unlock()
|
||||
|
||||
var (
|
||||
total int
|
||||
rest = p
|
||||
)
|
||||
for once := true; once || len(rest) > 0; once = false {
|
||||
select {
|
||||
case c.wrTx <- rest:
|
||||
n := <-c.wrRx
|
||||
rest = rest[n:]
|
||||
total += n
|
||||
case <-c.localWriteDone:
|
||||
return total, io.ErrClosedPipe
|
||||
case <-c.remoteReadDone:
|
||||
return total, io.ErrClosedPipe
|
||||
case <-c.writeDeadline.wait():
|
||||
return total, os.ErrDeadlineExceeded
|
||||
}
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
func (c *halfPipeConn) CloseWrite() error {
|
||||
c.writeOnce.Do(func() { close(c.localWriteDone) })
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *halfPipeConn) CloseRead() error {
|
||||
c.readOnce.Do(func() { close(c.localReadDone) })
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *halfPipeConn) Close() error {
|
||||
_ = c.CloseRead()
|
||||
_ = c.CloseWrite()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *halfPipeConn) SetDeadline(t time.Time) error {
|
||||
c.readDeadline.set(t)
|
||||
c.writeDeadline.set(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *halfPipeConn) SetReadDeadline(t time.Time) error {
|
||||
c.readDeadline.set(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *halfPipeConn) SetWriteDeadline(t time.Time) error {
|
||||
c.writeDeadline.set(t)
|
||||
return nil
|
||||
}
|
||||
@@ -241,38 +241,6 @@ func parseTunnelToken(body []byte) (string, error) {
|
||||
return token, nil
|
||||
}
|
||||
|
||||
type httpStreamConn struct {
|
||||
reader io.ReadCloser
|
||||
writer *io.PipeWriter
|
||||
cancel context.CancelFunc
|
||||
|
||||
localAddr net.Addr
|
||||
remoteAddr net.Addr
|
||||
}
|
||||
|
||||
func (c *httpStreamConn) Read(p []byte) (int, error) { return c.reader.Read(p) }
|
||||
func (c *httpStreamConn) Write(p []byte) (int, error) { return c.writer.Write(p) }
|
||||
|
||||
func (c *httpStreamConn) Close() error {
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
}
|
||||
if c.writer != nil {
|
||||
_ = c.writer.CloseWithError(io.ErrClosedPipe)
|
||||
}
|
||||
if c.reader != nil {
|
||||
return c.reader.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *httpStreamConn) LocalAddr() net.Addr { return c.localAddr }
|
||||
func (c *httpStreamConn) RemoteAddr() net.Addr { return c.remoteAddr }
|
||||
|
||||
func (c *httpStreamConn) SetDeadline(time.Time) error { return nil }
|
||||
func (c *httpStreamConn) SetReadDeadline(time.Time) error { return nil }
|
||||
func (c *httpStreamConn) SetWriteDeadline(time.Time) error { return nil }
|
||||
|
||||
type httpClientTarget struct {
|
||||
scheme string
|
||||
urlHost string
|
||||
@@ -332,6 +300,7 @@ type sessionDialInfo struct {
|
||||
client *http.Client
|
||||
pushURL string
|
||||
pullURL string
|
||||
finURL string
|
||||
closeURL string
|
||||
headerHost string
|
||||
auth *tunnelAuth
|
||||
@@ -350,7 +319,7 @@ func dialSessionWithClient(ctx context.Context, client *http.Client, target http
|
||||
}
|
||||
req.Host = target.headerHost
|
||||
applyTunnelHeaders(req.Header, target.headerHost, mode)
|
||||
applyTunnelAuthHeader(req.Header, auth, mode, http.MethodGet, "/session")
|
||||
applyTunnelAuth(req, auth, mode, http.MethodGet, "/session")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
@@ -375,12 +344,14 @@ func dialSessionWithClient(ctx context.Context, client *http.Client, target http
|
||||
|
||||
pushURL := (&url.URL{Scheme: target.scheme, Host: target.urlHost, Path: joinPathRoot(opts.PathRoot, "/api/v1/upload"), RawQuery: "token=" + url.QueryEscape(token)}).String()
|
||||
pullURL := (&url.URL{Scheme: target.scheme, Host: target.urlHost, Path: joinPathRoot(opts.PathRoot, "/stream"), RawQuery: "token=" + url.QueryEscape(token)}).String()
|
||||
finURL := (&url.URL{Scheme: target.scheme, Host: target.urlHost, Path: joinPathRoot(opts.PathRoot, "/api/v1/upload"), RawQuery: "token=" + url.QueryEscape(token) + "&fin=1"}).String()
|
||||
closeURL := (&url.URL{Scheme: target.scheme, Host: target.urlHost, Path: joinPathRoot(opts.PathRoot, "/api/v1/upload"), RawQuery: "token=" + url.QueryEscape(token) + "&close=1"}).String()
|
||||
|
||||
return &sessionDialInfo{
|
||||
client: client,
|
||||
pushURL: pushURL,
|
||||
pullURL: pullURL,
|
||||
finURL: finURL,
|
||||
closeURL: closeURL,
|
||||
headerHost: target.headerHost,
|
||||
auth: auth,
|
||||
@@ -409,7 +380,31 @@ func bestEffortCloseSession(client *http.Client, closeURL, headerHost string, mo
|
||||
}
|
||||
req.Host = headerHost
|
||||
applyTunnelHeaders(req.Header, headerHost, mode)
|
||||
applyTunnelAuthHeader(req.Header, auth, mode, http.MethodPost, "/api/v1/upload")
|
||||
applyTunnelAuth(req, auth, mode, http.MethodPost, "/api/v1/upload")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil || resp == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024))
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
|
||||
func bestEffortCloseWriteSession(client *http.Client, finURL, headerHost string, mode TunnelMode, auth *tunnelAuth) {
|
||||
if client == nil || finURL == "" || headerHost == "" {
|
||||
return
|
||||
}
|
||||
|
||||
closeCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(closeCtx, http.MethodPost, finURL, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req.Host = headerHost
|
||||
applyTunnelHeaders(req.Header, headerHost, mode)
|
||||
applyTunnelAuth(req, auth, mode, http.MethodPost, "/api/v1/upload")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil || resp == nil {
|
||||
@@ -420,160 +415,13 @@ func bestEffortCloseSession(client *http.Client, closeURL, headerHost string, mo
|
||||
}
|
||||
|
||||
func dialStreamWithClient(ctx context.Context, client *http.Client, target httpClientTarget, opts TunnelDialOptions) (net.Conn, error) {
|
||||
// Prefer split-session (Cloudflare-friendly). Fall back to stream-one for older servers / environments.
|
||||
c, errSplit := dialStreamSplitWithClient(ctx, client, target, opts)
|
||||
if errSplit == nil {
|
||||
return c, nil
|
||||
}
|
||||
c2, errOne := dialStreamOneWithClient(ctx, client, target, opts)
|
||||
if errOne == nil {
|
||||
return c2, nil
|
||||
}
|
||||
return nil, fmt.Errorf("dial stream failed: split: %v; stream-one: %w", errSplit, errOne)
|
||||
// "stream" mode uses split-stream to stay CDN-friendly by default.
|
||||
return dialStreamSplitWithClient(ctx, client, target, opts)
|
||||
}
|
||||
|
||||
func dialStream(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) {
|
||||
// Prefer split-session (Cloudflare-friendly). Fall back to stream-one for older servers / environments.
|
||||
c, errSplit := dialStreamSplit(ctx, serverAddress, opts)
|
||||
if errSplit == nil {
|
||||
return c, nil
|
||||
}
|
||||
c2, errOne := dialStreamOne(ctx, serverAddress, opts)
|
||||
if errOne == nil {
|
||||
return c2, nil
|
||||
}
|
||||
return nil, fmt.Errorf("dial stream failed: split: %v; stream-one: %w", errSplit, errOne)
|
||||
}
|
||||
|
||||
func dialStreamOneWithClient(ctx context.Context, client *http.Client, target httpClientTarget, opts TunnelDialOptions) (net.Conn, error) {
|
||||
if client == nil {
|
||||
return nil, fmt.Errorf("nil http client")
|
||||
}
|
||||
|
||||
auth := newTunnelAuth(opts.AuthKey, 0)
|
||||
r := rngPool.Get().(*mrand.Rand)
|
||||
basePath := paths[r.Intn(len(paths))]
|
||||
path := joinPathRoot(opts.PathRoot, basePath)
|
||||
ctype := contentTypes[r.Intn(len(contentTypes))]
|
||||
rngPool.Put(r)
|
||||
|
||||
u := url.URL{
|
||||
Scheme: target.scheme,
|
||||
Host: target.urlHost,
|
||||
Path: path,
|
||||
}
|
||||
|
||||
reqBodyR, reqBodyW := io.Pipe()
|
||||
|
||||
connCtx, connCancel := context.WithCancel(context.Background())
|
||||
req, err := http.NewRequestWithContext(connCtx, http.MethodPost, u.String(), reqBodyR)
|
||||
if err != nil {
|
||||
connCancel()
|
||||
_ = reqBodyW.Close()
|
||||
return nil, err
|
||||
}
|
||||
req.Host = target.headerHost
|
||||
|
||||
applyTunnelHeaders(req.Header, target.headerHost, TunnelModeStream)
|
||||
applyTunnelAuthHeader(req.Header, auth, TunnelModeStream, http.MethodPost, basePath)
|
||||
req.Header.Set("Content-Type", ctype)
|
||||
|
||||
type doResult struct {
|
||||
resp *http.Response
|
||||
err error
|
||||
}
|
||||
doCh := make(chan doResult, 1)
|
||||
go func() {
|
||||
resp, doErr := client.Do(req)
|
||||
doCh <- doResult{resp: resp, err: doErr}
|
||||
}()
|
||||
|
||||
streamConn := &httpStreamConn{
|
||||
writer: reqBodyW,
|
||||
cancel: connCancel,
|
||||
localAddr: &net.TCPAddr{},
|
||||
remoteAddr: &net.TCPAddr{},
|
||||
}
|
||||
|
||||
type upgradeResult struct {
|
||||
conn net.Conn
|
||||
err error
|
||||
}
|
||||
upgradeCh := make(chan upgradeResult, 1)
|
||||
if opts.Upgrade == nil {
|
||||
upgradeCh <- upgradeResult{conn: streamConn, err: nil}
|
||||
} else {
|
||||
go func() {
|
||||
upgradeConn, err := opts.Upgrade(streamConn)
|
||||
if err != nil {
|
||||
upgradeCh <- upgradeResult{conn: nil, err: err}
|
||||
return
|
||||
}
|
||||
if upgradeConn == nil {
|
||||
upgradeConn = streamConn
|
||||
}
|
||||
upgradeCh <- upgradeResult{conn: upgradeConn, err: nil}
|
||||
}()
|
||||
}
|
||||
|
||||
var (
|
||||
outConn net.Conn
|
||||
upgradeDone bool
|
||||
responseReady bool
|
||||
)
|
||||
|
||||
for !(upgradeDone && responseReady) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
_ = streamConn.Close()
|
||||
if outConn != nil && outConn != streamConn {
|
||||
_ = outConn.Close()
|
||||
}
|
||||
return nil, ctx.Err()
|
||||
|
||||
case u := <-upgradeCh:
|
||||
if u.err != nil {
|
||||
_ = streamConn.Close()
|
||||
return nil, u.err
|
||||
}
|
||||
outConn = u.conn
|
||||
if outConn == nil {
|
||||
outConn = streamConn
|
||||
}
|
||||
upgradeDone = true
|
||||
|
||||
case r := <-doCh:
|
||||
if r.err != nil {
|
||||
_ = streamConn.Close()
|
||||
if outConn != nil && outConn != streamConn {
|
||||
_ = outConn.Close()
|
||||
}
|
||||
return nil, r.err
|
||||
}
|
||||
if r.resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(io.LimitReader(r.resp.Body, 4*1024))
|
||||
_ = r.resp.Body.Close()
|
||||
_ = streamConn.Close()
|
||||
if outConn != nil && outConn != streamConn {
|
||||
_ = outConn.Close()
|
||||
}
|
||||
return nil, fmt.Errorf("stream bad status: %s (%s)", r.resp.Status, strings.TrimSpace(string(body)))
|
||||
}
|
||||
|
||||
streamConn.reader = r.resp.Body
|
||||
responseReady = true
|
||||
}
|
||||
}
|
||||
|
||||
return outConn, nil
|
||||
}
|
||||
|
||||
func dialStreamOne(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) {
|
||||
client, target, err := newHTTPClient(serverAddress, opts, 32)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dialStreamOneWithClient(ctx, client, target, opts)
|
||||
// "stream" mode uses split-stream to stay CDN-friendly by default.
|
||||
return dialStreamSplit(ctx, serverAddress, opts)
|
||||
}
|
||||
|
||||
type queuedConn struct {
|
||||
@@ -581,6 +429,9 @@ type queuedConn struct {
|
||||
closed chan struct{}
|
||||
|
||||
writeCh chan []byte
|
||||
// writeClosed is closed by CloseWrite to stop accepting new payloads.
|
||||
// When closed, Write returns io.ErrClosedPipe, but Read is unaffected.
|
||||
writeClosed chan struct{}
|
||||
|
||||
mu sync.Mutex
|
||||
readBuf []byte
|
||||
@@ -589,6 +440,18 @@ type queuedConn struct {
|
||||
remoteAddr net.Addr
|
||||
}
|
||||
|
||||
func (c *queuedConn) CloseWrite() error {
|
||||
if c == nil || c.writeClosed == nil {
|
||||
return nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
if !isClosedPipeChan(c.writeClosed) {
|
||||
close(c.writeClosed)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *queuedConn) closeWithError(err error) error {
|
||||
c.mu.Lock()
|
||||
select {
|
||||
@@ -640,6 +503,9 @@ func (c *queuedConn) Write(b []byte) (n int, err error) {
|
||||
case <-c.closed:
|
||||
c.mu.Unlock()
|
||||
return 0, c.closedErr()
|
||||
case <-c.writeClosed:
|
||||
c.mu.Unlock()
|
||||
return 0, io.ErrClosedPipe
|
||||
default:
|
||||
}
|
||||
c.mu.Unlock()
|
||||
@@ -651,6 +517,8 @@ func (c *queuedConn) Write(b []byte) (n int, err error) {
|
||||
return len(b), nil
|
||||
case <-c.closed:
|
||||
return 0, c.closedErr()
|
||||
case <-c.writeClosed:
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
}
|
||||
|
||||
@@ -670,6 +538,7 @@ type streamSplitConn struct {
|
||||
client *http.Client
|
||||
pushURL string
|
||||
pullURL string
|
||||
finURL string
|
||||
closeURL string
|
||||
headerHost string
|
||||
auth *tunnelAuth
|
||||
@@ -697,15 +566,17 @@ func newStreamSplitConnFromInfo(info *sessionDialInfo) *streamSplitConn {
|
||||
client: info.client,
|
||||
pushURL: info.pushURL,
|
||||
pullURL: info.pullURL,
|
||||
finURL: info.finURL,
|
||||
closeURL: info.closeURL,
|
||||
headerHost: info.headerHost,
|
||||
auth: info.auth,
|
||||
queuedConn: queuedConn{
|
||||
rxc: make(chan []byte, 256),
|
||||
closed: make(chan struct{}),
|
||||
writeCh: make(chan []byte, 256),
|
||||
localAddr: &net.TCPAddr{},
|
||||
remoteAddr: &net.TCPAddr{},
|
||||
rxc: make(chan []byte, 256),
|
||||
closed: make(chan struct{}),
|
||||
writeCh: make(chan []byte, 256),
|
||||
writeClosed: make(chan struct{}),
|
||||
localAddr: &net.TCPAddr{},
|
||||
remoteAddr: &net.TCPAddr{},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -793,7 +664,7 @@ func (c *streamSplitConn) pullLoop() {
|
||||
}
|
||||
req.Host = c.headerHost
|
||||
applyTunnelHeaders(req.Header, c.headerHost, TunnelModeStream)
|
||||
applyTunnelAuthHeader(req.Header, c.auth, TunnelModeStream, http.MethodGet, "/stream")
|
||||
applyTunnelAuth(req, c.auth, TunnelModeStream, http.MethodGet, "/stream")
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
@@ -891,7 +762,7 @@ func (c *streamSplitConn) pushLoop() {
|
||||
}
|
||||
req.Host = c.headerHost
|
||||
applyTunnelHeaders(req.Header, c.headerHost, TunnelModeStream)
|
||||
applyTunnelAuthHeader(req.Header, c.auth, TunnelModeStream, http.MethodPost, "/api/v1/upload")
|
||||
applyTunnelAuth(req, c.auth, TunnelModeStream, http.MethodPost, "/api/v1/upload")
|
||||
req.Header.Set("Content-Type", "application/octet-stream")
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
@@ -977,6 +848,27 @@ func (c *streamSplitConn) pushLoop() {
|
||||
return
|
||||
}
|
||||
resetTimer()
|
||||
case <-c.writeClosed:
|
||||
// Drain any already-accepted writes so CloseWrite does not lose data.
|
||||
for {
|
||||
select {
|
||||
case b := <-c.writeCh:
|
||||
if len(b) == 0 {
|
||||
continue
|
||||
}
|
||||
if buf.Len()+len(b) > maxBatchBytes {
|
||||
if err := flushWithRetry(); err != nil {
|
||||
_ = c.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
_, _ = buf.Write(b)
|
||||
default:
|
||||
_ = flushWithRetry()
|
||||
bestEffortCloseWriteSession(c.client, c.finURL, c.headerHost, TunnelModeStream, c.auth)
|
||||
return
|
||||
}
|
||||
}
|
||||
case <-c.closed:
|
||||
_ = flushWithRetry()
|
||||
return
|
||||
@@ -993,6 +885,7 @@ type pollConn struct {
|
||||
client *http.Client
|
||||
pushURL string
|
||||
pullURL string
|
||||
finURL string
|
||||
closeURL string
|
||||
headerHost string
|
||||
auth *tunnelAuth
|
||||
@@ -1037,15 +930,17 @@ func newPollConnFromInfo(info *sessionDialInfo) *pollConn {
|
||||
client: info.client,
|
||||
pushURL: info.pushURL,
|
||||
pullURL: info.pullURL,
|
||||
finURL: info.finURL,
|
||||
closeURL: info.closeURL,
|
||||
headerHost: info.headerHost,
|
||||
auth: info.auth,
|
||||
queuedConn: queuedConn{
|
||||
rxc: make(chan []byte, 128),
|
||||
closed: make(chan struct{}),
|
||||
writeCh: make(chan []byte, 256),
|
||||
localAddr: &net.TCPAddr{},
|
||||
remoteAddr: &net.TCPAddr{},
|
||||
rxc: make(chan []byte, 128),
|
||||
closed: make(chan struct{}),
|
||||
writeCh: make(chan []byte, 256),
|
||||
writeClosed: make(chan struct{}),
|
||||
localAddr: &net.TCPAddr{},
|
||||
remoteAddr: &net.TCPAddr{},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1117,14 +1012,14 @@ func (c *pollConn) pullLoop() {
|
||||
default:
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, c.pullURL, nil)
|
||||
req, err := http.NewRequestWithContext(c.ctx, http.MethodGet, c.pullURL, nil)
|
||||
if err != nil {
|
||||
_ = c.Close()
|
||||
return
|
||||
}
|
||||
req.Host = c.headerHost
|
||||
applyTunnelHeaders(req.Header, c.headerHost, TunnelModePoll)
|
||||
applyTunnelAuthHeader(req.Header, c.auth, TunnelModePoll, http.MethodGet, "/stream")
|
||||
applyTunnelAuth(req, c.auth, TunnelModePoll, http.MethodGet, "/stream")
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
@@ -1202,21 +1097,25 @@ func (c *pollConn) pushLoop() {
|
||||
return nil
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, c.pushURL, bytes.NewReader(buf.Bytes()))
|
||||
reqCtx, cancel := context.WithTimeout(c.ctx, 20*time.Second)
|
||||
req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, c.pushURL, bytes.NewReader(buf.Bytes()))
|
||||
if err != nil {
|
||||
cancel()
|
||||
return err
|
||||
}
|
||||
req.Host = c.headerHost
|
||||
applyTunnelHeaders(req.Header, c.headerHost, TunnelModePoll)
|
||||
applyTunnelAuthHeader(req.Header, c.auth, TunnelModePoll, http.MethodPost, "/api/v1/upload")
|
||||
applyTunnelAuth(req, c.auth, TunnelModePoll, http.MethodPost, "/api/v1/upload")
|
||||
req.Header.Set("Content-Type", "text/plain")
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return err
|
||||
}
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024))
|
||||
_ = resp.Body.Close()
|
||||
cancel()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("bad status: %s", resp.Status)
|
||||
}
|
||||
@@ -1309,6 +1208,41 @@ func (c *pollConn) pushLoop() {
|
||||
return
|
||||
}
|
||||
resetTimer()
|
||||
case <-c.writeClosed:
|
||||
// Drain any already-accepted writes so CloseWrite does not lose data.
|
||||
for {
|
||||
select {
|
||||
case b := <-c.writeCh:
|
||||
if len(b) == 0 {
|
||||
continue
|
||||
}
|
||||
for len(b) > 0 {
|
||||
chunk := b
|
||||
if len(chunk) > maxLineRawBytes {
|
||||
chunk = b[:maxLineRawBytes]
|
||||
}
|
||||
b = b[len(chunk):]
|
||||
|
||||
encLen := base64.StdEncoding.EncodedLen(len(chunk))
|
||||
if pendingRaw+len(chunk) > maxBatchBytes || buf.Len()+encLen+1 > maxBatchBytes*2 {
|
||||
if err := flushWithRetry(); err != nil {
|
||||
_ = c.closeWithError(fmt.Errorf("poll push flush failed: %w", err))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
tmp := make([]byte, base64.StdEncoding.EncodedLen(len(chunk)))
|
||||
base64.StdEncoding.Encode(tmp, chunk)
|
||||
buf.Write(tmp)
|
||||
buf.WriteByte('\n')
|
||||
pendingRaw += len(chunk)
|
||||
}
|
||||
default:
|
||||
_ = flushWithRetry()
|
||||
bestEffortCloseWriteSession(c.client, c.finURL, c.headerHost, TunnelModePoll, c.auth)
|
||||
return
|
||||
}
|
||||
}
|
||||
case <-c.closed:
|
||||
_ = flushWithRetry()
|
||||
return
|
||||
@@ -1478,19 +1412,50 @@ func (s *TunnelServer) HandleConn(rawConn net.Conn) (HandleResult, net.Conn, err
|
||||
|
||||
tunnelHeader := strings.ToLower(strings.TrimSpace(req.headers["x-sudoku-tunnel"]))
|
||||
if tunnelHeader == "" {
|
||||
// Not our tunnel; replay full bytes to legacy handler.
|
||||
prefix := make([]byte, 0, len(headerBytes)+len(buffered))
|
||||
prefix = append(prefix, headerBytes...)
|
||||
prefix = append(prefix, buffered...)
|
||||
return HandlePassThrough, newPreBufferedConn(rawConn, prefix), nil
|
||||
}
|
||||
if s.mode == TunnelModeLegacy {
|
||||
if s.passThroughOnReject {
|
||||
// Some CDNs / forward proxies may strip unknown headers. When AuthKey is enabled, we can
|
||||
// safely infer the intended tunnel mode by verifying the Authorization token against
|
||||
// both stream/poll modes and picking the one that matches.
|
||||
if s.auth != nil {
|
||||
u, err := url.ParseRequestURI(req.target)
|
||||
if err == nil {
|
||||
path, ok := stripPathRoot(s.pathRoot, u.Path)
|
||||
if ok && s.isAllowedBasePath(path) {
|
||||
authVal := req.headers["authorization"]
|
||||
if authVal == "" {
|
||||
authVal = u.Query().Get(tunnelAuthQueryKey)
|
||||
}
|
||||
streamOK := s.auth.verifyValue(authVal, TunnelModeStream, req.method, path, time.Now())
|
||||
pollOK := s.auth.verifyValue(authVal, TunnelModePoll, req.method, path, time.Now())
|
||||
switch {
|
||||
case streamOK && !pollOK:
|
||||
tunnelHeader = string(TunnelModeStream)
|
||||
case pollOK && !streamOK:
|
||||
tunnelHeader = string(TunnelModePoll)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if tunnelHeader == "" {
|
||||
// Not our tunnel; replay full bytes to legacy handler.
|
||||
prefix := make([]byte, 0, len(headerBytes)+len(buffered))
|
||||
prefix = append(prefix, headerBytes...)
|
||||
prefix = append(prefix, buffered...)
|
||||
return HandlePassThrough, newPreBufferedConn(rawConn, prefix), nil
|
||||
}
|
||||
}
|
||||
|
||||
reject := func() (HandleResult, net.Conn, error) {
|
||||
prefix := make([]byte, 0, len(headerBytes)+len(buffered))
|
||||
prefix = append(prefix, headerBytes...)
|
||||
prefix = append(prefix, buffered...)
|
||||
return HandlePassThrough, newRejectedPreBufferedConn(rawConn, prefix), nil
|
||||
}
|
||||
|
||||
if s.mode == TunnelModeLegacy {
|
||||
if s.passThroughOnReject {
|
||||
return reject()
|
||||
}
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusNotFound, "not found")
|
||||
_ = rawConn.Close()
|
||||
return HandleDone, nil, nil
|
||||
@@ -1500,10 +1465,7 @@ func (s *TunnelServer) HandleConn(rawConn net.Conn) (HandleResult, net.Conn, err
|
||||
case TunnelModeStream:
|
||||
if s.mode != TunnelModeStream && s.mode != TunnelModeAuto {
|
||||
if s.passThroughOnReject {
|
||||
prefix := make([]byte, 0, len(headerBytes)+len(buffered))
|
||||
prefix = append(prefix, headerBytes...)
|
||||
prefix = append(prefix, buffered...)
|
||||
return HandlePassThrough, newPreBufferedConn(rawConn, prefix), nil
|
||||
return reject()
|
||||
}
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusNotFound, "not found")
|
||||
_ = rawConn.Close()
|
||||
@@ -1513,10 +1475,7 @@ func (s *TunnelServer) HandleConn(rawConn net.Conn) (HandleResult, net.Conn, err
|
||||
case TunnelModePoll:
|
||||
if s.mode != TunnelModePoll && s.mode != TunnelModeAuto {
|
||||
if s.passThroughOnReject {
|
||||
prefix := make([]byte, 0, len(headerBytes)+len(buffered))
|
||||
prefix = append(prefix, headerBytes...)
|
||||
prefix = append(prefix, buffered...)
|
||||
return HandlePassThrough, newPreBufferedConn(rawConn, prefix), nil
|
||||
return reject()
|
||||
}
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusNotFound, "not found")
|
||||
_ = rawConn.Close()
|
||||
@@ -1525,10 +1484,7 @@ func (s *TunnelServer) HandleConn(rawConn net.Conn) (HandleResult, net.Conn, err
|
||||
return s.handlePoll(rawConn, req, headerBytes, buffered)
|
||||
default:
|
||||
if s.passThroughOnReject {
|
||||
prefix := make([]byte, 0, len(headerBytes)+len(buffered))
|
||||
prefix = append(prefix, headerBytes...)
|
||||
prefix = append(prefix, buffered...)
|
||||
return HandlePassThrough, newPreBufferedConn(rawConn, prefix), nil
|
||||
return reject()
|
||||
}
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusNotFound, "not found")
|
||||
_ = rawConn.Close()
|
||||
@@ -1619,13 +1575,52 @@ func readAllBuffered(r *bufio.Reader) []byte {
|
||||
|
||||
type preBufferedConn struct {
|
||||
net.Conn
|
||||
buf []byte
|
||||
buf []byte
|
||||
recorded []byte
|
||||
rejected bool
|
||||
}
|
||||
|
||||
func newPreBufferedConn(conn net.Conn, pre []byte) net.Conn {
|
||||
func (p *preBufferedConn) CloseWrite() error {
|
||||
if p == nil || p.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
if cw, ok := p.Conn.(interface{ CloseWrite() error }); ok {
|
||||
return cw.CloseWrite()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *preBufferedConn) CloseRead() error {
|
||||
if p == nil || p.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
if cr, ok := p.Conn.(interface{ CloseRead() error }); ok {
|
||||
return cr.CloseRead()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newPreBufferedConn(conn net.Conn, pre []byte) *preBufferedConn {
|
||||
cpy := make([]byte, len(pre))
|
||||
copy(cpy, pre)
|
||||
return &preBufferedConn{Conn: conn, buf: cpy}
|
||||
return &preBufferedConn{Conn: conn, buf: cpy, recorded: cpy}
|
||||
}
|
||||
|
||||
func newRejectedPreBufferedConn(conn net.Conn, pre []byte) *preBufferedConn {
|
||||
c := newPreBufferedConn(conn, pre)
|
||||
c.rejected = true
|
||||
return c
|
||||
}
|
||||
|
||||
func (p *preBufferedConn) IsHTTPMaskRejected() bool { return p.rejected }
|
||||
|
||||
func (p *preBufferedConn) GetBufferedAndRecorded() []byte {
|
||||
if len(p.recorded) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]byte, len(p.recorded))
|
||||
copy(out, p.recorded)
|
||||
return out
|
||||
}
|
||||
|
||||
func (p *preBufferedConn) Read(b []byte) (int, error) {
|
||||
@@ -1682,7 +1677,7 @@ func (s *TunnelServer) handleStream(rawConn net.Conn, req *httpRequestHeader, he
|
||||
prefix := make([]byte, 0, len(headerBytes)+len(buffered))
|
||||
prefix = append(prefix, headerBytes...)
|
||||
prefix = append(prefix, buffered...)
|
||||
return HandlePassThrough, newPreBufferedConn(rawConn, prefix), nil
|
||||
return HandlePassThrough, newRejectedPreBufferedConn(rawConn, prefix), nil
|
||||
}
|
||||
_ = writeSimpleHTTPResponse(rawConn, code, body)
|
||||
_ = rawConn.Close()
|
||||
@@ -1699,21 +1694,29 @@ func (s *TunnelServer) handleStream(rawConn net.Conn, req *httpRequestHeader, he
|
||||
if !ok || !s.isAllowedBasePath(path) {
|
||||
return rejectOrReply(http.StatusNotFound, "not found")
|
||||
}
|
||||
if !s.auth.verify(req.headers, TunnelModeStream, req.method, path, time.Now()) {
|
||||
authVal := req.headers["authorization"]
|
||||
if authVal == "" {
|
||||
authVal = u.Query().Get(tunnelAuthQueryKey)
|
||||
}
|
||||
if !s.auth.verifyValue(authVal, TunnelModeStream, req.method, path, time.Now()) {
|
||||
return rejectOrReply(http.StatusNotFound, "not found")
|
||||
}
|
||||
|
||||
token := u.Query().Get("token")
|
||||
closeFlag := u.Query().Get("close") == "1"
|
||||
finFlag := u.Query().Get("fin") == "1"
|
||||
|
||||
switch strings.ToUpper(req.method) {
|
||||
case http.MethodGet:
|
||||
// Stream split-session: GET /session (no token) => token + start tunnel on a server-side pipe.
|
||||
if token == "" && path == "/session" {
|
||||
return s.authorizeSession(rawConn)
|
||||
return s.sessionAuthorize(rawConn)
|
||||
}
|
||||
// Stream split-session: GET /stream?token=... => downlink poll.
|
||||
if token != "" && path == "/stream" {
|
||||
if s.passThroughOnReject && !s.sessionHas(token) {
|
||||
return rejectOrReply(http.StatusNotFound, "not found")
|
||||
}
|
||||
return s.streamPull(rawConn, token)
|
||||
}
|
||||
return rejectOrReply(http.StatusBadRequest, "bad request")
|
||||
@@ -1721,13 +1724,26 @@ func (s *TunnelServer) handleStream(rawConn net.Conn, req *httpRequestHeader, he
|
||||
case http.MethodPost:
|
||||
// Stream split-session: POST /api/v1/upload?token=... => uplink push.
|
||||
if token != "" && path == "/api/v1/upload" {
|
||||
if s.passThroughOnReject && !s.sessionHas(token) {
|
||||
return rejectOrReply(http.StatusNotFound, "not found")
|
||||
}
|
||||
if closeFlag {
|
||||
s.closeSession(token)
|
||||
return rejectOrReply(http.StatusOK, "")
|
||||
s.sessionClose(token)
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusOK, "")
|
||||
_ = rawConn.Close()
|
||||
return HandleDone, nil, nil
|
||||
}
|
||||
if finFlag {
|
||||
s.sessionCloseWrite(token)
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusOK, "")
|
||||
_ = rawConn.Close()
|
||||
return HandleDone, nil, nil
|
||||
}
|
||||
bodyReader, err := newRequestBodyReader(newPreBufferedConn(rawConn, buffered), req.headers)
|
||||
if err != nil {
|
||||
return rejectOrReply(http.StatusBadRequest, "bad request")
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusBadRequest, "bad request")
|
||||
_ = rawConn.Close()
|
||||
return HandleDone, nil, nil
|
||||
}
|
||||
return s.streamPush(rawConn, token, bodyReader)
|
||||
}
|
||||
@@ -1825,7 +1841,7 @@ func (s *TunnelServer) handlePoll(rawConn net.Conn, req *httpRequestHeader, head
|
||||
prefix := make([]byte, 0, len(headerBytes)+len(buffered))
|
||||
prefix = append(prefix, headerBytes...)
|
||||
prefix = append(prefix, buffered...)
|
||||
return HandlePassThrough, newPreBufferedConn(rawConn, prefix), nil
|
||||
return HandlePassThrough, newRejectedPreBufferedConn(rawConn, prefix), nil
|
||||
}
|
||||
_ = writeSimpleHTTPResponse(rawConn, code, body)
|
||||
_ = rawConn.Close()
|
||||
@@ -1841,18 +1857,26 @@ func (s *TunnelServer) handlePoll(rawConn net.Conn, req *httpRequestHeader, head
|
||||
if !ok || !s.isAllowedBasePath(path) {
|
||||
return rejectOrReply(http.StatusNotFound, "not found")
|
||||
}
|
||||
if !s.auth.verify(req.headers, TunnelModePoll, req.method, path, time.Now()) {
|
||||
authVal := req.headers["authorization"]
|
||||
if authVal == "" {
|
||||
authVal = u.Query().Get(tunnelAuthQueryKey)
|
||||
}
|
||||
if !s.auth.verifyValue(authVal, TunnelModePoll, req.method, path, time.Now()) {
|
||||
return rejectOrReply(http.StatusNotFound, "not found")
|
||||
}
|
||||
|
||||
token := u.Query().Get("token")
|
||||
closeFlag := u.Query().Get("close") == "1"
|
||||
finFlag := u.Query().Get("fin") == "1"
|
||||
switch strings.ToUpper(req.method) {
|
||||
case http.MethodGet:
|
||||
if token == "" && path == "/session" {
|
||||
return s.authorizeSession(rawConn)
|
||||
return s.sessionAuthorize(rawConn)
|
||||
}
|
||||
if token != "" && path == "/stream" {
|
||||
if s.passThroughOnReject && !s.sessionHas(token) {
|
||||
return rejectOrReply(http.StatusNotFound, "not found")
|
||||
}
|
||||
return s.pollPull(rawConn, token)
|
||||
}
|
||||
return rejectOrReply(http.StatusBadRequest, "bad request")
|
||||
@@ -1860,13 +1884,26 @@ func (s *TunnelServer) handlePoll(rawConn net.Conn, req *httpRequestHeader, head
|
||||
if token == "" || path != "/api/v1/upload" {
|
||||
return rejectOrReply(http.StatusBadRequest, "bad request")
|
||||
}
|
||||
if s.passThroughOnReject && !s.sessionHas(token) {
|
||||
return rejectOrReply(http.StatusNotFound, "not found")
|
||||
}
|
||||
if closeFlag {
|
||||
s.closeSession(token)
|
||||
return rejectOrReply(http.StatusOK, "")
|
||||
s.sessionClose(token)
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusOK, "")
|
||||
_ = rawConn.Close()
|
||||
return HandleDone, nil, nil
|
||||
}
|
||||
if finFlag {
|
||||
s.sessionCloseWrite(token)
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusOK, "")
|
||||
_ = rawConn.Close()
|
||||
return HandleDone, nil, nil
|
||||
}
|
||||
bodyReader, err := newRequestBodyReader(newPreBufferedConn(rawConn, buffered), req.headers)
|
||||
if err != nil {
|
||||
return rejectOrReply(http.StatusBadRequest, "bad request")
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusBadRequest, "bad request")
|
||||
_ = rawConn.Close()
|
||||
return HandleDone, nil, nil
|
||||
}
|
||||
return s.pollPush(rawConn, token, bodyReader)
|
||||
default:
|
||||
@@ -1874,7 +1911,7 @@ func (s *TunnelServer) handlePoll(rawConn net.Conn, req *httpRequestHeader, head
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TunnelServer) authorizeSession(rawConn net.Conn) (HandleResult, net.Conn, error) {
|
||||
func (s *TunnelServer) sessionAuthorize(rawConn net.Conn) (HandleResult, net.Conn, error) {
|
||||
token, err := newSessionToken()
|
||||
if err != nil {
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusInternalServerError, "internal error")
|
||||
@@ -1882,13 +1919,13 @@ func (s *TunnelServer) authorizeSession(rawConn net.Conn) (HandleResult, net.Con
|
||||
return HandleDone, nil, nil
|
||||
}
|
||||
|
||||
c1, c2 := net.Pipe()
|
||||
c1, c2 := newHalfPipe()
|
||||
|
||||
s.mu.Lock()
|
||||
s.sessions[token] = &tunnelSession{conn: c2, lastActive: time.Now()}
|
||||
s.mu.Unlock()
|
||||
|
||||
go s.reapSessionLater(token)
|
||||
go s.reapLater(token)
|
||||
|
||||
_ = writeTokenHTTPResponse(rawConn, token)
|
||||
_ = rawConn.Close()
|
||||
@@ -1903,31 +1940,50 @@ func newSessionToken() (string, error) {
|
||||
return base64.RawURLEncoding.EncodeToString(b[:]), nil
|
||||
}
|
||||
|
||||
func (s *TunnelServer) reapSessionLater(token string) {
|
||||
func (s *TunnelServer) reapLater(token string) {
|
||||
ttl := s.sessionTTL
|
||||
if ttl <= 0 {
|
||||
return
|
||||
}
|
||||
|
||||
timer := time.NewTimer(ttl)
|
||||
defer timer.Stop()
|
||||
<-timer.C
|
||||
|
||||
s.mu.Lock()
|
||||
sess, ok := s.sessions[token]
|
||||
if !ok {
|
||||
for {
|
||||
<-timer.C
|
||||
|
||||
s.mu.Lock()
|
||||
sess, ok := s.sessions[token]
|
||||
if !ok {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
idle := time.Since(sess.lastActive)
|
||||
if idle >= ttl {
|
||||
delete(s.sessions, token)
|
||||
s.mu.Unlock()
|
||||
_ = sess.conn.Close()
|
||||
return
|
||||
}
|
||||
next := ttl - idle
|
||||
s.mu.Unlock()
|
||||
return
|
||||
|
||||
// Avoid a tight loop under high-frequency activity; we only need best-effort cleanup.
|
||||
if next < 50*time.Millisecond {
|
||||
next = 50 * time.Millisecond
|
||||
}
|
||||
timer.Reset(next)
|
||||
}
|
||||
if time.Since(sess.lastActive) < ttl {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
delete(s.sessions, token)
|
||||
s.mu.Unlock()
|
||||
_ = sess.conn.Close()
|
||||
}
|
||||
|
||||
func (s *TunnelServer) getSession(token string) (*tunnelSession, bool) {
|
||||
func (s *TunnelServer) sessionHas(token string) bool {
|
||||
s.mu.Lock()
|
||||
_, ok := s.sessions[token]
|
||||
s.mu.Unlock()
|
||||
return ok
|
||||
}
|
||||
|
||||
func (s *TunnelServer) sessionGet(token string) (*tunnelSession, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
sess, ok := s.sessions[token]
|
||||
@@ -1938,7 +1994,7 @@ func (s *TunnelServer) getSession(token string) (*tunnelSession, bool) {
|
||||
return sess, true
|
||||
}
|
||||
|
||||
func (s *TunnelServer) closeSession(token string) {
|
||||
func (s *TunnelServer) sessionClose(token string) {
|
||||
s.mu.Lock()
|
||||
sess, ok := s.sessions[token]
|
||||
if ok {
|
||||
@@ -1950,8 +2006,20 @@ func (s *TunnelServer) closeSession(token string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TunnelServer) sessionCloseWrite(token string) {
|
||||
sess, ok := s.sessionGet(token)
|
||||
if !ok || sess == nil || sess.conn == nil {
|
||||
return
|
||||
}
|
||||
if cw, ok := sess.conn.(interface{ CloseWrite() error }); ok {
|
||||
_ = cw.CloseWrite()
|
||||
return
|
||||
}
|
||||
_ = sess.conn.Close()
|
||||
}
|
||||
|
||||
func (s *TunnelServer) pollPush(rawConn net.Conn, token string, body io.Reader) (HandleResult, net.Conn, error) {
|
||||
sess, ok := s.getSession(token)
|
||||
sess, ok := s.sessionGet(token)
|
||||
if !ok {
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusForbidden, "forbidden")
|
||||
_ = rawConn.Close()
|
||||
@@ -1985,7 +2053,7 @@ func (s *TunnelServer) pollPush(rawConn net.Conn, token string, body io.Reader)
|
||||
_, werr := sess.conn.Write(decoded[:n])
|
||||
_ = sess.conn.SetWriteDeadline(time.Time{})
|
||||
if werr != nil {
|
||||
s.closeSession(token)
|
||||
s.sessionClose(token)
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusGone, "gone")
|
||||
_ = rawConn.Close()
|
||||
return HandleDone, nil, nil
|
||||
@@ -1998,7 +2066,7 @@ func (s *TunnelServer) pollPush(rawConn net.Conn, token string, body io.Reader)
|
||||
}
|
||||
|
||||
func (s *TunnelServer) streamPush(rawConn net.Conn, token string, body io.Reader) (HandleResult, net.Conn, error) {
|
||||
sess, ok := s.getSession(token)
|
||||
sess, ok := s.sessionGet(token)
|
||||
if !ok {
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusForbidden, "forbidden")
|
||||
_ = rawConn.Close()
|
||||
@@ -2023,7 +2091,7 @@ func (s *TunnelServer) streamPush(rawConn net.Conn, token string, body io.Reader
|
||||
_, werr := sess.conn.Write(payload)
|
||||
_ = sess.conn.SetWriteDeadline(time.Time{})
|
||||
if werr != nil {
|
||||
s.closeSession(token)
|
||||
s.sessionClose(token)
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusGone, "gone")
|
||||
_ = rawConn.Close()
|
||||
return HandleDone, nil, nil
|
||||
@@ -2036,7 +2104,7 @@ func (s *TunnelServer) streamPush(rawConn net.Conn, token string, body io.Reader
|
||||
}
|
||||
|
||||
func (s *TunnelServer) streamPull(rawConn net.Conn, token string) (HandleResult, net.Conn, error) {
|
||||
sess, ok := s.getSession(token)
|
||||
sess, ok := s.sessionGet(token)
|
||||
if !ok {
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusForbidden, "forbidden")
|
||||
_ = rawConn.Close()
|
||||
@@ -2074,14 +2142,14 @@ func (s *TunnelServer) streamPull(rawConn net.Conn, token string) (HandleResult,
|
||||
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe) || errors.Is(err, net.ErrClosed) {
|
||||
return HandleDone, nil, nil
|
||||
}
|
||||
s.closeSession(token)
|
||||
s.sessionClose(token)
|
||||
return HandleDone, nil, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TunnelServer) pollPull(rawConn net.Conn, token string) (HandleResult, net.Conn, error) {
|
||||
sess, ok := s.getSession(token)
|
||||
sess, ok := s.sessionGet(token)
|
||||
if !ok {
|
||||
_ = writeSimpleHTTPResponse(rawConn, http.StatusForbidden, "forbidden")
|
||||
_ = rawConn.Close()
|
||||
@@ -2123,7 +2191,7 @@ func (s *TunnelServer) pollPull(rawConn net.Conn, token string) (HandleResult, n
|
||||
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe) || errors.Is(err, net.ErrClosed) {
|
||||
return HandleDone, nil, nil
|
||||
}
|
||||
s.closeSession(token)
|
||||
s.sessionClose(token)
|
||||
return HandleDone, nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,8 +52,28 @@ type Conn struct {
|
||||
pendingData []byte
|
||||
hintBuf []byte
|
||||
|
||||
rng *rand.Rand
|
||||
paddingRate float32
|
||||
rng *rand.Rand
|
||||
paddingThreshold uint64
|
||||
}
|
||||
|
||||
func (sc *Conn) CloseWrite() error {
|
||||
if sc == nil || sc.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
if cw, ok := sc.Conn.(interface{ CloseWrite() error }); ok {
|
||||
return cw.CloseWrite()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sc *Conn) CloseRead() error {
|
||||
if sc == nil || sc.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
if cr, ok := sc.Conn.(interface{ CloseRead() error }); ok {
|
||||
return cr.CloseRead()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewConn(c net.Conn, table *Table, pMin, pMax int, record bool) *Conn {
|
||||
@@ -64,19 +84,15 @@ func NewConn(c net.Conn, table *Table, pMin, pMax int, record bool) *Conn {
|
||||
seed := int64(binary.BigEndian.Uint64(seedBytes[:]))
|
||||
localRng := rand.New(rand.NewSource(seed))
|
||||
|
||||
min := float32(pMin) / 100.0
|
||||
rng := float32(pMax-pMin) / 100.0
|
||||
rate := min + localRng.Float32()*rng
|
||||
|
||||
sc := &Conn{
|
||||
Conn: c,
|
||||
table: table,
|
||||
reader: bufio.NewReaderSize(c, IOBufferSize),
|
||||
rawBuf: make([]byte, IOBufferSize),
|
||||
pendingData: make([]byte, 0, 4096),
|
||||
hintBuf: make([]byte, 0, 4),
|
||||
rng: localRng,
|
||||
paddingRate: rate,
|
||||
Conn: c,
|
||||
table: table,
|
||||
reader: bufio.NewReaderSize(c, IOBufferSize),
|
||||
rawBuf: make([]byte, IOBufferSize),
|
||||
pendingData: make([]byte, 0, 4096),
|
||||
hintBuf: make([]byte, 0, 4),
|
||||
rng: localRng,
|
||||
paddingThreshold: pickPaddingThreshold(localRng, pMin, pMax),
|
||||
}
|
||||
if record {
|
||||
sc.recorder = new(bytes.Buffer)
|
||||
@@ -127,7 +143,7 @@ func (sc *Conn) Write(p []byte) (n int, err error) {
|
||||
padLen := len(pads)
|
||||
|
||||
for _, b := range p {
|
||||
if sc.rng.Float32() < sc.paddingRate {
|
||||
if shouldPad(sc.rng, sc.paddingThreshold) {
|
||||
out = append(out, pads[sc.rng.Intn(padLen)])
|
||||
}
|
||||
|
||||
@@ -136,14 +152,14 @@ func (sc *Conn) Write(p []byte) (n int, err error) {
|
||||
|
||||
perm := perm4[sc.rng.Intn(len(perm4))]
|
||||
for _, idx := range perm {
|
||||
if sc.rng.Float32() < sc.paddingRate {
|
||||
if shouldPad(sc.rng, sc.paddingThreshold) {
|
||||
out = append(out, pads[sc.rng.Intn(padLen)])
|
||||
}
|
||||
out = append(out, puzzle[idx])
|
||||
}
|
||||
}
|
||||
|
||||
if sc.rng.Float32() < sc.paddingRate {
|
||||
if shouldPad(sc.rng, sc.paddingThreshold) {
|
||||
out = append(out, pads[sc.rng.Intn(padLen)])
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ const (
|
||||
)
|
||||
|
||||
// 1. 使用 12字节->16组 的块处理优化 Write (减少循环开销)
|
||||
// 2. 使用浮点随机概率判断 Padding,与纯 Sudoku 保持流量特征一致
|
||||
// 2. 使用整数阈值随机概率判断 Padding,与纯 Sudoku 保持流量特征一致
|
||||
// 3. Read 使用 copy 移动避免底层数组泄漏
|
||||
type PackedConn struct {
|
||||
net.Conn
|
||||
@@ -37,11 +37,31 @@ type PackedConn struct {
|
||||
readBitBuf uint64
|
||||
readBits int
|
||||
|
||||
// 随机数与填充控制 - 使用浮点随机,与 Conn 一致
|
||||
rng *rand.Rand
|
||||
paddingRate float32 // 与 Conn 保持一致的随机概率模型
|
||||
padMarker byte
|
||||
padPool []byte
|
||||
// 随机数与填充控制 - 使用整数阈值随机,与 Conn 一致
|
||||
rng *rand.Rand
|
||||
paddingThreshold uint64 // 与 Conn 保持一致的随机概率模型
|
||||
padMarker byte
|
||||
padPool []byte
|
||||
}
|
||||
|
||||
func (pc *PackedConn) CloseWrite() error {
|
||||
if pc == nil || pc.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
if cw, ok := pc.Conn.(interface{ CloseWrite() error }); ok {
|
||||
return cw.CloseWrite()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pc *PackedConn) CloseRead() error {
|
||||
if pc == nil || pc.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
if cr, ok := pc.Conn.(interface{ CloseRead() error }); ok {
|
||||
return cr.CloseRead()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewPackedConn(c net.Conn, table *Table, pMin, pMax int) *PackedConn {
|
||||
@@ -52,20 +72,15 @@ func NewPackedConn(c net.Conn, table *Table, pMin, pMax int) *PackedConn {
|
||||
seed := int64(binary.BigEndian.Uint64(seedBytes[:]))
|
||||
localRng := rand.New(rand.NewSource(seed))
|
||||
|
||||
// 与 Conn 保持一致的 padding 概率计算
|
||||
min := float32(pMin) / 100.0
|
||||
rng := float32(pMax-pMin) / 100.0
|
||||
rate := min + localRng.Float32()*rng
|
||||
|
||||
pc := &PackedConn{
|
||||
Conn: c,
|
||||
table: table,
|
||||
reader: bufio.NewReaderSize(c, IOBufferSize),
|
||||
rawBuf: make([]byte, IOBufferSize),
|
||||
pendingData: make([]byte, 0, 4096),
|
||||
writeBuf: make([]byte, 0, 4096),
|
||||
rng: localRng,
|
||||
paddingRate: rate,
|
||||
Conn: c,
|
||||
table: table,
|
||||
reader: bufio.NewReaderSize(c, IOBufferSize),
|
||||
rawBuf: make([]byte, IOBufferSize),
|
||||
pendingData: make([]byte, 0, 4096),
|
||||
writeBuf: make([]byte, 0, 4096),
|
||||
rng: localRng,
|
||||
paddingThreshold: pickPaddingThreshold(localRng, pMin, pMax),
|
||||
}
|
||||
|
||||
pc.padMarker = table.layout.padMarker
|
||||
@@ -80,9 +95,9 @@ func NewPackedConn(c net.Conn, table *Table, pMin, pMax int) *PackedConn {
|
||||
return pc
|
||||
}
|
||||
|
||||
// maybeAddPadding 内联辅助:根据浮点概率插入 padding
|
||||
// maybeAddPadding 内联辅助:根据概率阈值插入 padding
|
||||
func (pc *PackedConn) maybeAddPadding(out []byte) []byte {
|
||||
if pc.rng.Float32() < pc.paddingRate {
|
||||
if shouldPad(pc.rng, pc.paddingThreshold) {
|
||||
out = append(out, pc.getPaddingByte())
|
||||
}
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package sudoku
|
||||
|
||||
import "math/rand"
|
||||
|
||||
const probOne = uint64(1) << 32
|
||||
|
||||
func pickPaddingThreshold(r *rand.Rand, pMin, pMax int) uint64 {
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
if pMin < 0 {
|
||||
pMin = 0
|
||||
}
|
||||
if pMax < pMin {
|
||||
pMax = pMin
|
||||
}
|
||||
if pMax > 100 {
|
||||
pMax = 100
|
||||
}
|
||||
if pMin > 100 {
|
||||
pMin = 100
|
||||
}
|
||||
|
||||
min := uint64(pMin) * probOne / 100
|
||||
max := uint64(pMax) * probOne / 100
|
||||
if max <= min {
|
||||
return min
|
||||
}
|
||||
u := uint64(r.Uint32())
|
||||
return min + (u * (max - min) >> 32)
|
||||
}
|
||||
|
||||
func shouldPad(r *rand.Rand, threshold uint64) bool {
|
||||
if threshold == 0 {
|
||||
return false
|
||||
}
|
||||
if threshold >= probOne {
|
||||
return true
|
||||
}
|
||||
if r == nil {
|
||||
return false
|
||||
}
|
||||
return uint64(r.Uint32()) < threshold
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
package sudoku
|
||||
|
||||
import (
|
||||
crypto_rand "crypto/rand"
|
||||
"encoding/binary"
|
||||
"math/rand"
|
||||
"net"
|
||||
|
||||
"github.com/metacubex/mihomo/transport/sudoku/obfs/sudoku"
|
||||
)
|
||||
|
||||
// perm4 matches github.com/saba-futai/sudoku/pkg/obfs/sudoku perm4.
|
||||
var perm4 = [24][4]byte{
|
||||
{0, 1, 2, 3},
|
||||
{0, 1, 3, 2},
|
||||
{0, 2, 1, 3},
|
||||
{0, 2, 3, 1},
|
||||
{0, 3, 1, 2},
|
||||
{0, 3, 2, 1},
|
||||
{1, 0, 2, 3},
|
||||
{1, 0, 3, 2},
|
||||
{1, 2, 0, 3},
|
||||
{1, 2, 3, 0},
|
||||
{1, 3, 0, 2},
|
||||
{1, 3, 2, 0},
|
||||
{2, 0, 1, 3},
|
||||
{2, 0, 3, 1},
|
||||
{2, 1, 0, 3},
|
||||
{2, 1, 3, 0},
|
||||
{2, 3, 0, 1},
|
||||
{2, 3, 1, 0},
|
||||
{3, 0, 1, 2},
|
||||
{3, 0, 2, 1},
|
||||
{3, 1, 0, 2},
|
||||
{3, 1, 2, 0},
|
||||
{3, 2, 0, 1},
|
||||
{3, 2, 1, 0},
|
||||
}
|
||||
|
||||
type sudokuObfsWriter struct {
|
||||
conn net.Conn
|
||||
table *sudoku.Table
|
||||
rng *rand.Rand
|
||||
paddingRate float32
|
||||
|
||||
outBuf []byte
|
||||
pads []byte
|
||||
padLen int
|
||||
}
|
||||
|
||||
func newSudokuObfsWriter(conn net.Conn, table *sudoku.Table, pMin, pMax int) *sudokuObfsWriter {
|
||||
var seedBytes [8]byte
|
||||
if _, err := crypto_rand.Read(seedBytes[:]); err != nil {
|
||||
binary.BigEndian.PutUint64(seedBytes[:], uint64(rand.Int63()))
|
||||
}
|
||||
seed := int64(binary.BigEndian.Uint64(seedBytes[:]))
|
||||
localRng := rand.New(rand.NewSource(seed))
|
||||
|
||||
min := float32(pMin) / 100.0
|
||||
span := float32(pMax-pMin) / 100.0
|
||||
rate := min + localRng.Float32()*span
|
||||
|
||||
w := &sudokuObfsWriter{
|
||||
conn: conn,
|
||||
table: table,
|
||||
rng: localRng,
|
||||
paddingRate: rate,
|
||||
}
|
||||
w.pads = table.PaddingPool
|
||||
w.padLen = len(w.pads)
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *sudokuObfsWriter) Write(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// Worst-case: 4 hints + up to 6 paddings per input byte.
|
||||
needed := len(p)*10 + 1
|
||||
if cap(w.outBuf) < needed {
|
||||
w.outBuf = make([]byte, 0, needed)
|
||||
}
|
||||
out := w.outBuf[:0]
|
||||
|
||||
pads := w.pads
|
||||
padLen := w.padLen
|
||||
|
||||
for _, b := range p {
|
||||
if padLen > 0 && w.rng.Float32() < w.paddingRate {
|
||||
out = append(out, pads[w.rng.Intn(padLen)])
|
||||
}
|
||||
|
||||
puzzles := w.table.EncodeTable[b]
|
||||
puzzle := puzzles[w.rng.Intn(len(puzzles))]
|
||||
|
||||
perm := perm4[w.rng.Intn(len(perm4))]
|
||||
for _, idx := range perm {
|
||||
if padLen > 0 && w.rng.Float32() < w.paddingRate {
|
||||
out = append(out, pads[w.rng.Intn(padLen)])
|
||||
}
|
||||
out = append(out, puzzle[idx])
|
||||
}
|
||||
}
|
||||
|
||||
if padLen > 0 && w.rng.Float32() < w.paddingRate {
|
||||
out = append(out, pads[w.rng.Intn(padLen)])
|
||||
}
|
||||
|
||||
w.outBuf = out
|
||||
_, err := w.conn.Write(out)
|
||||
return len(p), err
|
||||
}
|
||||
@@ -136,7 +136,7 @@ type PacketConn struct {
|
||||
}
|
||||
|
||||
func (pc *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||
return WritePacket(pc, socks5.ParseAddr(addr.String()), b)
|
||||
return WritePacket(pc, socks5.ParseAddrToSocksAddr(addr), b)
|
||||
}
|
||||
|
||||
func (pc *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
|
||||
+12
-13
@@ -44,21 +44,20 @@ func StreamTLSConn(ctx context.Context, conn net.Conn, cfg *TLSConfig) (net.Conn
|
||||
}
|
||||
|
||||
if clientFingerprint, ok := tlsC.GetFingerprint(cfg.ClientFingerprint); ok {
|
||||
if cfg.Reality == nil {
|
||||
tlsConfig := tlsC.UConfig(tlsConfig)
|
||||
err = cfg.ECH.ClientHandleUTLS(ctx, tlsConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConn := tlsC.UClient(conn, tlsConfig, clientFingerprint)
|
||||
err = tlsConn.HandshakeContext(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tlsConn, nil
|
||||
} else {
|
||||
if cfg.Reality != nil {
|
||||
return tlsC.GetRealityConn(ctx, conn, clientFingerprint, tlsConfig.ServerName, cfg.Reality)
|
||||
}
|
||||
tlsConfig := tlsC.UConfig(tlsConfig)
|
||||
err = cfg.ECH.ClientHandleUTLS(ctx, tlsConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConn := tlsC.UClient(conn, tlsConfig, clientFingerprint)
|
||||
err = tlsConn.HandshakeContext(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tlsConn, nil
|
||||
}
|
||||
if cfg.Reality != nil {
|
||||
return nil, errors.New("REALITY is based on uTLS, please set a client-fingerprint")
|
||||
|
||||
@@ -42,7 +42,6 @@ type websocketWithEarlyDataConn struct {
|
||||
net.Conn
|
||||
wsWriter N.ExtendedWriter
|
||||
underlay net.Conn
|
||||
closed bool
|
||||
dialed chan bool
|
||||
cancel context.CancelFunc
|
||||
ctx context.Context
|
||||
@@ -204,7 +203,7 @@ func (wsedc *websocketWithEarlyDataConn) Dial(earlyData []byte) error {
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) Write(b []byte) (int, error) {
|
||||
if wsedc.closed {
|
||||
if wsedc.ctx.Err() != nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
if wsedc.Conn == nil {
|
||||
@@ -218,7 +217,7 @@ func (wsedc *websocketWithEarlyDataConn) Write(b []byte) (int, error) {
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) WriteBuffer(buffer *buf.Buffer) error {
|
||||
if wsedc.closed {
|
||||
if wsedc.ctx.Err() != nil {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if wsedc.Conn == nil {
|
||||
@@ -232,7 +231,7 @@ func (wsedc *websocketWithEarlyDataConn) WriteBuffer(buffer *buf.Buffer) error {
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) Read(b []byte) (int, error) {
|
||||
if wsedc.closed {
|
||||
if wsedc.ctx.Err() != nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
if wsedc.Conn == nil {
|
||||
@@ -246,7 +245,6 @@ func (wsedc *websocketWithEarlyDataConn) Read(b []byte) (int, error) {
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) Close() error {
|
||||
wsedc.closed = true
|
||||
wsedc.cancel()
|
||||
if wsedc.Conn == nil { // is dialing or not dialed
|
||||
return wsedc.underlay.Close()
|
||||
|
||||
@@ -208,20 +208,6 @@ func Proxies() map[string]C.Proxy {
|
||||
return proxies
|
||||
}
|
||||
|
||||
func ProxiesWithProviders() map[string]C.Proxy {
|
||||
allProxies := make(map[string]C.Proxy)
|
||||
for name, proxy := range proxies {
|
||||
allProxies[name] = proxy
|
||||
}
|
||||
for _, p := range providers {
|
||||
for _, proxy := range p.Proxies() {
|
||||
name := proxy.Name()
|
||||
allProxies[name] = proxy
|
||||
}
|
||||
}
|
||||
return allProxies
|
||||
}
|
||||
|
||||
// Providers return all compatible providers
|
||||
func Providers() map[string]P.ProxyProvider {
|
||||
return providers
|
||||
|
||||
Reference in new issue
Block a user