mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-03-02 19:39:52 +00:00
Compare commits
66 Commits
v1.19.19
...
Prerelease
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9033717190 | ||
|
|
dda1d525c1 | ||
|
|
3035ae89e3 | ||
|
|
c251e411e5 | ||
|
|
f6722ab79b | ||
|
|
4ca515896b | ||
|
|
836c972c54 | ||
|
|
43509da1a9 | ||
|
|
3752cb044f | ||
|
|
30391b40c4 | ||
|
|
05fbf552ec | ||
|
|
e4143cf1ad | ||
|
|
5eaf5d16ce | ||
|
|
9dee264f13 | ||
|
|
50480406cf | ||
|
|
6eb27ac3dc | ||
|
|
a949ad883c | ||
|
|
20bf57c117 | ||
|
|
60a9312057 | ||
|
|
9fda032a28 | ||
|
|
c3399fd346 | ||
|
|
445083b624 | ||
|
|
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 |
42
.github/workflows/build.yml
vendored
42
.github/workflows/build.yml
vendored
@@ -59,8 +59,8 @@ jobs:
|
||||
- { goos: linux, goarch: s390x, output: s390x, debian: s390x, rpm: s390x }
|
||||
- { goos: linux, goarch: ppc64le, output: ppc64le, debian: ppc64el, rpm: ppc64le }
|
||||
|
||||
# Go 1.25 with special patch can work on Windows 7
|
||||
# https://github.com/MetaCubeX/go/commits/release-branch.go1.25/
|
||||
# Go 1.26 with special patch can work on Windows 7
|
||||
# https://github.com/MetaCubeX/go/commits/release-branch.go1.26/
|
||||
- { goos: windows, goarch: '386', output: '386' }
|
||||
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible } # old style file name will be removed in next released
|
||||
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64 }
|
||||
@@ -82,6 +82,13 @@ jobs:
|
||||
- { goos: android, goarch: arm, ndk: armv7a-linux-androideabi34, output: armv7 }
|
||||
- { goos: android, goarch: arm64, ndk: aarch64-linux-android34, output: arm64-v8 }
|
||||
|
||||
# Go 1.25 with special patch can work on Windows 7
|
||||
# https://github.com/MetaCubeX/go/commits/release-branch.go1.25/
|
||||
- { goos: windows, goarch: '386', output: '386-go125', goversion: '1.25' }
|
||||
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-v1-go125, goversion: '1.25' }
|
||||
- { goos: windows, goarch: amd64, goamd64: v2, output: amd64-v2-go125, goversion: '1.25' }
|
||||
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-v3-go125, goversion: '1.25' }
|
||||
|
||||
# Go 1.24 with special patch can work on Windows 7
|
||||
# https://github.com/MetaCubeX/go/commits/release-branch.go1.24/
|
||||
- { goos: windows, goarch: '386', output: '386-go124', goversion: '1.24' }
|
||||
@@ -154,7 +161,7 @@ jobs:
|
||||
if: ${{ matrix.jobs.goversion == '' && matrix.jobs.abi != '1' }}
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: '1.25'
|
||||
go-version: '1.26'
|
||||
check-latest: true # Always check for the latest patch release
|
||||
|
||||
- name: Set up Go
|
||||
@@ -164,14 +171,30 @@ jobs:
|
||||
go-version: ${{ matrix.jobs.goversion }}
|
||||
check-latest: true # Always check for the latest patch release
|
||||
|
||||
- name: Set up Go1.24 loongarch abi1
|
||||
- name: Set up Go1.25 loongarch abi1
|
||||
if: ${{ matrix.jobs.goarch == 'loong64' && matrix.jobs.abi == '1' }}
|
||||
run: |
|
||||
wget -q https://github.com/MetaCubeX/loongarch64-golang/releases/download/1.24.0/go1.24.0.linux-amd64-abi1.tar.gz
|
||||
sudo tar zxf go1.24.0.linux-amd64-abi1.tar.gz -C /usr/local
|
||||
wget -q https://github.com/MetaCubeX/loongarch64-golang/releases/download/1.25.5/go1.25.5.linux-amd64-abi1.tar.gz
|
||||
sudo tar zxf go1.25.5.linux-amd64-abi1.tar.gz -C /usr/local
|
||||
echo "/usr/local/go/bin" >> $GITHUB_PATH
|
||||
|
||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||
# this patch file only works on golang1.26.x
|
||||
# that means after golang1.27 release it must be changed
|
||||
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.26/
|
||||
# revert:
|
||||
# 693def151adff1af707d82d28f55dba81ceb08e1: "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||
# 7c1157f9544922e96945196b47b95664b1e39108: "net: remove sysSocket fallback for Windows 7"
|
||||
# 48042aa09c2f878c4faa576948b07fe625c4707a: "syscall: remove Windows 7 console handle workaround"
|
||||
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
||||
# f0894a00f4b756d4b9b4078af2e686b359493583: "os: remove 5ms sleep on Windows in (*Process).Wait"
|
||||
# sepical fix:
|
||||
# - os.RemoveAll not working on Windows7
|
||||
- name: Revert Golang1.26 commit for Windows7/8
|
||||
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '' }}
|
||||
run: |
|
||||
cd $(go env GOROOT)
|
||||
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.26.patch
|
||||
|
||||
# this patch file only works on golang1.25.x
|
||||
# that means after golang1.26 release it must be changed
|
||||
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.25/
|
||||
@@ -184,12 +207,11 @@ jobs:
|
||||
# sepical fix:
|
||||
# - os.RemoveAll not working on Windows7
|
||||
- name: Revert Golang1.25 commit for Windows7/8
|
||||
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '' }}
|
||||
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.25' }}
|
||||
run: |
|
||||
cd $(go env GOROOT)
|
||||
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.25.patch
|
||||
|
||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||
# this patch file only works on golang1.24.x
|
||||
# that means after golang1.25 release it must be changed
|
||||
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.24/
|
||||
@@ -204,7 +226,6 @@ jobs:
|
||||
cd $(go env GOROOT)
|
||||
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.24.patch
|
||||
|
||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||
# this patch file only works on golang1.23.x
|
||||
# that means after golang1.24 release it must be changed
|
||||
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.23/
|
||||
@@ -219,7 +240,6 @@ jobs:
|
||||
cd $(go env GOROOT)
|
||||
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.23.patch
|
||||
|
||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||
# this patch file only works on golang1.22.x
|
||||
# that means after golang1.23 release it must be changed
|
||||
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.22/
|
||||
|
||||
10
.github/workflows/test.yml
vendored
10
.github/workflows/test.yml
vendored
@@ -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'
|
||||
- '1.25'
|
||||
- '1.24'
|
||||
- '1.23'
|
||||
@@ -51,17 +51,11 @@ 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' }}
|
||||
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' }}
|
||||
run: |
|
||||
cd $(go env GOROOT)
|
||||
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.26.patch
|
||||
|
||||
- name: Remove inbound test for macOS
|
||||
if: ${{ runner.os == 'macOS' }}
|
||||
run: |
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
397
adapter/outbound/masque.go
Normal file
397
adapter/outbound/masque.go
Normal file
@@ -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
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
mieruclient "github.com/enfein/mieru/v3/apis/client"
|
||||
mierucommon "github.com/enfein/mieru/v3/apis/common"
|
||||
mierumodel "github.com/enfein/mieru/v3/apis/model"
|
||||
mierutp "github.com/enfein/mieru/v3/apis/trafficpattern"
|
||||
mierupb "github.com/enfein/mieru/v3/pkg/appctl/appctlpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
@@ -28,16 +29,17 @@ type Mieru struct {
|
||||
|
||||
type MieruOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port,omitempty"`
|
||||
PortRange string `proxy:"port-range,omitempty"`
|
||||
Transport string `proxy:"transport"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
UserName string `proxy:"username"`
|
||||
Password string `proxy:"password"`
|
||||
Multiplexing string `proxy:"multiplexing,omitempty"`
|
||||
HandshakeMode string `proxy:"handshake-mode,omitempty"`
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port,omitempty"`
|
||||
PortRange string `proxy:"port-range,omitempty"`
|
||||
Transport string `proxy:"transport"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
UserName string `proxy:"username"`
|
||||
Password string `proxy:"password"`
|
||||
Multiplexing string `proxy:"multiplexing,omitempty"`
|
||||
HandshakeMode string `proxy:"handshake-mode,omitempty"`
|
||||
TrafficPattern string `proxy:"traffic-pattern,omitempty"`
|
||||
}
|
||||
|
||||
type mieruPacketDialer struct {
|
||||
@@ -291,6 +293,10 @@ func buildMieruClientConfig(option MieruOption) (*mieruclient.ClientConfig, erro
|
||||
if handshakeMode, ok := mierupb.HandshakeMode_value[option.HandshakeMode]; ok {
|
||||
config.Profile.HandshakeMode = (*mierupb.HandshakeMode)(&handshakeMode)
|
||||
}
|
||||
if option.TrafficPattern != "" {
|
||||
trafficPattern, _ := mierutp.Decode(option.TrafficPattern)
|
||||
config.Profile.TrafficPattern = trafficPattern
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@@ -345,6 +351,15 @@ func validateMieruOption(option MieruOption) error {
|
||||
return fmt.Errorf("invalid handshake mode: %s", option.HandshakeMode)
|
||||
}
|
||||
}
|
||||
if option.TrafficPattern != "" {
|
||||
trafficPattern, err := mierutp.Decode(option.TrafficPattern)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode traffic pattern %q: %w", option.TrafficPattern, err)
|
||||
}
|
||||
if err := mierutp.Validate(trafficPattern); err != nil {
|
||||
return fmt.Errorf("invalid traffic pattern %q: %w", option.TrafficPattern, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -31,12 +31,13 @@ func TestNewMieru(t *testing.T) {
|
||||
},
|
||||
{
|
||||
option: MieruOption{
|
||||
Name: "test",
|
||||
Server: "example.com",
|
||||
Port: 10003,
|
||||
Transport: "UDP",
|
||||
UserName: "test",
|
||||
Password: "test",
|
||||
Name: "test",
|
||||
Server: "example.com",
|
||||
Port: 10003,
|
||||
Transport: "UDP",
|
||||
UserName: "test",
|
||||
Password: "test",
|
||||
TrafficPattern: "GgQIARAK",
|
||||
},
|
||||
wantBaseAddr: "example.com:10003",
|
||||
},
|
||||
|
||||
@@ -12,9 +12,9 @@ import (
|
||||
|
||||
type RealityOptions struct {
|
||||
PublicKey string `proxy:"public-key"`
|
||||
ShortID string `proxy:"short-id"`
|
||||
ShortID string `proxy:"short-id,omitempty"`
|
||||
|
||||
SupportX25519MLKEM768 bool `proxy:"support-x25519mlkem768"`
|
||||
SupportX25519MLKEM768 bool `proxy:"support-x25519mlkem768,omitempty"`
|
||||
}
|
||||
|
||||
func (o RealityOptions) Parse() (*tlsC.RealityConfig, error) {
|
||||
|
||||
@@ -7,11 +7,11 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/transport/sudoku"
|
||||
"github.com/metacubex/mihomo/transport/sudoku/obfs/httpmask"
|
||||
)
|
||||
|
||||
type Sudoku struct {
|
||||
@@ -19,34 +19,43 @@ type Sudoku struct {
|
||||
option *SudokuOption
|
||||
baseConf sudoku.ProtocolConfig
|
||||
|
||||
httpMaskMu sync.Mutex
|
||||
httpMaskClient *sudoku.HTTPMaskTunnelClient
|
||||
muxMu sync.Mutex
|
||||
muxClient *sudoku.MultiplexClient
|
||||
|
||||
muxMu sync.Mutex
|
||||
muxClient *sudoku.MultiplexClient
|
||||
muxBackoffUntil time.Time
|
||||
muxLastErr error
|
||||
httpMaskMu sync.Mutex
|
||||
httpMaskClient *httpmask.TunnelClient
|
||||
httpMaskKey string
|
||||
}
|
||||
|
||||
type SudokuOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Key string `proxy:"key"`
|
||||
AEADMethod string `proxy:"aead-method,omitempty"`
|
||||
PaddingMin *int `proxy:"padding-min,omitempty"`
|
||||
PaddingMax *int `proxy:"padding-max,omitempty"`
|
||||
TableType string `proxy:"table-type,omitempty"` // "prefer_ascii" or "prefer_entropy"
|
||||
EnablePureDownlink *bool `proxy:"enable-pure-downlink,omitempty"`
|
||||
HTTPMask bool `proxy:"http-mask,omitempty"`
|
||||
HTTPMaskMode string `proxy:"http-mask-mode,omitempty"` // "legacy" (default), "stream", "poll", "auto"
|
||||
HTTPMaskTLS bool `proxy:"http-mask-tls,omitempty"` // only for http-mask-mode stream/poll/auto
|
||||
HTTPMaskHost string `proxy:"http-mask-host,omitempty"` // optional Host/SNI override (domain or domain:port)
|
||||
PathRoot string `proxy:"path-root,omitempty"` // optional first-level path prefix for HTTP tunnel endpoints
|
||||
HTTPMaskMultiplex string `proxy:"http-mask-multiplex,omitempty"` // "off" (default), "auto" (reuse h1/h2), "on" (single tunnel, multi-target)
|
||||
CustomTable string `proxy:"custom-table,omitempty"` // optional custom byte layout, e.g. xpxvvpvv
|
||||
CustomTables []string `proxy:"custom-tables,omitempty"` // optional table rotation patterns, overrides custom-table when non-empty
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Key string `proxy:"key"`
|
||||
AEADMethod string `proxy:"aead-method,omitempty"`
|
||||
PaddingMin *int `proxy:"padding-min,omitempty"`
|
||||
PaddingMax *int `proxy:"padding-max,omitempty"`
|
||||
TableType string `proxy:"table-type,omitempty"` // "prefer_ascii" or "prefer_entropy"
|
||||
EnablePureDownlink *bool `proxy:"enable-pure-downlink,omitempty"`
|
||||
HTTPMask *bool `proxy:"http-mask,omitempty"`
|
||||
HTTPMaskMode string `proxy:"http-mask-mode,omitempty"` // "legacy" (default), "stream", "poll", "auto", "ws"
|
||||
HTTPMaskTLS bool `proxy:"http-mask-tls,omitempty"` // only for http-mask-mode stream/poll/auto
|
||||
HTTPMaskHost string `proxy:"http-mask-host,omitempty"` // optional Host/SNI override (domain or domain:port)
|
||||
PathRoot string `proxy:"path-root,omitempty"` // optional first-level path prefix for HTTP tunnel endpoints
|
||||
HTTPMaskMultiplex string `proxy:"http-mask-multiplex,omitempty"` // "off" (default), "auto" (reuse h1/h2), "on" (single tunnel, multi-target)
|
||||
HTTPMaskOptions *SudokuHTTPMaskOptions `proxy:"httpmask,omitempty"`
|
||||
CustomTable string `proxy:"custom-table,omitempty"` // optional custom byte layout, e.g. xpxvvpvv
|
||||
CustomTables []string `proxy:"custom-tables,omitempty"` // optional table rotation patterns, overrides custom-table when non-empty
|
||||
}
|
||||
|
||||
type SudokuHTTPMaskOptions struct {
|
||||
Disable bool `proxy:"disable,omitempty"`
|
||||
Mode string `proxy:"mode,omitempty"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
Host string `proxy:"host,omitempty"`
|
||||
PathRoot string `proxy:"path_root,omitempty"`
|
||||
Multiplex string `proxy:"multiplex,omitempty"`
|
||||
}
|
||||
|
||||
// DialContext implements C.ProxyAdapter
|
||||
@@ -58,7 +67,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
|
||||
}
|
||||
@@ -76,7 +85,7 @@ func (s *Sudoku) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Con
|
||||
return nil, fmt.Errorf("encode target address failed: %w", err)
|
||||
}
|
||||
|
||||
if _, err = c.Write(addrBuf); err != nil {
|
||||
if err = sudoku.WriteKIPMessage(c, sudoku.KIPTypeOpenTCP, addrBuf); err != nil {
|
||||
return nil, fmt.Errorf("send target address failed: %w", err)
|
||||
}
|
||||
|
||||
@@ -99,9 +108,9 @@ func (s *Sudoku) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = sudoku.WritePreface(c); err != nil {
|
||||
if err = sudoku.WriteKIPMessage(c, sudoku.KIPTypeStartUoT, nil); err != nil {
|
||||
_ = c.Close()
|
||||
return nil, fmt.Errorf("send uot preface failed: %w", err)
|
||||
return nil, fmt.Errorf("start uot failed: %w", err)
|
||||
}
|
||||
|
||||
return newPacketConn(N.NewThreadSafePacketConn(sudoku.NewUoTPacketConn(c)), s), nil
|
||||
@@ -144,32 +153,45 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
|
||||
return nil, fmt.Errorf("key is required")
|
||||
}
|
||||
|
||||
tableType := strings.ToLower(option.TableType)
|
||||
if tableType == "" {
|
||||
tableType = "prefer_ascii"
|
||||
defaultConf := sudoku.DefaultConfig()
|
||||
tableType, err := sudoku.NormalizeTableType(option.TableType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tableType != "prefer_ascii" && tableType != "prefer_entropy" {
|
||||
return nil, fmt.Errorf("table-type must be prefer_ascii or prefer_entropy")
|
||||
paddingMin, paddingMax := sudoku.ResolvePadding(option.PaddingMin, option.PaddingMax, defaultConf.PaddingMin, defaultConf.PaddingMax)
|
||||
enablePureDownlink := sudoku.DerefBool(option.EnablePureDownlink, defaultConf.EnablePureDownlink)
|
||||
|
||||
disableHTTPMask := defaultConf.DisableHTTPMask
|
||||
if option.HTTPMask != nil {
|
||||
disableHTTPMask = !*option.HTTPMask
|
||||
}
|
||||
httpMaskMode := defaultConf.HTTPMaskMode
|
||||
if option.HTTPMaskMode != "" {
|
||||
httpMaskMode = option.HTTPMaskMode
|
||||
}
|
||||
httpMaskTLS := option.HTTPMaskTLS
|
||||
httpMaskHost := option.HTTPMaskHost
|
||||
pathRoot := strings.TrimSpace(option.PathRoot)
|
||||
httpMaskMultiplex := defaultConf.HTTPMaskMultiplex
|
||||
if option.HTTPMaskMultiplex != "" {
|
||||
httpMaskMultiplex = option.HTTPMaskMultiplex
|
||||
}
|
||||
|
||||
defaultConf := sudoku.DefaultConfig()
|
||||
paddingMin := defaultConf.PaddingMin
|
||||
paddingMax := defaultConf.PaddingMax
|
||||
if option.PaddingMin != nil {
|
||||
paddingMin = *option.PaddingMin
|
||||
}
|
||||
if option.PaddingMax != nil {
|
||||
paddingMax = *option.PaddingMax
|
||||
}
|
||||
if option.PaddingMin == nil && option.PaddingMax != nil && paddingMax < paddingMin {
|
||||
paddingMin = paddingMax
|
||||
}
|
||||
if option.PaddingMax == nil && option.PaddingMin != nil && paddingMax < paddingMin {
|
||||
paddingMax = paddingMin
|
||||
}
|
||||
enablePureDownlink := defaultConf.EnablePureDownlink
|
||||
if option.EnablePureDownlink != nil {
|
||||
enablePureDownlink = *option.EnablePureDownlink
|
||||
if hm := option.HTTPMaskOptions; hm != nil {
|
||||
disableHTTPMask = hm.Disable
|
||||
if hm.Mode != "" {
|
||||
httpMaskMode = hm.Mode
|
||||
}
|
||||
httpMaskTLS = hm.TLS
|
||||
httpMaskHost = hm.Host
|
||||
if pr := strings.TrimSpace(hm.PathRoot); pr != "" {
|
||||
pathRoot = pr
|
||||
}
|
||||
if mux := strings.TrimSpace(hm.Multiplex); mux != "" {
|
||||
httpMaskMultiplex = mux
|
||||
} else {
|
||||
httpMaskMultiplex = defaultConf.HTTPMaskMultiplex
|
||||
}
|
||||
}
|
||||
|
||||
baseConf := sudoku.ProtocolConfig{
|
||||
@@ -180,20 +202,14 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
|
||||
PaddingMax: paddingMax,
|
||||
EnablePureDownlink: enablePureDownlink,
|
||||
HandshakeTimeoutSeconds: defaultConf.HandshakeTimeoutSeconds,
|
||||
DisableHTTPMask: !option.HTTPMask,
|
||||
HTTPMaskMode: defaultConf.HTTPMaskMode,
|
||||
HTTPMaskTLSEnabled: option.HTTPMaskTLS,
|
||||
HTTPMaskHost: option.HTTPMaskHost,
|
||||
HTTPMaskPathRoot: strings.TrimSpace(option.PathRoot),
|
||||
HTTPMaskMultiplex: defaultConf.HTTPMaskMultiplex,
|
||||
DisableHTTPMask: disableHTTPMask,
|
||||
HTTPMaskMode: httpMaskMode,
|
||||
HTTPMaskTLSEnabled: httpMaskTLS,
|
||||
HTTPMaskHost: httpMaskHost,
|
||||
HTTPMaskPathRoot: pathRoot,
|
||||
HTTPMaskMultiplex: httpMaskMultiplex,
|
||||
}
|
||||
if option.HTTPMaskMode != "" {
|
||||
baseConf.HTTPMaskMode = option.HTTPMaskMode
|
||||
}
|
||||
if option.HTTPMaskMultiplex != "" {
|
||||
baseConf.HTTPMaskMultiplex = option.HTTPMaskMultiplex
|
||||
}
|
||||
tables, err := sudoku.NewTablesWithCustomPatterns(sudoku.ClientAEADSeed(option.Key), tableType, option.CustomTable, option.CustomTables)
|
||||
tables, err := sudoku.NewClientTablesWithCustomPatterns(sudoku.ClientAEADSeed(option.Key), tableType, option.CustomTable, option.CustomTables)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build table(s) failed: %w", err)
|
||||
}
|
||||
@@ -247,7 +263,7 @@ func normalizeHTTPMaskMultiplex(mode string) string {
|
||||
|
||||
func httpTunnelModeEnabled(mode string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(mode)) {
|
||||
case "stream", "poll", "auto":
|
||||
case "stream", "poll", "auto", "ws":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
@@ -265,7 +281,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 (
|
||||
@@ -274,14 +290,24 @@ func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfi
|
||||
)
|
||||
if !cfg.DisableHTTPMask && httpTunnelModeEnabled(cfg.HTTPMaskMode) {
|
||||
muxMode := normalizeHTTPMaskMultiplex(cfg.HTTPMaskMultiplex)
|
||||
switch muxMode {
|
||||
case "auto", "on":
|
||||
client, errX := s.getOrCreateHTTPMaskClient(cfg)
|
||||
if errX != nil {
|
||||
return nil, errX
|
||||
if muxMode == "auto" && strings.ToLower(strings.TrimSpace(cfg.HTTPMaskMode)) != "ws" {
|
||||
if client, cerr := s.getOrCreateHTTPMaskClient(cfg); cerr == nil && client != nil {
|
||||
c, err = client.DialTunnel(ctx, httpmask.TunnelDialOptions{
|
||||
Mode: cfg.HTTPMaskMode,
|
||||
TLSEnabled: cfg.HTTPMaskTLSEnabled,
|
||||
HostOverride: cfg.HTTPMaskHost,
|
||||
PathRoot: cfg.HTTPMaskPathRoot,
|
||||
AuthKey: sudoku.ClientAEADSeed(cfg.Key),
|
||||
Upgrade: upgrade,
|
||||
Multiplex: cfg.HTTPMaskMultiplex,
|
||||
DialContext: s.dialer.DialContext,
|
||||
})
|
||||
if err != nil {
|
||||
s.resetHTTPMaskClient()
|
||||
}
|
||||
}
|
||||
c, err = client.Dial(ctx, upgrade)
|
||||
default:
|
||||
}
|
||||
if c == nil && err == nil {
|
||||
c, err = sudoku.DialHTTPMaskTunnel(ctx, cfg.ServerAddress, cfg, s.dialer.DialContext, upgrade)
|
||||
}
|
||||
if err == nil && c != nil {
|
||||
@@ -303,7 +329,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 +338,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 +356,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 +379,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 +392,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()
|
||||
@@ -403,34 +401,51 @@ func (s *Sudoku) resetMuxClient() {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Sudoku) getOrCreateHTTPMaskClient(cfg *sudoku.ProtocolConfig) (*sudoku.HTTPMaskTunnelClient, error) {
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("nil adapter")
|
||||
}
|
||||
if cfg == nil {
|
||||
return nil, fmt.Errorf("config is required")
|
||||
}
|
||||
|
||||
s.httpMaskMu.Lock()
|
||||
defer s.httpMaskMu.Unlock()
|
||||
|
||||
if s.httpMaskClient != nil {
|
||||
return s.httpMaskClient, nil
|
||||
}
|
||||
|
||||
c, err := sudoku.NewHTTPMaskTunnelClient(cfg.ServerAddress, cfg, s.dialer.DialContext)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.httpMaskClient = c
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Sudoku) resetHTTPMaskClient() {
|
||||
s.httpMaskMu.Lock()
|
||||
defer s.httpMaskMu.Unlock()
|
||||
if s.httpMaskClient != nil {
|
||||
s.httpMaskClient.CloseIdleConnections()
|
||||
s.httpMaskClient = nil
|
||||
s.httpMaskKey = ""
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Sudoku) getOrCreateHTTPMaskClient(cfg *sudoku.ProtocolConfig) (*httpmask.TunnelClient, error) {
|
||||
if s == nil || cfg == nil {
|
||||
return nil, fmt.Errorf("nil adapter or config")
|
||||
}
|
||||
|
||||
key := cfg.ServerAddress + "|" + strconv.FormatBool(cfg.HTTPMaskTLSEnabled) + "|" + strings.TrimSpace(cfg.HTTPMaskHost)
|
||||
|
||||
s.httpMaskMu.Lock()
|
||||
if s.httpMaskClient != nil && s.httpMaskKey == key {
|
||||
client := s.httpMaskClient
|
||||
s.httpMaskMu.Unlock()
|
||||
return client, nil
|
||||
}
|
||||
s.httpMaskMu.Unlock()
|
||||
|
||||
client, err := httpmask.NewTunnelClient(cfg.ServerAddress, httpmask.TunnelClientOptions{
|
||||
TLSEnabled: cfg.HTTPMaskTLSEnabled,
|
||||
HostOverride: cfg.HTTPMaskHost,
|
||||
DialContext: s.dialer.DialContext,
|
||||
MaxIdleConns: 32,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.httpMaskMu.Lock()
|
||||
defer s.httpMaskMu.Unlock()
|
||||
if s.httpMaskClient != nil && s.httpMaskKey == key {
|
||||
client.CloseIdleConnections()
|
||||
return s.httpMaskClient, nil
|
||||
}
|
||||
if s.httpMaskClient != nil {
|
||||
s.httpMaskClient.CloseIdleConnections()
|
||||
}
|
||||
s.httpMaskClient = client
|
||||
s.httpMaskKey = key
|
||||
return client, nil
|
||||
}
|
||||
|
||||
@@ -27,9 +27,8 @@ type Trojan struct {
|
||||
hexPassword [trojan.KeyLength]byte
|
||||
|
||||
// for gun mux
|
||||
gunTLSConfig *tls.Config
|
||||
gunConfig *gun.Config
|
||||
transport *gun.TransportWrap
|
||||
gunTransport *gun.TransportWrap
|
||||
|
||||
realityConfig *tlsC.RealityConfig
|
||||
echConfig *ech.Config
|
||||
@@ -66,7 +65,6 @@ type TrojanSSOption struct {
|
||||
Password string `proxy:"password,omitempty"`
|
||||
}
|
||||
|
||||
// StreamConnContext implements C.ProxyAdapter
|
||||
func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) {
|
||||
switch t.option.Network {
|
||||
case "ws":
|
||||
@@ -118,7 +116,7 @@ func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.
|
||||
|
||||
c, err = vmess.StreamWebsocketConn(ctx, c, wsOpts)
|
||||
case "grpc":
|
||||
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig, t.echConfig, t.realityConfig)
|
||||
break // already handle in gun transport
|
||||
default:
|
||||
// default tcp network
|
||||
// handle TLS
|
||||
@@ -179,27 +177,14 @@ func (t *Trojan) writeHeaderContext(ctx context.Context, c net.Conn, metadata *C
|
||||
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||
var c net.Conn
|
||||
// gun transport
|
||||
if t.transport != nil {
|
||||
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func(c net.Conn) {
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = t.streamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return NewConn(c, t), nil
|
||||
if t.gunTransport != nil {
|
||||
c, err = gun.StreamGunWithTransport(t.gunTransport, t.gunConfig)
|
||||
} else {
|
||||
c, err = t.dialer.DialContext(ctx, "tcp", t.addr)
|
||||
}
|
||||
c, err = t.dialer.DialContext(ctx, "tcp", t.addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||
}
|
||||
|
||||
defer func(c net.Conn) {
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
@@ -219,35 +204,19 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
}
|
||||
|
||||
var c net.Conn
|
||||
|
||||
// grpc transport
|
||||
if t.transport != nil {
|
||||
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||
}
|
||||
defer func(c net.Conn) {
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = t.streamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pc := trojan.NewPacketConn(c)
|
||||
return newPacketConn(pc, t), err
|
||||
if t.gunTransport != nil {
|
||||
c, err = gun.StreamGunWithTransport(t.gunTransport, t.gunConfig)
|
||||
} else {
|
||||
c, err = t.dialer.DialContext(ctx, "tcp", t.addr)
|
||||
}
|
||||
if err = t.ResolveUDP(ctx, metadata); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, err = t.dialer.DialContext(ctx, "tcp", t.addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||
}
|
||||
defer func(c net.Conn) {
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = t.StreamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -271,8 +240,8 @@ func (t *Trojan) ProxyInfo() C.ProxyInfo {
|
||||
|
||||
// Close implements C.ProxyAdapter
|
||||
func (t *Trojan) Close() error {
|
||||
if t.transport != nil {
|
||||
return t.transport.Close()
|
||||
if t.gunTransport != nil {
|
||||
return t.gunTransport.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -336,29 +305,24 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
tlsConfig, err := ca.GetTLSConfig(ca.Option{
|
||||
TLSConfig: &tls.Config{
|
||||
NextProtos: option.ALPN,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
InsecureSkipVerify: option.SkipCertVerify,
|
||||
ServerName: option.SNI,
|
||||
},
|
||||
Fingerprint: option.Fingerprint,
|
||||
Certificate: option.Certificate,
|
||||
PrivateKey: option.PrivateKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
tlsConfig := &vmess.TLSConfig{
|
||||
Host: option.SNI,
|
||||
SkipCertVerify: option.SkipCertVerify,
|
||||
FingerPrint: option.Fingerprint,
|
||||
Certificate: option.Certificate,
|
||||
PrivateKey: option.PrivateKey,
|
||||
ClientFingerprint: option.ClientFingerprint,
|
||||
NextProtos: []string{"h2"},
|
||||
ECH: t.echConfig,
|
||||
Reality: t.realityConfig,
|
||||
}
|
||||
|
||||
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig, option.ClientFingerprint, t.echConfig, t.realityConfig)
|
||||
t.gunTransport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||
|
||||
t.gunTLSConfig = tlsConfig
|
||||
t.gunConfig = &gun.Config{
|
||||
ServiceName: option.GrpcOpts.GrpcServiceName,
|
||||
UserAgent: option.GrpcOpts.GrpcUserAgent,
|
||||
Host: option.SNI,
|
||||
ClientFingerprint: option.ClientFingerprint,
|
||||
ServiceName: option.GrpcOpts.GrpcServiceName,
|
||||
UserAgent: option.GrpcOpts.GrpcUserAgent,
|
||||
Host: option.SNI,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
144
adapter/outbound/trusttunnel.go
Normal file
144
adapter/outbound/trusttunnel.go
Normal file
@@ -0,0 +1,144 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/transport/trusttunnel"
|
||||
"github.com/metacubex/mihomo/transport/vmess"
|
||||
)
|
||||
|
||||
type TrustTunnel struct {
|
||||
*Base
|
||||
client *trusttunnel.Client
|
||||
option *TrustTunnelOption
|
||||
}
|
||||
|
||||
type TrustTunnelOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
UserName string `proxy:"username,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
ALPN []string `proxy:"alpn,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
Certificate string `proxy:"certificate,omitempty"`
|
||||
PrivateKey string `proxy:"private-key,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
HealthCheck bool `proxy:"health-check,omitempty"`
|
||||
|
||||
Quic bool `proxy:"quic,omitempty"`
|
||||
CongestionController string `proxy:"congestion-controller,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
}
|
||||
|
||||
func (t *TrustTunnel) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||
c, err := t.client.Dial(ctx, metadata.RemoteAddress())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewConn(c, t), nil
|
||||
}
|
||||
|
||||
func (t *TrustTunnel) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||
if err = t.ResolveUDP(ctx, metadata); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pc, err := t.client.ListenPacket(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newPacketConn(N.NewThreadSafePacketConn(pc), t), nil
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
func (t *TrustTunnel) SupportUOT() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// ProxyInfo implements C.ProxyAdapter
|
||||
func (t *TrustTunnel) ProxyInfo() C.ProxyInfo {
|
||||
info := t.Base.ProxyInfo()
|
||||
info.DialerProxy = t.option.DialerProxy
|
||||
return info
|
||||
}
|
||||
|
||||
// Close implements C.ProxyAdapter
|
||||
func (t *TrustTunnel) Close() error {
|
||||
return t.client.Close()
|
||||
}
|
||||
|
||||
func NewTrustTunnel(option TrustTunnelOption) (*TrustTunnel, error) {
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
outbound := &TrustTunnel{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.TrustTunnel,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
option: &option,
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
|
||||
tOption := trusttunnel.ClientOptions{
|
||||
Dialer: outbound.dialer,
|
||||
ResolvUDP: func(ctx context.Context, server string) (netip.AddrPort, error) {
|
||||
udpAddr, err := resolveUDPAddr(ctx, "udp", server, option.IPVersion)
|
||||
if err != nil {
|
||||
return netip.AddrPort{}, err
|
||||
}
|
||||
return udpAddr.AddrPort(), nil
|
||||
},
|
||||
Server: addr,
|
||||
Username: option.UserName,
|
||||
Password: option.Password,
|
||||
QUIC: option.Quic,
|
||||
QUICCongestionControl: option.CongestionController,
|
||||
QUICCwnd: option.CWND,
|
||||
HealthCheck: option.HealthCheck,
|
||||
}
|
||||
echConfig, err := option.ECHOpts.Parse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConfig := &vmess.TLSConfig{
|
||||
Host: option.SNI,
|
||||
SkipCertVerify: option.SkipCertVerify,
|
||||
NextProtos: option.ALPN,
|
||||
FingerPrint: option.Fingerprint,
|
||||
Certificate: option.Certificate,
|
||||
PrivateKey: option.PrivateKey,
|
||||
ClientFingerprint: option.ClientFingerprint,
|
||||
ECH: echConfig,
|
||||
}
|
||||
if tlsConfig.Host == "" {
|
||||
tlsConfig.Host = option.Server
|
||||
}
|
||||
tOption.TLSConfig = tlsConfig
|
||||
|
||||
client, err := trusttunnel.NewClient(context.TODO(), tOption)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
outbound.client = client
|
||||
|
||||
return outbound, nil
|
||||
}
|
||||
@@ -33,9 +33,8 @@ type Vless struct {
|
||||
encryption *encryption.ClientInstance
|
||||
|
||||
// for gun mux
|
||||
gunTLSConfig *tls.Config
|
||||
gunConfig *gun.Config
|
||||
transport *gun.TransportWrap
|
||||
gunTransport *gun.TransportWrap
|
||||
|
||||
realityConfig *tlsC.RealityConfig
|
||||
echConfig *ech.Config
|
||||
@@ -151,7 +150,7 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
||||
|
||||
c, err = vmess.StreamH2Conn(ctx, c, h2Opts)
|
||||
case "grpc":
|
||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.echConfig, v.realityConfig)
|
||||
break // already handle in gun transport
|
||||
default:
|
||||
// default tcp network
|
||||
// handle TLS
|
||||
@@ -234,23 +233,11 @@ func (v *Vless) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (ne
|
||||
func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||
var c net.Conn
|
||||
// gun transport
|
||||
if v.transport != nil {
|
||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func(c net.Conn) {
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = v.streamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return NewConn(c, v), nil
|
||||
if v.gunTransport != nil {
|
||||
c, err = gun.StreamGunWithTransport(v.gunTransport, v.gunConfig)
|
||||
} else {
|
||||
c, err = v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
}
|
||||
c, err = v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||
}
|
||||
@@ -272,28 +259,11 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (
|
||||
}
|
||||
var c net.Conn
|
||||
// gun transport
|
||||
if v.transport != nil {
|
||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func(c net.Conn) {
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = v.streamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||
}
|
||||
|
||||
return v.ListenPacketOnStreamConn(ctx, c, metadata)
|
||||
if v.gunTransport != nil {
|
||||
c, err = gun.StreamGunWithTransport(v.gunTransport, v.gunConfig)
|
||||
} else {
|
||||
c, err = v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
}
|
||||
|
||||
if err = v.ResolveUDP(ctx, metadata); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c, err = v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||
}
|
||||
@@ -348,8 +318,8 @@ func (v *Vless) ProxyInfo() C.ProxyInfo {
|
||||
|
||||
// Close implements C.ProxyAdapter
|
||||
func (v *Vless) Close() error {
|
||||
if v.transport != nil {
|
||||
return v.transport.Close()
|
||||
if v.gunTransport != nil {
|
||||
return v.gunTransport.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -461,38 +431,35 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
}
|
||||
|
||||
gunConfig := &gun.Config{
|
||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||
UserAgent: v.option.GrpcOpts.GrpcUserAgent,
|
||||
Host: v.option.ServerName,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
ServiceName: option.GrpcOpts.GrpcServiceName,
|
||||
UserAgent: option.GrpcOpts.GrpcUserAgent,
|
||||
Host: option.ServerName,
|
||||
}
|
||||
if option.ServerName == "" {
|
||||
gunConfig.Host = v.addr
|
||||
}
|
||||
var tlsConfig *tls.Config
|
||||
var tlsConfig *vmess.TLSConfig
|
||||
if option.TLS {
|
||||
tlsConfig, err = ca.GetTLSConfig(ca.Option{
|
||||
TLSConfig: &tls.Config{
|
||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||
ServerName: v.option.ServerName,
|
||||
},
|
||||
Fingerprint: v.option.Fingerprint,
|
||||
Certificate: v.option.Certificate,
|
||||
PrivateKey: v.option.PrivateKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
tlsConfig = &vmess.TLSConfig{
|
||||
Host: option.ServerName,
|
||||
SkipCertVerify: option.SkipCertVerify,
|
||||
FingerPrint: option.Fingerprint,
|
||||
Certificate: option.Certificate,
|
||||
PrivateKey: option.PrivateKey,
|
||||
ClientFingerprint: option.ClientFingerprint,
|
||||
NextProtos: []string{"h2"},
|
||||
ECH: v.echConfig,
|
||||
Reality: v.realityConfig,
|
||||
}
|
||||
if option.ServerName == "" {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsConfig.ServerName = host
|
||||
tlsConfig.Host = host
|
||||
}
|
||||
}
|
||||
|
||||
v.gunTLSConfig = tlsConfig
|
||||
v.gunConfig = gunConfig
|
||||
|
||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint, v.echConfig, v.realityConfig)
|
||||
v.gunTransport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||
}
|
||||
|
||||
return v, nil
|
||||
|
||||
@@ -34,9 +34,8 @@ type Vmess struct {
|
||||
option *VmessOption
|
||||
|
||||
// for gun mux
|
||||
gunTLSConfig *tls.Config
|
||||
gunConfig *gun.Config
|
||||
transport *gun.TransportWrap
|
||||
gunTransport *gun.TransportWrap
|
||||
|
||||
realityConfig *tlsC.RealityConfig
|
||||
echConfig *ech.Config
|
||||
@@ -98,7 +97,6 @@ type WSOptions struct {
|
||||
V2rayHttpUpgradeFastOpen bool `proxy:"v2ray-http-upgrade-fast-open,omitempty"`
|
||||
}
|
||||
|
||||
// StreamConnContext implements C.ProxyAdapter
|
||||
func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) {
|
||||
switch v.option.Network {
|
||||
case "ws":
|
||||
@@ -205,7 +203,7 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
||||
|
||||
c, err = mihomoVMess.StreamH2Conn(ctx, c, h2Opts)
|
||||
case "grpc":
|
||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.echConfig, v.realityConfig)
|
||||
break // already handle in gun transport
|
||||
default:
|
||||
// handle TLS
|
||||
if v.option.TLS {
|
||||
@@ -296,23 +294,11 @@ func (v *Vmess) streamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
||||
func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||
var c net.Conn
|
||||
// gun transport
|
||||
if v.transport != nil {
|
||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func(c net.Conn) {
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = v.streamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return NewConn(c, v), nil
|
||||
if v.gunTransport != nil {
|
||||
c, err = gun.StreamGunWithTransport(v.gunTransport, v.gunConfig)
|
||||
} else {
|
||||
c, err = v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
}
|
||||
c, err = v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||
}
|
||||
@@ -331,27 +317,11 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (
|
||||
}
|
||||
var c net.Conn
|
||||
// gun transport
|
||||
if v.transport != nil {
|
||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func(c net.Conn) {
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = v.streamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||
}
|
||||
return v.ListenPacketOnStreamConn(ctx, c, metadata)
|
||||
if v.gunTransport != nil {
|
||||
c, err = gun.StreamGunWithTransport(v.gunTransport, v.gunConfig)
|
||||
} else {
|
||||
c, err = v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
}
|
||||
|
||||
if err = v.ResolveUDP(ctx, metadata); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c, err = v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||
}
|
||||
@@ -375,8 +345,8 @@ func (v *Vmess) ProxyInfo() C.ProxyInfo {
|
||||
|
||||
// Close implements C.ProxyAdapter
|
||||
func (v *Vmess) Close() error {
|
||||
if v.transport != nil {
|
||||
return v.transport.Close()
|
||||
if v.gunTransport != nil {
|
||||
return v.gunTransport.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -467,38 +437,35 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
}
|
||||
|
||||
gunConfig := &gun.Config{
|
||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||
UserAgent: v.option.GrpcOpts.GrpcUserAgent,
|
||||
Host: v.option.ServerName,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
ServiceName: option.GrpcOpts.GrpcServiceName,
|
||||
UserAgent: option.GrpcOpts.GrpcUserAgent,
|
||||
Host: option.ServerName,
|
||||
}
|
||||
if option.ServerName == "" {
|
||||
gunConfig.Host = v.addr
|
||||
}
|
||||
var tlsConfig *tls.Config
|
||||
var tlsConfig *mihomoVMess.TLSConfig
|
||||
if option.TLS {
|
||||
tlsConfig, err = ca.GetTLSConfig(ca.Option{
|
||||
TLSConfig: &tls.Config{
|
||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||
ServerName: v.option.ServerName,
|
||||
},
|
||||
Fingerprint: v.option.Fingerprint,
|
||||
Certificate: v.option.Certificate,
|
||||
PrivateKey: v.option.PrivateKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
tlsConfig = &mihomoVMess.TLSConfig{
|
||||
Host: option.ServerName,
|
||||
SkipCertVerify: option.SkipCertVerify,
|
||||
FingerPrint: option.Fingerprint,
|
||||
Certificate: option.Certificate,
|
||||
PrivateKey: option.PrivateKey,
|
||||
ClientFingerprint: option.ClientFingerprint,
|
||||
NextProtos: []string{"h2"},
|
||||
ECH: v.echConfig,
|
||||
Reality: v.realityConfig,
|
||||
}
|
||||
if option.ServerName == "" {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsConfig.ServerName = host
|
||||
tlsConfig.Host = host
|
||||
}
|
||||
}
|
||||
|
||||
v.gunTLSConfig = tlsConfig
|
||||
v.gunConfig = gunConfig
|
||||
|
||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint, v.echConfig, v.realityConfig)
|
||||
v.gunTransport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||
}
|
||||
|
||||
return v, nil
|
||||
|
||||
@@ -77,8 +77,8 @@ type WireGuardOption struct {
|
||||
}
|
||||
|
||||
type WireGuardPeerOption struct {
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Server string `proxy:"server,omitempty"`
|
||||
Port int `proxy:"port,omitempty"`
|
||||
PublicKey string `proxy:"public-key,omitempty"`
|
||||
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
||||
Reserved []uint8 `proxy:"reserved,omitempty"`
|
||||
@@ -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 {
|
||||
|
||||
@@ -272,7 +272,7 @@ func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error, fn func(
|
||||
|
||||
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
||||
if gb.failedTimes >= gb.maxFailedTimes {
|
||||
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
||||
log.Warnln("because %s failed multiple times, activate health check", gb.Name())
|
||||
fn()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,10 +42,6 @@ type GroupCommonOption struct {
|
||||
IncludeAllProviders bool `group:"include-all-providers,omitempty"`
|
||||
Hidden bool `group:"hidden,omitempty"`
|
||||
Icon string `group:"icon,omitempty"`
|
||||
|
||||
// removed configs, only for error logging
|
||||
Interface string `group:"interface-name,omitempty"`
|
||||
RoutingMark int `group:"routing-mark,omitempty"`
|
||||
}
|
||||
|
||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]P.ProxyProvider, AllProxies []string, AllProviders []string) (C.ProxyAdapter, error) {
|
||||
@@ -62,12 +58,15 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
||||
return nil, errFormat
|
||||
}
|
||||
|
||||
if groupOption.RoutingMark != 0 {
|
||||
if _, ok := config["routing-mark"]; ok {
|
||||
log.Errorln("The group [%s] with routing-mark configuration was removed, please set it directly on the proxy instead", groupOption.Name)
|
||||
}
|
||||
if groupOption.Interface != "" {
|
||||
if _, ok := config["interface-name"]; ok {
|
||||
log.Errorln("The group [%s] with interface-name configuration was removed, please set it directly on the proxy instead", groupOption.Name)
|
||||
}
|
||||
if _, ok := config["dialer-proxy"]; ok {
|
||||
log.Errorln("The group [%s] with dialer-proxy configuration is not allowed, please set it directly on the proxy instead", groupOption.Name)
|
||||
}
|
||||
|
||||
groupName := groupOption.Name
|
||||
|
||||
|
||||
@@ -159,6 +159,20 @@ 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)
|
||||
case "trusttunnel":
|
||||
trustTunnelOption := &outbound.TrustTunnelOption{BasicOption: basicOption}
|
||||
err = decoder.Decode(mapping, trustTunnelOption)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
proxy, err = outbound.NewTrustTunnel(*trustTunnelOption)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||
}
|
||||
|
||||
88
adapter/provider/override.go
Normal file
88
adapter/provider/override.go
Normal file
@@ -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-name"] = *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))
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package buf
|
||||
|
||||
import (
|
||||
"github.com/metacubex/sing/common"
|
||||
"github.com/metacubex/sing/common/buf"
|
||||
)
|
||||
|
||||
@@ -9,14 +8,52 @@ const BufferSize = buf.BufferSize
|
||||
|
||||
type Buffer = buf.Buffer
|
||||
|
||||
var New = buf.New
|
||||
var NewPacket = buf.NewPacket
|
||||
var NewSize = buf.NewSize
|
||||
var With = buf.With
|
||||
var As = buf.As
|
||||
var ReleaseMulti = buf.ReleaseMulti
|
||||
func New() *Buffer {
|
||||
return buf.New()
|
||||
}
|
||||
|
||||
var (
|
||||
Must = common.Must
|
||||
Error = common.Error
|
||||
)
|
||||
func NewPacket() *Buffer {
|
||||
return buf.NewPacket()
|
||||
}
|
||||
|
||||
func NewSize(size int) *Buffer {
|
||||
return buf.NewSize(size)
|
||||
}
|
||||
|
||||
func With(data []byte) *Buffer {
|
||||
return buf.With(data)
|
||||
}
|
||||
|
||||
func As(data []byte) *Buffer {
|
||||
return buf.As(data)
|
||||
}
|
||||
|
||||
func ReleaseMulti(buffers []*Buffer) {
|
||||
buf.ReleaseMulti(buffers)
|
||||
}
|
||||
|
||||
func Error(_ any, err error) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func Must(errs ...error) {
|
||||
for _, err := range errs {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Must1[T any](result T, err error) T {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func Must2[T any, T2 any](result T, result2 T2, err error) (T, T2) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return result, result2
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
8
common/orderedmap/doc.go
Normal file
8
common/orderedmap/doc.go
Normal file
@@ -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
|
||||
139
common/orderedmap/json.go
Normal file
139
common/orderedmap/json.go
Normal file
@@ -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
|
||||
}
|
||||
117
common/orderedmap/json_fuzz_test.go
Normal file
117
common/orderedmap/json_fuzz_test.go
Normal file
@@ -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
|
||||
}
|
||||
338
common/orderedmap/json_test.go
Normal file
338
common/orderedmap/json_test.go
Normal file
@@ -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: `{"<22>":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)
|
||||
}
|
||||
}
|
||||
295
common/orderedmap/orderedmap.go
Normal file
295
common/orderedmap/orderedmap.go
Normal file
@@ -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
|
||||
}
|
||||
384
common/orderedmap/orderedmap_test.go
Normal file
384
common/orderedmap/orderedmap_test.go
Normal file
@@ -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())
|
||||
})
|
||||
}
|
||||
76
common/orderedmap/utils_test.go
Normal file
76
common/orderedmap/utils_test.go
Normal file
@@ -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)
|
||||
}
|
||||
71
common/orderedmap/yaml.go
Normal file
71
common/orderedmap/yaml.go
Normal file
@@ -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
|
||||
}
|
||||
82
common/orderedmap/yaml_fuzz_test.go
Normal file
82
common/orderedmap/yaml_fuzz_test.go
Normal file
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
334
common/orderedmap/yaml_test.go
Normal file
334
common/orderedmap/yaml_test.go
Normal file
@@ -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: "<22>: 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)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
@@ -38,58 +39,7 @@ func (d *Decoder) Decode(src map[string]any, dst any) error {
|
||||
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
||||
return fmt.Errorf("decode must recive a ptr struct")
|
||||
}
|
||||
t := reflect.TypeOf(dst).Elem()
|
||||
v := reflect.ValueOf(dst).Elem()
|
||||
for idx := 0; idx < v.NumField(); idx++ {
|
||||
field := t.Field(idx)
|
||||
if field.Anonymous {
|
||||
if err := d.decodeStruct(field.Name, src, v.Field(idx)); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
tag := field.Tag.Get(d.option.TagName)
|
||||
key, omitKey, found := strings.Cut(tag, ",")
|
||||
omitempty := found && omitKey == "omitempty"
|
||||
|
||||
// As a special case, if the field tag is "-", the field is always omitted.
|
||||
// Note that a field with name "-" can still be generated using the tag "-,".
|
||||
if key == "-" {
|
||||
continue
|
||||
}
|
||||
|
||||
value, ok := src[key]
|
||||
if !ok {
|
||||
if d.option.KeyReplacer != nil {
|
||||
key = d.option.KeyReplacer.Replace(key)
|
||||
}
|
||||
|
||||
for _strKey := range src {
|
||||
strKey := _strKey
|
||||
if d.option.KeyReplacer != nil {
|
||||
strKey = d.option.KeyReplacer.Replace(strKey)
|
||||
}
|
||||
if strings.EqualFold(key, strKey) {
|
||||
value = src[_strKey]
|
||||
ok = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if !ok || value == nil {
|
||||
if omitempty {
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("key '%s' missing", key)
|
||||
}
|
||||
|
||||
err := d.decode(key, value, v.Field(idx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return d.decode("", src, reflect.ValueOf(dst).Elem())
|
||||
}
|
||||
|
||||
// isNil returns true if the input is nil or a typed nil pointer.
|
||||
@@ -456,6 +406,7 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
||||
dataValKeysUnused[dataValKey.Interface()] = struct{}{}
|
||||
}
|
||||
|
||||
targetValKeysUnused := make(map[any]struct{})
|
||||
errors := make([]string, 0)
|
||||
|
||||
// This slice will keep track of all the structs we'll be decoding.
|
||||
@@ -470,6 +421,11 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
||||
field reflect.StructField
|
||||
val reflect.Value
|
||||
}
|
||||
|
||||
// remainField is set to a valid field set with the "remain" tag if
|
||||
// we are keeping track of remaining values.
|
||||
var remainField *field
|
||||
|
||||
var fields []field
|
||||
for len(structs) > 0 {
|
||||
structVal := structs[0]
|
||||
@@ -479,30 +435,47 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
||||
|
||||
for i := 0; i < structType.NumField(); i++ {
|
||||
fieldType := structType.Field(i)
|
||||
fieldKind := fieldType.Type.Kind()
|
||||
fieldVal := structVal.Field(i)
|
||||
if fieldVal.Kind() == reflect.Ptr && fieldVal.Elem().Kind() == reflect.Struct {
|
||||
// Handle embedded struct pointers as embedded structs.
|
||||
fieldVal = fieldVal.Elem()
|
||||
}
|
||||
|
||||
// If "squash" is specified in the tag, we squash the field down.
|
||||
squash := false
|
||||
squash := fieldVal.Kind() == reflect.Struct && fieldType.Anonymous
|
||||
remain := false
|
||||
|
||||
// We always parse the tags cause we're looking for other tags too
|
||||
tagParts := strings.Split(fieldType.Tag.Get(d.option.TagName), ",")
|
||||
for _, tag := range tagParts[1:] {
|
||||
if tag == "squash" {
|
||||
squash = true
|
||||
break
|
||||
}
|
||||
|
||||
if tag == "remain" {
|
||||
remain = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if squash {
|
||||
if fieldKind != reflect.Struct {
|
||||
if fieldVal.Kind() != reflect.Struct {
|
||||
errors = append(errors,
|
||||
fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind).Error())
|
||||
fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldVal.Kind()).Error())
|
||||
} else {
|
||||
structs = append(structs, structVal.FieldByName(fieldType.Name))
|
||||
structs = append(structs, fieldVal)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Normal struct field, store it away
|
||||
fields = append(fields, field{fieldType, structVal.Field(i)})
|
||||
// Build our field
|
||||
if remain {
|
||||
remainField = &field{fieldType, fieldVal}
|
||||
} else {
|
||||
// Normal struct field, store it away
|
||||
fields = append(fields, field{fieldType, fieldVal})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -511,8 +484,8 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
||||
field, fieldValue := f.field, f.val
|
||||
fieldName := field.Name
|
||||
|
||||
tagValue := field.Tag.Get(d.option.TagName)
|
||||
tagValue = strings.SplitN(tagValue, ",", 2)[0]
|
||||
tagParts := strings.Split(field.Tag.Get(d.option.TagName), ",")
|
||||
tagValue := tagParts[0]
|
||||
if tagValue != "" {
|
||||
fieldName = tagValue
|
||||
}
|
||||
@@ -521,6 +494,13 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
||||
continue
|
||||
}
|
||||
|
||||
omitempty := false
|
||||
for _, tag := range tagParts[1:] {
|
||||
if tag == "omitempty" {
|
||||
omitempty = true
|
||||
}
|
||||
}
|
||||
|
||||
rawMapKey := reflect.ValueOf(fieldName)
|
||||
rawMapVal := dataVal.MapIndex(rawMapKey)
|
||||
if !rawMapVal.IsValid() {
|
||||
@@ -548,7 +528,10 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
||||
|
||||
if !rawMapVal.IsValid() {
|
||||
// There was no matching key in the map for the value in
|
||||
// the struct. Just ignore.
|
||||
// the struct. Remember it for potential errors and metadata.
|
||||
if !omitempty {
|
||||
targetValKeysUnused[fieldName] = struct{}{}
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -570,7 +553,7 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
||||
// If the name is empty string, then we're at the root, and we
|
||||
// don't dot-join the fields.
|
||||
if name != "" {
|
||||
fieldName = fmt.Sprintf("%s.%s", name, fieldName)
|
||||
fieldName = name + "." + fieldName
|
||||
}
|
||||
|
||||
if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil {
|
||||
@@ -578,6 +561,36 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
||||
}
|
||||
}
|
||||
|
||||
// If we have a "remain"-tagged field and we have unused keys then
|
||||
// we put the unused keys directly into the remain field.
|
||||
if remainField != nil && len(dataValKeysUnused) > 0 {
|
||||
// Build a map of only the unused values
|
||||
remain := map[interface{}]interface{}{}
|
||||
for key := range dataValKeysUnused {
|
||||
remain[key] = dataVal.MapIndex(reflect.ValueOf(key)).Interface()
|
||||
}
|
||||
|
||||
// Decode it as-if we were just decoding this map onto our map.
|
||||
if err := d.decodeMap(name, remain, remainField.val); err != nil {
|
||||
errors = append(errors, err.Error())
|
||||
}
|
||||
|
||||
// Set the map to nil so we have none so that the next check will
|
||||
// not error (ErrorUnused)
|
||||
dataValKeysUnused = nil
|
||||
}
|
||||
|
||||
if len(targetValKeysUnused) > 0 {
|
||||
keys := make([]string, 0, len(targetValKeysUnused))
|
||||
for rawKey := range targetValKeysUnused {
|
||||
keys = append(keys, rawKey.(string))
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
err := fmt.Errorf("'%s' has unset fields: %s", name, strings.Join(keys, ", "))
|
||||
errors = append(errors, err.Error())
|
||||
}
|
||||
|
||||
if len(errors) > 0 {
|
||||
return fmt.Errorf(strings.Join(errors, ","))
|
||||
}
|
||||
|
||||
@@ -139,6 +139,49 @@ func TestStructure_Nest(t *testing.T) {
|
||||
assert.Equal(t, s.BazOptional, goal)
|
||||
}
|
||||
|
||||
func TestStructure_DoubleNest(t *testing.T) {
|
||||
rawMap := map[string]any{
|
||||
"bar": map[string]any{
|
||||
"foo": 1,
|
||||
},
|
||||
}
|
||||
|
||||
goal := BazOptional{
|
||||
Foo: 1,
|
||||
}
|
||||
|
||||
s := &struct {
|
||||
Bar struct {
|
||||
BazOptional
|
||||
} `test:"bar"`
|
||||
}{}
|
||||
err := decoder.Decode(rawMap, s)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, s.Bar.BazOptional, goal)
|
||||
}
|
||||
|
||||
func TestStructure_Remain(t *testing.T) {
|
||||
rawMap := map[string]any{
|
||||
"foo": 1,
|
||||
"bar": "test",
|
||||
"extra": false,
|
||||
}
|
||||
|
||||
goal := &Baz{
|
||||
Foo: 1,
|
||||
Bar: "test",
|
||||
}
|
||||
|
||||
s := &struct {
|
||||
Baz
|
||||
Remain map[string]any `test:",remain"`
|
||||
}{}
|
||||
err := decoder.Decode(rawMap, s)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, *goal, s.Baz)
|
||||
assert.Equal(t, map[string]any{"extra": false}, s.Remain)
|
||||
}
|
||||
|
||||
func TestStructure_SliceNilValue(t *testing.T) {
|
||||
rawMap := map[string]any{
|
||||
"foo": 1,
|
||||
@@ -228,6 +271,23 @@ func TestStructure_Pointer(t *testing.T) {
|
||||
assert.Nil(t, s.Bar)
|
||||
}
|
||||
|
||||
func TestStructure_PointerStruct(t *testing.T) {
|
||||
rawMap := map[string]any{
|
||||
"foo": "foo",
|
||||
}
|
||||
|
||||
s := &struct {
|
||||
Foo *string `test:"foo,omitempty"`
|
||||
Bar *Baz `test:"bar,omitempty"`
|
||||
}{}
|
||||
|
||||
err := decoder.Decode(rawMap, s)
|
||||
assert.Nil(t, err)
|
||||
assert.NotNil(t, s.Foo)
|
||||
assert.Equal(t, "foo", *s.Foo)
|
||||
assert.Nil(t, s.Bar)
|
||||
}
|
||||
|
||||
type num struct {
|
||||
a int
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -50,7 +50,7 @@ func HttpRequest(ctx context.Context, url, method string, header map[string][]st
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := header["User-Agent"]; !ok {
|
||||
if req.Header.Get("User-Agent") == "" {
|
||||
req.Header.Set("User-Agent", UA())
|
||||
}
|
||||
|
||||
|
||||
@@ -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,47 @@ 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 ConnectionState = utls.ConnectionState
|
||||
|
||||
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 +189,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 +236,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
|
||||
}
|
||||
|
||||
|
||||
160
config/config.go
160
config/config.go
@@ -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
|
||||
|
||||
79
config/utils_test.go
Normal file
79
config/utils_test.go
Normal file
@@ -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,8 @@ const (
|
||||
Mieru
|
||||
AnyTLS
|
||||
Sudoku
|
||||
Masque
|
||||
TrustTunnel
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -212,6 +214,10 @@ func (at AdapterType) String() string {
|
||||
return "AnyTLS"
|
||||
case Sudoku:
|
||||
return "Sudoku"
|
||||
case Masque:
|
||||
return "Masque"
|
||||
case TrustTunnel:
|
||||
return "TrustTunnel"
|
||||
case Relay:
|
||||
return "Relay"
|
||||
case Selector:
|
||||
|
||||
@@ -40,6 +40,7 @@ const (
|
||||
ANYTLS
|
||||
MIERU
|
||||
SUDOKU
|
||||
TRUSTTUNNEL
|
||||
INNER
|
||||
)
|
||||
|
||||
@@ -115,6 +116,8 @@ func (t Type) String() string {
|
||||
return "Mieru"
|
||||
case SUDOKU:
|
||||
return "Sudoku"
|
||||
case TRUSTTUNNEL:
|
||||
return "TrustTunnel"
|
||||
case INNER:
|
||||
return "Inner"
|
||||
default:
|
||||
@@ -159,6 +162,8 @@ func ParseType(t string) (*Type, error) {
|
||||
res = MIERU
|
||||
case "SUDOKU":
|
||||
res = SUDOKU
|
||||
case "TRUSTTUNNEL":
|
||||
res = TRUSTTUNNEL
|
||||
case "INNER":
|
||||
res = INNER
|
||||
default:
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
10
dns/doh.go
10
dns/doh.go
@@ -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
|
||||
|
||||
31
dns/doq.go
31
dns/doq.go
@@ -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)
|
||||
|
||||
176
dns/dot.go
Normal file
176
dns/dot.go
Normal file
@@ -0,0 +1,176 @@
|
||||
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
|
||||
disableReuse 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
|
||||
|
||||
if !t.disableReuse {
|
||||
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
|
||||
}
|
||||
|
||||
if !t.disableReuse {
|
||||
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()
|
||||
} else {
|
||||
_ = conn.Close()
|
||||
}
|
||||
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() {
|
||||
if !t.disableReuse {
|
||||
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
|
||||
}
|
||||
if params["disable-reuse"] == "true" {
|
||||
c.disableReuse = true
|
||||
}
|
||||
runtime.SetFinalizer(c, (*dnsOverTLS).Close)
|
||||
return c
|
||||
}
|
||||
@@ -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":
|
||||
|
||||
137
docs/config.yaml
137
docs/config.yaml
@@ -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 不兼容!!!
|
||||
@@ -1055,6 +1077,8 @@ proxies: # socks5
|
||||
# multiplexing: MULTIPLEXING_LOW
|
||||
# 如果想开启 0-RTT 握手,请设置为 HANDSHAKE_NO_WAIT,否则请设置为 HANDSHAKE_STANDARD。默认值为 HANDSHAKE_STANDARD
|
||||
# handshake-mode: HANDSHAKE_STANDARD
|
||||
# 一个 base64 字符串用于微调网络行为
|
||||
# traffic-pattern: ""
|
||||
|
||||
# sudoku
|
||||
- name: sudoku
|
||||
@@ -1062,19 +1086,29 @@ 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-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)
|
||||
# 推荐:使用 httpmask 对象统一管理 HTTPMask 相关字段:
|
||||
httpmask:
|
||||
disable: false # true 禁用所有 HTTP 伪装/隧道
|
||||
mode: legacy # 可选:legacy(默认)、stream(split-stream)、poll、auto(先 stream 再 poll)、ws(WebSocket 隧道)
|
||||
# tls: true # 可选:仅在 mode 为 stream/poll/auto/ws 时生效;true 强制 https/wss;false 强制 http/ws(不会根据端口自动推断)
|
||||
# host: "" # 可选:覆盖 Host/SNI(支持 example.com 或 example.com:443);仅在 mode 为 stream/poll/auto/ws 时生效
|
||||
# path_root: "" # 可选:HTTP 隧道端点一级路径前缀(双方需一致),例如 "aabbcc" 或 "/aabbcc/" => /aabbcc/session、/aabbcc/stream、/aabbcc/api/v1/upload、/aabbcc/ws
|
||||
# multiplex: off # 可选:off(默认)、auto(复用底层 HTTP 连接,减少建链 RTT)、on(Sudoku mux 单隧道多目标;仅在 mode=stream/poll/auto 生效;ws 强制 off)
|
||||
#
|
||||
# 向后兼容旧写法:
|
||||
# http-mask: true # 是否启用 http 掩码
|
||||
# http-mask-mode: legacy # 可选:legacy(默认)、stream(split-stream)、poll、auto(先 stream 再 poll)、ws(WebSocket 隧道)
|
||||
# http-mask-tls: true # 可选:仅在 http-mask-mode 为 stream/poll/auto/ws 时生效;true 强制 https/wss;false 强制 http/ws
|
||||
# http-mask-host: "" # 可选:覆盖 Host/SNI(支持 example.com 或 example.com:443);仅在 http-mask-mode 为 stream/poll/auto/ws 时生效
|
||||
# path-root: "" # 可选:HTTP 隧道端点一级路径前缀(双方需一致)
|
||||
# http-mask-multiplex: off # 可选:off(默认)、auto(复用底层 HTTP 连接)、on(Sudoku mux 单隧道多目标;ws 强制 off)
|
||||
enable-pure-downlink: false # 可选:false=带宽优化下行(更快,要求 aead-method != none);true=纯 Sudoku 下行
|
||||
|
||||
# anytls
|
||||
- name: anytls
|
||||
@@ -1093,6 +1127,23 @@ proxies: # socks5
|
||||
# - http/1.1
|
||||
# skip-cert-verify: true
|
||||
|
||||
# trusttunnel
|
||||
- name: trusttunnel
|
||||
type: trusttunnel
|
||||
server: 1.2.3.4
|
||||
port: 443
|
||||
username: username
|
||||
password: password
|
||||
# client-fingerprint: chrome
|
||||
health-check: true
|
||||
udp: true
|
||||
# sni: "example.com"
|
||||
# alpn:
|
||||
# - h2
|
||||
# skip-cert-verify: true
|
||||
# quic: true # 默认为false
|
||||
# congestion-controller: bbr
|
||||
|
||||
# dns 出站会将请求劫持到内部 dns 模块,所有请求均在内部处理
|
||||
- name: "dns-out"
|
||||
type: dns
|
||||
@@ -1606,23 +1657,35 @@ listeners:
|
||||
users:
|
||||
username1: password1
|
||||
username2: password2
|
||||
# 一个 base64 字符串用于微调网络行为
|
||||
# traffic-pattern: ""
|
||||
|
||||
- name: sudoku-in-1
|
||||
type: sudoku
|
||||
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)
|
||||
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
|
||||
handshake-timeout: 5 # 可选(秒)
|
||||
enable-pure-downlink: false # 可选:false=带宽优化下行(更快,要求 aead-method != none);true=纯 Sudoku 下行
|
||||
# 推荐:使用 httpmask 对象统一管理 HTTPMask 相关字段:
|
||||
httpmask:
|
||||
disable: false # true 禁用所有 HTTP 伪装/隧道
|
||||
mode: legacy # 可选:legacy(默认)、stream(split-stream)、poll、auto(先 stream 再 poll)、ws(WebSocket 隧道)
|
||||
# path_root: "" # 可选:HTTP 隧道端点一级路径前缀(双方需一致),例如 "aabbcc" 或 "/aabbcc/" => /aabbcc/session、/aabbcc/stream、/aabbcc/api/v1/upload、/aabbcc/ws
|
||||
#
|
||||
# 可选:当启用 HTTPMask 且识别到“像 HTTP 但不符合 tunnel/auth”的请求时,将原始字节透传给 fallback(常用于与其他服务共端口):
|
||||
# fallback: "127.0.0.1:80"
|
||||
#
|
||||
# 向后兼容旧写法:
|
||||
# disable-http-mask: false # 可选:禁用 http 掩码/隧道(默认为 false)
|
||||
# http-mask-mode: legacy # 可选:legacy(默认)、stream(split-stream)、poll、auto(先 stream 再 poll)、ws(WebSocket 隧道)
|
||||
# path-root: "" # 可选:HTTP 隧道端点一级路径前缀(双方需一致)
|
||||
|
||||
|
||||
|
||||
@@ -1709,6 +1772,30 @@ listeners:
|
||||
# masquerade: http://127.0.0.1:8080 #作为反向代理
|
||||
# masquerade: https://127.0.0.1:8080 #作为反向代理
|
||||
|
||||
- name: trusttunnel-in-1
|
||||
type: trusttunnel
|
||||
port: 10821 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||
users:
|
||||
- username: 1
|
||||
password: 9d0cb9d0-964f-4ef6-897d-6c6b3ccf9e68
|
||||
certificate: ./server.crt # 证书 PEM 格式,或者 证书的路径
|
||||
private-key: ./server.key # 证书对应的私钥 PEM 格式,或者私钥路径
|
||||
network: ["tcp", "udp"] # http2+http3
|
||||
congestion-controller: bbr
|
||||
# 下面两项为mTLS配置项,如果client-auth-type设置为 "verify-if-given" 或 "require-and-verify" 则client-auth-cert必须不为空
|
||||
# client-auth-type: "" # 可选值:""、"request"、"require-any"、"verify-if-given"、"require-and-verify"
|
||||
# client-auth-cert: string # 证书 PEM 格式,或者 证书的路径
|
||||
# 如果填写则开启ech(可由 mihomo generate ech-keypair <明文域名> 生成)
|
||||
# ech-key: |
|
||||
# -----BEGIN ECH KEYS-----
|
||||
# ACATwY30o/RKgD6hgeQxwrSiApLaCgU+HKh7B6SUrAHaDwBD/g0APwAAIAAgHjzK
|
||||
# madSJjYQIf9o1N5GXjkW4DEEeb17qMxHdwMdNnwADAABAAEAAQACAAEAAwAIdGVz
|
||||
# dC5jb20AAA==
|
||||
# -----END ECH KEYS-----
|
||||
|
||||
# 注意,listeners中的tun仅提供给高级用户使用,普通用户应使用顶层配置中的tun
|
||||
- name: tun-in-1
|
||||
type: tun
|
||||
|
||||
50
go.mod
50
go.mod
@@ -3,75 +3,80 @@ module github.com/metacubex/mihomo
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.1.0
|
||||
github.com/bahlo/generic-list-go v0.2.0
|
||||
github.com/coreos/go-iptables v0.8.0
|
||||
github.com/dlclark/regexp2 v1.11.5
|
||||
github.com/enfein/mieru/v3 v3.26.2
|
||||
github.com/enfein/mieru/v3 v3.28.0
|
||||
github.com/gobwas/ws v1.4.0
|
||||
github.com/gofrs/uuid/v5 v5.4.0
|
||||
github.com/golang/snappy v1.0.0
|
||||
github.com/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/edwards25519 v1.2.0
|
||||
github.com/metacubex/fswatch v0.1.1
|
||||
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759
|
||||
github.com/metacubex/http v0.1.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.20260213014310-4df8f0de5b56
|
||||
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.16-0.20260213034958-b09e3f5bbae6
|
||||
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
|
||||
|
||||
50
go.sum
50
go.sum
@@ -1,5 +1,3 @@
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/RyuaNerin/go-krypto v1.3.0 h1:smavTzSMAx8iuVlGb4pEwl9MD2qicqMzuXR2QWp2/Pg=
|
||||
github.com/RyuaNerin/go-krypto v1.3.0/go.mod h1:9R9TU936laAIqAmjcHo/LsaXYOZlymudOAxjaBf62UM=
|
||||
github.com/RyuaNerin/testingutil v0.1.0 h1:IYT6JL57RV3U2ml3dLHZsVtPOP6yNK7WUVdzzlpNrss=
|
||||
@@ -12,8 +10,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,8 +18,10 @@ 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/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/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.28.0 h1:4OsFPUIjKfQ6ymfyX1Laqz7h+zB8TxuK1m0isnYJ8ww=
|
||||
github.com/enfein/mieru/v3 v3.28.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
|
||||
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 h1:kXYqH/sL8dS/FdoFjr12ePjnLPorPo2FsnrHNuXSDyo=
|
||||
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358/go.mod h1:hkIFzoiIPZYxdFOOLyDho59b7SrDfo+w3h+yWdlg45I=
|
||||
github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 h1:8j2RH289RJplhA6WfdaPqzg1MjH2K8wX5e0uhAxrw2g=
|
||||
@@ -59,7 +57,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 +69,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,8 +87,12 @@ 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/edwards25519 v1.2.0 h1:pIQZLBsjQgg3Nl/c86YYFEUAbL5qQRnPq4LrgIw0KK4=
|
||||
github.com/metacubex/edwards25519 v1.2.0/go.mod h1:NCQF3J/Ki7382FJuokwsywEIIEI/gro/3smyXgQJsx0=
|
||||
github.com/metacubex/fswatch v0.1.1 h1:jqU7C/v+g0qc2RUFgmAOPoVvfl2BXXUXEumn6oQuxhU=
|
||||
github.com/metacubex/fswatch v0.1.1/go.mod h1:czrTT7Zlbz7vWft8RQu9Qqh+JoX+Nnb+UabuyN1YsgI=
|
||||
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759 h1:cjd4biTvOzK9ubNCCkQ+ldc4YSH/rILn53l/xGBFHHI=
|
||||
@@ -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.20260213014310-4df8f0de5b56 h1:7yfF31COW2hiCovb5+3uSxRl3UKWOXjpS0j4N5U0qZ8=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260213014310-4df8f0de5b56/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.16-0.20260213034958-b09e3f5bbae6 h1:3yeZyDHGBmI/1XLsWBhr1sLhifWHkJa5J5Kf8djIbqs=
|
||||
github.com/metacubex/sing-tun v0.4.16-0.20260213034958-b09e3f5bbae6/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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ type SudokuServer struct {
|
||||
DisableHTTPMask bool `json:"disable-http-mask,omitempty"`
|
||||
HTTPMaskMode string `json:"http-mask-mode,omitempty"`
|
||||
PathRoot string `json:"path-root,omitempty"`
|
||||
Fallback string `json:"fallback,omitempty"`
|
||||
|
||||
// mihomo private extension (not the part of standard Sudoku protocol)
|
||||
MuxOption sing.MuxOption `json:"mux-option,omitempty"`
|
||||
|
||||
24
listener/config/trusttunnel.go
Normal file
24
listener/config/trusttunnel.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
type TrustTunnelServer struct {
|
||||
Enable bool `yaml:"enable" json:"enable"`
|
||||
Listen string `yaml:"listen" json:"listen"`
|
||||
Users map[string]string `yaml:"users" json:"users,omitempty"`
|
||||
Certificate string `yaml:"certificate" json:"certificate"`
|
||||
PrivateKey string `yaml:"private-key" json:"private-key"`
|
||||
ClientAuthType string `yaml:"client-auth-type" json:"client-auth-type,omitempty"`
|
||||
ClientAuthCert string `yaml:"client-auth-cert" json:"client-auth-cert,omitempty"`
|
||||
EchKey string `yaml:"ech-key" json:"ech-key"`
|
||||
Network []string `yaml:"network" json:"network,omitempty"`
|
||||
CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
|
||||
CWND int `yaml:"cwnd" json:"cwnd,omitempty"`
|
||||
}
|
||||
|
||||
func (t TrustTunnelServer) String() string {
|
||||
b, _ := json.Marshal(t)
|
||||
return string(b)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
mieruserver "github.com/enfein/mieru/v3/apis/server"
|
||||
mierutp "github.com/enfein/mieru/v3/apis/trafficpattern"
|
||||
mierupb "github.com/enfein/mieru/v3/pkg/appctl/appctlpb"
|
||||
)
|
||||
|
||||
@@ -26,8 +27,9 @@ type Mieru struct {
|
||||
|
||||
type MieruOption struct {
|
||||
BaseOption
|
||||
Transport string `inbound:"transport"`
|
||||
Users map[string]string `inbound:"users"`
|
||||
Transport string `inbound:"transport"`
|
||||
Users map[string]string `inbound:"users"`
|
||||
TrafficPattern string `inbound:"traffic-pattern,omitempty"`
|
||||
}
|
||||
|
||||
type mieruListenerFactory struct{}
|
||||
@@ -154,10 +156,13 @@ func buildMieruServerConfig(option *MieruOption, ports utils.IntRanges[uint16])
|
||||
Password: proto.String(password),
|
||||
})
|
||||
}
|
||||
var trafficPattern *mierupb.TrafficPattern
|
||||
trafficPattern, _ = mierutp.Decode(option.TrafficPattern)
|
||||
return &mieruserver.ServerConfig{
|
||||
Config: &mierupb.ServerConfig{
|
||||
PortBindings: portBindings,
|
||||
Users: users,
|
||||
PortBindings: portBindings,
|
||||
Users: users,
|
||||
TrafficPattern: trafficPattern,
|
||||
},
|
||||
StreamListenerFactory: mieruListenerFactory{},
|
||||
PacketListenerFactory: mieruListenerFactory{},
|
||||
@@ -179,5 +184,14 @@ func validateMieruOption(option *MieruOption) error {
|
||||
return fmt.Errorf("password is empty")
|
||||
}
|
||||
}
|
||||
if option.TrafficPattern != "" {
|
||||
trafficPattern, err := mierutp.Decode(option.TrafficPattern)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode traffic pattern %q: %w", option.TrafficPattern, err)
|
||||
}
|
||||
if err := mierutp.Validate(trafficPattern); err != nil {
|
||||
return fmt.Errorf("invalid traffic pattern %q: %w", option.TrafficPattern, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -61,6 +61,20 @@ func TestNewMieru(t *testing.T) {
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "valid traffic pattern",
|
||||
args: args{
|
||||
option: &inbound.MieruOption{
|
||||
BaseOption: inbound.BaseOption{
|
||||
Port: "8080",
|
||||
},
|
||||
Transport: "TCP",
|
||||
Users: map[string]string{"user": "pass"},
|
||||
TrafficPattern: "GgQIARAK",
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "invalid - no port",
|
||||
args: args{
|
||||
@@ -135,6 +149,20 @@ func TestNewMieru(t *testing.T) {
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "invalid traffic pattern",
|
||||
args: args{
|
||||
option: &inbound.MieruOption{
|
||||
BaseOption: inbound.BaseOption{
|
||||
Port: "8080",
|
||||
},
|
||||
Transport: "TCP",
|
||||
Users: map[string]string{"user": "pass"},
|
||||
TrafficPattern: "1212ababXYYX",
|
||||
},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
@@ -13,23 +13,31 @@ import (
|
||||
|
||||
type SudokuOption struct {
|
||||
BaseOption
|
||||
Key string `inbound:"key"`
|
||||
AEADMethod string `inbound:"aead-method,omitempty"`
|
||||
PaddingMin *int `inbound:"padding-min,omitempty"`
|
||||
PaddingMax *int `inbound:"padding-max,omitempty"`
|
||||
TableType string `inbound:"table-type,omitempty"` // "prefer_ascii" or "prefer_entropy"
|
||||
HandshakeTimeoutSecond *int `inbound:"handshake-timeout,omitempty"`
|
||||
EnablePureDownlink *bool `inbound:"enable-pure-downlink,omitempty"`
|
||||
CustomTable string `inbound:"custom-table,omitempty"` // optional custom byte layout, e.g. xpxvvpvv
|
||||
CustomTables []string `inbound:"custom-tables,omitempty"`
|
||||
DisableHTTPMask bool `inbound:"disable-http-mask,omitempty"`
|
||||
HTTPMaskMode string `inbound:"http-mask-mode,omitempty"` // "legacy" (default), "stream", "poll", "auto"
|
||||
PathRoot string `inbound:"path-root,omitempty"` // optional first-level path prefix for HTTP tunnel endpoints
|
||||
Key string `inbound:"key"`
|
||||
AEADMethod string `inbound:"aead-method,omitempty"`
|
||||
PaddingMin *int `inbound:"padding-min,omitempty"`
|
||||
PaddingMax *int `inbound:"padding-max,omitempty"`
|
||||
TableType string `inbound:"table-type,omitempty"` // "prefer_ascii" or "prefer_entropy"
|
||||
HandshakeTimeoutSecond *int `inbound:"handshake-timeout,omitempty"`
|
||||
EnablePureDownlink *bool `inbound:"enable-pure-downlink,omitempty"`
|
||||
CustomTable string `inbound:"custom-table,omitempty"` // optional custom byte layout, e.g. xpxvvpvv
|
||||
CustomTables []string `inbound:"custom-tables,omitempty"`
|
||||
DisableHTTPMask bool `inbound:"disable-http-mask,omitempty"`
|
||||
HTTPMaskMode string `inbound:"http-mask-mode,omitempty"` // "legacy" (default), "stream", "poll", "auto"
|
||||
PathRoot string `inbound:"path-root,omitempty"` // optional first-level path prefix for HTTP tunnel endpoints
|
||||
Fallback string `inbound:"fallback,omitempty"`
|
||||
HTTPMaskOptions *SudokuHTTPMaskOptions `inbound:"httpmask,omitempty"`
|
||||
|
||||
// mihomo private extension (not the part of standard Sudoku protocol)
|
||||
MuxOption MuxOption `inbound:"mux-option,omitempty"`
|
||||
}
|
||||
|
||||
type SudokuHTTPMaskOptions struct {
|
||||
Disable bool `inbound:"disable,omitempty"`
|
||||
Mode string `inbound:"mode,omitempty"`
|
||||
PathRoot string `inbound:"path_root,omitempty"`
|
||||
}
|
||||
|
||||
func (o SudokuOption) Equal(config C.InboundConfig) bool {
|
||||
return optionToString(o) == optionToString(config)
|
||||
}
|
||||
@@ -65,6 +73,16 @@ func NewSudoku(options *SudokuOption) (*Sudoku, error) {
|
||||
DisableHTTPMask: options.DisableHTTPMask,
|
||||
HTTPMaskMode: options.HTTPMaskMode,
|
||||
PathRoot: strings.TrimSpace(options.PathRoot),
|
||||
Fallback: strings.TrimSpace(options.Fallback),
|
||||
}
|
||||
if hm := options.HTTPMaskOptions; hm != nil {
|
||||
serverConf.DisableHTTPMask = hm.Disable
|
||||
if hm.Mode != "" {
|
||||
serverConf.HTTPMaskMode = hm.Mode
|
||||
}
|
||||
if pr := strings.TrimSpace(hm.PathRoot); pr != "" {
|
||||
serverConf.PathRoot = pr
|
||||
}
|
||||
}
|
||||
serverConf.MuxOption = options.MuxOption.Build()
|
||||
|
||||
|
||||
@@ -168,16 +168,17 @@ func TestInboundSudoku_CustomTable(t *testing.T) {
|
||||
func TestInboundSudoku_HTTPMaskMode(t *testing.T) {
|
||||
key := "test_key_http_mask_mode"
|
||||
|
||||
for _, mode := range []string{"legacy", "stream", "poll", "auto"} {
|
||||
for _, mode := range []string{"ws", "stream", "poll", "auto"} {
|
||||
mode := mode
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
inboundOptions := inbound.SudokuOption{
|
||||
Key: key,
|
||||
HTTPMaskMode: mode,
|
||||
}
|
||||
httpMask := true
|
||||
outboundOptions := outbound.SudokuOption{
|
||||
Key: key,
|
||||
HTTPMask: true,
|
||||
HTTPMask: &httpMask,
|
||||
HTTPMaskMode: mode,
|
||||
}
|
||||
testInboundSudoku(t, inboundOptions, outboundOptions)
|
||||
|
||||
96
listener/inbound/trusttunnel.go
Normal file
96
listener/inbound/trusttunnel.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package inbound
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
LC "github.com/metacubex/mihomo/listener/config"
|
||||
"github.com/metacubex/mihomo/listener/trusttunnel"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
)
|
||||
|
||||
type TrustTunnelOption struct {
|
||||
BaseOption
|
||||
Users AuthUsers `inbound:"users,omitempty"`
|
||||
Certificate string `inbound:"certificate"`
|
||||
PrivateKey string `inbound:"private-key"`
|
||||
ClientAuthType string `inbound:"client-auth-type,omitempty"`
|
||||
ClientAuthCert string `inbound:"client-auth-cert,omitempty"`
|
||||
EchKey string `inbound:"ech-key,omitempty"`
|
||||
Network []string `inbound:"network,omitempty"`
|
||||
CongestionController string `inbound:"congestion-controller,omitempty"`
|
||||
CWND int `inbound:"cwnd,omitempty"`
|
||||
}
|
||||
|
||||
func (o TrustTunnelOption) Equal(config C.InboundConfig) bool {
|
||||
return optionToString(o) == optionToString(config)
|
||||
}
|
||||
|
||||
type TrustTunnel struct {
|
||||
*Base
|
||||
config *TrustTunnelOption
|
||||
l C.MultiAddrListener
|
||||
vs LC.TrustTunnelServer
|
||||
}
|
||||
|
||||
func NewTrustTunnel(options *TrustTunnelOption) (*TrustTunnel, error) {
|
||||
base, err := NewBase(&options.BaseOption)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
users := make(map[string]string)
|
||||
for _, user := range options.Users {
|
||||
users[user.Username] = user.Password
|
||||
}
|
||||
return &TrustTunnel{
|
||||
Base: base,
|
||||
config: options,
|
||||
vs: LC.TrustTunnelServer{
|
||||
Enable: true,
|
||||
Listen: base.RawAddress(),
|
||||
Users: users,
|
||||
Certificate: options.Certificate,
|
||||
PrivateKey: options.PrivateKey,
|
||||
ClientAuthType: options.ClientAuthType,
|
||||
ClientAuthCert: options.ClientAuthCert,
|
||||
EchKey: options.EchKey,
|
||||
Network: options.Network,
|
||||
CongestionController: options.CongestionController,
|
||||
CWND: options.CWND,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Config implements constant.InboundListener
|
||||
func (v *TrustTunnel) Config() C.InboundConfig {
|
||||
return v.config
|
||||
}
|
||||
|
||||
// Address implements constant.InboundListener
|
||||
func (v *TrustTunnel) Address() string {
|
||||
var addrList []string
|
||||
if v.l != nil {
|
||||
for _, addr := range v.l.AddrList() {
|
||||
addrList = append(addrList, addr.String())
|
||||
}
|
||||
}
|
||||
return strings.Join(addrList, ",")
|
||||
}
|
||||
|
||||
// Listen implements constant.InboundListener
|
||||
func (v *TrustTunnel) Listen(tunnel C.Tunnel) error {
|
||||
var err error
|
||||
v.l, err = trusttunnel.New(v.vs, tunnel, v.Additions()...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Infoln("TrustTunnel[%s] proxy listening at: %s", v.Name(), v.Address())
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close implements constant.InboundListener
|
||||
func (v *TrustTunnel) Close() error {
|
||||
return v.l.Close()
|
||||
}
|
||||
|
||||
var _ C.InboundListener = (*TrustTunnel)(nil)
|
||||
109
listener/inbound/trusttunnel_test.go
Normal file
109
listener/inbound/trusttunnel_test.go
Normal file
@@ -0,0 +1,109 @@
|
||||
package inbound_test
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"testing"
|
||||
|
||||
"github.com/metacubex/mihomo/adapter/outbound"
|
||||
"github.com/metacubex/mihomo/listener/inbound"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func testInboundTrustTunnel(t *testing.T, inboundOptions inbound.TrustTunnelOption, outboundOptions outbound.TrustTunnelOption) {
|
||||
t.Parallel()
|
||||
inboundOptions.BaseOption = inbound.BaseOption{
|
||||
NameStr: "trusttunnel_inbound",
|
||||
Listen: "127.0.0.1",
|
||||
Port: "0",
|
||||
}
|
||||
inboundOptions.Users = []inbound.AuthUser{{Username: "test", Password: userUUID}}
|
||||
in, err := inbound.NewTrustTunnel(&inboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
}
|
||||
|
||||
tunnel := NewHttpTestTunnel()
|
||||
defer tunnel.Close()
|
||||
|
||||
err = in.Listen(tunnel)
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
}
|
||||
defer in.Close()
|
||||
|
||||
addrPort, err := netip.ParseAddrPort(in.Address())
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
}
|
||||
|
||||
outboundOptions.Name = "trusttunnel_outbound"
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.UserName = "test"
|
||||
outboundOptions.Password = userUUID
|
||||
|
||||
out, err := outbound.NewTrustTunnel(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
tunnel.DoTest(t, out)
|
||||
}
|
||||
|
||||
func testInboundTrustTunnelTLS(t *testing.T, quic bool) {
|
||||
inboundOptions := inbound.TrustTunnelOption{
|
||||
Certificate: tlsCertificate,
|
||||
PrivateKey: tlsPrivateKey,
|
||||
}
|
||||
outboundOptions := outbound.TrustTunnelOption{
|
||||
Fingerprint: tlsFingerprint,
|
||||
HealthCheck: true,
|
||||
}
|
||||
if quic {
|
||||
inboundOptions.Network = []string{"udp"}
|
||||
inboundOptions.CongestionController = "bbr"
|
||||
outboundOptions.Quic = true
|
||||
}
|
||||
testInboundTrustTunnel(t, inboundOptions, outboundOptions)
|
||||
t.Run("ECH", func(t *testing.T) {
|
||||
inboundOptions := inboundOptions
|
||||
outboundOptions := outboundOptions
|
||||
inboundOptions.EchKey = echKeyPem
|
||||
outboundOptions.ECHOpts = outbound.ECHOptions{
|
||||
Enable: true,
|
||||
Config: echConfigBase64,
|
||||
}
|
||||
testInboundTrustTunnel(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
t.Run("mTLS", func(t *testing.T) {
|
||||
inboundOptions := inboundOptions
|
||||
outboundOptions := outboundOptions
|
||||
inboundOptions.ClientAuthCert = tlsAuthCertificate
|
||||
outboundOptions.Certificate = tlsAuthCertificate
|
||||
outboundOptions.PrivateKey = tlsAuthPrivateKey
|
||||
testInboundTrustTunnel(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
t.Run("mTLS+ECH", func(t *testing.T) {
|
||||
inboundOptions := inboundOptions
|
||||
outboundOptions := outboundOptions
|
||||
inboundOptions.ClientAuthCert = tlsAuthCertificate
|
||||
outboundOptions.Certificate = tlsAuthCertificate
|
||||
outboundOptions.PrivateKey = tlsAuthPrivateKey
|
||||
inboundOptions.EchKey = echKeyPem
|
||||
outboundOptions.ECHOpts = outbound.ECHOptions{
|
||||
Enable: true,
|
||||
Config: echConfigBase64,
|
||||
}
|
||||
testInboundTrustTunnel(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
}
|
||||
|
||||
func TestInboundTrustTunnel_H2(t *testing.T) {
|
||||
testInboundTrustTunnelTLS(t, true)
|
||||
}
|
||||
|
||||
func TestInboundTrustTunnel_QUIC(t *testing.T) {
|
||||
testInboundTrustTunnelTLS(t, true)
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -26,7 +26,7 @@ type VmessOption struct {
|
||||
type VmessUser struct {
|
||||
Username string `inbound:"username,omitempty"`
|
||||
UUID string `inbound:"uuid"`
|
||||
AlterID int `inbound:"alterId"`
|
||||
AlterID int `inbound:"alterId,omitempty"`
|
||||
}
|
||||
|
||||
func (o VmessOption) Equal(config C.InboundConfig) bool {
|
||||
|
||||
@@ -141,6 +141,13 @@ func ParseListener(mapping map[string]any) (C.InboundListener, error) {
|
||||
return nil, err
|
||||
}
|
||||
listener, err = IN.NewSudoku(sudokuOption)
|
||||
case "trusttunnel":
|
||||
trusttunnelOption := &IN.TrustTunnelOption{}
|
||||
err = decoder.Decode(mapping, trusttunnelOption)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
listener, err = IN.NewTrustTunnel(trusttunnelOption)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
package sudoku
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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/inner"
|
||||
"github.com/metacubex/mihomo/listener/sing"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
"github.com/metacubex/mihomo/transport/socks5"
|
||||
@@ -21,6 +26,7 @@ type Listener struct {
|
||||
closed bool
|
||||
protoConf sudoku.ProtocolConfig
|
||||
tunnelSrv *sudoku.HTTPMaskTunnelServer
|
||||
fallback string
|
||||
handler *sing.ListenerHandler
|
||||
}
|
||||
|
||||
@@ -47,12 +53,19 @@ func (l *Listener) Close() error {
|
||||
}
|
||||
|
||||
func (l *Listener) handleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
|
||||
log.Debugln("[Sudoku] accepted %s", conn.RemoteAddr())
|
||||
handshakeConn := conn
|
||||
handshakeCfg := &l.protoConf
|
||||
closeConns := func() {
|
||||
_ = handshakeConn.Close()
|
||||
if handshakeConn != conn {
|
||||
_ = conn.Close()
|
||||
}
|
||||
}
|
||||
if l.tunnelSrv != nil {
|
||||
c, cfg, done, err := l.tunnelSrv.WrapConn(conn)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
closeConns()
|
||||
return
|
||||
}
|
||||
if done {
|
||||
@@ -66,9 +79,43 @@ func (l *Listener) handleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbou
|
||||
}
|
||||
}
|
||||
|
||||
session, err := sudoku.ServerHandshake(handshakeConn, handshakeCfg)
|
||||
if l.fallback != "" {
|
||||
if r, ok := handshakeConn.(interface{ IsHTTPMaskRejected() bool }); ok && r.IsHTTPMaskRejected() {
|
||||
fb, err := inner.HandleTcp(tunnel, l.fallback, "")
|
||||
if err != nil {
|
||||
closeConns()
|
||||
return
|
||||
}
|
||||
N.Relay(handshakeConn, fb)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
cConn, meta, err := sudoku.ServerHandshake(handshakeConn, handshakeCfg)
|
||||
if err != nil {
|
||||
_ = handshakeConn.Close()
|
||||
fallbackAddr := l.fallback
|
||||
var susp *sudoku.SuspiciousError
|
||||
isSuspicious := errors.As(err, &susp) && susp != nil && susp.Conn != nil
|
||||
if isSuspicious {
|
||||
log.Warnln("[Sudoku] suspicious handshake from %s: %v", conn.RemoteAddr(), err)
|
||||
if fallbackAddr != "" {
|
||||
fb, err := inner.HandleTcp(tunnel, fallbackAddr, "")
|
||||
if err == nil {
|
||||
relayToFallback(susp.Conn, conn, fb)
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.Debugln("[Sudoku] handshake failed from %s: %v", conn.RemoteAddr(), err)
|
||||
}
|
||||
closeConns()
|
||||
return
|
||||
}
|
||||
|
||||
session, err := sudoku.ReadServerSession(cConn, meta)
|
||||
if err != nil {
|
||||
log.Warnln("[Sudoku] read session failed from %s: %v", conn.RemoteAddr(), err)
|
||||
_ = cConn.Close()
|
||||
if handshakeConn != conn {
|
||||
_ = conn.Close()
|
||||
}
|
||||
@@ -101,6 +148,7 @@ func (l *Listener) handleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbou
|
||||
default:
|
||||
targetAddr := socks5.ParseAddr(session.Target)
|
||||
if targetAddr == nil {
|
||||
log.Warnln("[Sudoku] invalid target from %s: %q", conn.RemoteAddr(), session.Target)
|
||||
_ = session.Conn.Close()
|
||||
return
|
||||
}
|
||||
@@ -112,6 +160,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 +178,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...))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,6 +210,24 @@ func (p *uotPacket) LocalAddr() net.Addr {
|
||||
return p.rAddr
|
||||
}
|
||||
|
||||
func relayToFallback(wrapper net.Conn, rawConn net.Conn, fallback net.Conn) {
|
||||
if wrapper != nil {
|
||||
if recorder, ok := wrapper.(interface{ GetBufferedAndRecorded() []byte }); ok {
|
||||
badData := recorder.GetBufferedAndRecorded()
|
||||
if len(badData) > 0 {
|
||||
_ = fallback.SetWriteDeadline(time.Now().Add(3 * time.Second))
|
||||
if _, err := io.Copy(fallback, bytes.NewReader(badData)); err != nil {
|
||||
_ = fallback.Close()
|
||||
_ = rawConn.Close()
|
||||
return
|
||||
}
|
||||
_ = fallback.SetWriteDeadline(time.Time{})
|
||||
}
|
||||
}
|
||||
}
|
||||
N.Relay(rawConn, fallback)
|
||||
}
|
||||
|
||||
func New(config LC.SudokuServer, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
|
||||
if len(additions) == 0 {
|
||||
additions = []inbound.Addition{
|
||||
@@ -184,42 +252,24 @@ func New(config LC.SudokuServer, tunnel C.Tunnel, additions ...inbound.Addition)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tableType := strings.ToLower(config.TableType)
|
||||
if tableType == "" {
|
||||
tableType = "prefer_ascii"
|
||||
}
|
||||
|
||||
defaultConf := sudoku.DefaultConfig()
|
||||
paddingMin := defaultConf.PaddingMin
|
||||
paddingMax := defaultConf.PaddingMax
|
||||
if config.PaddingMin != nil {
|
||||
paddingMin = *config.PaddingMin
|
||||
}
|
||||
if config.PaddingMax != nil {
|
||||
paddingMax = *config.PaddingMax
|
||||
}
|
||||
if config.PaddingMin == nil && config.PaddingMax != nil && paddingMax < paddingMin {
|
||||
paddingMin = paddingMax
|
||||
}
|
||||
if config.PaddingMax == nil && config.PaddingMin != nil && paddingMax < paddingMin {
|
||||
paddingMax = paddingMin
|
||||
}
|
||||
enablePureDownlink := defaultConf.EnablePureDownlink
|
||||
if config.EnablePureDownlink != nil {
|
||||
enablePureDownlink = *config.EnablePureDownlink
|
||||
}
|
||||
|
||||
tables, err := sudoku.NewTablesWithCustomPatterns(config.Key, tableType, config.CustomTable, config.CustomTables)
|
||||
tableType, err := sudoku.NormalizeTableType(config.TableType)
|
||||
if err != nil {
|
||||
_ = l.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
handshakeTimeout := defaultConf.HandshakeTimeoutSeconds
|
||||
if config.HandshakeTimeoutSecond != nil {
|
||||
handshakeTimeout = *config.HandshakeTimeoutSecond
|
||||
defaultConf := sudoku.DefaultConfig()
|
||||
paddingMin, paddingMax := sudoku.ResolvePadding(config.PaddingMin, config.PaddingMax, defaultConf.PaddingMin, defaultConf.PaddingMax)
|
||||
enablePureDownlink := sudoku.DerefBool(config.EnablePureDownlink, defaultConf.EnablePureDownlink)
|
||||
|
||||
tables, err := sudoku.NewServerTablesWithCustomPatterns(sudoku.ServerAEADSeed(config.Key), tableType, config.CustomTable, config.CustomTables)
|
||||
if err != nil {
|
||||
_ = l.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
handshakeTimeout := sudoku.DerefInt(config.HandshakeTimeoutSecond, defaultConf.HandshakeTimeoutSeconds)
|
||||
|
||||
protoConf := sudoku.ProtocolConfig{
|
||||
Key: config.Key,
|
||||
AEADMethod: defaultConf.AEADMethod,
|
||||
@@ -245,8 +295,13 @@ func New(config LC.SudokuServer, tunnel C.Tunnel, additions ...inbound.Addition)
|
||||
addr: config.Listen,
|
||||
protoConf: protoConf,
|
||||
handler: h,
|
||||
fallback: strings.TrimSpace(config.Fallback),
|
||||
}
|
||||
if sl.fallback != "" {
|
||||
sl.tunnelSrv = sudoku.NewHTTPMaskTunnelServerWithFallback(&sl.protoConf)
|
||||
} else {
|
||||
sl.tunnelSrv = sudoku.NewHTTPMaskTunnelServer(&sl.protoConf)
|
||||
}
|
||||
sl.tunnelSrv = sudoku.NewHTTPMaskTunnelServer(&sl.protoConf)
|
||||
|
||||
go func() {
|
||||
for {
|
||||
|
||||
@@ -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...))
|
||||
}
|
||||
|
||||
188
listener/trusttunnel/server.go
Normal file
188
listener/trusttunnel/server.go
Normal file
@@ -0,0 +1,188 @@
|
||||
package trusttunnel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/metacubex/mihomo/adapter/inbound"
|
||||
"github.com/metacubex/mihomo/common/sockopt"
|
||||
"github.com/metacubex/mihomo/component/ca"
|
||||
"github.com/metacubex/mihomo/component/ech"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
LC "github.com/metacubex/mihomo/listener/config"
|
||||
"github.com/metacubex/mihomo/listener/sing"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
"github.com/metacubex/mihomo/ntp"
|
||||
"github.com/metacubex/mihomo/transport/trusttunnel"
|
||||
|
||||
"github.com/metacubex/tls"
|
||||
)
|
||||
|
||||
type Listener struct {
|
||||
closed bool
|
||||
config LC.TrustTunnelServer
|
||||
listeners []net.Listener
|
||||
udpListeners []net.PacketConn
|
||||
tlsConfig *tls.Config
|
||||
services []*trusttunnel.Service
|
||||
}
|
||||
|
||||
func New(config LC.TrustTunnelServer, tunnel C.Tunnel, additions ...inbound.Addition) (sl *Listener, err error) {
|
||||
if len(additions) == 0 {
|
||||
additions = []inbound.Addition{
|
||||
inbound.WithInName("DEFAULT-TRUSTTUNNEL"),
|
||||
inbound.WithSpecialRules(""),
|
||||
}
|
||||
}
|
||||
|
||||
tlsConfig := &tls.Config{Time: ntp.Now}
|
||||
if config.Certificate != "" && config.PrivateKey != "" {
|
||||
certLoader, err := ca.NewTLSKeyPairLoader(config.Certificate, config.PrivateKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConfig.GetCertificate = func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
return certLoader()
|
||||
}
|
||||
|
||||
if config.EchKey != "" {
|
||||
err = ech.LoadECHKey(config.EchKey, tlsConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
tlsConfig.ClientAuth = ca.ClientAuthTypeFromString(config.ClientAuthType)
|
||||
if len(config.ClientAuthCert) > 0 {
|
||||
if tlsConfig.ClientAuth == tls.NoClientCert {
|
||||
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
|
||||
}
|
||||
}
|
||||
if tlsConfig.ClientAuth == tls.VerifyClientCertIfGiven || tlsConfig.ClientAuth == tls.RequireAndVerifyClientCert {
|
||||
pool, err := ca.LoadCertificates(config.ClientAuthCert)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConfig.ClientCAs = pool
|
||||
}
|
||||
|
||||
sl = &Listener{
|
||||
config: config,
|
||||
tlsConfig: tlsConfig,
|
||||
}
|
||||
|
||||
h, err := sing.NewListenerHandler(sing.ListenerConfig{
|
||||
Tunnel: tunnel,
|
||||
Type: C.TRUSTTUNNEL,
|
||||
Additions: additions,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if tlsConfig.GetCertificate == nil {
|
||||
return nil, errors.New("disallow using TrustTunnel without certificates config")
|
||||
}
|
||||
|
||||
if len(config.Network) == 0 {
|
||||
config.Network = []string{"tcp"}
|
||||
}
|
||||
listenTCP, listenUDP := false, false
|
||||
for _, network := range config.Network {
|
||||
network = strings.ToLower(network)
|
||||
switch {
|
||||
case strings.HasPrefix(network, "tcp"):
|
||||
listenTCP = true
|
||||
case strings.HasPrefix(network, "udp"):
|
||||
listenUDP = true
|
||||
}
|
||||
}
|
||||
|
||||
for _, addr := range strings.Split(config.Listen, ",") {
|
||||
addr := addr
|
||||
|
||||
var (
|
||||
tcpListener net.Listener
|
||||
udpConn net.PacketConn
|
||||
)
|
||||
if listenTCP {
|
||||
tcpListener, err = inbound.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
_ = sl.Close()
|
||||
return nil, err
|
||||
}
|
||||
sl.listeners = append(sl.listeners, tcpListener)
|
||||
}
|
||||
if listenUDP {
|
||||
udpConn, err = inbound.ListenPacket("udp", addr)
|
||||
if err != nil {
|
||||
_ = sl.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := sockopt.UDPReuseaddr(udpConn); err != nil {
|
||||
log.Warnln("Failed to Reuse UDP Address: %s", err)
|
||||
}
|
||||
sl.udpListeners = append(sl.udpListeners, udpConn)
|
||||
}
|
||||
|
||||
service := trusttunnel.NewService(trusttunnel.ServiceOptions{
|
||||
Ctx: context.Background(),
|
||||
Logger: log.SingLogger,
|
||||
Handler: h,
|
||||
ICMPHandler: nil,
|
||||
QUICCongestionControl: config.CongestionController,
|
||||
QUICCwnd: config.CWND,
|
||||
})
|
||||
service.UpdateUsers(config.Users)
|
||||
err = service.Start(tcpListener, udpConn, tlsConfig)
|
||||
if err != nil {
|
||||
_ = sl.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sl.services = append(sl.services, service)
|
||||
}
|
||||
|
||||
return sl, nil
|
||||
}
|
||||
|
||||
func (l *Listener) Close() error {
|
||||
l.closed = true
|
||||
var retErr error
|
||||
for _, lis := range l.services {
|
||||
err := lis.Close()
|
||||
if err != nil {
|
||||
retErr = err
|
||||
}
|
||||
}
|
||||
for _, lis := range l.listeners {
|
||||
err := lis.Close()
|
||||
if err != nil {
|
||||
retErr = err
|
||||
}
|
||||
}
|
||||
for _, lis := range l.udpListeners {
|
||||
err := lis.Close()
|
||||
if err != nil {
|
||||
retErr = err
|
||||
}
|
||||
}
|
||||
return retErr
|
||||
}
|
||||
|
||||
func (l *Listener) Config() string {
|
||||
return l.config.String()
|
||||
}
|
||||
|
||||
func (l *Listener) AddrList() (addrList []net.Addr) {
|
||||
for _, lis := range l.listeners {
|
||||
addrList = append(addrList, lis.Addr())
|
||||
}
|
||||
for _, lis := range l.udpListeners {
|
||||
addrList = append(addrList, lis.LocalAddr())
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,9 +18,9 @@ import (
|
||||
|
||||
"github.com/metacubex/mihomo/common/buf"
|
||||
"github.com/metacubex/mihomo/common/pool"
|
||||
"github.com/metacubex/mihomo/component/ech"
|
||||
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/transport/vmess"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/http/httptrace"
|
||||
@@ -40,10 +40,10 @@ var defaultHeader = http.Header{
|
||||
type DialFn = func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||
|
||||
type Conn struct {
|
||||
initFn func() (io.ReadCloser, netAddr, error)
|
||||
initFn func() (io.ReadCloser, NetAddr, error)
|
||||
writer io.Writer // writer must not nil
|
||||
closer io.Closer
|
||||
netAddr
|
||||
NetAddr
|
||||
|
||||
initOnce sync.Once
|
||||
initErr error
|
||||
@@ -59,10 +59,9 @@ type Conn struct {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
ServiceName string
|
||||
UserAgent string
|
||||
Host string
|
||||
ClientFingerprint string
|
||||
ServiceName string
|
||||
UserAgent string
|
||||
Host string
|
||||
}
|
||||
|
||||
func (g *Conn) initReader() {
|
||||
@@ -74,7 +73,7 @@ func (g *Conn) initReader() {
|
||||
}
|
||||
return
|
||||
}
|
||||
g.netAddr = addr
|
||||
g.NetAddr = addr
|
||||
|
||||
g.closeMutex.Lock()
|
||||
defer g.closeMutex.Unlock()
|
||||
@@ -247,7 +246,7 @@ func (g *Conn) SetDeadline(t time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewHTTP2Client(dialFn DialFn, tlsConfig *tls.Config, clientFingerprint string, echConfig *ech.Config, realityConfig *tlsC.RealityConfig) *TransportWrap {
|
||||
func NewHTTP2Client(dialFn DialFn, tlsConfig *vmess.TLSConfig) *TransportWrap {
|
||||
dialFunc := func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, C.DefaultTLSTimeout)
|
||||
defer cancel()
|
||||
@@ -260,65 +259,33 @@ func NewHTTP2Client(dialFn DialFn, tlsConfig *tls.Config, clientFingerprint stri
|
||||
return pconn, nil
|
||||
}
|
||||
|
||||
if clientFingerprint, ok := tlsC.GetFingerprint(clientFingerprint); ok {
|
||||
if realityConfig == nil {
|
||||
tlsConfig := tlsC.UConfig(cfg)
|
||||
err := echConfig.ClientHandleUTLS(ctx, tlsConfig)
|
||||
if err != nil {
|
||||
pconn.Close()
|
||||
return nil, err
|
||||
}
|
||||
tlsConn := tlsC.UClient(pconn, tlsConfig, clientFingerprint)
|
||||
if err := tlsConn.HandshakeContext(ctx); err != nil {
|
||||
pconn.Close()
|
||||
return nil, err
|
||||
}
|
||||
conn, err := vmess.StreamTLSConn(ctx, pconn, tlsConfig)
|
||||
if err != nil {
|
||||
_ = pconn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if tlsConfig.Reality == nil { // reality doesn't return the negotiated ALPN
|
||||
switch tlsConn := conn.(type) {
|
||||
case interface{ ConnectionState() tls.ConnectionState }:
|
||||
state := tlsConn.ConnectionState()
|
||||
if p := state.NegotiatedProtocol; p != http.Http2NextProtoTLS {
|
||||
tlsConn.Close()
|
||||
_ = conn.Close()
|
||||
return nil, fmt.Errorf("http2: unexpected ALPN protocol %s, want %s", p, http.Http2NextProtoTLS)
|
||||
}
|
||||
return tlsConn, nil
|
||||
} else {
|
||||
realityConn, err := tlsC.GetRealityConn(ctx, pconn, clientFingerprint, cfg.ServerName, realityConfig)
|
||||
if err != nil {
|
||||
pconn.Close()
|
||||
return nil, err
|
||||
case interface{ ConnectionState() tlsC.ConnectionState }:
|
||||
state := tlsConn.ConnectionState()
|
||||
if p := state.NegotiatedProtocol; p != http.Http2NextProtoTLS {
|
||||
_ = conn.Close()
|
||||
return nil, fmt.Errorf("http2: unexpected ALPN protocol %s, want %s", p, http.Http2NextProtoTLS)
|
||||
}
|
||||
//state := realityConn.(*utls.UConn).ConnectionState()
|
||||
//if p := state.NegotiatedProtocol; p != http.Http2NextProtoTLS {
|
||||
// realityConn.Close()
|
||||
// return nil, fmt.Errorf("http2: unexpected ALPN protocol %s, want %s", p, http.Http2NextProtoTLS)
|
||||
//}
|
||||
return realityConn, nil
|
||||
}
|
||||
}
|
||||
if realityConfig != nil {
|
||||
return nil, errors.New("REALITY is based on uTLS, please set a client-fingerprint")
|
||||
}
|
||||
|
||||
err = echConfig.ClientHandle(ctx, cfg)
|
||||
if err != nil {
|
||||
pconn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
conn := tls.Client(pconn, cfg)
|
||||
if err := conn.HandshakeContext(ctx); err != nil {
|
||||
pconn.Close()
|
||||
return nil, err
|
||||
}
|
||||
state := conn.ConnectionState()
|
||||
if p := state.NegotiatedProtocol; p != http.Http2NextProtoTLS {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("http2: unexpected ALPN protocol %s, want %s", p, http.Http2NextProtoTLS)
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
transport := &http.Http2Transport{
|
||||
DialTLSContext: dialFunc,
|
||||
TLSClientConfig: tlsConfig,
|
||||
AllowHTTP: false,
|
||||
DisableCompression: true,
|
||||
PingTimeout: 0,
|
||||
@@ -351,7 +318,7 @@ func StreamGunWithTransport(transport *TransportWrap, cfg *Config) (net.Conn, er
|
||||
|
||||
header := defaultHeader.Clone()
|
||||
if cfg.UserAgent != "" {
|
||||
header["user-agent"] = []string{cfg.UserAgent}
|
||||
header.Set("User-Agent", cfg.UserAgent)
|
||||
}
|
||||
|
||||
request := &http.Request{
|
||||
@@ -372,12 +339,12 @@ func StreamGunWithTransport(transport *TransportWrap, cfg *Config) (net.Conn, er
|
||||
request = request.WithContext(transport.ctx)
|
||||
|
||||
conn := &Conn{
|
||||
initFn: func() (io.ReadCloser, netAddr, error) {
|
||||
nAddr := netAddr{}
|
||||
initFn: func() (io.ReadCloser, NetAddr, error) {
|
||||
nAddr := NetAddr{}
|
||||
trace := &httptrace.ClientTrace{
|
||||
GotConn: func(connInfo httptrace.GotConnInfo) {
|
||||
nAddr.localAddr = connInfo.Conn.LocalAddr()
|
||||
nAddr.remoteAddr = connInfo.Conn.RemoteAddr()
|
||||
nAddr.SetLocalAddr(connInfo.Conn.LocalAddr())
|
||||
nAddr.SetRemoteAddr(connInfo.Conn.RemoteAddr())
|
||||
},
|
||||
}
|
||||
request = request.WithContext(httptrace.WithClientTrace(request.Context(), trace))
|
||||
@@ -394,12 +361,12 @@ func StreamGunWithTransport(transport *TransportWrap, cfg *Config) (net.Conn, er
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func StreamGunWithConn(conn net.Conn, tlsConfig *tls.Config, cfg *Config, echConfig *ech.Config, realityConfig *tlsC.RealityConfig) (net.Conn, error) {
|
||||
func StreamGunWithConn(conn net.Conn, tlsConfig *vmess.TLSConfig, cfg *Config) (net.Conn, error) {
|
||||
dialFn := func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
transport := NewHTTP2Client(dialFn, tlsConfig, cfg.ClientFingerprint, echConfig, realityConfig)
|
||||
transport := NewHTTP2Client(dialFn, tlsConfig)
|
||||
c, err := StreamGunWithTransport(transport, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/metacubex/mihomo/common/buf"
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/http/h2c"
|
||||
@@ -42,17 +41,9 @@ func NewServerHandler(options ServerOption) http.Handler {
|
||||
writer.WriteHeader(http.StatusOK)
|
||||
|
||||
conn := &Conn{
|
||||
initFn: func() (io.ReadCloser, netAddr, error) {
|
||||
nAddr := netAddr{}
|
||||
if request.RemoteAddr != "" {
|
||||
metadata := C.Metadata{}
|
||||
if err := metadata.SetRemoteAddress(request.RemoteAddr); err == nil {
|
||||
nAddr.remoteAddr = net.TCPAddrFromAddrPort(metadata.AddrPort())
|
||||
}
|
||||
}
|
||||
if addr, ok := request.Context().Value(http.LocalAddrContextKey).(net.Addr); ok {
|
||||
nAddr.localAddr = addr
|
||||
}
|
||||
initFn: func() (io.ReadCloser, NetAddr, error) {
|
||||
nAddr := NetAddr{}
|
||||
nAddr.SetAddrFromRequest(request)
|
||||
return request.Body, nAddr, nil
|
||||
},
|
||||
writer: writer,
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
)
|
||||
|
||||
@@ -18,20 +20,40 @@ type TransportWrap struct {
|
||||
func (tw *TransportWrap) Close() error {
|
||||
tw.closeOnce.Do(func() {
|
||||
tw.cancel()
|
||||
closeTransport(tw.Http2Transport)
|
||||
CloseTransport(tw.Http2Transport)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
type netAddr struct {
|
||||
type NetAddr struct {
|
||||
remoteAddr net.Addr
|
||||
localAddr net.Addr
|
||||
}
|
||||
|
||||
func (addr netAddr) RemoteAddr() net.Addr {
|
||||
func (addr NetAddr) RemoteAddr() net.Addr {
|
||||
return addr.remoteAddr
|
||||
}
|
||||
|
||||
func (addr netAddr) LocalAddr() net.Addr {
|
||||
func (addr NetAddr) LocalAddr() net.Addr {
|
||||
return addr.localAddr
|
||||
}
|
||||
|
||||
func (addr *NetAddr) SetAddrFromRequest(request *http.Request) {
|
||||
if request.RemoteAddr != "" {
|
||||
metadata := C.Metadata{}
|
||||
if err := metadata.SetRemoteAddress(request.RemoteAddr); err == nil {
|
||||
addr.remoteAddr = net.TCPAddrFromAddrPort(metadata.AddrPort())
|
||||
}
|
||||
}
|
||||
if netAddr, ok := request.Context().Value(http.LocalAddrContextKey).(net.Addr); ok {
|
||||
addr.localAddr = netAddr
|
||||
}
|
||||
}
|
||||
|
||||
func (addr *NetAddr) SetRemoteAddr(remoteAddr net.Addr) {
|
||||
addr.remoteAddr = remoteAddr
|
||||
}
|
||||
|
||||
func (addr *NetAddr) SetLocalAddr(localAddr net.Addr) {
|
||||
addr.localAddr = localAddr
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ func closeClientConn(cc *http.Http2ClientConn) { // like forceCloseConn() in htt
|
||||
_ = cc.Close()
|
||||
}
|
||||
|
||||
func closeTransport(tr *http.Http2Transport) {
|
||||
func CloseTransport(tr *http.Http2Transport) {
|
||||
connPool := transportConnPool(tr)
|
||||
p := (*clientConnPool)((*efaceWords)(unsafe.Pointer(&connPool)).data)
|
||||
p.mu.Lock()
|
||||
|
||||
226
transport/masque/masque.go
Normal file
226
transport/masque/masque.go
Normal file
@@ -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) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func EncodeAddress(rawAddr string) ([]byte, error) {
|
||||
@@ -20,13 +21,21 @@ func EncodeAddress(rawAddr string) ([]byte, error) {
|
||||
}
|
||||
|
||||
var buf []byte
|
||||
if i := strings.IndexByte(host, '%'); i >= 0 {
|
||||
// Zone identifiers are not representable in SOCKS5 IPv6 address encoding.
|
||||
host = host[:i]
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
if ip4 := ip.To4(); ip4 != nil {
|
||||
buf = append(buf, 0x01) // IPv4
|
||||
buf = append(buf, ip4...)
|
||||
} else {
|
||||
buf = append(buf, 0x04) // IPv6
|
||||
buf = append(buf, ip...)
|
||||
ip16 := ip.To16()
|
||||
if ip16 == nil {
|
||||
return nil, fmt.Errorf("invalid ipv6: %q", host)
|
||||
}
|
||||
buf = append(buf, ip16...)
|
||||
}
|
||||
} else {
|
||||
if len(host) > 255 {
|
||||
|
||||
@@ -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,9 +47,10 @@ 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
|
||||
// - "ws": WebSocket tunnel (GET upgrade), CDN-friendly
|
||||
HTTPMaskMode string
|
||||
|
||||
// HTTPMaskTLSEnabled enables HTTPS for HTTP tunnel modes (client-side).
|
||||
@@ -108,13 +110,14 @@ func (c *ProtocolConfig) Validate() error {
|
||||
}
|
||||
|
||||
switch strings.ToLower(strings.TrimSpace(c.HTTPMaskMode)) {
|
||||
case "", "legacy", "stream", "poll", "auto":
|
||||
case "", "legacy", "stream", "poll", "auto", "ws":
|
||||
default:
|
||||
return fmt.Errorf("invalid http-mask-mode: %s, must be one of: legacy, stream, poll, auto", c.HTTPMaskMode)
|
||||
return fmt.Errorf("invalid http-mask-mode: %s, must be one of: legacy, stream, poll, auto, ws", c.HTTPMaskMode)
|
||||
}
|
||||
|
||||
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++ {
|
||||
@@ -164,6 +167,44 @@ func DefaultConfig() *ProtocolConfig {
|
||||
}
|
||||
}
|
||||
|
||||
func DerefInt(v *int, def int) int {
|
||||
if v == nil {
|
||||
return def
|
||||
}
|
||||
return *v
|
||||
}
|
||||
|
||||
func DerefBool(v *bool, def bool) bool {
|
||||
if v == nil {
|
||||
return def
|
||||
}
|
||||
return *v
|
||||
}
|
||||
|
||||
// ResolvePadding applies defaults and keeps min/max consistent when only one side is provided.
|
||||
func ResolvePadding(min, max *int, defMin, defMax int) (int, int) {
|
||||
paddingMin := DerefInt(min, defMin)
|
||||
paddingMax := DerefInt(max, defMax)
|
||||
switch {
|
||||
case min == nil && max != nil && paddingMax < paddingMin:
|
||||
paddingMin = paddingMax
|
||||
case max == nil && min != nil && paddingMax < paddingMin:
|
||||
paddingMax = paddingMin
|
||||
}
|
||||
return paddingMin, paddingMax
|
||||
}
|
||||
|
||||
func NormalizeTableType(tableType string) (string, error) {
|
||||
switch t := strings.ToLower(strings.TrimSpace(tableType)); t {
|
||||
case "", "prefer_ascii":
|
||||
return "prefer_ascii", nil
|
||||
case "prefer_entropy":
|
||||
return "prefer_entropy", nil
|
||||
default:
|
||||
return "", fmt.Errorf("table-type must be prefer_ascii or prefer_entropy")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ProtocolConfig) tableCandidates() []*sudoku.Table {
|
||||
if c == nil {
|
||||
return nil
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"filippo.io/edwards25519"
|
||||
"github.com/metacubex/edwards25519"
|
||||
)
|
||||
|
||||
// KeyPair holds the scalar private key and point public key
|
||||
@@ -80,8 +80,8 @@ func RecoverPublicKey(keyHex string) (*edwards25519.Point, error) {
|
||||
return nil, fmt.Errorf("invalid scalar: %w", err)
|
||||
}
|
||||
return new(edwards25519.Point).ScalarBaseMult(x), nil
|
||||
|
||||
} else if len(keyBytes) == 64 {
|
||||
}
|
||||
if len(keyBytes) == 64 {
|
||||
// Split Key r || k
|
||||
rBytes := keyBytes[:32]
|
||||
kBytes := keyBytes[32:]
|
||||
|
||||
374
transport/sudoku/crypto/record_conn.go
Normal file
374
transport/sudoku/crypto/record_conn.go
Normal file
@@ -0,0 +1,374 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/crypto/chacha20poly1305"
|
||||
)
|
||||
|
||||
// KeyUpdateAfterBytes controls automatic key rotation based on plaintext bytes.
|
||||
// It is a package var (not config) to enable targeted tests with smaller thresholds.
|
||||
var KeyUpdateAfterBytes int64 = 32 << 20 // 32 MiB
|
||||
|
||||
const (
|
||||
recordHeaderSize = 12 // epoch(uint32) + seq(uint64) - also used as nonce+AAD.
|
||||
maxFrameBodySize = 65535
|
||||
)
|
||||
|
||||
type recordKeys struct {
|
||||
baseSend []byte
|
||||
baseRecv []byte
|
||||
}
|
||||
|
||||
// RecordConn is a framed AEAD net.Conn with:
|
||||
// - deterministic per-record nonce (epoch+seq)
|
||||
// - per-direction key rotation (epoch), driven by plaintext byte counters
|
||||
// - replay/out-of-order protection within the connection (strict seq check)
|
||||
//
|
||||
// Wire format per record:
|
||||
// - uint16 bodyLen
|
||||
// - header[12] = epoch(uint32 BE) || seq(uint64 BE) (plaintext)
|
||||
// - ciphertext = AEAD(header as nonce, plaintext, header as AAD)
|
||||
type RecordConn struct {
|
||||
net.Conn
|
||||
method string
|
||||
|
||||
writeMu sync.Mutex
|
||||
readMu sync.Mutex
|
||||
|
||||
keys recordKeys
|
||||
|
||||
sendAEAD cipher.AEAD
|
||||
sendAEADEpoch uint32
|
||||
|
||||
recvAEAD cipher.AEAD
|
||||
recvAEADEpoch uint32
|
||||
|
||||
// Send direction state.
|
||||
sendEpoch uint32
|
||||
sendSeq uint64
|
||||
sendBytes int64
|
||||
|
||||
// Receive direction state.
|
||||
recvEpoch uint32
|
||||
recvSeq uint64
|
||||
|
||||
readBuf bytes.Buffer
|
||||
|
||||
// writeFrame is a reusable buffer for [len||header||ciphertext] on the wire.
|
||||
// Guarded by writeMu.
|
||||
writeFrame []byte
|
||||
}
|
||||
|
||||
func (c *RecordConn) CloseWrite() error {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
if cw, ok := c.Conn.(interface{ CloseWrite() error }); ok {
|
||||
return cw.CloseWrite()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *RecordConn) CloseRead() error {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
if cr, ok := c.Conn.(interface{ CloseRead() error }); ok {
|
||||
return cr.CloseRead()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewRecordConn(conn net.Conn, method string, baseSend, baseRecv []byte) (*RecordConn, error) {
|
||||
if conn == nil {
|
||||
return nil, fmt.Errorf("nil conn")
|
||||
}
|
||||
method = normalizeAEADMethod(method)
|
||||
if method != "none" {
|
||||
if err := validateBaseKey(baseSend); err != nil {
|
||||
return nil, fmt.Errorf("invalid send base key: %w", err)
|
||||
}
|
||||
if err := validateBaseKey(baseRecv); err != nil {
|
||||
return nil, fmt.Errorf("invalid recv base key: %w", err)
|
||||
}
|
||||
}
|
||||
rc := &RecordConn{Conn: conn, method: method}
|
||||
rc.keys = recordKeys{baseSend: cloneBytes(baseSend), baseRecv: cloneBytes(baseRecv)}
|
||||
return rc, nil
|
||||
}
|
||||
|
||||
func (c *RecordConn) Rekey(baseSend, baseRecv []byte) error {
|
||||
if c == nil {
|
||||
return fmt.Errorf("nil conn")
|
||||
}
|
||||
if c.method != "none" {
|
||||
if err := validateBaseKey(baseSend); err != nil {
|
||||
return fmt.Errorf("invalid send base key: %w", err)
|
||||
}
|
||||
if err := validateBaseKey(baseRecv); err != nil {
|
||||
return fmt.Errorf("invalid recv base key: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
c.writeMu.Lock()
|
||||
c.readMu.Lock()
|
||||
defer c.readMu.Unlock()
|
||||
defer c.writeMu.Unlock()
|
||||
|
||||
c.keys = recordKeys{baseSend: cloneBytes(baseSend), baseRecv: cloneBytes(baseRecv)}
|
||||
c.sendEpoch = 0
|
||||
c.sendSeq = 0
|
||||
c.sendBytes = 0
|
||||
c.recvEpoch = 0
|
||||
c.recvSeq = 0
|
||||
c.readBuf.Reset()
|
||||
|
||||
c.sendAEAD = nil
|
||||
c.recvAEAD = nil
|
||||
c.sendAEADEpoch = 0
|
||||
c.recvAEADEpoch = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeAEADMethod(method string) string {
|
||||
switch method {
|
||||
case "", "chacha20-poly1305":
|
||||
return "chacha20-poly1305"
|
||||
case "aes-128-gcm", "none":
|
||||
return method
|
||||
default:
|
||||
return method
|
||||
}
|
||||
}
|
||||
|
||||
func validateBaseKey(b []byte) error {
|
||||
if len(b) < 32 {
|
||||
return fmt.Errorf("need at least 32 bytes, got %d", len(b))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cloneBytes(b []byte) []byte {
|
||||
if len(b) == 0 {
|
||||
return nil
|
||||
}
|
||||
return append([]byte(nil), b...)
|
||||
}
|
||||
|
||||
func (c *RecordConn) newAEADFor(base []byte, epoch uint32) (cipher.AEAD, error) {
|
||||
if c.method == "none" {
|
||||
return nil, nil
|
||||
}
|
||||
key := deriveEpochKey(base, epoch, c.method)
|
||||
switch c.method {
|
||||
case "aes-128-gcm":
|
||||
block, err := aes.NewCipher(key[:16])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if a.NonceSize() != recordHeaderSize {
|
||||
return nil, fmt.Errorf("unexpected gcm nonce size: %d", a.NonceSize())
|
||||
}
|
||||
return a, nil
|
||||
case "chacha20-poly1305":
|
||||
a, err := chacha20poly1305.New(key[:32])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if a.NonceSize() != recordHeaderSize {
|
||||
return nil, fmt.Errorf("unexpected chacha nonce size: %d", a.NonceSize())
|
||||
}
|
||||
return a, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported cipher: %s", c.method)
|
||||
}
|
||||
}
|
||||
|
||||
func deriveEpochKey(base []byte, epoch uint32, method string) []byte {
|
||||
var b [4]byte
|
||||
binary.BigEndian.PutUint32(b[:], epoch)
|
||||
mac := hmac.New(sha256.New, base)
|
||||
_, _ = mac.Write([]byte("sudoku-record:"))
|
||||
_, _ = mac.Write([]byte(method))
|
||||
_, _ = mac.Write(b[:])
|
||||
return mac.Sum(nil)
|
||||
}
|
||||
|
||||
func (c *RecordConn) maybeBumpSendEpochLocked(addedPlain int) {
|
||||
if KeyUpdateAfterBytes <= 0 || c.method == "none" {
|
||||
return
|
||||
}
|
||||
c.sendBytes += int64(addedPlain)
|
||||
threshold := KeyUpdateAfterBytes * int64(c.sendEpoch+1)
|
||||
if c.sendBytes < threshold {
|
||||
return
|
||||
}
|
||||
c.sendEpoch++
|
||||
c.sendSeq = 0
|
||||
}
|
||||
|
||||
func (c *RecordConn) Write(p []byte) (int, error) {
|
||||
if c == nil || c.Conn == nil {
|
||||
return 0, net.ErrClosed
|
||||
}
|
||||
if c.method == "none" {
|
||||
return c.Conn.Write(p)
|
||||
}
|
||||
|
||||
c.writeMu.Lock()
|
||||
defer c.writeMu.Unlock()
|
||||
|
||||
total := 0
|
||||
for len(p) > 0 {
|
||||
if c.sendAEAD == nil || c.sendAEADEpoch != c.sendEpoch {
|
||||
a, err := c.newAEADFor(c.keys.baseSend, c.sendEpoch)
|
||||
if err != nil {
|
||||
return total, err
|
||||
}
|
||||
c.sendAEAD = a
|
||||
c.sendAEADEpoch = c.sendEpoch
|
||||
}
|
||||
aead := c.sendAEAD
|
||||
|
||||
maxPlain := maxFrameBodySize - recordHeaderSize - aead.Overhead()
|
||||
if maxPlain <= 0 {
|
||||
return total, errors.New("frame size too small")
|
||||
}
|
||||
n := len(p)
|
||||
if n > maxPlain {
|
||||
n = maxPlain
|
||||
}
|
||||
chunk := p[:n]
|
||||
p = p[n:]
|
||||
|
||||
var header [recordHeaderSize]byte
|
||||
binary.BigEndian.PutUint32(header[:4], c.sendEpoch)
|
||||
binary.BigEndian.PutUint64(header[4:], c.sendSeq)
|
||||
c.sendSeq++
|
||||
|
||||
cipherLen := n + aead.Overhead()
|
||||
bodyLen := recordHeaderSize + cipherLen
|
||||
frameLen := 2 + bodyLen
|
||||
if bodyLen > maxFrameBodySize {
|
||||
return total, errors.New("frame too large")
|
||||
}
|
||||
if cap(c.writeFrame) < frameLen {
|
||||
c.writeFrame = make([]byte, frameLen)
|
||||
}
|
||||
frame := c.writeFrame[:frameLen]
|
||||
binary.BigEndian.PutUint16(frame[:2], uint16(bodyLen))
|
||||
copy(frame[2:2+recordHeaderSize], header[:])
|
||||
|
||||
dst := frame[2+recordHeaderSize : 2+recordHeaderSize : frameLen]
|
||||
_ = aead.Seal(dst[:0], header[:], chunk, header[:])
|
||||
|
||||
if err := writeFull(c.Conn, frame); err != nil {
|
||||
return total, err
|
||||
}
|
||||
|
||||
total += n
|
||||
c.maybeBumpSendEpochLocked(n)
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
func (c *RecordConn) Read(p []byte) (int, error) {
|
||||
if c == nil || c.Conn == nil {
|
||||
return 0, net.ErrClosed
|
||||
}
|
||||
if c.method == "none" {
|
||||
return c.Conn.Read(p)
|
||||
}
|
||||
|
||||
c.readMu.Lock()
|
||||
defer c.readMu.Unlock()
|
||||
|
||||
if c.readBuf.Len() > 0 {
|
||||
return c.readBuf.Read(p)
|
||||
}
|
||||
|
||||
var lenBuf [2]byte
|
||||
if _, err := io.ReadFull(c.Conn, lenBuf[:]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
bodyLen := int(binary.BigEndian.Uint16(lenBuf[:]))
|
||||
if bodyLen < recordHeaderSize {
|
||||
return 0, errors.New("frame too short")
|
||||
}
|
||||
if bodyLen > maxFrameBodySize {
|
||||
return 0, errors.New("frame too large")
|
||||
}
|
||||
|
||||
body := make([]byte, bodyLen)
|
||||
if _, err := io.ReadFull(c.Conn, body); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
header := body[:recordHeaderSize]
|
||||
ciphertext := body[recordHeaderSize:]
|
||||
|
||||
epoch := binary.BigEndian.Uint32(header[:4])
|
||||
seq := binary.BigEndian.Uint64(header[4:])
|
||||
|
||||
if epoch < c.recvEpoch {
|
||||
return 0, fmt.Errorf("replayed epoch: got %d want >=%d", epoch, c.recvEpoch)
|
||||
}
|
||||
if epoch == c.recvEpoch && seq != c.recvSeq {
|
||||
return 0, fmt.Errorf("out of order: epoch=%d got=%d want=%d", epoch, seq, c.recvSeq)
|
||||
}
|
||||
if epoch > c.recvEpoch {
|
||||
const maxJump = 8
|
||||
if epoch-c.recvEpoch > maxJump {
|
||||
return 0, fmt.Errorf("epoch jump too large: got=%d want<=%d", epoch-c.recvEpoch, maxJump)
|
||||
}
|
||||
c.recvEpoch = epoch
|
||||
c.recvSeq = 0
|
||||
if seq != 0 {
|
||||
return 0, fmt.Errorf("out of order: epoch advanced to %d but seq=%d", epoch, seq)
|
||||
}
|
||||
}
|
||||
|
||||
if c.recvAEAD == nil || c.recvAEADEpoch != c.recvEpoch {
|
||||
a, err := c.newAEADFor(c.keys.baseRecv, c.recvEpoch)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
c.recvAEAD = a
|
||||
c.recvAEADEpoch = c.recvEpoch
|
||||
}
|
||||
aead := c.recvAEAD
|
||||
|
||||
plaintext, err := aead.Open(nil, header, ciphertext, header)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("decryption failed: epoch=%d seq=%d: %w", epoch, seq, err)
|
||||
}
|
||||
c.recvSeq++
|
||||
|
||||
c.readBuf.Write(plaintext)
|
||||
return c.readBuf.Read(p)
|
||||
}
|
||||
|
||||
func writeFull(w io.Writer, b []byte) error {
|
||||
for len(b) > 0 {
|
||||
n, err := w.Write(b)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b = b[n:]
|
||||
}
|
||||
return 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"
|
||||
@@ -146,12 +43,17 @@ func TestCustomTablesRotation_ProbedByServer(t *testing.T) {
|
||||
go func() {
|
||||
defer close(errCh)
|
||||
defer serverConn.Close()
|
||||
session, err := ServerHandshake(serverConn, serverCfg)
|
||||
c, meta, err := ServerHandshake(serverConn, serverCfg)
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
defer session.Conn.Close()
|
||||
session, err := ReadServerSession(c, meta)
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
if session.Type != SessionTypeTCP {
|
||||
errCh <- io.ErrUnexpectedEOF
|
||||
return
|
||||
@@ -172,7 +74,7 @@ func TestCustomTablesRotation_ProbedByServer(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("encode addr: %v", err)
|
||||
}
|
||||
if _, err := cConn.Write(addrBuf); err != nil {
|
||||
if err := WriteKIPMessage(cConn, KIPTypeOpenTCP, addrBuf); err != nil {
|
||||
t.Fatalf("write addr: %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,20 +2,20 @@ package sudoku
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"bytes"
|
||||
"crypto/ecdh"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/transport/sudoku/crypto"
|
||||
"github.com/metacubex/mihomo/transport/sudoku/obfs/httpmask"
|
||||
"github.com/metacubex/mihomo/transport/sudoku/obfs/sudoku"
|
||||
|
||||
"github.com/metacubex/mihomo/log"
|
||||
)
|
||||
|
||||
type SessionType int
|
||||
@@ -31,18 +31,96 @@ type ServerSession struct {
|
||||
Type SessionType
|
||||
Target string
|
||||
|
||||
// UserHash is a stable per-key identifier derived from the handshake payload.
|
||||
// It is primarily useful for debugging / user attribution when table rotation is enabled.
|
||||
// UserHash is a stable per-key identifier derived from the client hello payload.
|
||||
UserHash string
|
||||
}
|
||||
|
||||
type bufferedConn struct {
|
||||
net.Conn
|
||||
r *bufio.Reader
|
||||
type HandshakeMeta struct {
|
||||
UserHash string
|
||||
}
|
||||
|
||||
func (bc *bufferedConn) Read(p []byte) (int, error) {
|
||||
return bc.r.Read(p)
|
||||
// SuspiciousError indicates a potential probing attempt or protocol violation.
|
||||
// When returned, Conn (if non-nil) should contain all bytes already consumed/buffered so the caller
|
||||
// can perform a best-effort fallback relay (e.g. to a local web server) without losing the request.
|
||||
type SuspiciousError struct {
|
||||
Err error
|
||||
Conn net.Conn
|
||||
}
|
||||
|
||||
func (e *SuspiciousError) Error() string {
|
||||
if e == nil || e.Err == nil {
|
||||
return ""
|
||||
}
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
func (e *SuspiciousError) Unwrap() error { return e.Err }
|
||||
|
||||
type recordedConn struct {
|
||||
net.Conn
|
||||
recorded []byte
|
||||
}
|
||||
|
||||
func (rc *recordedConn) GetBufferedAndRecorded() []byte { return rc.recorded }
|
||||
|
||||
type prefixedRecorderConn struct {
|
||||
net.Conn
|
||||
prefix []byte
|
||||
}
|
||||
|
||||
func (pc *prefixedRecorderConn) GetBufferedAndRecorded() []byte {
|
||||
var rest []byte
|
||||
if r, ok := pc.Conn.(interface{ GetBufferedAndRecorded() []byte }); ok {
|
||||
rest = r.GetBufferedAndRecorded()
|
||||
}
|
||||
out := make([]byte, 0, len(pc.prefix)+len(rest))
|
||||
out = append(out, pc.prefix...)
|
||||
out = append(out, rest...)
|
||||
return out
|
||||
}
|
||||
|
||||
// bufferedRecorderConn wraps a net.Conn and a shared bufio.Reader so we can expose buffered bytes.
|
||||
// This is used for legacy HTTP mask parsing errors so callers can fall back to a real HTTP server.
|
||||
type bufferedRecorderConn struct {
|
||||
net.Conn
|
||||
r *bufio.Reader
|
||||
recorder *bytes.Buffer
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (bc *bufferedRecorderConn) Read(p []byte) (n int, err error) {
|
||||
n, err = bc.r.Read(p)
|
||||
if n > 0 && bc.recorder != nil {
|
||||
bc.mu.Lock()
|
||||
bc.recorder.Write(p[:n])
|
||||
bc.mu.Unlock()
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (bc *bufferedRecorderConn) GetBufferedAndRecorded() []byte {
|
||||
if bc == nil {
|
||||
return nil
|
||||
}
|
||||
bc.mu.Lock()
|
||||
defer bc.mu.Unlock()
|
||||
|
||||
var recorded []byte
|
||||
if bc.recorder != nil {
|
||||
recorded = bc.recorder.Bytes()
|
||||
}
|
||||
buffered := 0
|
||||
if bc.r != nil {
|
||||
buffered = bc.r.Buffered()
|
||||
}
|
||||
if buffered <= 0 {
|
||||
return recorded
|
||||
}
|
||||
peeked, _ := bc.r.Peek(buffered)
|
||||
full := make([]byte, len(recorded)+len(peeked))
|
||||
copy(full, recorded)
|
||||
copy(full[len(recorded):], peeked)
|
||||
return full
|
||||
}
|
||||
|
||||
type preBufferedConn struct {
|
||||
@@ -62,6 +140,26 @@ func (p *preBufferedConn) Read(b []byte) (int, error) {
|
||||
return p.Conn.Read(b)
|
||||
}
|
||||
|
||||
func (p *preBufferedConn) CloseWrite() error {
|
||||
if p == 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 {
|
||||
return nil
|
||||
}
|
||||
if cr, ok := p.Conn.(interface{ CloseRead() error }); ok {
|
||||
return cr.CloseRead()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type directionalConn struct {
|
||||
net.Conn
|
||||
reader io.Reader
|
||||
@@ -69,6 +167,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)
|
||||
}
|
||||
@@ -93,6 +200,26 @@ func (c *directionalConn) Close() error {
|
||||
return firstErr
|
||||
}
|
||||
|
||||
func (c *directionalConn) CloseWrite() error {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
if cw, ok := c.Conn.(interface{ CloseWrite() error }); ok {
|
||||
return cw.CloseWrite()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *directionalConn) CloseRead() error {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
if cr, ok := c.Conn.(interface{ CloseRead() error }); ok {
|
||||
return cr.CloseRead()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func absInt64(v int64) int64 {
|
||||
if v < 0 {
|
||||
return -v
|
||||
@@ -100,111 +227,35 @@ func absInt64(v int64) int64 {
|
||||
return v
|
||||
}
|
||||
|
||||
const (
|
||||
downlinkModePure byte = 0x01
|
||||
downlinkModePacked byte = 0x02
|
||||
)
|
||||
|
||||
func downlinkMode(cfg *ProtocolConfig) byte {
|
||||
if cfg.EnablePureDownlink {
|
||||
return downlinkModePure
|
||||
}
|
||||
return downlinkModePacked
|
||||
}
|
||||
|
||||
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 isLegacyHTTPMaskMode(mode string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(mode)) {
|
||||
case "", "legacy":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func buildHandshakePayload(key string) [16]byte {
|
||||
var payload [16]byte
|
||||
binary.BigEndian.PutUint64(payload[:8], uint64(time.Now().Unix()))
|
||||
|
||||
// Align with upstream: only decode hex bytes when this key is an ED25519 key material.
|
||||
// For plain UUID/strings (even if they look like hex), hash the string bytes as-is.
|
||||
src := []byte(key)
|
||||
if _, err := crypto.RecoverPublicKey(key); err == nil {
|
||||
if keyBytes, decErr := hex.DecodeString(key); decErr == nil && len(keyBytes) > 0 {
|
||||
src = keyBytes
|
||||
}
|
||||
}
|
||||
|
||||
hash := sha256.Sum256(src)
|
||||
copy(payload[8:], hash[:8])
|
||||
return payload
|
||||
}
|
||||
|
||||
func NewTable(key string, tableType string) *sudoku.Table {
|
||||
table, err := NewTableWithCustom(key, tableType, "")
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("[Sudoku] failed to init tables: %v", err))
|
||||
}
|
||||
return table
|
||||
}
|
||||
|
||||
func NewTableWithCustom(key string, tableType string, customTable string) (*sudoku.Table, error) {
|
||||
start := time.Now()
|
||||
table, err := sudoku.NewTableWithCustom(key, tableType, customTable)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Infoln("[Sudoku] Tables initialized (%s, custom=%v) in %v", tableType, customTable != "", time.Since(start))
|
||||
return table, nil
|
||||
}
|
||||
|
||||
func ClientAEADSeed(key string) string {
|
||||
if recovered, err := crypto.RecoverPublicKey(key); err == nil {
|
||||
return crypto.EncodePoint(recovered)
|
||||
}
|
||||
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).
|
||||
// ClientHandshake performs the client-side Sudoku handshake (no target request).
|
||||
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")
|
||||
}
|
||||
@@ -212,8 +263,8 @@ func ClientHandshakeWithOptions(rawConn net.Conn, cfg *ProtocolConfig, opt Clien
|
||||
return nil, fmt.Errorf("invalid config: %w", err)
|
||||
}
|
||||
|
||||
if !cfg.DisableHTTPMask {
|
||||
if err := WriteHTTPMaskHeader(rawConn, cfg.ServerAddress, cfg.HTTPMaskPathRoot, opt.HTTPMaskStrategy); err != nil {
|
||||
if !cfg.DisableHTTPMask && isLegacyHTTPMaskMode(cfg.HTTPMaskMode) {
|
||||
if err := httpmask.WriteRandomRequestHeaderWithPathRoot(rawConn, cfg.ServerAddress, cfg.HTTPMaskPathRoot); err != nil {
|
||||
return nil, fmt.Errorf("write http mask failed: %w", err)
|
||||
}
|
||||
}
|
||||
@@ -223,32 +274,68 @@ func ClientHandshakeWithOptions(rawConn net.Conn, cfg *ProtocolConfig, opt Clien
|
||||
return nil, err
|
||||
}
|
||||
|
||||
seed := ClientAEADSeed(cfg.Key)
|
||||
obfsConn := buildClientObfsConn(rawConn, cfg, table)
|
||||
cConn, err := crypto.NewAEADConn(obfsConn, ClientAEADSeed(cfg.Key), cfg.AEADMethod)
|
||||
pskC2S, pskS2C := derivePSKDirectionalBases(seed)
|
||||
rc, err := crypto.NewRecordConn(obfsConn, cfg.AEADMethod, pskC2S, pskS2C)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("setup crypto failed: %w", err)
|
||||
}
|
||||
|
||||
handshake := buildHandshakePayload(cfg.Key)
|
||||
if _, err := cConn.Write(handshake[:]); err != nil {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("send handshake failed: %w", err)
|
||||
}
|
||||
if _, err := cConn.Write([]byte{downlinkMode(cfg)}); err != nil {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("send downlink mode failed: %w", err)
|
||||
if _, err := kipHandshakeClient(rc, seed, kipUserHashFromKey(cfg.Key), KIPFeatAll); err != nil {
|
||||
_ = rc.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return cConn, nil
|
||||
return rc, nil
|
||||
}
|
||||
|
||||
// ServerHandshake performs Sudoku server-side handshake and detects UoT preface.
|
||||
func ServerHandshake(rawConn net.Conn, cfg *ProtocolConfig) (*ServerSession, error) {
|
||||
func readFirstSessionMessage(conn net.Conn) (*KIPMessage, error) {
|
||||
for {
|
||||
msg, err := ReadKIPMessage(conn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if msg.Type == KIPTypeKeepAlive {
|
||||
continue
|
||||
}
|
||||
return msg, nil
|
||||
}
|
||||
}
|
||||
|
||||
func maybeConsumeLegacyHTTPMask(rawConn net.Conn, r *bufio.Reader, cfg *ProtocolConfig) ([]byte, *SuspiciousError) {
|
||||
if rawConn == nil || r == nil || cfg == nil || cfg.DisableHTTPMask || !isLegacyHTTPMaskMode(cfg.HTTPMaskMode) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
peekBytes, _ := r.Peek(4) // ignore error; subsequent read will handle it
|
||||
if !httpmask.LooksLikeHTTPRequestStart(peekBytes) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
consumed, err := httpmask.ConsumeHeader(r)
|
||||
if err == nil {
|
||||
return consumed, nil
|
||||
}
|
||||
|
||||
recorder := new(bytes.Buffer)
|
||||
if len(consumed) > 0 {
|
||||
recorder.Write(consumed)
|
||||
}
|
||||
badConn := &bufferedRecorderConn{Conn: rawConn, r: r, recorder: recorder}
|
||||
return consumed, &SuspiciousError{Err: fmt.Errorf("invalid http header: %w", err), Conn: badConn}
|
||||
}
|
||||
|
||||
// ServerHandshake performs the server-side KIP handshake.
|
||||
func ServerHandshake(rawConn net.Conn, cfg *ProtocolConfig) (net.Conn, *HandshakeMeta, error) {
|
||||
if rawConn == nil {
|
||||
return nil, nil, fmt.Errorf("nil conn")
|
||||
}
|
||||
if cfg == nil {
|
||||
return nil, fmt.Errorf("config is required")
|
||||
return nil, nil, fmt.Errorf("config is required")
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, fmt.Errorf("invalid config: %w", err)
|
||||
return nil, nil, fmt.Errorf("invalid config: %w", err)
|
||||
}
|
||||
|
||||
handshakeTimeout := time.Duration(cfg.HandshakeTimeoutSeconds) * time.Second
|
||||
@@ -256,128 +343,113 @@ func ServerHandshake(rawConn net.Conn, cfg *ProtocolConfig) (*ServerSession, err
|
||||
handshakeTimeout = 5 * time.Second
|
||||
}
|
||||
|
||||
rawConn.SetReadDeadline(time.Now().Add(handshakeTimeout))
|
||||
|
||||
bufReader := bufio.NewReader(rawConn)
|
||||
if !cfg.DisableHTTPMask {
|
||||
if peek, err := bufReader.Peek(4); err == nil && httpmask.LooksLikeHTTPRequestStart(peek) {
|
||||
if _, err := httpmask.ConsumeHeader(bufReader); err != nil {
|
||||
return nil, fmt.Errorf("invalid http header: %w", err)
|
||||
}
|
||||
}
|
||||
_ = rawConn.SetReadDeadline(time.Now().Add(handshakeTimeout))
|
||||
defer func() { _ = rawConn.SetReadDeadline(time.Time{}) }()
|
||||
|
||||
httpHeaderData, susp := maybeConsumeLegacyHTTPMask(rawConn, bufReader, cfg)
|
||||
if susp != nil {
|
||||
return nil, nil, susp
|
||||
}
|
||||
|
||||
selectedTable, preRead, err := selectTableByProbe(bufReader, cfg, cfg.tableCandidates())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
combined := make([]byte, 0, len(httpHeaderData)+len(preRead))
|
||||
combined = append(combined, httpHeaderData...)
|
||||
combined = append(combined, preRead...)
|
||||
return nil, nil, &SuspiciousError{Err: err, Conn: &recordedConn{Conn: rawConn, recorded: combined}}
|
||||
}
|
||||
|
||||
baseConn := &preBufferedConn{Conn: rawConn, buf: preRead}
|
||||
bConn := &bufferedConn{Conn: baseConn, r: bufio.NewReader(baseConn)}
|
||||
sConn, obfsConn := buildServerObfsConn(bConn, cfg, selectedTable, true)
|
||||
cConn, err := crypto.NewAEADConn(obfsConn, cfg.Key, cfg.AEADMethod)
|
||||
sConn, obfsConn := buildServerObfsConn(baseConn, cfg, selectedTable, true)
|
||||
|
||||
seed := ServerAEADSeed(cfg.Key)
|
||||
pskC2S, pskS2C := derivePSKDirectionalBases(seed)
|
||||
// Server side: recv is client->server, send is server->client.
|
||||
rc, err := crypto.NewRecordConn(obfsConn, cfg.AEADMethod, pskS2C, pskC2S)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("crypto setup failed: %w", err)
|
||||
return nil, nil, fmt.Errorf("setup crypto failed: %w", err)
|
||||
}
|
||||
|
||||
var handshakeBuf [16]byte
|
||||
if _, err := io.ReadFull(cConn, handshakeBuf[:]); err != nil {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("read handshake failed: %w", err)
|
||||
msg, err := ReadKIPMessage(rc)
|
||||
if err != nil {
|
||||
return nil, nil, &SuspiciousError{Err: fmt.Errorf("handshake read failed: %w", err), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
|
||||
}
|
||||
if msg.Type != KIPTypeClientHello {
|
||||
return nil, nil, &SuspiciousError{Err: fmt.Errorf("unexpected handshake message: %d", msg.Type), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
|
||||
}
|
||||
ch, err := DecodeKIPClientHelloPayload(msg.Payload)
|
||||
if err != nil {
|
||||
return nil, nil, &SuspiciousError{Err: fmt.Errorf("decode client hello failed: %w", err), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
|
||||
}
|
||||
if absInt64(time.Now().Unix()-ch.Timestamp.Unix()) > int64(kipHandshakeSkew.Seconds()) {
|
||||
return nil, nil, &SuspiciousError{Err: fmt.Errorf("time skew/replay"), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
|
||||
}
|
||||
|
||||
ts := int64(binary.BigEndian.Uint64(handshakeBuf[:8]))
|
||||
if absInt64(time.Now().Unix()-ts) > 60 {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("timestamp skew detected")
|
||||
userHashHex := hex.EncodeToString(ch.UserHash[:])
|
||||
if !globalHandshakeReplay.allow(userHashHex, ch.Nonce, time.Now()) {
|
||||
return nil, nil, &SuspiciousError{Err: fmt.Errorf("replay"), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
|
||||
}
|
||||
|
||||
curve := ecdh.X25519()
|
||||
serverEphemeral, err := curve.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, nil, &SuspiciousError{Err: fmt.Errorf("ecdh generate failed: %w", err), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
|
||||
}
|
||||
shared, err := x25519SharedSecret(serverEphemeral, ch.ClientPub[:])
|
||||
if err != nil {
|
||||
return nil, nil, &SuspiciousError{Err: fmt.Errorf("ecdh failed: %w", err), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
|
||||
}
|
||||
sessC2S, sessS2C, err := deriveSessionDirectionalBases(seed, shared, ch.Nonce)
|
||||
if err != nil {
|
||||
return nil, nil, &SuspiciousError{Err: fmt.Errorf("derive session keys failed: %w", err), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
|
||||
}
|
||||
|
||||
var serverPub [kipHelloPubSize]byte
|
||||
copy(serverPub[:], serverEphemeral.PublicKey().Bytes())
|
||||
sh := &KIPServerHello{
|
||||
Nonce: ch.Nonce,
|
||||
ServerPub: serverPub,
|
||||
SelectedFeats: ch.Features & KIPFeatAll,
|
||||
}
|
||||
if err := WriteKIPMessage(rc, KIPTypeServerHello, sh.EncodePayload()); err != nil {
|
||||
return nil, nil, &SuspiciousError{Err: fmt.Errorf("write server hello failed: %w", err), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
|
||||
}
|
||||
if err := rc.Rekey(sessS2C, sessC2S); err != nil {
|
||||
return nil, nil, &SuspiciousError{Err: fmt.Errorf("rekey failed: %w", err), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
|
||||
}
|
||||
|
||||
userHash := userHashFromHandshake(handshakeBuf[:])
|
||||
sConn.StopRecording()
|
||||
|
||||
modeBuf := []byte{0}
|
||||
if _, err := io.ReadFull(cConn, modeBuf); err != nil {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("read downlink mode failed: %w", err)
|
||||
}
|
||||
if modeBuf[0] != downlinkMode(cfg) {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("downlink mode mismatch: client=%d server=%d", modeBuf[0], downlinkMode(cfg))
|
||||
}
|
||||
|
||||
firstByte := make([]byte, 1)
|
||||
if _, err := io.ReadFull(cConn, firstByte); err != nil {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("read first byte failed: %w", err)
|
||||
}
|
||||
|
||||
if firstByte[0] == MultiplexMagicByte {
|
||||
rawConn.SetReadDeadline(time.Time{})
|
||||
return &ServerSession{Conn: cConn, Type: SessionTypeMultiplex, UserHash: userHash}, nil
|
||||
}
|
||||
|
||||
if firstByte[0] == UoTMagicByte {
|
||||
version := make([]byte, 1)
|
||||
if _, err := io.ReadFull(cConn, version); err != nil {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("read uot version failed: %w", err)
|
||||
}
|
||||
if version[0] != uotVersion {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("unsupported uot version: %d", version[0])
|
||||
}
|
||||
rawConn.SetReadDeadline(time.Time{})
|
||||
return &ServerSession{Conn: cConn, Type: SessionTypeUoT, UserHash: userHash}, nil
|
||||
}
|
||||
|
||||
prefixed := &preBufferedConn{Conn: cConn, buf: firstByte}
|
||||
target, err := DecodeAddress(prefixed)
|
||||
if err != nil {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("read target address failed: %w", err)
|
||||
}
|
||||
|
||||
rawConn.SetReadDeadline(time.Time{})
|
||||
log.Debugln("[Sudoku] incoming TCP session target: %s", target)
|
||||
return &ServerSession{
|
||||
Conn: prefixed,
|
||||
Type: SessionTypeTCP,
|
||||
Target: target,
|
||||
UserHash: userHash,
|
||||
}, nil
|
||||
return rc, &HandshakeMeta{UserHash: userHashHex}, nil
|
||||
}
|
||||
|
||||
func GenKeyPair() (privateKey, publicKey string, err error) {
|
||||
// Generate Master Key
|
||||
pair, err := crypto.GenerateMasterKey()
|
||||
if err != nil {
|
||||
return
|
||||
// ReadServerSession consumes the first post-handshake KIP control message and returns the session intent.
|
||||
func ReadServerSession(conn net.Conn, meta *HandshakeMeta) (*ServerSession, error) {
|
||||
if conn == nil {
|
||||
return nil, fmt.Errorf("nil conn")
|
||||
}
|
||||
// Split the master private key to get Available Private Key
|
||||
availablePrivateKey, err := crypto.SplitPrivateKey(pair.Private)
|
||||
if err != nil {
|
||||
return
|
||||
userHash := ""
|
||||
if meta != nil {
|
||||
userHash = meta.UserHash
|
||||
}
|
||||
privateKey = availablePrivateKey // Available Private Key for client
|
||||
publicKey = crypto.EncodePoint(pair.Public) // Master Public Key for server
|
||||
return
|
||||
}
|
||||
|
||||
func normalizeHTTPMaskStrategy(strategy string) string {
|
||||
s := strings.TrimSpace(strings.ToLower(strategy))
|
||||
switch s {
|
||||
case "", "random":
|
||||
return "random"
|
||||
case "ws":
|
||||
return "websocket"
|
||||
first, err := readFirstSessionMessage(conn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch first.Type {
|
||||
case KIPTypeStartUoT:
|
||||
return &ServerSession{Conn: conn, Type: SessionTypeUoT, UserHash: userHash}, nil
|
||||
case KIPTypeStartMux:
|
||||
return &ServerSession{Conn: conn, Type: SessionTypeMultiplex, UserHash: userHash}, nil
|
||||
case KIPTypeOpenTCP:
|
||||
target, err := DecodeAddress(bytes.NewReader(first.Payload))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode target address failed: %w", err)
|
||||
}
|
||||
return &ServerSession{Conn: conn, Type: SessionTypeTCP, Target: target, UserHash: userHash}, nil
|
||||
default:
|
||||
return s
|
||||
return nil, fmt.Errorf("unknown kip message: %d", first.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func userHashFromHandshake(handshakeBuf []byte) string {
|
||||
if len(handshakeBuf) < 16 {
|
||||
return ""
|
||||
}
|
||||
return hex.EncodeToString(handshakeBuf[8:16])
|
||||
}
|
||||
|
||||
73
transport/sudoku/handshake_kip.go
Normal file
73
transport/sudoku/handshake_kip.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package sudoku
|
||||
|
||||
import (
|
||||
"crypto/ecdh"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/transport/sudoku/crypto"
|
||||
)
|
||||
|
||||
const kipHandshakeSkew = 60 * time.Second
|
||||
|
||||
func kipHandshakeClient(rc *crypto.RecordConn, seed string, userHash [kipHelloUserHashSize]byte, feats uint32) (uint32, error) {
|
||||
if rc == nil {
|
||||
return 0, fmt.Errorf("nil conn")
|
||||
}
|
||||
|
||||
curve := ecdh.X25519()
|
||||
ephemeral, err := curve.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("ecdh generate failed: %w", err)
|
||||
}
|
||||
|
||||
var nonce [kipHelloNonceSize]byte
|
||||
if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil {
|
||||
return 0, fmt.Errorf("nonce generate failed: %w", err)
|
||||
}
|
||||
|
||||
var clientPub [kipHelloPubSize]byte
|
||||
copy(clientPub[:], ephemeral.PublicKey().Bytes())
|
||||
|
||||
ch := &KIPClientHello{
|
||||
Timestamp: time.Now(),
|
||||
UserHash: userHash,
|
||||
Nonce: nonce,
|
||||
ClientPub: clientPub,
|
||||
Features: feats,
|
||||
}
|
||||
if err := WriteKIPMessage(rc, KIPTypeClientHello, ch.EncodePayload()); err != nil {
|
||||
return 0, fmt.Errorf("write client hello failed: %w", err)
|
||||
}
|
||||
|
||||
msg, err := ReadKIPMessage(rc)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read server hello failed: %w", err)
|
||||
}
|
||||
if msg.Type != KIPTypeServerHello {
|
||||
return 0, fmt.Errorf("unexpected handshake message: %d", msg.Type)
|
||||
}
|
||||
sh, err := DecodeKIPServerHelloPayload(msg.Payload)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("decode server hello failed: %w", err)
|
||||
}
|
||||
if sh.Nonce != nonce {
|
||||
return 0, fmt.Errorf("handshake nonce mismatch")
|
||||
}
|
||||
|
||||
shared, err := x25519SharedSecret(ephemeral, sh.ServerPub[:])
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("ecdh failed: %w", err)
|
||||
}
|
||||
sessC2S, sessS2C, err := deriveSessionDirectionalBases(seed, shared, nonce)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("derive session keys failed: %w", err)
|
||||
}
|
||||
if err := rc.Rekey(sessC2S, sessS2C); err != nil {
|
||||
return 0, fmt.Errorf("rekey failed: %w", err)
|
||||
}
|
||||
|
||||
return sh.SelectedFeats, nil
|
||||
}
|
||||
@@ -124,13 +124,18 @@ func runPackedTCPSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
|
||||
|
||||
// Server side
|
||||
go func() {
|
||||
session, err := ServerHandshake(serverConn, cfg)
|
||||
c, meta, err := ServerHandshake(serverConn, cfg)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("server handshake tcp: %w", err)
|
||||
return
|
||||
}
|
||||
defer session.Conn.Close()
|
||||
defer c.Close()
|
||||
|
||||
session, err := ReadServerSession(c, meta)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("server read session tcp: %w", err)
|
||||
return
|
||||
}
|
||||
if session.Type != SessionTypeTCP {
|
||||
errCh <- fmt.Errorf("unexpected session type: %v", session.Type)
|
||||
return
|
||||
@@ -159,8 +164,8 @@ func runPackedTCPSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
|
||||
errCh <- fmt.Errorf("encode address: %w", err)
|
||||
return
|
||||
}
|
||||
if _, err := cConn.Write(addrBuf); err != nil {
|
||||
errCh <- fmt.Errorf("client send addr: %w", err)
|
||||
if err := WriteKIPMessage(cConn, KIPTypeOpenTCP, addrBuf); err != nil {
|
||||
errCh <- fmt.Errorf("client send open tcp: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -182,13 +187,18 @@ func runPackedUoTSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
|
||||
|
||||
// Server side
|
||||
go func() {
|
||||
session, err := ServerHandshake(serverConn, cfg)
|
||||
c, meta, err := ServerHandshake(serverConn, cfg)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("server handshake uot: %w", err)
|
||||
return
|
||||
}
|
||||
defer session.Conn.Close()
|
||||
defer c.Close()
|
||||
|
||||
session, err := ReadServerSession(c, meta)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("server read session uot: %w", err)
|
||||
return
|
||||
}
|
||||
if session.Type != SessionTypeUoT {
|
||||
errCh <- fmt.Errorf("unexpected session type: %v", session.Type)
|
||||
return
|
||||
@@ -208,8 +218,8 @@ func runPackedUoTSession(id int, cfg *ProtocolConfig, errCh chan<- error) {
|
||||
}
|
||||
defer cConn.Close()
|
||||
|
||||
if err := WritePreface(cConn); err != nil {
|
||||
errCh <- fmt.Errorf("client write preface: %w", err)
|
||||
if err := WriteKIPMessage(cConn, KIPTypeStartUoT, nil); err != nil {
|
||||
errCh <- fmt.Errorf("client start uot: %w", err)
|
||||
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
|
||||
}
|
||||
@@ -15,6 +15,14 @@ type HTTPMaskTunnelServer struct {
|
||||
}
|
||||
|
||||
func NewHTTPMaskTunnelServer(cfg *ProtocolConfig) *HTTPMaskTunnelServer {
|
||||
return newHTTPMaskTunnelServer(cfg, false)
|
||||
}
|
||||
|
||||
func NewHTTPMaskTunnelServerWithFallback(cfg *ProtocolConfig) *HTTPMaskTunnelServer {
|
||||
return newHTTPMaskTunnelServer(cfg, true)
|
||||
}
|
||||
|
||||
func newHTTPMaskTunnelServer(cfg *ProtocolConfig, passThroughOnReject bool) *HTTPMaskTunnelServer {
|
||||
if cfg == nil {
|
||||
return &HTTPMaskTunnelServer{}
|
||||
}
|
||||
@@ -22,11 +30,13 @@ func NewHTTPMaskTunnelServer(cfg *ProtocolConfig) *HTTPMaskTunnelServer {
|
||||
var ts *httpmask.TunnelServer
|
||||
if !cfg.DisableHTTPMask {
|
||||
switch strings.ToLower(strings.TrimSpace(cfg.HTTPMaskMode)) {
|
||||
case "stream", "poll", "auto":
|
||||
case "stream", "poll", "auto", "ws":
|
||||
ts = httpmask.NewTunnelServer(httpmask.TunnelServerOptions{
|
||||
Mode: cfg.HTTPMaskMode,
|
||||
PathRoot: cfg.HTTPMaskPathRoot,
|
||||
AuthKey: ClientAEADSeed(cfg.Key),
|
||||
AuthKey: ServerAEADSeed(cfg.Key),
|
||||
// When upstream fallback is enabled, preserve rejected HTTP requests for the caller.
|
||||
PassThroughOnReject: passThroughOnReject,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -62,6 +72,14 @@ func (s *HTTPMaskTunnelServer) WrapConn(rawConn net.Conn) (handshakeConn net.Con
|
||||
case httpmask.HandleStartTunnel:
|
||||
inner := *s.cfg
|
||||
inner.DisableHTTPMask = true
|
||||
// HTTPMask tunnel modes (stream/poll/auto/ws) add extra round trips before the first
|
||||
// handshake bytes can reach ServerHandshake, especially under high concurrency.
|
||||
// Bump the handshake timeout for tunneled conns to avoid flaky timeouts while keeping
|
||||
// the default strict for raw TCP handshakes.
|
||||
const minTunneledHandshakeTimeoutSeconds = 15
|
||||
if inner.HandshakeTimeoutSeconds <= 0 || inner.HandshakeTimeoutSeconds < minTunneledHandshakeTimeoutSeconds {
|
||||
inner.HandshakeTimeoutSeconds = minTunneledHandshakeTimeoutSeconds
|
||||
}
|
||||
return c, &inner, false, nil
|
||||
default:
|
||||
return nil, nil, true, nil
|
||||
@@ -70,7 +88,7 @@ func (s *HTTPMaskTunnelServer) WrapConn(rawConn net.Conn) (handshakeConn net.Con
|
||||
|
||||
type TunnelDialer func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||
|
||||
// DialHTTPMaskTunnel dials a CDN-capable HTTP tunnel (stream/poll/auto) and returns a stream carrying raw Sudoku bytes.
|
||||
// DialHTTPMaskTunnel dials a CDN-capable HTTP tunnel (stream/poll/auto/ws) and returns a stream carrying raw Sudoku bytes.
|
||||
func DialHTTPMaskTunnel(ctx context.Context, serverAddress string, cfg *ProtocolConfig, dial TunnelDialer, upgrade func(net.Conn) (net.Conn, error)) (net.Conn, error) {
|
||||
if cfg == nil {
|
||||
return nil, fmt.Errorf("config is required")
|
||||
@@ -79,7 +97,7 @@ func DialHTTPMaskTunnel(ctx context.Context, serverAddress string, cfg *Protocol
|
||||
return nil, fmt.Errorf("http mask is disabled")
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(cfg.HTTPMaskMode)) {
|
||||
case "stream", "poll", "auto":
|
||||
case "stream", "poll", "auto", "ws":
|
||||
default:
|
||||
return nil, fmt.Errorf("http-mask-mode=%q does not use http tunnel", cfg.HTTPMaskMode)
|
||||
}
|
||||
@@ -94,64 +112,3 @@ func DialHTTPMaskTunnel(ctx context.Context, serverAddress string, cfg *Protocol
|
||||
DialContext: dial,
|
||||
})
|
||||
}
|
||||
|
||||
type HTTPMaskTunnelClient struct {
|
||||
mode string
|
||||
pathRoot string
|
||||
authKey string
|
||||
client *httpmask.TunnelClient
|
||||
}
|
||||
|
||||
func NewHTTPMaskTunnelClient(serverAddress string, cfg *ProtocolConfig, dial TunnelDialer) (*HTTPMaskTunnelClient, error) {
|
||||
if cfg == nil {
|
||||
return nil, fmt.Errorf("config is required")
|
||||
}
|
||||
if cfg.DisableHTTPMask {
|
||||
return nil, fmt.Errorf("http mask is disabled")
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(cfg.HTTPMaskMode)) {
|
||||
case "stream", "poll", "auto":
|
||||
default:
|
||||
return nil, fmt.Errorf("http-mask-mode=%q does not use http tunnel", cfg.HTTPMaskMode)
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(cfg.HTTPMaskMultiplex)) {
|
||||
case "auto", "on":
|
||||
default:
|
||||
return nil, fmt.Errorf("http-mask-multiplex=%q does not enable reuse", cfg.HTTPMaskMultiplex)
|
||||
}
|
||||
|
||||
c, err := httpmask.NewTunnelClient(serverAddress, httpmask.TunnelClientOptions{
|
||||
TLSEnabled: cfg.HTTPMaskTLSEnabled,
|
||||
HostOverride: cfg.HTTPMaskHost,
|
||||
DialContext: dial,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &HTTPMaskTunnelClient{
|
||||
mode: cfg.HTTPMaskMode,
|
||||
pathRoot: cfg.HTTPMaskPathRoot,
|
||||
authKey: ClientAEADSeed(cfg.Key),
|
||||
client: c,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *HTTPMaskTunnelClient) Dial(ctx context.Context, upgrade func(net.Conn) (net.Conn, error)) (net.Conn, error) {
|
||||
if c == nil || c.client == nil {
|
||||
return nil, fmt.Errorf("nil httpmask tunnel client")
|
||||
}
|
||||
return c.client.DialTunnel(ctx, httpmask.TunnelDialOptions{
|
||||
Mode: c.mode,
|
||||
PathRoot: c.pathRoot,
|
||||
AuthKey: c.authKey,
|
||||
Upgrade: upgrade,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *HTTPMaskTunnelClient) CloseIdleConnections() {
|
||||
if c == nil || c.client == nil {
|
||||
return
|
||||
}
|
||||
c.client.CloseIdleConnections()
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ func startTunnelServer(t *testing.T, cfg *ProtocolConfig, handle func(*ServerSes
|
||||
return
|
||||
}
|
||||
|
||||
session, err := ServerHandshake(handshakeConn, handshakeCfg)
|
||||
cConn, meta, err := ServerHandshake(handshakeConn, handshakeCfg)
|
||||
if err != nil {
|
||||
_ = handshakeConn.Close()
|
||||
if handshakeConn != conn {
|
||||
@@ -70,8 +70,13 @@ func startTunnelServer(t *testing.T, cfg *ProtocolConfig, handle func(*ServerSes
|
||||
errC <- err
|
||||
return
|
||||
}
|
||||
defer session.Conn.Close()
|
||||
defer cConn.Close()
|
||||
|
||||
session, err := ReadServerSession(cConn, meta)
|
||||
if err != nil {
|
||||
errC <- err
|
||||
return
|
||||
}
|
||||
if handleErr := handle(session); handleErr != nil {
|
||||
errC <- handleErr
|
||||
}
|
||||
@@ -172,7 +177,7 @@ func TestHTTPMaskTunnel_Stream_TCPRoundTrip(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("encode addr: %v", err)
|
||||
}
|
||||
if _, err := cConn.Write(addrBuf); err != nil {
|
||||
if err := WriteKIPMessage(cConn, KIPTypeOpenTCP, addrBuf); err != nil {
|
||||
t.Fatalf("write addr: %v", err)
|
||||
}
|
||||
|
||||
@@ -239,8 +244,8 @@ func TestHTTPMaskTunnel_Poll_UoTRoundTrip(t *testing.T) {
|
||||
}
|
||||
defer cConn.Close()
|
||||
|
||||
if err := WritePreface(cConn); err != nil {
|
||||
t.Fatalf("write preface: %v", err)
|
||||
if err := WriteKIPMessage(cConn, KIPTypeStartUoT, nil); err != nil {
|
||||
t.Fatalf("start uot: %v", err)
|
||||
}
|
||||
if err := WriteDatagram(cConn, target, payload); err != nil {
|
||||
t.Fatalf("write datagram: %v", err)
|
||||
@@ -305,7 +310,68 @@ func TestHTTPMaskTunnel_Auto_TCPRoundTrip(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("encode addr: %v", err)
|
||||
}
|
||||
if _, err := cConn.Write(addrBuf); err != nil {
|
||||
if err := WriteKIPMessage(cConn, KIPTypeOpenTCP, 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)
|
||||
}
|
||||
|
||||
stop()
|
||||
for err := range errCh {
|
||||
t.Fatalf("server error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPMaskTunnel_WS_TCPRoundTrip(t *testing.T) {
|
||||
key := "tunnel-ws-key"
|
||||
target := "1.1.1.1:80"
|
||||
|
||||
serverCfg := newTunnelTestTable(t, key)
|
||||
serverCfg.HTTPMaskMode = "ws"
|
||||
|
||||
addr, stop, errCh := startTunnelServer(t, serverCfg, func(s *ServerSession) error {
|
||||
if s.Type != SessionTypeTCP {
|
||||
return fmt.Errorf("unexpected session type: %v", s.Type)
|
||||
}
|
||||
if s.Target != target {
|
||||
return fmt.Errorf("target mismatch: %s", s.Target)
|
||||
}
|
||||
_, _ = s.Conn.Write([]byte("ok"))
|
||||
return nil
|
||||
})
|
||||
defer stop()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
clientCfg := *serverCfg
|
||||
clientCfg.ServerAddress = addr
|
||||
|
||||
tunnelConn, err := DialHTTPMaskTunnel(ctx, clientCfg.ServerAddress, &clientCfg, (&net.Dialer{}).DialContext, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("dial tunnel: %v", err)
|
||||
}
|
||||
defer tunnelConn.Close()
|
||||
|
||||
handshakeCfg := clientCfg
|
||||
handshakeCfg.DisableHTTPMask = true
|
||||
cConn, err := ClientHandshake(tunnelConn, &handshakeCfg)
|
||||
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 := WriteKIPMessage(cConn, KIPTypeOpenTCP, addrBuf); err != nil {
|
||||
t.Fatalf("write addr: %v", err)
|
||||
}
|
||||
|
||||
@@ -406,7 +472,7 @@ func TestHTTPMaskTunnel_Soak_Concurrent(t *testing.T) {
|
||||
runErr <- fmt.Errorf("encode addr: %w", err)
|
||||
return
|
||||
}
|
||||
if _, err := cConn.Write(addrBuf); err != nil {
|
||||
if err := WriteKIPMessage(cConn, KIPTypeOpenTCP, addrBuf); err != nil {
|
||||
runErr <- fmt.Errorf("write addr: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
97
transport/sudoku/init.go
Normal file
97
transport/sudoku/init.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package sudoku
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/metacubex/edwards25519"
|
||||
"github.com/metacubex/mihomo/transport/sudoku/crypto"
|
||||
"github.com/metacubex/mihomo/transport/sudoku/obfs/sudoku"
|
||||
)
|
||||
|
||||
func NewTable(key string, tableType string) *sudoku.Table {
|
||||
table, err := NewTableWithCustom(key, tableType, "")
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("[Sudoku] failed to init tables: %v", err))
|
||||
}
|
||||
return table
|
||||
}
|
||||
|
||||
func NewTableWithCustom(key string, tableType string, customTable string) (*sudoku.Table, error) {
|
||||
table, err := sudoku.NewTableWithCustom(key, tableType, customTable)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return table, nil
|
||||
}
|
||||
|
||||
// ClientAEADSeed returns a canonical "seed" that is stable between client private key material and server public key.
|
||||
func ClientAEADSeed(key string) string {
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
b, err := hex.DecodeString(key)
|
||||
if err != nil {
|
||||
return key
|
||||
}
|
||||
|
||||
// Client-side key material can be:
|
||||
// - split private key: 64 bytes hex (r||k)
|
||||
// - master private scalar: 32 bytes hex (x)
|
||||
// - PSK string: non-hex
|
||||
//
|
||||
// We intentionally do NOT treat a 32-byte hex as a public key here; the client is expected
|
||||
// to carry private material. Server-side should use ServerAEADSeed for public keys.
|
||||
switch len(b) {
|
||||
case 64:
|
||||
case 32:
|
||||
default:
|
||||
return key
|
||||
}
|
||||
if recovered, err := crypto.RecoverPublicKey(key); err == nil {
|
||||
return crypto.EncodePoint(recovered)
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
// ServerAEADSeed returns a canonical seed for server-side configuration.
|
||||
//
|
||||
// When key is a public key (32-byte compressed point, hex), it returns the canonical point encoding.
|
||||
// When key is private key material (split/master scalar), it derives and returns the public key.
|
||||
func ServerAEADSeed(key string) string {
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
b, err := hex.DecodeString(key)
|
||||
if err != nil {
|
||||
return key
|
||||
}
|
||||
|
||||
// Prefer interpreting 32-byte hex as a public key point, to avoid accidental scalar parsing.
|
||||
if len(b) == 32 {
|
||||
if p, err := new(edwards25519.Point).SetBytes(b); err == nil {
|
||||
return hex.EncodeToString(p.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to client-side rules for private key materials / other formats.
|
||||
return ClientAEADSeed(key)
|
||||
}
|
||||
|
||||
// GenKeyPair generates a client "available private key" and the corresponding server public key.
|
||||
func GenKeyPair() (privateKey, publicKey string, err error) {
|
||||
pair, err := crypto.GenerateMasterKey()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
availablePrivateKey, err := crypto.SplitPrivateKey(pair.Private)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return availablePrivateKey, crypto.EncodePoint(pair.Public), nil
|
||||
}
|
||||
44
transport/sudoku/init_test.go
Normal file
44
transport/sudoku/init_test.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package sudoku
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
"github.com/metacubex/edwards25519"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestClientAEADSeed_IsStableForPrivAndPub(t *testing.T) {
|
||||
for i := 0; i < 64; i++ {
|
||||
priv, pub, err := GenKeyPair()
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, pub, ClientAEADSeed(priv))
|
||||
require.Equal(t, pub, ServerAEADSeed(pub))
|
||||
require.Equal(t, pub, ServerAEADSeed(priv))
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientAEADSeed_Supports32ByteMasterScalar(t *testing.T) {
|
||||
var seed [64]byte
|
||||
_, err := rand.Read(seed[:])
|
||||
require.NoError(t, err)
|
||||
|
||||
s, err := edwards25519.NewScalar().SetUniformBytes(seed[:])
|
||||
require.NoError(t, err)
|
||||
|
||||
keyHex := hex.EncodeToString(s.Bytes())
|
||||
require.Len(t, keyHex, 64)
|
||||
require.NotEqual(t, keyHex, ClientAEADSeed(keyHex))
|
||||
require.Equal(t, ClientAEADSeed(keyHex), ServerAEADSeed(ClientAEADSeed(keyHex)))
|
||||
}
|
||||
|
||||
func TestServerAEADSeed_LeavesPublicKeyAsIs(t *testing.T) {
|
||||
for i := 0; i < 64; i++ {
|
||||
priv, pub, err := GenKeyPair()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, pub, ServerAEADSeed(pub))
|
||||
require.Equal(t, pub, ServerAEADSeed(priv))
|
||||
}
|
||||
}
|
||||
206
transport/sudoku/kip.go
Normal file
206
transport/sudoku/kip.go
Normal file
@@ -0,0 +1,206 @@
|
||||
package sudoku
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
kipMagic = "kip"
|
||||
|
||||
KIPTypeClientHello byte = 0x01
|
||||
KIPTypeServerHello byte = 0x02
|
||||
|
||||
KIPTypeOpenTCP byte = 0x10
|
||||
KIPTypeStartMux byte = 0x11
|
||||
KIPTypeStartUoT byte = 0x12
|
||||
KIPTypeKeepAlive byte = 0x14
|
||||
)
|
||||
|
||||
// KIP feature bits are advisory capability flags negotiated during the handshake.
|
||||
// They represent control-plane message families.
|
||||
const (
|
||||
KIPFeatOpenTCP uint32 = 1 << 0
|
||||
KIPFeatMux uint32 = 1 << 1
|
||||
KIPFeatUoT uint32 = 1 << 2
|
||||
KIPFeatKeepAlive uint32 = 1 << 4
|
||||
|
||||
KIPFeatAll = KIPFeatOpenTCP | KIPFeatMux | KIPFeatUoT | KIPFeatKeepAlive
|
||||
)
|
||||
|
||||
const (
|
||||
kipHelloUserHashSize = 8
|
||||
kipHelloNonceSize = 16
|
||||
kipHelloPubSize = 32
|
||||
kipMaxPayload = 64 * 1024
|
||||
)
|
||||
|
||||
var errKIP = errors.New("kip protocol error")
|
||||
|
||||
type KIPMessage struct {
|
||||
Type byte
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
func WriteKIPMessage(w io.Writer, typ byte, payload []byte) error {
|
||||
if w == nil {
|
||||
return fmt.Errorf("%w: nil writer", errKIP)
|
||||
}
|
||||
if len(payload) > kipMaxPayload {
|
||||
return fmt.Errorf("%w: payload too large: %d", errKIP, len(payload))
|
||||
}
|
||||
|
||||
var hdr [3 + 1 + 2]byte
|
||||
copy(hdr[:3], []byte(kipMagic))
|
||||
hdr[3] = typ
|
||||
binary.BigEndian.PutUint16(hdr[4:], uint16(len(payload)))
|
||||
|
||||
if err := writeFull(w, hdr[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(payload) == 0 {
|
||||
return nil
|
||||
}
|
||||
return writeFull(w, payload)
|
||||
}
|
||||
|
||||
func ReadKIPMessage(r io.Reader) (*KIPMessage, error) {
|
||||
if r == nil {
|
||||
return nil, fmt.Errorf("%w: nil reader", errKIP)
|
||||
}
|
||||
var hdr [3 + 1 + 2]byte
|
||||
if _, err := io.ReadFull(r, hdr[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if string(hdr[:3]) != kipMagic {
|
||||
return nil, fmt.Errorf("%w: bad magic", errKIP)
|
||||
}
|
||||
typ := hdr[3]
|
||||
n := int(binary.BigEndian.Uint16(hdr[4:]))
|
||||
if n < 0 || n > kipMaxPayload {
|
||||
return nil, fmt.Errorf("%w: invalid payload length: %d", errKIP, n)
|
||||
}
|
||||
var payload []byte
|
||||
if n > 0 {
|
||||
payload = make([]byte, n)
|
||||
if _, err := io.ReadFull(r, payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &KIPMessage{Type: typ, Payload: payload}, nil
|
||||
}
|
||||
|
||||
type KIPClientHello struct {
|
||||
Timestamp time.Time
|
||||
UserHash [kipHelloUserHashSize]byte
|
||||
Nonce [kipHelloNonceSize]byte
|
||||
ClientPub [kipHelloPubSize]byte
|
||||
Features uint32
|
||||
}
|
||||
|
||||
type KIPServerHello struct {
|
||||
Nonce [kipHelloNonceSize]byte
|
||||
ServerPub [kipHelloPubSize]byte
|
||||
SelectedFeats uint32
|
||||
}
|
||||
|
||||
func kipUserHashFromKey(psk string) [kipHelloUserHashSize]byte {
|
||||
var out [kipHelloUserHashSize]byte
|
||||
psk = strings.TrimSpace(psk)
|
||||
if psk == "" {
|
||||
return out
|
||||
}
|
||||
|
||||
// Align with upstream: when the client carries private key material (or even just a public key),
|
||||
// prefer hashing the raw hex bytes so different split/master keys can be distinguished.
|
||||
if keyBytes, err := hex.DecodeString(psk); err == nil && len(keyBytes) > 0 {
|
||||
sum := sha256.Sum256(keyBytes)
|
||||
copy(out[:], sum[:kipHelloUserHashSize])
|
||||
return out
|
||||
}
|
||||
|
||||
sum := sha256.Sum256([]byte(psk))
|
||||
copy(out[:], sum[:kipHelloUserHashSize])
|
||||
return out
|
||||
}
|
||||
|
||||
func KIPUserHashHexFromKey(psk string) string {
|
||||
uh := kipUserHashFromKey(psk)
|
||||
return hex.EncodeToString(uh[:])
|
||||
}
|
||||
|
||||
func (m *KIPClientHello) EncodePayload() []byte {
|
||||
var b bytes.Buffer
|
||||
var tmp [8]byte
|
||||
binary.BigEndian.PutUint64(tmp[:], uint64(m.Timestamp.Unix()))
|
||||
b.Write(tmp[:])
|
||||
b.Write(m.UserHash[:])
|
||||
b.Write(m.Nonce[:])
|
||||
b.Write(m.ClientPub[:])
|
||||
var f [4]byte
|
||||
binary.BigEndian.PutUint32(f[:], m.Features)
|
||||
b.Write(f[:])
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func DecodeKIPClientHelloPayload(payload []byte) (*KIPClientHello, error) {
|
||||
const minLen = 8 + kipHelloUserHashSize + kipHelloNonceSize + kipHelloPubSize + 4
|
||||
if len(payload) < minLen {
|
||||
return nil, fmt.Errorf("%w: client hello too short", errKIP)
|
||||
}
|
||||
var h KIPClientHello
|
||||
ts := int64(binary.BigEndian.Uint64(payload[:8]))
|
||||
h.Timestamp = time.Unix(ts, 0)
|
||||
off := 8
|
||||
copy(h.UserHash[:], payload[off:off+kipHelloUserHashSize])
|
||||
off += kipHelloUserHashSize
|
||||
copy(h.Nonce[:], payload[off:off+kipHelloNonceSize])
|
||||
off += kipHelloNonceSize
|
||||
copy(h.ClientPub[:], payload[off:off+kipHelloPubSize])
|
||||
off += kipHelloPubSize
|
||||
h.Features = binary.BigEndian.Uint32(payload[off : off+4])
|
||||
return &h, nil
|
||||
}
|
||||
|
||||
func (m *KIPServerHello) EncodePayload() []byte {
|
||||
var b bytes.Buffer
|
||||
b.Write(m.Nonce[:])
|
||||
b.Write(m.ServerPub[:])
|
||||
var f [4]byte
|
||||
binary.BigEndian.PutUint32(f[:], m.SelectedFeats)
|
||||
b.Write(f[:])
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func DecodeKIPServerHelloPayload(payload []byte) (*KIPServerHello, error) {
|
||||
const want = kipHelloNonceSize + kipHelloPubSize + 4
|
||||
if len(payload) != want {
|
||||
return nil, fmt.Errorf("%w: server hello bad len: %d", errKIP, len(payload))
|
||||
}
|
||||
var h KIPServerHello
|
||||
off := 0
|
||||
copy(h.Nonce[:], payload[off:off+kipHelloNonceSize])
|
||||
off += kipHelloNonceSize
|
||||
copy(h.ServerPub[:], payload[off:off+kipHelloPubSize])
|
||||
off += kipHelloPubSize
|
||||
h.SelectedFeats = binary.BigEndian.Uint32(payload[off : off+4])
|
||||
return &h, nil
|
||||
}
|
||||
|
||||
func writeFull(w io.Writer, b []byte) error {
|
||||
for len(b) > 0 {
|
||||
n, err := w.Write(b)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b = b[n:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user