mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-11-28 06:38:32 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cbd11db1e1 | ||
|
|
f62ebd0d04 | ||
|
|
e10a1a707f | ||
|
|
de51c4b840 | ||
|
|
a198581333 | ||
|
|
e3972e78fa | ||
|
|
d41d75795e | ||
|
|
63e4d5a312 | ||
|
|
2f510e86ad | ||
|
|
3b85577f20 | ||
|
|
dc5c2ecc00 | ||
|
|
578b88190a | ||
|
|
5ab5eb31f6 | ||
|
|
1f93334106 | ||
|
|
02dd143fbb | ||
|
|
a1c09adb91 | ||
|
|
6414c563dd | ||
|
|
45ca4ae12a | ||
|
|
01111ffac1 | ||
|
|
7870f8f839 | ||
|
|
73740c771c | ||
|
|
bcfd434df3 | ||
|
|
85c1798f7d | ||
|
|
d924f1ca62 | ||
|
|
1c4f7c4de6 | ||
|
|
26edbaae0b | ||
|
|
27efee2dc7 | ||
|
|
d20e85081a | ||
|
|
1095055136 | ||
|
|
24b6de71fc | ||
|
|
93d33faa4f | ||
|
|
85c2f6a773 | ||
|
|
59ffb63734 | ||
|
|
26e3d220a5 | ||
|
|
38fd8974b6 | ||
|
|
eca44d08d7 | ||
|
|
5b54b3ad46 | ||
|
|
76bf840121 | ||
|
|
8c40e36087 | ||
|
|
42810015f9 | ||
|
|
e64f58f333 | ||
|
|
94a7a3f3c0 | ||
|
|
174cba4cce | ||
|
|
be9164e55f | ||
|
|
1e76df7377 | ||
|
|
e68eca6c3d | ||
|
|
8e2aba40fc | ||
|
|
2c6ff7251d | ||
|
|
2cd1443c04 | ||
|
|
793f61ec67 | ||
|
|
ea19cda0c9 | ||
|
|
da28fe33c8 | ||
|
|
acbc92f021 | ||
|
|
0daa3ff722 | ||
|
|
aff8dc73e1 | ||
|
|
ad730ae974 | ||
|
|
d67572bbae | ||
|
|
084a09e4af | ||
|
|
1686d5633f | ||
|
|
f74bd8badc | ||
|
|
e3d67b3227 | ||
|
|
1f80d91552 | ||
|
|
d08c8853e3 | ||
|
|
7031b75698 | ||
|
|
5184081ac3 | ||
|
|
dbaf85b71b | ||
|
|
5bdb1cc7e1 | ||
|
|
11848509fb | ||
|
|
ab56858d00 | ||
|
|
01edf45ce0 | ||
|
|
e928ef59c1 | ||
|
|
c710025559 | ||
|
|
dafdd06b30 | ||
|
|
fd2112ecbe | ||
|
|
9761bcd7f9 | ||
|
|
1e62d55418 | ||
|
|
1abd12619a | ||
|
|
f99d4e1be6 | ||
|
|
fb590a845f | ||
|
|
b60e687eb7 | ||
|
|
316f5df1f1 | ||
|
|
d7ac7b5239 | ||
|
|
358fa5eb24 | ||
|
|
90b1066e1a | ||
|
|
bd72c65b5e | ||
|
|
317bfc206a | ||
|
|
fc8c5a24b1 | ||
|
|
8f2d84f915 | ||
|
|
38cb06d3a5 | ||
|
|
4065583ae4 | ||
|
|
f30a64f93f | ||
|
|
f1c365611d | ||
|
|
2dd7d59942 | ||
|
|
d610afef1b | ||
|
|
5b28a0ee46 | ||
|
|
5639e93f72 | ||
|
|
03e1f44921 | ||
|
|
f69331f45f | ||
|
|
52edebd155 | ||
|
|
7a6a650902 | ||
|
|
6e15299cab | ||
|
|
72f133f4bd | ||
|
|
301d580d8a | ||
|
|
3809a03c9f | ||
|
|
0ddf4bbffd | ||
|
|
d27f3201ab | ||
|
|
a2aca027e4 | ||
|
|
cb652ddb7d | ||
|
|
a52a27ed56 | ||
|
|
060711fb7d | ||
|
|
8c26d61ce3 | ||
|
|
f2da5b7c27 | ||
|
|
d60b336dfc | ||
|
|
a531449b84 | ||
|
|
a05c94b4ad | ||
|
|
ff98700df2 | ||
|
|
0dec35ed69 | ||
|
|
d2fcf71c4a | ||
|
|
b230c90d13 | ||
|
|
b1a07d2006 | ||
|
|
31ece04ab0 | ||
|
|
e9e23c4e98 |
No files matched your search
@@ -221,6 +221,7 @@ jobs:
|
||||
if: ${{ matrix.jobs.test == 'test' }}
|
||||
run: |
|
||||
export SKIP_CONCURRENT_TEST=1
|
||||
export SKIP_INTEROP_TEST=1
|
||||
go test ./...
|
||||
echo "---test with_gvisor---"
|
||||
go test ./... -tags "with_gvisor" -count=1
|
||||
|
||||
@@ -42,6 +42,8 @@ jobs:
|
||||
GOTOOLCHAIN: local
|
||||
# Fix mingw trying to be smart and converting paths https://github.com/moby/moby/issues/24029#issuecomment-250412919
|
||||
MSYS_NO_PATHCONV: true
|
||||
# Skip mihomo inbound interop test
|
||||
SKIP_INTEROP_TEST: 1
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
|
||||
+53
-55
@@ -5,8 +5,10 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"github.com/metacubex/mihomo/common/atomic"
|
||||
"github.com/metacubex/mihomo/common/sockopt"
|
||||
"github.com/metacubex/mihomo/component/keepalive"
|
||||
"github.com/metacubex/mihomo/component/mptcp"
|
||||
|
||||
@@ -14,34 +16,68 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
lc = tfo.ListenConfig{
|
||||
DisableTFO: true,
|
||||
}
|
||||
mutex sync.RWMutex
|
||||
globalTFO = atomic.NewBool(false)
|
||||
globalMPTCP = atomic.NewBool(false)
|
||||
)
|
||||
|
||||
func SetTfo(open bool) {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
lc.DisableTFO = !open
|
||||
globalTFO.Store(open)
|
||||
}
|
||||
|
||||
func Tfo() bool {
|
||||
mutex.RLock()
|
||||
defer mutex.RUnlock()
|
||||
return !lc.DisableTFO
|
||||
return globalTFO.Load()
|
||||
}
|
||||
|
||||
func SetMPTCP(open bool) {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
mptcp.SetNetListenConfig(&lc.ListenConfig, open)
|
||||
globalMPTCP.Store(open)
|
||||
}
|
||||
|
||||
func MPTCP() bool {
|
||||
mutex.RLock()
|
||||
defer mutex.RUnlock()
|
||||
return mptcp.GetNetListenConfig(&lc.ListenConfig)
|
||||
return globalMPTCP.Load()
|
||||
}
|
||||
|
||||
type ListenConfig struct {
|
||||
routeMark int
|
||||
}
|
||||
|
||||
func NewListenConfig() *ListenConfig {
|
||||
return &ListenConfig{}
|
||||
}
|
||||
|
||||
func (l *ListenConfig) SetRouteMark(mark int) {
|
||||
l.routeMark = mark
|
||||
}
|
||||
|
||||
func (l ListenConfig) newListenConfig() *tfo.ListenConfig {
|
||||
lc := tfo.ListenConfig{DisableTFO: !Tfo()}
|
||||
keepalive.SetNetListenConfig(&lc.ListenConfig)
|
||||
mptcp.SetNetListenConfig(&lc.ListenConfig, MPTCP())
|
||||
lc.Control = func(network, address string, c syscall.RawConn) error {
|
||||
if l.routeMark != 0 {
|
||||
err := sockopt.RawConnMark(c, l.routeMark)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return &lc
|
||||
}
|
||||
|
||||
func (l ListenConfig) Listen(ctx context.Context, network, address string) (net.Listener, error) {
|
||||
address, err := preResolve(network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return l.newListenConfig().Listen(ctx, network, address)
|
||||
}
|
||||
|
||||
func (l ListenConfig) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
|
||||
address, err := preResolve(network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return l.newListenConfig().ListenPacket(ctx, network, address)
|
||||
}
|
||||
|
||||
func preResolve(network, address string) (string, error) {
|
||||
@@ -67,41 +103,3 @@ func preResolve(network, address string) (string, error) {
|
||||
}
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
|
||||
address, err := preResolve(network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mutex.RLock()
|
||||
defer mutex.RUnlock()
|
||||
return lc.Listen(ctx, network, address)
|
||||
}
|
||||
|
||||
func Listen(network, address string) (net.Listener, error) {
|
||||
return ListenContext(context.Background(), network, address)
|
||||
}
|
||||
|
||||
func ListenPacketContext(ctx context.Context, network, address string) (net.PacketConn, error) {
|
||||
address, err := preResolve(network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mutex.RLock()
|
||||
defer mutex.RUnlock()
|
||||
return lc.ListenPacket(ctx, network, address)
|
||||
}
|
||||
|
||||
func ListenPacket(network, address string) (net.PacketConn, error) {
|
||||
return ListenPacketContext(context.Background(), network, address)
|
||||
}
|
||||
|
||||
func init() {
|
||||
keepalive.SetDisableKeepAliveCallback.Register(func(b bool) {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
keepalive.SetNetListenConfig(&lc.ListenConfig)
|
||||
})
|
||||
}
|
||||
@@ -63,7 +63,7 @@ func (t *AnyTLS) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
|
||||
// create uot on tcp
|
||||
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
||||
return newPacketConn(N.NewThreadSafePacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination})), t), nil
|
||||
return NewPacketConn(N.NewThreadSafePacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination})), t), nil
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
|
||||
@@ -210,7 +210,7 @@ func (b *BasicOption) NewDialer(opts []dialer.Option) C.Dialer {
|
||||
cDialer := b.DialerForAPI
|
||||
if cDialer == nil {
|
||||
if b.DialerProxy != "" {
|
||||
cDialer = proxydialer.NewByName(b.DialerProxy)
|
||||
cDialer = proxydialer.NewByName(b.DialerProxy, b.NewTunnel())
|
||||
} else {
|
||||
cDialer = dialer.NewDialer(opts...)
|
||||
}
|
||||
@@ -339,7 +339,7 @@ func (c *packetConn) AddRef(ref any) {
|
||||
c.EnhancePacketConn = N.NewRefPacketConn(c.EnhancePacketConn, ref) // add ref for autoCloseProxyAdapter
|
||||
}
|
||||
|
||||
func newPacketConn(pc net.PacketConn, a ProxyAdapter) C.PacketConn {
|
||||
func NewPacketConn(pc net.PacketConn, a ProxyAdapter) C.PacketConn {
|
||||
epc := N.NewEnhancePacketConn(pc)
|
||||
if _, ok := pc.(syscall.Conn); !ok { // exclusion system conn like *net.UDPConn
|
||||
epc = N.NewDeadlineEnhancePacketConn(epc) // most conn from outbound can't handle readDeadline correctly
|
||||
|
||||
@@ -46,7 +46,7 @@ func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.loopBack.NewPacketConn(newPacketConn(pc, d)), nil
|
||||
return d.loopBack.NewPacketConn(NewPacketConn(pc, d)), nil
|
||||
}
|
||||
|
||||
func (d *Direct) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||
|
||||
@@ -38,7 +38,7 @@ func (d *Dns) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
return newPacketConn(&dnsPacketConn{
|
||||
return NewPacketConn(&dnsPacketConn{
|
||||
response: make(chan dnsPacket, 1),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
@@ -107,7 +107,7 @@ func (d *dnsPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||
ctx, cancel := context.WithTimeout(d.ctx, resolver.DefaultDnsRelayTimeout)
|
||||
defer cancel()
|
||||
|
||||
buf, err = resolver.RelayDnsPacket(ctx, buf[:len(p)], buf)
|
||||
buf, err := resolver.RelayDnsPacket(ctx, buf[:len(p)], buf)
|
||||
if err != nil {
|
||||
put()
|
||||
return
|
||||
|
||||
@@ -58,7 +58,7 @@ func (g *GostRelay) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
||||
return nil, fmt.Errorf("%s udp connect error: %w", g.addr, err)
|
||||
}
|
||||
|
||||
return newPacketConn(pc, g), nil
|
||||
return NewPacketConn(pc, g), nil
|
||||
}
|
||||
|
||||
func (g *GostRelay) ProxyInfo() C.ProxyInfo {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"github.com/metacubex/mihomo/component/ca"
|
||||
"github.com/metacubex/mihomo/component/dialer"
|
||||
"github.com/metacubex/mihomo/component/ech"
|
||||
@@ -19,7 +20,7 @@ import (
|
||||
"github.com/metacubex/mihomo/transport/hysteria/obfs"
|
||||
"github.com/metacubex/mihomo/transport/hysteria/pmtud_fix"
|
||||
"github.com/metacubex/mihomo/transport/hysteria/transport"
|
||||
"github.com/metacubex/mihomo/transport/hysteria/utils"
|
||||
hyUtils "github.com/metacubex/mihomo/transport/hysteria/utils"
|
||||
|
||||
"github.com/metacubex/tls"
|
||||
|
||||
@@ -66,10 +67,10 @@ func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newPacketConn(&hyPacketConn{udpConn}, h), nil
|
||||
return NewPacketConn(&hyPacketConn{udpConn}, h), nil
|
||||
}
|
||||
|
||||
func (h *Hysteria) genHdc(ctx context.Context) utils.PacketDialer {
|
||||
func (h *Hysteria) genHdc(ctx context.Context) hyUtils.PacketDialer {
|
||||
return &hyDialerWithContext{
|
||||
ctx: context.Background(),
|
||||
hyDialer: func(network string, rAddr net.Addr) (net.PacketConn, error) {
|
||||
@@ -128,12 +129,12 @@ type HysteriaOption struct {
|
||||
|
||||
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
||||
var up, down uint64
|
||||
up = StringToBps(c.Up)
|
||||
up = utils.StringToBps(c.Up)
|
||||
if up == 0 {
|
||||
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
|
||||
}
|
||||
|
||||
down = StringToBps(c.Down)
|
||||
down = utils.StringToBps(c.Down)
|
||||
if down == 0 {
|
||||
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
|
||||
}
|
||||
|
||||
@@ -38,26 +38,28 @@ type Hysteria2 struct {
|
||||
|
||||
type Hysteria2Option struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port,omitempty"`
|
||||
Ports string `proxy:"ports,omitempty"`
|
||||
HopInterval string `proxy:"hop-interval,omitempty"`
|
||||
Up string `proxy:"up,omitempty"`
|
||||
Down string `proxy:"down,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
Obfs string `proxy:"obfs,omitempty"`
|
||||
ObfsPassword string `proxy:"obfs-password,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
Certificate string `proxy:"certificate,omitempty"`
|
||||
PrivateKey string `proxy:"private-key,omitempty"`
|
||||
ALPN []string `proxy:"alpn,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
BBRProfile string `proxy:"bbr-profile,omitempty"`
|
||||
UdpMTU int `proxy:"udp-mtu,omitempty"`
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port,omitempty"`
|
||||
Ports string `proxy:"ports,omitempty"`
|
||||
HopInterval string `proxy:"hop-interval,omitempty"`
|
||||
Up string `proxy:"up,omitempty"`
|
||||
Down string `proxy:"down,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
Obfs string `proxy:"obfs,omitempty"`
|
||||
ObfsPassword string `proxy:"obfs-password,omitempty"`
|
||||
ObfsMinPacketSize int `proxy:"obfs-min-packet-size,omitempty"`
|
||||
ObfsMaxPacketSize int `proxy:"obfs-max-packet-size,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
Certificate string `proxy:"certificate,omitempty"`
|
||||
PrivateKey string `proxy:"private-key,omitempty"`
|
||||
ALPN []string `proxy:"alpn,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
BBRProfile string `proxy:"bbr-profile,omitempty"`
|
||||
UdpMTU int `proxy:"udp-mtu,omitempty"`
|
||||
|
||||
RealmOpts Hysteria2RealmOption `proxy:"realm-opts,omitempty"`
|
||||
|
||||
@@ -103,7 +105,7 @@ func (h *Hysteria2) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
||||
if pc == nil {
|
||||
return nil, errors.New("packetConn is nil")
|
||||
}
|
||||
return newPacketConn(N.NewThreadSafePacketConn(pc), h), nil
|
||||
return NewPacketConn(N.NewThreadSafePacketConn(pc), h), nil
|
||||
}
|
||||
|
||||
// Close implements C.ProxyAdapter
|
||||
@@ -139,6 +141,8 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
|
||||
var salamanderPassword string
|
||||
var geckoPassword string
|
||||
var geckoMinPacketSize, geckoMaxPacketSize int
|
||||
if len(option.Obfs) > 0 {
|
||||
if option.ObfsPassword == "" {
|
||||
return nil, errors.New("missing obfs password")
|
||||
@@ -146,6 +150,10 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||
switch option.Obfs {
|
||||
case hysteria2.ObfsTypeSalamander:
|
||||
salamanderPassword = option.ObfsPassword
|
||||
case hysteria2.ObfsTypeGecko:
|
||||
geckoPassword = option.ObfsPassword
|
||||
geckoMinPacketSize = option.ObfsMinPacketSize
|
||||
geckoMaxPacketSize = option.ObfsMaxPacketSize
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown obfs type: %s", option.Obfs)
|
||||
}
|
||||
@@ -196,9 +204,12 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||
clientOptions := hysteria2.ClientOptions{
|
||||
Context: context.TODO(),
|
||||
Logger: log.SingLogger,
|
||||
SendBPS: StringToBps(option.Up),
|
||||
ReceiveBPS: StringToBps(option.Down),
|
||||
SendBPS: utils.StringToBps(option.Up),
|
||||
ReceiveBPS: utils.StringToBps(option.Down),
|
||||
SalamanderPassword: salamanderPassword,
|
||||
GeckoPassword: geckoPassword,
|
||||
GeckoMinPacketSize: geckoMinPacketSize,
|
||||
GeckoMaxPacketSize: geckoMaxPacketSize,
|
||||
Password: option.Password,
|
||||
TLSConfig: tlsClientConfig,
|
||||
QUICConfig: quicConfig,
|
||||
@@ -286,7 +297,7 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||
if ipv4 && !ipv6 {
|
||||
return resolver.LookupIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||
} else if ipv6 && !ipv4 {
|
||||
return resolver.LookupIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||
return resolver.LookupIPv6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||
}
|
||||
return resolver.LookupIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||
},
|
||||
|
||||
+138
-38
@@ -12,7 +12,6 @@ import (
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/atomic"
|
||||
@@ -31,6 +30,7 @@ import (
|
||||
wireguard "github.com/metacubex/sing-wireguard"
|
||||
M "github.com/metacubex/sing/common/metadata"
|
||||
"github.com/metacubex/tls"
|
||||
"golang.org/x/sync/semaphore"
|
||||
)
|
||||
|
||||
type Masque struct {
|
||||
@@ -41,10 +41,11 @@ type Masque struct {
|
||||
resolver resolver.Resolver
|
||||
uri string
|
||||
h2Transport *http.Transport
|
||||
l4Client *masque.L4Client
|
||||
|
||||
runCtx context.Context
|
||||
runCancel context.CancelFunc
|
||||
runMutex sync.Mutex
|
||||
runLock *semaphore.Weighted
|
||||
running atomic.Bool
|
||||
runDevice atomic.Bool
|
||||
|
||||
@@ -53,19 +54,20 @@ type Masque struct {
|
||||
|
||||
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"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Network string `proxy:"network,omitempty"`
|
||||
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"`
|
||||
HandshakeTimeout int `proxy:"handshake-timeout,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Network string `proxy:"network,omitempty"`
|
||||
|
||||
CongestionController string `proxy:"congestion-controller,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
@@ -104,6 +106,9 @@ func (option MasqueOption) Prefixes() ([]netip.Prefix, error) {
|
||||
}
|
||||
|
||||
func NewMasque(option MasqueOption) (*Masque, error) {
|
||||
if option.HandshakeTimeout < 0 {
|
||||
return nil, errors.New("masque handshake timeout must be non-negative")
|
||||
}
|
||||
outbound := &Masque{
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
@@ -115,6 +120,7 @@ func NewMasque(option MasqueOption) (*Masque, error) {
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
runLock: semaphore.NewWeighted(1),
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
|
||||
@@ -144,6 +150,8 @@ func NewMasque(option MasqueOption) (*Masque, error) {
|
||||
return nil, fmt.Errorf("failed to assert public key as ECDSA")
|
||||
}
|
||||
|
||||
l4proxy := option.Network == "h3-l4proxy"
|
||||
|
||||
uri := option.URI
|
||||
if uri == "" {
|
||||
uri = masque.ConnectURI
|
||||
@@ -153,6 +161,9 @@ func NewMasque(option MasqueOption) (*Masque, error) {
|
||||
sni := option.SNI
|
||||
if sni == "" {
|
||||
sni = masque.ConnectSNI
|
||||
if l4proxy {
|
||||
sni = masque.L4ConnectSNI
|
||||
}
|
||||
}
|
||||
|
||||
tlsConfig, err := masque.PrepareTlsConfig(privKey, ecPubKey, sni, option.SkipCertVerify)
|
||||
@@ -197,30 +208,39 @@ func NewMasque(option MasqueOption) (*Masque, error) {
|
||||
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 l4proxy {
|
||||
outbound.l4Client = masque.NewL4Client(outbound.runCtx, outbound.dialQuic)
|
||||
if outbound.udp {
|
||||
log.Warnln("[Masque](%s) L4 proxy mode is not supported for UDP", outbound.name)
|
||||
outbound.udp = false
|
||||
}
|
||||
has6 = true // l4 proxy mode always has ipv6
|
||||
} else {
|
||||
prefixes, err := option.Prefixes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
for _, address := range prefixes {
|
||||
if !address.Addr().Unmap().Is4() {
|
||||
has6 = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,12 +261,36 @@ func NewMasque(option MasqueOption) (*Masque, error) {
|
||||
return outbound, nil
|
||||
}
|
||||
|
||||
func (w *Masque) dialQuic(ctx context.Context) (net.PacketConn, *quic.Conn, error) {
|
||||
pc, quicConn, err := common.DialQuic(ctx, w.addr, w.DialOptions(), w.dialer, w.tlsConfig, w.quicConfig, false)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
common.SetCongestionController(quicConn, w.option.CongestionController, w.option.CWND, w.option.BBRProfile)
|
||||
return pc, quicConn, nil
|
||||
}
|
||||
|
||||
func (w *Masque) run(ctx context.Context) error {
|
||||
if w.running.Load() {
|
||||
return nil
|
||||
}
|
||||
w.runMutex.Lock()
|
||||
defer w.runMutex.Unlock()
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
stop := contextutils.AfterFunc(w.runCtx, cancel)
|
||||
defer func() {
|
||||
stop()
|
||||
cancel()
|
||||
}()
|
||||
|
||||
if err := w.runLock.Acquire(runCtx, 1); err != nil {
|
||||
return err
|
||||
}
|
||||
releaseRunLock := true
|
||||
defer func() {
|
||||
if releaseRunLock {
|
||||
w.runLock.Release(1)
|
||||
}
|
||||
}()
|
||||
|
||||
// double-check like sync.Once
|
||||
if w.running.Load() {
|
||||
return nil
|
||||
@@ -256,6 +300,31 @@ func (w *Masque) run(ctx context.Context) error {
|
||||
return w.runCtx.Err()
|
||||
}
|
||||
|
||||
if w.option.HandshakeTimeout > 0 {
|
||||
resultCh := make(chan error, 1)
|
||||
releaseRunLock = false
|
||||
go func() {
|
||||
defer w.runLock.Release(1)
|
||||
|
||||
handshakeTimeout := time.Duration(w.option.HandshakeTimeout) * time.Second
|
||||
handshakeCtx, handshakeCancel := context.WithTimeout(w.runCtx, handshakeTimeout)
|
||||
defer handshakeCancel()
|
||||
|
||||
resultCh <- w.startLocked(handshakeCtx)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-resultCh:
|
||||
return err
|
||||
case <-runCtx.Done():
|
||||
return runCtx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
return w.startLocked(runCtx)
|
||||
}
|
||||
|
||||
func (w *Masque) startLocked(ctx context.Context) error {
|
||||
if !w.runDevice.Load() {
|
||||
err := w.tunDevice.Start()
|
||||
if err != nil {
|
||||
@@ -275,11 +344,10 @@ func (w *Masque) run(ctx context.Context) error {
|
||||
}
|
||||
} else {
|
||||
var quicConn *quic.Conn
|
||||
pc, quicConn, err = common.DialQuic(ctx, w.addr, w.DialOptions(), w.dialer, w.tlsConfig, w.quicConfig, false)
|
||||
pc, quicConn, err = w.dialQuic(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
common.SetCongestionController(quicConn, w.option.CongestionController, w.option.CWND, w.option.BBRProfile)
|
||||
|
||||
closer, ipConn, err = masque.ConnectTunnel(ctx, quicConn, w.uri)
|
||||
if err != nil {
|
||||
@@ -314,7 +382,7 @@ func (w *Masque) run(ctx context.Context) error {
|
||||
}
|
||||
icmp, err := ipConn.WritePacket(buf[:sizes[0]])
|
||||
if err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
if errors.Is(err, net.ErrClosed) || errors.Is(err, io.ErrClosedPipe) {
|
||||
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
|
||||
return
|
||||
}
|
||||
@@ -335,7 +403,7 @@ func (w *Masque) run(ctx context.Context) error {
|
||||
for runCtx.Err() == nil {
|
||||
buf, err := ipConn.ReadPacket()
|
||||
if err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
if errors.Is(err, net.ErrClosed) || errors.Is(err, io.ErrClosedPipe) {
|
||||
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
|
||||
return
|
||||
}
|
||||
@@ -358,10 +426,39 @@ func (w *Masque) Close() error {
|
||||
if w.tunDevice != nil {
|
||||
w.tunDevice.Close()
|
||||
}
|
||||
if w.l4Client != nil {
|
||||
w.l4Client.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Masque) dialContextL4(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||
var conn net.Conn
|
||||
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(w.l4Client))
|
||||
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||
} else {
|
||||
conn, err = w.l4Client.DialContext(ctx, "tcp", metadata.AddrPort().String())
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if conn == nil {
|
||||
return nil, errors.New("conn is nil")
|
||||
}
|
||||
return NewConn(conn, w), nil
|
||||
}
|
||||
|
||||
func (w *Masque) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||
if w.l4Client != nil {
|
||||
return w.dialContextL4(ctx, metadata)
|
||||
}
|
||||
var conn net.Conn
|
||||
if err = w.run(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -388,6 +485,9 @@ func (w *Masque) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Con
|
||||
}
|
||||
|
||||
func (w *Masque) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||
if w.l4Client != nil {
|
||||
return nil, errors.New("masque L4 proxy mode is not supported for UDP")
|
||||
}
|
||||
var pc net.PacketConn
|
||||
if err = w.run(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -402,7 +502,7 @@ func (w *Masque) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
if pc == nil {
|
||||
return nil, errors.New("packetConn is nil")
|
||||
}
|
||||
return newPacketConn(pc, w), nil
|
||||
return NewPacketConn(pc, w), nil
|
||||
}
|
||||
|
||||
func (w *Masque) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||
|
||||
@@ -96,7 +96,7 @@ func (m *Mieru) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dial to %s failed: %w", metadata.UDPAddr(), err)
|
||||
}
|
||||
return newPacketConn(N.NewThreadSafePacketConn(mierucommon.NewUDPAssociateWrapper(mierucommon.NewPacketOverStreamTunnel(c))), m), nil
|
||||
return NewPacketConn(N.NewThreadSafePacketConn(mierucommon.NewUDPAssociateWrapper(mierucommon.NewPacketOverStreamTunnel(c))), m), nil
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
|
||||
+185
-65
@@ -8,7 +8,9 @@ import (
|
||||
"net/netip"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/contextutils"
|
||||
"github.com/metacubex/mihomo/component/dialer"
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
@@ -17,8 +19,8 @@ import (
|
||||
ovpn "github.com/metacubex/mihomo/transport/openvpn"
|
||||
|
||||
wireguard "github.com/metacubex/sing-wireguard"
|
||||
E "github.com/metacubex/sing/common/exceptions"
|
||||
M "github.com/metacubex/sing/common/metadata"
|
||||
"golang.org/x/sync/semaphore"
|
||||
)
|
||||
|
||||
type OpenVPN struct {
|
||||
@@ -33,46 +35,58 @@ type OpenVPN struct {
|
||||
|
||||
runCtx context.Context
|
||||
runCancel context.CancelFunc
|
||||
runMutex sync.Mutex
|
||||
runLock *semaphore.Weighted
|
||||
running bool
|
||||
}
|
||||
|
||||
type OpenVPNOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Proto string `proxy:"proto,omitempty"`
|
||||
Dev string `proxy:"dev,omitempty"`
|
||||
Cipher string `proxy:"cipher,omitempty"`
|
||||
Auth string `proxy:"auth,omitempty"`
|
||||
CA string `proxy:"ca"`
|
||||
Cert string `proxy:"cert,omitempty"`
|
||||
Key string `proxy:"key,omitempty"`
|
||||
TLSCrypt string `proxy:"tls-crypt"`
|
||||
Username string `proxy:"username,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
MTU int `proxy:"mtu,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Proto string `proxy:"proto,omitempty"`
|
||||
Dev string `proxy:"dev,omitempty"`
|
||||
Cipher string `proxy:"cipher,omitempty"`
|
||||
Auth string `proxy:"auth,omitempty"`
|
||||
CompLZO string `proxy:"comp-lzo,omitempty"`
|
||||
CA string `proxy:"ca"`
|
||||
Cert string `proxy:"cert,omitempty"`
|
||||
Key string `proxy:"key,omitempty"`
|
||||
TLSCrypt string `proxy:"tls-crypt,omitempty"`
|
||||
Username string `proxy:"username,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
PeerInfo map[string]string `proxy:"peer-info,omitempty"`
|
||||
Ping int `proxy:"ping,omitempty"`
|
||||
PingRestart int `proxy:"ping-restart,omitempty"`
|
||||
HandshakeTimeout int `proxy:"handshake-timeout,omitempty"`
|
||||
MTU int `proxy:"mtu,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
|
||||
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
||||
Dns []string `proxy:"dns,omitempty"`
|
||||
}
|
||||
|
||||
func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
|
||||
if option.HandshakeTimeout < 0 {
|
||||
return nil, errors.New("openvpn handshake timeout must be non-negative")
|
||||
}
|
||||
cfg := &ovpn.ClientConfig{
|
||||
RemoteHost: option.Server,
|
||||
RemotePort: uint16(option.Port),
|
||||
Proto: option.Proto,
|
||||
Dev: option.Dev,
|
||||
Cipher: option.Cipher,
|
||||
Auth: option.Auth,
|
||||
CA: []byte(option.CA),
|
||||
Cert: []byte(option.Cert),
|
||||
Key: []byte(option.Key),
|
||||
TLSCrypt: []byte(option.TLSCrypt),
|
||||
Username: option.Username,
|
||||
Password: option.Password,
|
||||
RemoteHost: option.Server,
|
||||
RemotePort: uint16(option.Port),
|
||||
Proto: option.Proto,
|
||||
Dev: option.Dev,
|
||||
Cipher: option.Cipher,
|
||||
Auth: option.Auth,
|
||||
CompLZO: option.CompLZO,
|
||||
CA: []byte(option.CA),
|
||||
Cert: []byte(option.Cert),
|
||||
Key: []byte(option.Key),
|
||||
TLSCrypt: []byte(option.TLSCrypt),
|
||||
Username: option.Username,
|
||||
Password: option.Password,
|
||||
PeerInfo: option.PeerInfo,
|
||||
PingInterval: time.Duration(option.Ping) * time.Second,
|
||||
PingRestart: time.Duration(option.PingRestart) * time.Second,
|
||||
}
|
||||
if err := cfg.Prepare(); err != nil {
|
||||
return nil, err
|
||||
@@ -91,8 +105,9 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
config: cfg,
|
||||
option: &option,
|
||||
config: cfg,
|
||||
runLock: semaphore.NewWeighted(1),
|
||||
}
|
||||
if option.RemoteDnsResolve && len(option.Dns) > 0 {
|
||||
nss, err := dns.ParseNameServer(option.Dns)
|
||||
@@ -107,54 +122,62 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
|
||||
}
|
||||
|
||||
func (o *OpenVPN) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||
if err = o.run(ctx); err != nil {
|
||||
tunDevice, r, err := o.run(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var conn net.Conn
|
||||
if !metadata.Resolved() || o.resolver != nil {
|
||||
r := resolver.DefaultResolver
|
||||
if o.resolver != nil {
|
||||
r = o.resolver
|
||||
if !metadata.Resolved() || r != nil {
|
||||
if r == nil {
|
||||
r = resolver.DefaultResolver
|
||||
}
|
||||
options := o.DialOptions()
|
||||
options = append(options, dialer.WithResolver(r))
|
||||
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: o.tunDevice}))
|
||||
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: tunDevice}))
|
||||
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||
} else {
|
||||
conn, err = o.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
||||
conn, err = tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if conn == nil {
|
||||
return nil, E.New("conn is nil")
|
||||
return nil, errors.New("conn is nil")
|
||||
}
|
||||
return NewConn(conn, o), nil
|
||||
}
|
||||
|
||||
func (o *OpenVPN) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||
var pc net.PacketConn
|
||||
if err = o.run(ctx); err != nil {
|
||||
tunDevice, r, err := o.run(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = o.ResolveUDP(ctx, metadata); err != nil {
|
||||
if err = o.resolveUDP(ctx, metadata, r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pc, err = o.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
||||
pc, err = tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if pc == nil {
|
||||
return nil, errors.New("packetConn is nil")
|
||||
}
|
||||
return newPacketConn(pc, o), nil
|
||||
return NewPacketConn(pc, o), nil
|
||||
}
|
||||
|
||||
func (o *OpenVPN) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||
if (!metadata.Resolved() || o.resolver != nil) && metadata.Host != "" {
|
||||
r := resolver.DefaultResolver
|
||||
if o.resolver != nil {
|
||||
r = o.resolver
|
||||
_, r, err := o.run(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return o.resolveUDP(ctx, metadata, r)
|
||||
}
|
||||
|
||||
func (o *OpenVPN) resolveUDP(ctx context.Context, metadata *C.Metadata, r resolver.Resolver) error {
|
||||
if (!metadata.Resolved() || r != nil) && metadata.Host != "" {
|
||||
if r == nil {
|
||||
r = resolver.DefaultResolver
|
||||
}
|
||||
ip, err := resolveIPWithResolver(ctx, metadata.Host, o.prefer, r)
|
||||
if err != nil {
|
||||
@@ -179,13 +202,13 @@ func (o *OpenVPN) Close() error {
|
||||
if o.runCancel != nil {
|
||||
o.runCancel()
|
||||
}
|
||||
o.runMutex.Lock()
|
||||
_ = o.runLock.Acquire(context.Background(), 1)
|
||||
client := o.client
|
||||
tunDevice := o.tunDevice
|
||||
o.client = nil
|
||||
o.tunDevice = nil
|
||||
o.running = false
|
||||
o.runMutex.Unlock()
|
||||
o.runLock.Release(1)
|
||||
|
||||
if client != nil {
|
||||
_ = client.Close()
|
||||
@@ -196,31 +219,81 @@ func (o *OpenVPN) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *OpenVPN) run(ctx context.Context) error {
|
||||
o.runMutex.Lock()
|
||||
defer o.runMutex.Unlock()
|
||||
func (o *OpenVPN) run(ctx context.Context) (wireguard.Device, resolver.Resolver, error) {
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
stop := contextutils.AfterFunc(o.runCtx, cancel)
|
||||
defer func() {
|
||||
stop()
|
||||
cancel()
|
||||
}()
|
||||
|
||||
if err := o.runLock.Acquire(runCtx, 1); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
releaseRunLock := true
|
||||
defer func() {
|
||||
if releaseRunLock {
|
||||
o.runLock.Release(1)
|
||||
}
|
||||
}()
|
||||
|
||||
if o.running {
|
||||
return nil
|
||||
if o.tunDevice == nil {
|
||||
return nil, nil, net.ErrClosed
|
||||
}
|
||||
return o.tunDevice, o.resolver, nil
|
||||
}
|
||||
if o.runCtx.Err() != nil {
|
||||
return o.runCtx.Err()
|
||||
return nil, nil, o.runCtx.Err()
|
||||
}
|
||||
|
||||
packetIO, err := o.openPacketIO(ctx)
|
||||
if o.option.HandshakeTimeout > 0 {
|
||||
type runResult struct {
|
||||
tunDevice wireguard.Device
|
||||
resolver resolver.Resolver
|
||||
err error
|
||||
}
|
||||
|
||||
releaseRunLock = false
|
||||
resultCh := make(chan runResult, 1)
|
||||
go func() {
|
||||
defer o.runLock.Release(1)
|
||||
|
||||
handshakeTimeout := time.Duration(o.option.HandshakeTimeout) * time.Second
|
||||
handshakeCtx, handshakeCancel := context.WithTimeout(o.runCtx, handshakeTimeout)
|
||||
defer handshakeCancel()
|
||||
|
||||
tunDevice, r, err := o.startLocked(handshakeCtx)
|
||||
resultCh <- runResult{tunDevice: tunDevice, resolver: r, err: err}
|
||||
}()
|
||||
|
||||
select {
|
||||
case result := <-resultCh:
|
||||
return result.tunDevice, result.resolver, result.err
|
||||
case <-runCtx.Done():
|
||||
return nil, nil, runCtx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
return o.startLocked(runCtx)
|
||||
}
|
||||
|
||||
func (o *OpenVPN) startLocked(handshakeCtx context.Context) (wireguard.Device, resolver.Resolver, error) {
|
||||
packetIO, err := o.openPacketIO(handshakeCtx)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, nil, fmt.Errorf("connect OpenVPN server: %w", err)
|
||||
}
|
||||
client, err := ovpn.NewClient(o.config, packetIO)
|
||||
if err != nil {
|
||||
_ = packetIO.Close()
|
||||
return err
|
||||
return nil, nil, err
|
||||
}
|
||||
push, err := client.Handshake(ctx)
|
||||
push, err := client.Handshake(handshakeCtx)
|
||||
if err != nil {
|
||||
_ = client.Close()
|
||||
return err
|
||||
return nil, nil, fmt.Errorf("make OpenVPN handshake: %w", err)
|
||||
}
|
||||
log.Debugln("[OpenVPN](%s) handshake complete: prefixes=%v peer-id=%d dns=%v redirect=%t block-ipv6=%t", o.name, push.Prefixes, push.PeerID, push.DNS, push.Redirect, push.BlockIPv6)
|
||||
log.Debugln("[OpenVPN](%s) handshake complete: prefixes=%v routes=%v peer-id=%d dns=%v redirect=%t block-ipv6=%t", o.name, push.Prefixes, push.Routes, push.PeerID, push.DNS, push.Redirect, push.BlockIPv6)
|
||||
|
||||
mtu := o.option.MTU
|
||||
if mtu == 0 {
|
||||
@@ -229,12 +302,12 @@ func (o *OpenVPN) run(ctx context.Context) error {
|
||||
tunDevice, err := wireguard.NewStackDevice(push.Prefixes, uint32(mtu))
|
||||
if err != nil {
|
||||
_ = client.Close()
|
||||
return E.Cause(err, "create OpenVPN stack device")
|
||||
return nil, nil, fmt.Errorf("create OpenVPN stack device: %w", err)
|
||||
}
|
||||
if err := tunDevice.Start(); err != nil {
|
||||
_ = client.Close()
|
||||
_ = tunDevice.Close()
|
||||
return err
|
||||
return nil, nil, err
|
||||
}
|
||||
o.client = client
|
||||
o.tunDevice = tunDevice
|
||||
@@ -250,7 +323,7 @@ func (o *OpenVPN) run(ctx context.Context) error {
|
||||
})
|
||||
}
|
||||
o.startPacketLoops()
|
||||
return nil
|
||||
return o.tunDevice, o.resolver, nil
|
||||
}
|
||||
|
||||
func openVPNPrefixesHas6(prefixes []netip.Prefix) bool {
|
||||
@@ -291,13 +364,13 @@ func (o *OpenVPN) startPacketLoops() {
|
||||
runCancel()
|
||||
_ = client.Close()
|
||||
_ = tunDevice.Close()
|
||||
o.runMutex.Lock()
|
||||
_ = o.runLock.Acquire(context.Background(), 1)
|
||||
if o.client == client {
|
||||
o.client = nil
|
||||
o.tunDevice = nil
|
||||
o.running = false
|
||||
}
|
||||
o.runMutex.Unlock()
|
||||
o.runLock.Release(1)
|
||||
})
|
||||
}
|
||||
go func() {
|
||||
@@ -342,4 +415,51 @@ func (o *OpenVPN) startPacketLoops() {
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if o.config.PingInterval > 0 {
|
||||
go func() {
|
||||
defer stop()
|
||||
ticker := time.NewTicker(o.config.PingInterval)
|
||||
defer ticker.Stop()
|
||||
for runCtx.Err() == nil {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if sinceSend := client.SinceSend(); sinceSend >= o.config.PingInterval {
|
||||
if err := client.WritePing(runCtx); err != nil {
|
||||
if !errors.Is(err, context.Canceled) && !errors.Is(err, net.ErrClosed) {
|
||||
log.Warnln("[OpenVPN](%s) error writing ping packet: %v", o.name, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Debugln("[OpenVPN](%s) sent ping packet after %s idle", o.name, sinceSend.Round(time.Second))
|
||||
}
|
||||
case <-runCtx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
if o.config.PingRestart > 0 {
|
||||
go func() {
|
||||
defer stop()
|
||||
ticker := time.NewTicker(o.config.PingRestart)
|
||||
defer ticker.Stop()
|
||||
for runCtx.Err() == nil {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if sinceReceive := client.SinceReceive(); sinceReceive >= o.config.PingRestart {
|
||||
log.Warnln(
|
||||
"[OpenVPN](%s) ping-restart timeout: no packet received for %s",
|
||||
o.name,
|
||||
sinceReceive.Round(time.Second),
|
||||
)
|
||||
return
|
||||
}
|
||||
case <-runCtx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
if err := r.ResolveUDP(ctx, metadata); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newPacketConn(&nopPacketConn{}, r), nil
|
||||
return NewPacketConn(&nopPacketConn{}, r), nil
|
||||
}
|
||||
|
||||
func (r *Reject) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||
@@ -88,6 +88,17 @@ func NewPass() *Reject {
|
||||
}
|
||||
}
|
||||
|
||||
func NewPassRule() *Reject {
|
||||
return &Reject{
|
||||
Base: &Base{
|
||||
name: "PASS-RULE",
|
||||
tp: C.PassRule,
|
||||
udp: true,
|
||||
prefer: C.DualStack,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type nopConn struct{}
|
||||
|
||||
func (rw nopConn) Read(b []byte) (int, error) { return 0, io.EOF }
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
)
|
||||
|
||||
type Rematch struct {
|
||||
*Base
|
||||
targetRematchName *string
|
||||
targetSubRule *string
|
||||
}
|
||||
|
||||
type RematchOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
TargetRematchName *string `proxy:"target-rematch-name,omitempty"`
|
||||
TargetSubRule *string `proxy:"target-sub-rule,omitempty"`
|
||||
}
|
||||
|
||||
func (l *Rematch) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||
l.applyMetadata(metadata)
|
||||
return NewConn(nopConn{}, l), nil
|
||||
}
|
||||
|
||||
func (l *Rematch) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||
l.applyMetadata(metadata)
|
||||
return NewPacketConn(&nopPacketConn{}, l), nil
|
||||
}
|
||||
|
||||
func (l *Rematch) applyMetadata(metadata *C.Metadata) {
|
||||
if l.targetRematchName != nil {
|
||||
metadata.RematchName = *l.targetRematchName
|
||||
}
|
||||
if l.targetSubRule != nil {
|
||||
metadata.SpecialRules = *l.targetSubRule
|
||||
}
|
||||
}
|
||||
|
||||
func NewRematch(option RematchOption) (*Rematch, error) {
|
||||
if option.TargetRematchName == nil && option.TargetSubRule == nil {
|
||||
return nil, fmt.Errorf("rematch %s requires at least one of target-rematch-name or target-sub-rule", option.Name)
|
||||
}
|
||||
return &Rematch{
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.Rematch,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
}),
|
||||
targetRematchName: option.TargetRematchName,
|
||||
targetSubRule: option.TargetSubRule,
|
||||
}, nil
|
||||
}
|
||||
@@ -100,10 +100,13 @@ type shadowTLSOption struct {
|
||||
}
|
||||
|
||||
type restlsOption struct {
|
||||
Password string `obfs:"password"`
|
||||
Host string `obfs:"host"`
|
||||
VersionHint string `obfs:"version-hint"`
|
||||
RestlsScript string `obfs:"restls-script,omitempty"`
|
||||
Password string `obfs:"password"`
|
||||
Host string `obfs:"host"`
|
||||
VersionHint string `obfs:"version-hint"`
|
||||
RestlsScript string `obfs:"restls-script,omitempty"`
|
||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||
ForceTLS12 bool `obfs:"force-tls12,omitempty"` // for test
|
||||
}
|
||||
|
||||
type kcpTunOption struct {
|
||||
@@ -240,9 +243,9 @@ func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
||||
}
|
||||
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
||||
if ss.option.UDPOverTCPVersion == uot.LegacyVersion {
|
||||
return newPacketConn(N.NewThreadSafePacketConn(uot.NewConn(c, uot.Request{Destination: destination})), ss), nil
|
||||
return NewPacketConn(N.NewThreadSafePacketConn(uot.NewConn(c, uot.Request{Destination: destination})), ss), nil
|
||||
} else {
|
||||
return newPacketConn(N.NewThreadSafePacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination})), ss), nil
|
||||
return NewPacketConn(N.NewThreadSafePacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination})), ss), nil
|
||||
}
|
||||
}
|
||||
if err := ss.ResolveUDP(ctx, metadata); err != nil {
|
||||
@@ -254,7 +257,7 @@ func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
||||
return nil, err
|
||||
}
|
||||
pc = ss.method.DialPacketConn(bufio.NewBindPacketConn(pc, addr))
|
||||
return newPacketConn(pc, ss), nil
|
||||
return NewPacketConn(pc, ss), nil
|
||||
}
|
||||
|
||||
// ProxyInfo implements C.ProxyAdapter
|
||||
@@ -404,7 +407,14 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
||||
}
|
||||
|
||||
restlsConfig.InsecureSkipVerify = restlsOpt.SkipCertVerify
|
||||
if restlsOpt.Fingerprint != "" {
|
||||
err = restls.SetFingerprint(restlsConfig, restlsOpt.Fingerprint)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
||||
}
|
||||
}
|
||||
restlsConfig.ForceTLS12 = restlsOpt.ForceTLS12
|
||||
} else if option.Plugin == kcptun.Mode {
|
||||
obfsMode = kcptun.Mode
|
||||
kcptunOpt := &kcpTunOption{}
|
||||
|
||||
@@ -96,7 +96,7 @@ func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Me
|
||||
|
||||
epc := ssr.cipher.PacketConn(N.NewEnhancePacketConn(pc))
|
||||
epc = ssr.protocol.PacketConn(epc)
|
||||
return newPacketConn(&ssrPacketConn{EnhancePacketConn: epc, rAddr: addr}, ssr), nil
|
||||
return NewPacketConn(&ssrPacketConn{EnhancePacketConn: epc, rAddr: addr}, ssr), nil
|
||||
}
|
||||
|
||||
// ProxyInfo implements C.ProxyAdapter
|
||||
@@ -189,7 +189,12 @@ func (spc *ssrPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return spc.EnhancePacketConn.WriteTo(packet[3:], spc.rAddr)
|
||||
packet = packet[3:]
|
||||
_, err = spc.EnhancePacketConn.WriteTo(packet, spc.rAddr)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
func (spc *ssrPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"github.com/metacubex/mihomo/component/proxydialer"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
@@ -59,7 +60,7 @@ func (s *SingMux) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
if pc == nil {
|
||||
return nil, E.New("packetConn is nil")
|
||||
}
|
||||
return newPacketConn(N.NewThreadSafePacketConn(pc), s), nil
|
||||
return NewPacketConn(N.NewThreadSafePacketConn(pc), s), nil
|
||||
}
|
||||
|
||||
func (s *SingMux) SupportUDP() bool {
|
||||
@@ -106,8 +107,8 @@ func NewSingMux(option SingMuxOption, proxy ProxyAdapter) (ProxyAdapter, error)
|
||||
TCPTimeout: C.DefaultTCPTimeout,
|
||||
Brutal: mux.BrutalOptions{
|
||||
Enabled: option.BrutalOpts.Enabled,
|
||||
SendBPS: StringToBps(option.BrutalOpts.Up),
|
||||
ReceiveBPS: StringToBps(option.BrutalOpts.Down),
|
||||
SendBPS: utils.StringToBps(option.BrutalOpts.Up),
|
||||
ReceiveBPS: utils.StringToBps(option.BrutalOpts.Down),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
+87
-37
@@ -10,51 +10,58 @@ import (
|
||||
"github.com/metacubex/mihomo/common/structure"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
|
||||
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
|
||||
"github.com/metacubex/mihomo/transport/snell"
|
||||
)
|
||||
|
||||
type Snell struct {
|
||||
*Base
|
||||
option *SnellOption
|
||||
psk []byte
|
||||
pool *snell.Pool
|
||||
obfsOption *simpleObfsOption
|
||||
version int
|
||||
option *SnellOption
|
||||
psk []byte
|
||||
pool *snell.Pool
|
||||
obfsOption *simpleObfsOption
|
||||
shadowTLSOption *shadowtls.ShadowTLSOption
|
||||
version int
|
||||
reuse bool
|
||||
}
|
||||
|
||||
type SnellOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Psk string `proxy:"psk"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Version int `proxy:"version,omitempty"`
|
||||
ObfsOpts map[string]any `proxy:"obfs-opts,omitempty"`
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Psk string `proxy:"psk"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Version int `proxy:"version,omitempty"`
|
||||
Reuse bool `proxy:"reuse,omitempty"`
|
||||
ObfsOpts map[string]any `proxy:"obfs-opts,omitempty"`
|
||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
type streamOption struct {
|
||||
psk []byte
|
||||
version int
|
||||
addr string
|
||||
obfsOption *simpleObfsOption
|
||||
}
|
||||
|
||||
func snellStreamConn(c net.Conn, option streamOption) *snell.Snell {
|
||||
switch option.obfsOption.Mode {
|
||||
func (s *Snell) streamConnContext(ctx context.Context, c net.Conn) (*snell.Snell, error) {
|
||||
var err error
|
||||
switch s.obfsOption.Mode {
|
||||
case "tls":
|
||||
c = obfs.NewTLSObfs(c, option.obfsOption.Host)
|
||||
c = obfs.NewTLSObfs(c, s.obfsOption.Host)
|
||||
case "http":
|
||||
_, port, _ := net.SplitHostPort(option.addr)
|
||||
c = obfs.NewHTTPObfs(c, option.obfsOption.Host, port)
|
||||
_, port, _ := net.SplitHostPort(s.addr)
|
||||
c = obfs.NewHTTPObfs(c, s.obfsOption.Host, port)
|
||||
case shadowtls.Mode:
|
||||
c, err = shadowtls.NewShadowTLS(ctx, c, s.shadowTLSOption)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return snell.StreamConn(c, option.psk, option.version)
|
||||
return snell.StreamConn(c, s.psk, s.version), nil
|
||||
}
|
||||
|
||||
// StreamConnContext implements C.ProxyAdapter
|
||||
func (s *Snell) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
c = snellStreamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||
err := s.writeHeaderContext(ctx, c, metadata)
|
||||
c, err := s.streamConnContext(ctx, c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = s.writeHeaderContext(ctx, c, metadata)
|
||||
return c, err
|
||||
}
|
||||
|
||||
@@ -66,15 +73,20 @@ func (s *Snell) writeHeaderContext(ctx context.Context, c net.Conn, metadata *C.
|
||||
|
||||
if metadata.NetWork == C.UDP {
|
||||
err = snell.WriteUDPHeader(c, s.version)
|
||||
if err == nil && s.version >= snell.Version4 {
|
||||
if sc, ok := c.(*snell.Snell); ok {
|
||||
err = sc.ReadReply()
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
err = snell.WriteHeader(c, metadata.String(), uint(metadata.DstPort), s.version)
|
||||
err = snell.WriteHeaderWithReuse(c, metadata.String(), uint(metadata.DstPort), s.version, s.reuse)
|
||||
return
|
||||
}
|
||||
|
||||
// DialContext implements C.ProxyAdapter
|
||||
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||
if s.version == snell.Version2 {
|
||||
if s.reuse {
|
||||
c, err := s.pool.Get()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -84,6 +96,9 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn
|
||||
_ = c.Close()
|
||||
return nil, err
|
||||
}
|
||||
if pc, ok := c.(*snell.PoolConn); ok {
|
||||
pc.MarkReusable()
|
||||
}
|
||||
return NewConn(c, s), err
|
||||
}
|
||||
|
||||
@@ -115,9 +130,12 @@ func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (
|
||||
}(c)
|
||||
|
||||
c, err = s.StreamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pc := snell.PacketConn(c)
|
||||
return newPacketConn(pc, s), nil
|
||||
return NewPacketConn(pc, s), nil
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
@@ -142,9 +160,34 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
||||
return nil, fmt.Errorf("snell %s initialize obfs error: %w", addr, err)
|
||||
}
|
||||
|
||||
var shadowTLSOpt *shadowtls.ShadowTLSOption
|
||||
switch obfsOption.Mode {
|
||||
case "tls", "http", "":
|
||||
break
|
||||
case shadowtls.Mode:
|
||||
opt := &shadowTLSOption{
|
||||
Version: 2,
|
||||
}
|
||||
if err := decoder.Decode(option.ObfsOpts, opt); err != nil {
|
||||
return nil, fmt.Errorf("snell %s initialize shadow-tls-plugin error: %w", addr, err)
|
||||
}
|
||||
|
||||
shadowTLSOpt = &shadowtls.ShadowTLSOption{
|
||||
Password: opt.Password,
|
||||
Host: opt.Host,
|
||||
Fingerprint: opt.Fingerprint,
|
||||
Certificate: opt.Certificate,
|
||||
PrivateKey: opt.PrivateKey,
|
||||
ClientFingerprint: option.ClientFingerprint,
|
||||
SkipCertVerify: opt.SkipCertVerify,
|
||||
Version: opt.Version,
|
||||
}
|
||||
|
||||
if opt.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||
shadowTLSOpt.ALPN = opt.ALPN
|
||||
} else {
|
||||
shadowTLSOpt.ALPN = shadowtls.DefaultALPN
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("snell %s obfs mode error: %s", addr, obfsOption.Mode)
|
||||
}
|
||||
@@ -153,12 +196,17 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
||||
if option.Version == 0 {
|
||||
option.Version = snell.DefaultSnellVersion
|
||||
}
|
||||
if option.Version == snell.Version5 {
|
||||
// Snell v5 servers are backward-compatible with v4 clients.
|
||||
option.Version = snell.Version4
|
||||
}
|
||||
reuse := option.Version == snell.Version2 || (option.Version == snell.Version4 && option.Reuse)
|
||||
switch option.Version {
|
||||
case snell.Version1, snell.Version2:
|
||||
if option.UDP {
|
||||
return nil, fmt.Errorf("snell version %d not support UDP", option.Version)
|
||||
}
|
||||
case snell.Version3:
|
||||
case snell.Version3, snell.Version4:
|
||||
default:
|
||||
return nil, fmt.Errorf("snell version error: %d", option.Version)
|
||||
}
|
||||
@@ -176,21 +224,23 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
psk: psk,
|
||||
obfsOption: obfsOption,
|
||||
version: option.Version,
|
||||
option: &option,
|
||||
psk: psk,
|
||||
obfsOption: obfsOption,
|
||||
shadowTLSOption: shadowTLSOpt,
|
||||
version: option.Version,
|
||||
reuse: reuse,
|
||||
}
|
||||
s.dialer = option.NewDialer(s.DialOptions())
|
||||
|
||||
if option.Version == snell.Version2 {
|
||||
if s.reuse {
|
||||
s.pool = snell.NewPool(func(ctx context.Context) (*snell.Snell, error) {
|
||||
c, err := s.dialer.DialContext(ctx, "tcp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return snellStreamConn(c, streamOption{psk, option.Version, addr, obfsOption}), nil
|
||||
return s.streamConnContext(ctx, c)
|
||||
})
|
||||
}
|
||||
return s, nil
|
||||
|
||||
@@ -151,7 +151,7 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
pc.Close()
|
||||
}()
|
||||
|
||||
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
||||
return NewPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
||||
}
|
||||
|
||||
// ProxyInfo implements C.ProxyAdapter
|
||||
@@ -222,7 +222,11 @@ func (uc *socksPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return uc.PacketConn.WriteTo(packet, uc.rAddr)
|
||||
_, err = uc.PacketConn.WriteTo(packet, uc.rAddr)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
func (uc *socksPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
|
||||
@@ -66,7 +66,7 @@ func (s *Sudoku) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Con
|
||||
}
|
||||
|
||||
muxMode := normalizeHTTPMaskMultiplex(cfg.HTTPMaskMultiplex)
|
||||
if muxMode == "on" && !cfg.DisableHTTPMask && httpTunnelModeEnabled(cfg.HTTPMaskMode) {
|
||||
if muxMode == "on" {
|
||||
stream, muxErr := s.dialMultiplex(ctx, cfg.TargetAddress)
|
||||
if muxErr == nil {
|
||||
return NewConn(stream, s), nil
|
||||
@@ -113,7 +113,7 @@ func (s *Sudoku) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
return nil, fmt.Errorf("start uot failed: %w", err)
|
||||
}
|
||||
|
||||
return newPacketConn(N.NewThreadSafePacketConn(sudoku.NewUoTPacketConn(c)), s), nil
|
||||
return NewPacketConn(N.NewThreadSafePacketConn(sudoku.NewUoTPacketConn(c)), s), nil
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build !no_tailscale
|
||||
//go:build with_gvisor && !no_tailscale
|
||||
|
||||
package outbound
|
||||
|
||||
@@ -21,10 +21,13 @@ import (
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
"github.com/metacubex/tailscale/envknob"
|
||||
"github.com/metacubex/tailscale/hostinfo"
|
||||
"github.com/metacubex/tailscale/ipn"
|
||||
"github.com/metacubex/tailscale/net/netmon"
|
||||
"github.com/metacubex/tailscale/tailcfg"
|
||||
"github.com/metacubex/tailscale/tsnet"
|
||||
D "github.com/miekg/dns"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
type Tailscale struct {
|
||||
@@ -62,23 +65,44 @@ type TailscaleOption struct {
|
||||
}
|
||||
|
||||
func init() {
|
||||
hostinfo.RegisterHostinfoNewHook(func(hi *tailcfg.Hostinfo) {
|
||||
hi.IPNVersion = C.MihomoName + " " + C.Version
|
||||
})
|
||||
envknob.SetNoLogsNoSupport()
|
||||
if runtime.GOOS == "android" { // Android SDK 30 no longer permits Go's net.Interfaces to work (Issue 2293)
|
||||
netmon.RegisterInterfaceGetter(func() (nif []netmon.Interface, err error) {
|
||||
log.Debugln("[Tailscale] InterfaceGetter: start, IsForceAnet: %v", anet.IsForceAnet())
|
||||
ifaces, err := anet.Interfaces()
|
||||
if err != nil {
|
||||
log.Warnln("[Tailscale] anet.Interfaces failed: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
for _, iff := range ifaces {
|
||||
addrs, err := anet.InterfaceAddrsByInterface(&iff)
|
||||
if err != nil {
|
||||
log.Warnln("[Tailscale] anet.InterfaceAddrsByInterface(%v) failed: %v", iff.Name, err)
|
||||
continue
|
||||
}
|
||||
nif = append(nif, netmon.Interface{
|
||||
Interface: &iff,
|
||||
AltAddrs: addrs,
|
||||
Interface: &net.Interface{
|
||||
Index: iff.Index,
|
||||
MTU: iff.MTU,
|
||||
Name: iff.Name,
|
||||
HardwareAddr: iff.HardwareAddr,
|
||||
Flags: iff.Flags,
|
||||
},
|
||||
AltAddrs: addrs,
|
||||
})
|
||||
}
|
||||
|
||||
log.Debugln("[Tailscale] InterfaceGetter: %v", lo.Map(nif, func(item netmon.Interface, index int) string {
|
||||
var addrs any
|
||||
addrs, err := item.Addrs()
|
||||
if err != nil {
|
||||
addrs = err
|
||||
}
|
||||
return fmt.Sprintf("{Name: %s, Addrs: %v, IsUp: %v, IsLoopback: %v}", item.Name, addrs, item.IsUp(), item.IsLoopback())
|
||||
}))
|
||||
return
|
||||
})
|
||||
}
|
||||
@@ -119,15 +143,30 @@ func NewTailscale(option TailscaleOption) (*Tailscale, error) {
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
outbound.server = &tsnet.Server{
|
||||
Dir: option.StateDir,
|
||||
Hostname: option.Hostname,
|
||||
AuthKey: option.AuthKey,
|
||||
ControlURL: option.ControlURL,
|
||||
Ephemeral: option.Ephemeral,
|
||||
SystemDialer: outbound.dialer.DialContext,
|
||||
SystemPacketListener: tailscalePacketListener{dialer: outbound.dialer},
|
||||
ExtraRootCAs: ca.GetCertPool(),
|
||||
LookupHook: tailscaleLookupHook,
|
||||
Dir: option.StateDir,
|
||||
Hostname: option.Hostname,
|
||||
AuthKey: option.AuthKey,
|
||||
ControlURL: option.ControlURL,
|
||||
Ephemeral: option.Ephemeral,
|
||||
SystemDialer: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
log.Debugln("[Tailscale](%s) SystemDialer: start dial %s %s", option.Name, network, address)
|
||||
conn, err := outbound.dialer.DialContext(ctx, network, address)
|
||||
log.Debugln("[Tailscale](%s) SystemDialer: finish dial %s %s, err: %v", option.Name, network, address, err)
|
||||
return conn, err
|
||||
},
|
||||
SystemPacketListener: func(ctx context.Context, network, address string) (net.PacketConn, error) {
|
||||
log.Debugln("[Tailscale](%s) SystemPacketListener: start listen %s %s", option.Name, network, address)
|
||||
pc, err := outbound.dialer.ListenPacket(ctx, network, address, netip.AddrPort{})
|
||||
log.Debugln("[Tailscale](%s) SystemPacketListener: finish listen %s %s, err: %v", option.Name, network, address, err)
|
||||
return pc, err
|
||||
},
|
||||
ExtraRootCAs: ca.GetCertPool(),
|
||||
LookupHook: func(ctx context.Context, host string) ([]netip.Addr, error) {
|
||||
log.Debugln("[Tailscale](%s) LookupHook: start lookup %s", option.Name, host)
|
||||
ips, err := resolver.LookupIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||
log.Debugln("[Tailscale](%s) LookupHook: finish lookup %s, ips: %v, err: %v", option.Name, host, ips, err)
|
||||
return ips, err
|
||||
},
|
||||
UserLogf: func(format string, args ...any) {
|
||||
log.Infoln("[Tailscale](%s) %s", option.Name, fmt.Sprintf(format, args...))
|
||||
},
|
||||
@@ -304,21 +343,31 @@ func tailscaleExitNodeNeedsStatus(option TailscaleOption) bool {
|
||||
return !ok
|
||||
}
|
||||
|
||||
func tailscaleLookupHook(ctx context.Context, host string) ([]netip.Addr, error) {
|
||||
return resolver.LookupIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||
}
|
||||
|
||||
func (t *Tailscale) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||
if err = t.ensureStarted(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
netStack, err := t.server.Netstack(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v4, v6 := t.server.TailscaleIPs()
|
||||
options := t.DialOptions()
|
||||
options = append(options, dialer.WithResolver(t.dnsResolver))
|
||||
options = append(options, dialer.WithNetDialer(dialer.NetDialerFunc(func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if err = t.checkTailscaleRoute(ctx, network, address); err != nil {
|
||||
dst, err := netip.ParseAddrPort(address) // the dialer will resolve the domain to ip
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t.server.Dial(ctx, network, address)
|
||||
src := v4
|
||||
if dst.Addr().Is6() {
|
||||
src = v6
|
||||
}
|
||||
tcpConn, err := netStack.DialContextTCPWithBind(ctx, src, dst)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tcpConn, nil
|
||||
})))
|
||||
var conn net.Conn
|
||||
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||
@@ -350,7 +399,7 @@ func (t *Tailscale) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
||||
if pc == nil {
|
||||
return nil, errors.New("packetConn is nil")
|
||||
}
|
||||
return newPacketConn(pc, t), nil
|
||||
return NewPacketConn(pc, t), nil
|
||||
}
|
||||
|
||||
func (t *Tailscale) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||
@@ -364,17 +413,6 @@ func (t *Tailscale) ResolveUDP(ctx context.Context, metadata *C.Metadata) error
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Tailscale) checkTailscaleRoute(ctx context.Context, network, address string) error {
|
||||
ipp, viaTailscale, err := t.server.DialPlan(ctx, network, address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !viaTailscale {
|
||||
return fmt.Errorf("destination %s is not routed by Tailscale; configure exit-node or accept an advertised subnet route", ipp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type tailscaleDNSTransport struct {
|
||||
tailscale *Tailscale
|
||||
}
|
||||
@@ -436,11 +474,3 @@ func (t *Tailscale) Close() error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type tailscalePacketListener struct {
|
||||
dialer C.Dialer
|
||||
}
|
||||
|
||||
func (l tailscalePacketListener) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
|
||||
return l.dialer.ListenPacket(ctx, network, address, netip.AddrPort{})
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build no_tailscale
|
||||
//go:build !with_gvisor || no_tailscale
|
||||
|
||||
package outbound
|
||||
|
||||
@@ -24,5 +24,5 @@ type TailscaleOption struct {
|
||||
}
|
||||
|
||||
func NewTailscale(option TailscaleOption) (*Tailscale, error) {
|
||||
return nil, fmt.Errorf("tailscale support is disabled by no_tailscale build tag")
|
||||
return nil, fmt.Errorf("tailscale support is disabled by \"no_tailscale\" build tag or not include \"with_gvisor\" build tag")
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package outbound
|
||||
|
||||
import "github.com/metacubex/mihomo/transport/tlsmirror"
|
||||
|
||||
type TLSMirrorOptions struct {
|
||||
PrimaryKey string `proxy:"primary-key,omitempty"`
|
||||
ExplicitNonceCipherSuites []uint16 `proxy:"explicit-nonce-ciphersuites,omitempty"`
|
||||
DeferInstanceDerivedWriteTime TLSMirrorTimeSpec `proxy:"defer-instance-derived-write-time,omitempty"`
|
||||
TransportLayerPadding TLSMirrorTransportLayerPadding `proxy:"transport-layer-padding,omitempty"`
|
||||
ConnectionEnrolment *TLSMirrorConnectionEnrolment `proxy:"connection-enrolment,omitempty"`
|
||||
EmbeddedTrafficGenerator TLSMirrorTrafficGenerator `proxy:"embedded-traffic-generator,omitempty"`
|
||||
SequenceWatermarkingEnabled bool `proxy:"sequence-watermarking-enabled,omitempty"`
|
||||
}
|
||||
|
||||
type TLSMirrorConnectionEnrolment struct {
|
||||
PrimaryIngressOutbound string `proxy:"primary-ingress-outbound,omitempty"`
|
||||
PrimaryEgressOutbound string `proxy:"primary-egress-outbound,omitempty"`
|
||||
}
|
||||
|
||||
func (e *TLSMirrorConnectionEnrolment) Build() *tlsmirror.ConnectionEnrolment {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return &tlsmirror.ConnectionEnrolment{
|
||||
PrimaryIngressOutbound: e.PrimaryIngressOutbound,
|
||||
PrimaryEgressOutbound: e.PrimaryEgressOutbound,
|
||||
}
|
||||
}
|
||||
|
||||
type TLSMirrorTimeSpec struct {
|
||||
BaseNanoseconds uint64 `proxy:"base-nanoseconds,omitempty"`
|
||||
UniformRandomMultiplierNanoseconds uint64 `proxy:"uniform-random-multiplier-nanoseconds,omitempty"`
|
||||
}
|
||||
|
||||
func (s TLSMirrorTimeSpec) Build() tlsmirror.TimeSpec {
|
||||
return tlsmirror.TimeSpec{
|
||||
BaseNanoseconds: s.BaseNanoseconds,
|
||||
UniformRandomMultiplierNanoseconds: s.UniformRandomMultiplierNanoseconds,
|
||||
}
|
||||
}
|
||||
|
||||
type TLSMirrorTransportLayerPadding struct {
|
||||
Enabled bool `proxy:"enabled,omitempty"`
|
||||
}
|
||||
|
||||
func (p TLSMirrorTransportLayerPadding) Build() tlsmirror.TransportLayerPadding {
|
||||
return tlsmirror.TransportLayerPadding{
|
||||
Enabled: p.Enabled,
|
||||
}
|
||||
}
|
||||
|
||||
type TLSMirrorTrafficGenerator struct {
|
||||
Steps []TLSMirrorTrafficStep `proxy:"steps,omitempty"`
|
||||
}
|
||||
|
||||
func (g TLSMirrorTrafficGenerator) Build() *tlsmirror.TrafficGenerator {
|
||||
if len(g.Steps) == 0 {
|
||||
return nil
|
||||
}
|
||||
steps := make([]tlsmirror.TrafficStep, 0, len(g.Steps))
|
||||
for _, step := range g.Steps {
|
||||
steps = append(steps, step.Build())
|
||||
}
|
||||
return &tlsmirror.TrafficGenerator{Steps: steps}
|
||||
}
|
||||
|
||||
type TLSMirrorTrafficStep struct {
|
||||
Name string `proxy:"name,omitempty"`
|
||||
Host string `proxy:"host,omitempty"`
|
||||
Path string `proxy:"path,omitempty"`
|
||||
Method string `proxy:"method,omitempty"`
|
||||
Headers []TLSMirrorTrafficHeader `proxy:"headers,omitempty"`
|
||||
NextStep []TLSMirrorTrafficTransferCandidate `proxy:"next-step,omitempty"`
|
||||
ConnectionReady bool `proxy:"connection-ready,omitempty"`
|
||||
ConnectionRecallExit bool `proxy:"connection-recall-exit,omitempty"`
|
||||
WaitTime TLSMirrorTimeSpec `proxy:"wait-time,omitempty"`
|
||||
H2DoNotWaitForDownloadFinish bool `proxy:"h2-do-not-wait-for-download-finish,omitempty"`
|
||||
}
|
||||
|
||||
func (s TLSMirrorTrafficStep) Build() tlsmirror.TrafficStep {
|
||||
headers := make([]tlsmirror.TrafficHeader, 0, len(s.Headers))
|
||||
for _, header := range s.Headers {
|
||||
headers = append(headers, header.Build())
|
||||
}
|
||||
nextStep := make([]tlsmirror.TrafficTransferCandidate, 0, len(s.NextStep))
|
||||
for _, candidate := range s.NextStep {
|
||||
nextStep = append(nextStep, candidate.Build())
|
||||
}
|
||||
return tlsmirror.TrafficStep{
|
||||
Name: s.Name,
|
||||
Host: s.Host,
|
||||
Path: s.Path,
|
||||
Method: s.Method,
|
||||
Headers: headers,
|
||||
NextStep: nextStep,
|
||||
ConnectionReady: s.ConnectionReady,
|
||||
ConnectionRecallExit: s.ConnectionRecallExit,
|
||||
WaitTime: s.WaitTime.Build(),
|
||||
H2DoNotWaitForDownloadFinish: s.H2DoNotWaitForDownloadFinish,
|
||||
}
|
||||
}
|
||||
|
||||
type TLSMirrorTrafficHeader struct {
|
||||
Name string `proxy:"name,omitempty"`
|
||||
Value string `proxy:"value,omitempty"`
|
||||
Values []string `proxy:"values,omitempty"`
|
||||
}
|
||||
|
||||
func (h TLSMirrorTrafficHeader) Build() tlsmirror.TrafficHeader {
|
||||
return tlsmirror.TrafficHeader{
|
||||
Name: h.Name,
|
||||
Value: h.Value,
|
||||
Values: h.Values,
|
||||
}
|
||||
}
|
||||
|
||||
type TLSMirrorTrafficTransferCandidate struct {
|
||||
Weight int32 `proxy:"weight,omitempty"`
|
||||
GotoLocation int `proxy:"goto-location,omitempty"`
|
||||
}
|
||||
|
||||
func (c TLSMirrorTrafficTransferCandidate) Build() tlsmirror.TrafficTransferCandidate {
|
||||
return tlsmirror.TrafficTransferCandidate{
|
||||
Weight: c.Weight,
|
||||
GotoLocation: c.GotoLocation,
|
||||
}
|
||||
}
|
||||
|
||||
func (o TLSMirrorOptions) Build() *tlsmirror.Config {
|
||||
if o.PrimaryKey == "" {
|
||||
return nil
|
||||
}
|
||||
return &tlsmirror.Config{
|
||||
PrimaryKey: o.PrimaryKey,
|
||||
ExplicitNonceCipherSuites: o.ExplicitNonceCipherSuites,
|
||||
DeferInstanceDerivedWrite: o.DeferInstanceDerivedWriteTime.Build(),
|
||||
TransportLayerPadding: o.TransportLayerPadding.Build(),
|
||||
ConnectionEnrolment: o.ConnectionEnrolment.Build(),
|
||||
SequenceWatermarkingEnabled: o.SequenceWatermarkingEnabled,
|
||||
EmbeddedTrafficGenerator: o.EmbeddedTrafficGenerator.Build(),
|
||||
}
|
||||
}
|
||||
@@ -219,7 +219,7 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
}
|
||||
|
||||
pc := trojan.NewPacketConn(c)
|
||||
return newPacketConn(pc, t), err
|
||||
return NewPacketConn(pc, t), err
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
|
||||
@@ -63,7 +63,7 @@ func (t *TrustTunnel) ListenPacketContext(ctx context.Context, metadata *C.Metad
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newPacketConn(N.NewThreadSafePacketConn(pc), t), nil
|
||||
return NewPacketConn(N.NewThreadSafePacketConn(pc), t), nil
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
|
||||
@@ -97,16 +97,16 @@ func (t *Tuic) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_
|
||||
|
||||
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
||||
if t.option.UDPOverStreamVersion == uot.LegacyVersion {
|
||||
return newPacketConn(uot.NewConn(c, uot.Request{Destination: destination}), t), nil
|
||||
return NewPacketConn(uot.NewConn(c, uot.Request{Destination: destination}), t), nil
|
||||
} else {
|
||||
return newPacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination}), t), nil
|
||||
return NewPacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination}), t), nil
|
||||
}
|
||||
}
|
||||
pc, err := t.client.ListenPacket(ctx, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newPacketConn(pc, t), nil
|
||||
return NewPacketConn(pc, t), nil
|
||||
}
|
||||
|
||||
func (t *Tuic) dial(ctx context.Context) (quicConn *quic.Conn, err error) {
|
||||
|
||||
@@ -3,10 +3,8 @@ package outbound
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
@@ -78,42 +76,3 @@ func safeConnClose(c net.Conn, err error) {
|
||||
_ = c.Close()
|
||||
}
|
||||
}
|
||||
|
||||
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
||||
|
||||
func StringToBps(s string) uint64 {
|
||||
if s == "" {
|
||||
return 0
|
||||
}
|
||||
|
||||
// when have not unit, use Mbps
|
||||
if v, err := strconv.Atoi(s); err == nil {
|
||||
return StringToBps(fmt.Sprintf("%d Mbps", v))
|
||||
}
|
||||
|
||||
m := rateStringRegexp.FindStringSubmatch(s)
|
||||
if m == nil {
|
||||
return 0
|
||||
}
|
||||
var n uint64 = 1
|
||||
switch m[2] {
|
||||
case "T":
|
||||
n *= 1000
|
||||
fallthrough
|
||||
case "G":
|
||||
n *= 1000
|
||||
fallthrough
|
||||
case "M":
|
||||
n *= 1000
|
||||
fallthrough
|
||||
case "K":
|
||||
n *= 1000
|
||||
}
|
||||
v, _ := strconv.ParseUint(m[1], 10, 64)
|
||||
n *= v
|
||||
if m[3] == "b" {
|
||||
// Bits, need to convert to bytes
|
||||
n /= 8
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -93,6 +93,8 @@ type XHTTPOptions struct {
|
||||
UplinkHTTPMethod string `proxy:"uplink-http-method,omitempty"`
|
||||
SessionPlacement string `proxy:"session-placement,omitempty"`
|
||||
SessionKey string `proxy:"session-key,omitempty"`
|
||||
SessionTable string `proxy:"session-table,omitempty"`
|
||||
SessionLength string `proxy:"session-length,omitempty"`
|
||||
SeqPlacement string `proxy:"seq-placement,omitempty"`
|
||||
SeqKey string `proxy:"seq-key,omitempty"`
|
||||
UplinkDataPlacement string `proxy:"uplink-data-placement,omitempty"`
|
||||
@@ -346,18 +348,18 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (
|
||||
if metadata.SourceValid() {
|
||||
globalID = utils.GlobalID(metadata.SourceAddress())
|
||||
}
|
||||
return newPacketConn(N.NewThreadSafePacketConn(
|
||||
return NewPacketConn(N.NewThreadSafePacketConn(
|
||||
vmessSing.NewXUDPConn(c,
|
||||
globalID,
|
||||
M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||
), v), nil
|
||||
} else if v.option.PacketAddr {
|
||||
return newPacketConn(N.NewThreadSafePacketConn(
|
||||
return NewPacketConn(N.NewThreadSafePacketConn(
|
||||
packetaddr.NewConn(v.client.PacketConn(c, metadata.UDPAddr()),
|
||||
M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||
), v), nil
|
||||
}
|
||||
return newPacketConn(N.NewThreadSafePacketConn(v.client.PacketConn(c, metadata.UDPAddr())), v), nil
|
||||
return NewPacketConn(N.NewThreadSafePacketConn(v.client.PacketConn(c, metadata.UDPAddr())), v), nil
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
@@ -569,6 +571,8 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
UplinkHTTPMethod: v.option.XHTTPOpts.UplinkHTTPMethod,
|
||||
SessionPlacement: v.option.XHTTPOpts.SessionPlacement,
|
||||
SessionKey: v.option.XHTTPOpts.SessionKey,
|
||||
SessionTable: v.option.XHTTPOpts.SessionTable,
|
||||
SessionLength: v.option.XHTTPOpts.SessionLength,
|
||||
SeqPlacement: v.option.XHTTPOpts.SeqPlacement,
|
||||
SeqKey: v.option.XHTTPOpts.SeqKey,
|
||||
UplinkDataPlacement: v.option.XHTTPOpts.UplinkDataPlacement,
|
||||
|
||||
+158
-48
@@ -13,10 +13,13 @@ import (
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"github.com/metacubex/mihomo/component/ca"
|
||||
"github.com/metacubex/mihomo/component/ech"
|
||||
"github.com/metacubex/mihomo/component/proxydialer"
|
||||
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/ntp"
|
||||
"github.com/metacubex/mihomo/transport/gun"
|
||||
"github.com/metacubex/mihomo/transport/mekya"
|
||||
"github.com/metacubex/mihomo/transport/mkcp"
|
||||
mihomoVMess "github.com/metacubex/mihomo/transport/vmess"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
@@ -34,7 +37,8 @@ type Vmess struct {
|
||||
option *VmessOption
|
||||
|
||||
// for gun mux
|
||||
gunClient *gun.Client
|
||||
gunClient *gun.Client
|
||||
mekyaClient *mekya.Client
|
||||
|
||||
realityConfig *tlsC.RealityConfig
|
||||
echConfig *ech.Config
|
||||
@@ -42,33 +46,90 @@ type Vmess struct {
|
||||
|
||||
type VmessOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
UUID string `proxy:"uuid"`
|
||||
AlterID int `proxy:"alterId"`
|
||||
Cipher string `proxy:"cipher"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Network string `proxy:"network,omitempty"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
ALPN []string `proxy:"alpn,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
Certificate string `proxy:"certificate,omitempty"`
|
||||
PrivateKey string `proxy:"private-key,omitempty"`
|
||||
ServerName string `proxy:"servername,omitempty"`
|
||||
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||
XUDP bool `proxy:"xudp,omitempty"`
|
||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
||||
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
UUID string `proxy:"uuid"`
|
||||
AlterID int `proxy:"alterId"`
|
||||
Cipher string `proxy:"cipher"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Network string `proxy:"network,omitempty"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
ALPN []string `proxy:"alpn,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
Certificate string `proxy:"certificate,omitempty"`
|
||||
PrivateKey string `proxy:"private-key,omitempty"`
|
||||
ServerName string `proxy:"servername,omitempty"`
|
||||
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||
TLSMirrorOpts TLSMirrorOptions `proxy:"tlsmirror-opts,omitempty"`
|
||||
MekyaOpts MekyaOptions `proxy:"mekya-opts,omitempty"`
|
||||
MKCPOpts MKCPOptions `proxy:"mkcp-opts,omitempty"`
|
||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||
XUDP bool `proxy:"xudp,omitempty"`
|
||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
||||
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
type MKCPOptions struct {
|
||||
MTU uint32 `proxy:"mtu,omitempty"`
|
||||
TTI uint32 `proxy:"tti,omitempty"`
|
||||
UplinkCapacity uint32 `proxy:"uplink-capacity,omitempty"`
|
||||
DownlinkCapacity uint32 `proxy:"downlink-capacity,omitempty"`
|
||||
Congestion bool `proxy:"congestion,omitempty"`
|
||||
WriteBuffer uint32 `proxy:"write-buffer,omitempty"`
|
||||
ReadBuffer uint32 `proxy:"read-buffer,omitempty"`
|
||||
Seed string `proxy:"seed,omitempty"`
|
||||
Header string `proxy:"header,omitempty"`
|
||||
}
|
||||
|
||||
func (o MKCPOptions) Build() mkcp.Config {
|
||||
return mkcp.Config{
|
||||
MTU: o.MTU,
|
||||
TTI: o.TTI,
|
||||
UplinkCapacity: o.UplinkCapacity,
|
||||
DownlinkCapacity: o.DownlinkCapacity,
|
||||
Congestion: o.Congestion,
|
||||
WriteBuffer: o.WriteBuffer,
|
||||
ReadBuffer: o.ReadBuffer,
|
||||
Seed: o.Seed,
|
||||
Header: o.Header,
|
||||
}
|
||||
}
|
||||
|
||||
type MekyaOptions struct {
|
||||
URL string `proxy:"url,omitempty"`
|
||||
H2PoolSize int `proxy:"h2-pool-size,omitempty"`
|
||||
MaxWriteDelay int `proxy:"max-write-delay,omitempty"`
|
||||
MaxRequestSize int `proxy:"max-request-size,omitempty"`
|
||||
PollingIntervalInitial int `proxy:"polling-interval-initial,omitempty"`
|
||||
MaxWriteSize int `proxy:"max-write-size,omitempty"`
|
||||
MaxWriteDurationMs int `proxy:"max-write-duration-ms,omitempty"`
|
||||
MaxSimultaneousWriteConnection int `proxy:"max-simultaneous-write-connection,omitempty"`
|
||||
PacketWritingBuffer int `proxy:"packet-writing-buffer,omitempty"`
|
||||
KCP MKCPOptions `proxy:"kcp,omitempty"`
|
||||
}
|
||||
|
||||
func (o MekyaOptions) Build() mekya.Config {
|
||||
return mekya.Config{
|
||||
KCP: o.KCP.Build(),
|
||||
URL: o.URL,
|
||||
H2PoolSize: o.H2PoolSize,
|
||||
MaxWriteDelay: o.MaxWriteDelay,
|
||||
MaxRequestSize: o.MaxRequestSize,
|
||||
PollingIntervalInitial: o.PollingIntervalInitial,
|
||||
MaxWriteSize: o.MaxWriteSize,
|
||||
MaxWriteDurationMs: o.MaxWriteDurationMs,
|
||||
MaxSimultaneousWriteConnection: o.MaxSimultaneousWriteConnection,
|
||||
PacketWritingBuffer: o.PacketWritingBuffer,
|
||||
}
|
||||
}
|
||||
|
||||
type HTTPOptions struct {
|
||||
@@ -124,25 +185,32 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
||||
}
|
||||
|
||||
if v.option.TLS {
|
||||
wsOpts.TLS = true
|
||||
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
|
||||
TLSConfig: &tls.Config{
|
||||
ServerName: host,
|
||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||
NextProtos: []string{"http/1.1"},
|
||||
},
|
||||
Fingerprint: v.option.Fingerprint,
|
||||
Certificate: v.option.Certificate,
|
||||
PrivateKey: v.option.PrivateKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if v.option.TLSMirrorOpts.PrimaryKey != "" {
|
||||
c, err = v.streamTLSConn(ctx, c, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
wsOpts.TLS = true
|
||||
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
|
||||
TLSConfig: &tls.Config{
|
||||
ServerName: host,
|
||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||
NextProtos: []string{"http/1.1"},
|
||||
},
|
||||
Fingerprint: v.option.Fingerprint,
|
||||
Certificate: v.option.Certificate,
|
||||
PrivateKey: v.option.PrivateKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if v.option.ServerName != "" {
|
||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||
wsOpts.TLSConfig.ServerName = host
|
||||
if v.option.ServerName != "" {
|
||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||
wsOpts.TLSConfig.ServerName = host
|
||||
}
|
||||
}
|
||||
}
|
||||
c, err = mihomoVMess.StreamWebsocketConn(ctx, c, wsOpts)
|
||||
@@ -176,6 +244,8 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
||||
c, err = mihomoVMess.StreamH2Conn(ctx, c, h2Opts)
|
||||
case "grpc":
|
||||
break // already handle in dialContext
|
||||
case "mekya":
|
||||
break // already handle in dialContext
|
||||
default:
|
||||
// default tcp network
|
||||
// handle TLS
|
||||
@@ -258,6 +328,8 @@ func (v *Vmess) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (ne
|
||||
ECH: v.echConfig,
|
||||
Reality: v.realityConfig,
|
||||
NextProtos: v.option.ALPN,
|
||||
TLSMirror: v.option.TLSMirrorOpts.Build(),
|
||||
TLSMirrorDialer: proxydialer.New(v, false).DialContext,
|
||||
}
|
||||
|
||||
if isH2 {
|
||||
@@ -278,6 +350,14 @@ func (v *Vmess) dialContext(ctx context.Context) (c net.Conn, err error) {
|
||||
switch v.option.Network {
|
||||
case "grpc": // gun transport
|
||||
return v.gunClient.Dial()
|
||||
case "mekya":
|
||||
return v.mekyaClient.Dial(ctx)
|
||||
case "mkcp", "kcp":
|
||||
rawConn, err := v.dialer.DialContext(ctx, "udp", v.addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return mkcp.Dial(ctx, rawConn, v.option.MKCPOpts.Build())
|
||||
default:
|
||||
}
|
||||
return v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
@@ -320,9 +400,9 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (
|
||||
}
|
||||
|
||||
if pc, ok := c.(net.PacketConn); ok {
|
||||
return newPacketConn(N.NewThreadSafePacketConn(pc), v), nil
|
||||
return NewPacketConn(N.NewThreadSafePacketConn(pc), v), nil
|
||||
}
|
||||
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||
return NewPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||
}
|
||||
|
||||
// ProxyInfo implements C.ProxyAdapter
|
||||
@@ -340,6 +420,11 @@ func (v *Vmess) Close() error {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
if v.mekyaClient != nil {
|
||||
if err := v.mekyaClient.Close(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
@@ -407,6 +492,29 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
if len(option.HTTP2Opts.Host) == 0 {
|
||||
option.HTTP2Opts.Host = append(option.HTTP2Opts.Host, "www.example.com")
|
||||
}
|
||||
case "mekya":
|
||||
if len(v.option.ALPN) == 0 {
|
||||
v.option.ALPN = []string{"h2", "http/1.1"}
|
||||
}
|
||||
cfg := option.MekyaOpts.Build()
|
||||
if cfg.URL == "" {
|
||||
cfg.URL = "https://" + v.addr
|
||||
}
|
||||
v.mekyaClient, err = mekya.NewClient(context.Background(), func(ctx context.Context) (net.Conn, error) {
|
||||
rawConn, err := v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn, err := v.streamTLSConn(ctx, rawConn, false)
|
||||
if err != nil {
|
||||
_ = rawConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
return conn, nil
|
||||
}, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "grpc":
|
||||
dialFn := func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
c, err := v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||
@@ -437,6 +545,8 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
NextProtos: []string{"h2"},
|
||||
ECH: v.echConfig,
|
||||
Reality: v.realityConfig,
|
||||
TLSMirror: option.TLSMirrorOpts.Build(),
|
||||
TLSMirrorDialer: proxydialer.New(v, false).DialContext,
|
||||
}
|
||||
if option.ServerName == "" {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
|
||||
@@ -591,7 +591,7 @@ func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
||||
if pc == nil {
|
||||
return nil, E.New("packetConn is nil")
|
||||
}
|
||||
return newPacketConn(pc, w), nil
|
||||
return NewPacketConn(pc, w), nil
|
||||
}
|
||||
|
||||
func (w *WireGuard) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
P "github.com/metacubex/mihomo/constant/provider"
|
||||
)
|
||||
|
||||
type FallbackOption struct{}
|
||||
|
||||
type Fallback struct {
|
||||
*GroupBase
|
||||
disableUDP bool
|
||||
@@ -90,6 +92,7 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||
"fixed": f.selected,
|
||||
"hidden": f.Hidden(),
|
||||
"icon": f.Icon(),
|
||||
"emptyFallback": f.EmptyFallback().Name(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -156,7 +159,7 @@ func (f *Fallback) Proxies() []C.Proxy {
|
||||
return f.GetProxies(false)
|
||||
}
|
||||
|
||||
func NewFallback(option *GroupCommonOption, providers []P.ProxyProvider) *Fallback {
|
||||
func NewFallback(option GroupCommonOption, fallbackOption FallbackOption, emptyFallback C.Proxy, providers []P.ProxyProvider) (*Fallback, error) {
|
||||
return &Fallback{
|
||||
GroupBase: NewGroupBase(GroupBaseOption{
|
||||
Name: option.Name,
|
||||
@@ -168,10 +171,11 @@ func NewFallback(option *GroupCommonOption, providers []P.ProxyProvider) *Fallba
|
||||
ExcludeType: option.ExcludeType,
|
||||
TestTimeout: option.TestTimeout,
|
||||
MaxFailedTimes: option.MaxFailedTimes,
|
||||
EmptyFallback: emptyFallback,
|
||||
Providers: providers,
|
||||
}),
|
||||
disableUDP: option.DisableUDP,
|
||||
testUrl: option.URL,
|
||||
expectedStatus: option.ExpectedStatus,
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
P "github.com/metacubex/mihomo/constant/provider"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
"github.com/metacubex/mihomo/tunnel"
|
||||
|
||||
"github.com/dlclark/regexp2"
|
||||
"golang.org/x/exp/slices"
|
||||
@@ -34,6 +33,7 @@ type GroupBase struct {
|
||||
failedTesting atomic.Bool
|
||||
testTimeout int
|
||||
maxFailedTimes int
|
||||
emptyFallback C.Proxy
|
||||
|
||||
// for GetProxies
|
||||
getProxiesMutex sync.Mutex
|
||||
@@ -51,6 +51,7 @@ type GroupBaseOption struct {
|
||||
ExcludeType string
|
||||
TestTimeout int
|
||||
MaxFailedTimes int
|
||||
EmptyFallback C.Proxy
|
||||
Providers []P.ProxyProvider
|
||||
}
|
||||
|
||||
@@ -87,6 +88,7 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||
failedTesting: atomic.NewBool(false),
|
||||
testTimeout: opt.TestTimeout,
|
||||
maxFailedTimes: opt.MaxFailedTimes,
|
||||
emptyFallback: opt.EmptyFallback,
|
||||
}
|
||||
|
||||
if gb.testTimeout == 0 {
|
||||
@@ -107,6 +109,10 @@ func (gb *GroupBase) Icon() string {
|
||||
return gb.icon
|
||||
}
|
||||
|
||||
func (gb *GroupBase) EmptyFallback() C.Proxy {
|
||||
return gb.emptyFallback
|
||||
}
|
||||
|
||||
func (gb *GroupBase) Touch() {
|
||||
for _, pd := range gb.providers {
|
||||
pd.Touch()
|
||||
@@ -218,7 +224,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
||||
}
|
||||
|
||||
if len(proxies) == 0 {
|
||||
return []C.Proxy{tunnel.Proxies()["COMPATIBLE"]}
|
||||
return []C.Proxy{gb.EmptyFallback()}
|
||||
}
|
||||
|
||||
// only cache when proxies not empty
|
||||
|
||||
@@ -19,7 +19,9 @@ import (
|
||||
"golang.org/x/net/publicsuffix"
|
||||
)
|
||||
|
||||
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy
|
||||
type LoadBalanceOption struct {
|
||||
Strategy string `group:"strategy,omitempty"`
|
||||
}
|
||||
|
||||
type LoadBalance struct {
|
||||
*GroupBase
|
||||
@@ -29,14 +31,9 @@ type LoadBalance struct {
|
||||
expectedStatus string
|
||||
}
|
||||
|
||||
var errStrategy = errors.New("unsupported strategy")
|
||||
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy
|
||||
|
||||
func parseStrategy(config map[string]any) string {
|
||||
if strategy, ok := config["strategy"].(string); ok {
|
||||
return strategy
|
||||
}
|
||||
return "consistent-hashing"
|
||||
}
|
||||
var errStrategy = errors.New("unsupported strategy")
|
||||
|
||||
func getKey(metadata *C.Metadata) string {
|
||||
if metadata == nil {
|
||||
@@ -234,6 +231,7 @@ func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||
"expectedStatus": lb.expectedStatus,
|
||||
"hidden": lb.Hidden(),
|
||||
"icon": lb.Icon(),
|
||||
"emptyFallback": lb.EmptyFallback().Name(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -249,17 +247,17 @@ func (lb *LoadBalance) Now() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func NewLoadBalance(option *GroupCommonOption, providers []P.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
|
||||
func NewLoadBalance(option GroupCommonOption, loadBalanceOption LoadBalanceOption, emptyFallback C.Proxy, providers []P.ProxyProvider) (lb *LoadBalance, err error) {
|
||||
var strategyFn strategyFn
|
||||
switch strategy {
|
||||
case "consistent-hashing":
|
||||
switch loadBalanceOption.Strategy {
|
||||
case "", "consistent-hashing":
|
||||
strategyFn = strategyConsistentHashing(option.URL)
|
||||
case "round-robin":
|
||||
strategyFn = strategyRoundRobin(option.URL)
|
||||
case "sticky-sessions":
|
||||
strategyFn = strategyStickySessions(option.URL)
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
||||
return nil, fmt.Errorf("%w: %s", errStrategy, loadBalanceOption.Strategy)
|
||||
}
|
||||
return &LoadBalance{
|
||||
GroupBase: NewGroupBase(GroupBaseOption{
|
||||
@@ -272,6 +270,7 @@ func NewLoadBalance(option *GroupCommonOption, providers []P.ProxyProvider, stra
|
||||
ExcludeType: option.ExcludeType,
|
||||
TestTimeout: option.TestTimeout,
|
||||
MaxFailedTimes: option.MaxFailedTimes,
|
||||
EmptyFallback: emptyFallback,
|
||||
Providers: providers,
|
||||
}),
|
||||
strategyFn: strategyFn,
|
||||
|
||||
@@ -31,6 +31,7 @@ type GroupCommonOption struct {
|
||||
Interval int `group:"interval,omitempty"`
|
||||
TestTimeout int `group:"timeout,omitempty"`
|
||||
MaxFailedTimes int `group:"max-failed-times,omitempty"`
|
||||
EmptyFallback string `group:"empty-fallback,omitempty"`
|
||||
Lazy bool `group:"lazy,omitempty"`
|
||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||
Filter string `group:"filter,omitempty"`
|
||||
@@ -44,13 +45,13 @@ type GroupCommonOption struct {
|
||||
Icon string `group:"icon,omitempty"`
|
||||
}
|
||||
|
||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]P.ProxyProvider, AllProxies []string, AllProviders []string) (C.ProxyAdapter, error) {
|
||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]P.ProxyProvider, AllProxies []string, AllProviders []string) (ProxyGroup, error) {
|
||||
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
||||
|
||||
groupOption := &GroupCommonOption{
|
||||
groupOption := GroupCommonOption{
|
||||
Lazy: true,
|
||||
}
|
||||
if err := decoder.Decode(config, groupOption); err != nil {
|
||||
if err := decoder.Decode(config, &groupOption); err != nil {
|
||||
return nil, errFormat
|
||||
}
|
||||
|
||||
@@ -70,6 +71,17 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
||||
|
||||
groupName := groupOption.Name
|
||||
|
||||
if groupOption.EmptyFallback == "" {
|
||||
groupOption.EmptyFallback = "COMPATIBLE"
|
||||
}
|
||||
emptyFallback, ok := proxyMap[groupOption.EmptyFallback]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s: empty fallback proxy '%s' not found", groupName, groupOption.EmptyFallback)
|
||||
}
|
||||
if _, ok := emptyFallback.Adapter().(ProxyGroup); ok { // strictly forbidden to fill in a proxy group for empty-fallback
|
||||
return nil, fmt.Errorf("%s: empty fallback proxy '%s' not found", groupName, groupOption.EmptyFallback)
|
||||
}
|
||||
|
||||
providers := []P.ProxyProvider{}
|
||||
|
||||
if groupOption.IncludeAll {
|
||||
@@ -98,7 +110,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
||||
groupOption.Proxies = append(groupOption.Proxies, AllProxies...)
|
||||
}
|
||||
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||
groupOption.Proxies = []string{"COMPATIBLE"}
|
||||
groupOption.Proxies = []string{groupOption.EmptyFallback}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,25 +184,40 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
||||
providersMap[groupName] = pd
|
||||
}
|
||||
|
||||
var group C.ProxyAdapter
|
||||
switch groupOption.Type {
|
||||
case "url-test":
|
||||
opts := parseURLTestOption(config)
|
||||
group = NewURLTest(groupOption, providers, opts...)
|
||||
opt := URLTestOption{}
|
||||
err = decoder.Decode(config, &opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewURLTest(groupOption, opt, emptyFallback, providers)
|
||||
case "select":
|
||||
group = NewSelector(groupOption, providers)
|
||||
opt := SelectorOption{}
|
||||
err = decoder.Decode(config, &opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewSelector(groupOption, opt, emptyFallback, providers)
|
||||
case "fallback":
|
||||
group = NewFallback(groupOption, providers)
|
||||
opt := FallbackOption{}
|
||||
err = decoder.Decode(config, &opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewFallback(groupOption, opt, emptyFallback, providers)
|
||||
case "load-balance":
|
||||
strategy := parseStrategy(config)
|
||||
return NewLoadBalance(groupOption, providers, strategy)
|
||||
opt := LoadBalanceOption{}
|
||||
err = decoder.Decode(config, &opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewLoadBalance(groupOption, opt, emptyFallback, providers)
|
||||
case "relay":
|
||||
return nil, fmt.Errorf("%w: The group [%s] with relay type was removed, please using dialer-proxy instead", errType, groupName)
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: %s", errType, groupOption.Type)
|
||||
}
|
||||
|
||||
return group, nil
|
||||
}
|
||||
|
||||
func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
||||
|
||||
@@ -9,6 +9,10 @@ import (
|
||||
P "github.com/metacubex/mihomo/constant/provider"
|
||||
)
|
||||
|
||||
type SelectorOption struct {
|
||||
DefaultSelected string `group:"default-selected,omitempty"`
|
||||
}
|
||||
|
||||
type Selector struct {
|
||||
*GroupBase
|
||||
disableUDP bool
|
||||
@@ -62,12 +66,13 @@ func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||
}
|
||||
|
||||
return json.Marshal(map[string]any{
|
||||
"type": s.Type().String(),
|
||||
"now": s.Now(),
|
||||
"all": all,
|
||||
"testUrl": url,
|
||||
"hidden": s.Hidden(),
|
||||
"icon": s.Icon(),
|
||||
"type": s.Type().String(),
|
||||
"now": s.Now(),
|
||||
"all": all,
|
||||
"testUrl": url,
|
||||
"hidden": s.Hidden(),
|
||||
"icon": s.Icon(),
|
||||
"emptyFallback": s.EmptyFallback().Name(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -114,7 +119,7 @@ func (s *Selector) Proxies() []C.Proxy {
|
||||
return s.GetProxies(false)
|
||||
}
|
||||
|
||||
func NewSelector(option *GroupCommonOption, providers []P.ProxyProvider) *Selector {
|
||||
func NewSelector(option GroupCommonOption, selectorOption SelectorOption, emptyFallback C.Proxy, providers []P.ProxyProvider) (*Selector, error) {
|
||||
return &Selector{
|
||||
GroupBase: NewGroupBase(GroupBaseOption{
|
||||
Name: option.Name,
|
||||
@@ -126,10 +131,11 @@ func NewSelector(option *GroupCommonOption, providers []P.ProxyProvider) *Select
|
||||
ExcludeType: option.ExcludeType,
|
||||
TestTimeout: option.TestTimeout,
|
||||
MaxFailedTimes: option.MaxFailedTimes,
|
||||
EmptyFallback: emptyFallback,
|
||||
Providers: providers,
|
||||
}),
|
||||
selected: "COMPATIBLE",
|
||||
selected: selectorOption.DefaultSelected,
|
||||
disableUDP: option.DisableUDP,
|
||||
testUrl: option.URL,
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
@@ -14,12 +14,8 @@ import (
|
||||
P "github.com/metacubex/mihomo/constant/provider"
|
||||
)
|
||||
|
||||
type urlTestOption func(*URLTest)
|
||||
|
||||
func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
||||
return func(u *URLTest) {
|
||||
u.tolerance = tolerance
|
||||
}
|
||||
type URLTestOption struct {
|
||||
Tolerance uint16 `group:"tolerance,omitempty"`
|
||||
}
|
||||
|
||||
type URLTest struct {
|
||||
@@ -180,6 +176,7 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||
"fixed": u.selected,
|
||||
"hidden": u.Hidden(),
|
||||
"icon": u.Icon(),
|
||||
"emptyFallback": u.EmptyFallback().Name(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -195,20 +192,10 @@ func (u *URLTest) URLTest(ctx context.Context, url string, expectedStatus utils.
|
||||
return u.GroupBase.URLTest(ctx, u.testUrl, expectedStatus)
|
||||
}
|
||||
|
||||
func parseURLTestOption(config map[string]any) []urlTestOption {
|
||||
opts := []urlTestOption{}
|
||||
|
||||
// tolerance
|
||||
if elm, ok := config["tolerance"]; ok {
|
||||
if tolerance, ok := elm.(int); ok {
|
||||
opts = append(opts, urlTestWithTolerance(uint16(tolerance)))
|
||||
}
|
||||
func NewURLTest(option GroupCommonOption, urlTestOption URLTestOption, emptyFallback C.Proxy, providers []P.ProxyProvider) (*URLTest, error) {
|
||||
if emptyFallback == nil {
|
||||
return nil, errors.New("empty fallback proxy not exist")
|
||||
}
|
||||
|
||||
return opts
|
||||
}
|
||||
|
||||
func NewURLTest(option *GroupCommonOption, providers []P.ProxyProvider, options ...urlTestOption) *URLTest {
|
||||
urlTest := &URLTest{
|
||||
GroupBase: NewGroupBase(GroupBaseOption{
|
||||
Name: option.Name,
|
||||
@@ -220,17 +207,15 @@ func NewURLTest(option *GroupCommonOption, providers []P.ProxyProvider, options
|
||||
ExcludeType: option.ExcludeType,
|
||||
TestTimeout: option.TestTimeout,
|
||||
MaxFailedTimes: option.MaxFailedTimes,
|
||||
EmptyFallback: emptyFallback,
|
||||
Providers: providers,
|
||||
}),
|
||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||
disableUDP: option.DisableUDP,
|
||||
testUrl: option.URL,
|
||||
expectedStatus: option.ExpectedStatus,
|
||||
tolerance: urlTestOption.Tolerance,
|
||||
}
|
||||
|
||||
for _, option := range options {
|
||||
option(urlTest)
|
||||
}
|
||||
|
||||
return urlTest
|
||||
return urlTest, nil
|
||||
}
|
||||
@@ -139,6 +139,13 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error)
|
||||
break
|
||||
}
|
||||
proxy = outbound.NewRejectWithOption(*rejectOption)
|
||||
case "rematch":
|
||||
rematchOption := &outbound.RematchOption{BasicOption: basicOption}
|
||||
err = decoder.Decode(mapping, rematchOption)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
proxy, err = outbound.NewRematch(*rematchOption)
|
||||
case "ssh":
|
||||
sshOption := &outbound.SshOption{BasicOption: basicOption}
|
||||
err = decoder.Decode(mapping, sshOption)
|
||||
|
||||
@@ -37,6 +37,7 @@ type proxyProviderSchema struct {
|
||||
DialerProxy string `provider:"dialer-proxy,omitempty"`
|
||||
SizeLimit int64 `provider:"size-limit,omitempty"`
|
||||
Payload []map[string]any `provider:"payload,omitempty"`
|
||||
AgeSecretKey string `provider:"age-secret-key,omitempty"`
|
||||
|
||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||
Override overrideSchema `provider:"override,omitempty"`
|
||||
@@ -69,7 +70,7 @@ func ParseProxyProvider(name string, mapping map[string]any, tunnel C.Tunnel) (P
|
||||
}
|
||||
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, uint(schema.HealthCheck.TestTimeout), hcInterval, schema.HealthCheck.Lazy, expectedStatus)
|
||||
|
||||
parser, err := NewProxiesParser(name, tunnel, schema.Filter, schema.ExcludeFilter, schema.ExcludeType, schema.DialerProxy, schema.Override)
|
||||
parser, err := NewProxiesParser(name, tunnel, schema.Filter, schema.ExcludeFilter, schema.ExcludeType, schema.DialerProxy, schema.Override, schema.AgeSecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/metacubex/mihomo/common/convert"
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"github.com/metacubex/mihomo/common/yaml"
|
||||
"github.com/metacubex/mihomo/component/age"
|
||||
"github.com/metacubex/mihomo/component/profile/cachefile"
|
||||
"github.com/metacubex/mihomo/component/resource"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
@@ -204,7 +205,7 @@ func NewProxySetProvider(name string, interval time.Duration, payload []map[stri
|
||||
hc.setProxies(proxies)
|
||||
}
|
||||
|
||||
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, parser, pd.setProxies)
|
||||
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, nil, parser, pd.setProxies)
|
||||
pd.Fetcher = fetcher
|
||||
if httpVehicle, ok := vehicle.(*resource.HTTPVehicle); ok {
|
||||
httpVehicle.SetInRead(func(resp *http.Response) {
|
||||
@@ -339,7 +340,7 @@ func (cp *CompatibleProvider) Close() error {
|
||||
return cp.compatibleProvider.Close()
|
||||
}
|
||||
|
||||
func NewProxiesParser(pdName string, tunnel C.Tunnel, filter string, excludeFilter string, excludeType string, dialerProxy string, override overrideSchema) (resource.Parser[[]C.Proxy], error) {
|
||||
func NewProxiesParser(pdName string, tunnel C.Tunnel, filter string, excludeFilter string, excludeType string, dialerProxy string, override overrideSchema, ageSecretKey string) (resource.Parser[[]C.Proxy], error) {
|
||||
var excludeTypeArray []string
|
||||
if excludeType != "" {
|
||||
excludeTypeArray = strings.Split(excludeType, "|")
|
||||
@@ -365,9 +366,21 @@ func NewProxiesParser(pdName string, tunnel C.Tunnel, filter string, excludeFilt
|
||||
filterRegs = append(filterRegs, filterReg)
|
||||
}
|
||||
|
||||
if ageSecretKey != "" {
|
||||
if err := age.VeritySecretKeys(ageSecretKey); err != nil {
|
||||
return nil, fmt.Errorf("invalid age-secret-key: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return func(buf []byte) ([]C.Proxy, error) {
|
||||
schema := &ProxySchema{}
|
||||
|
||||
// decrypt config
|
||||
buf, err := age.DecryptBytes(buf, ageSecretKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt config error: %w", err)
|
||||
}
|
||||
|
||||
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||
proxies, err1 := convert.ConvertsV2Ray(buf)
|
||||
if err1 != nil {
|
||||
|
||||
@@ -69,8 +69,10 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||
|
||||
proxies = append(proxies, hysteria)
|
||||
|
||||
case "hysteria2", "hy2":
|
||||
urlHysteria2, err := url.Parse(line)
|
||||
case "hysteria2", "hy2", "hysteria2+realm", "hy2+realm":
|
||||
realmMode := strings.HasSuffix(scheme, "+realm")
|
||||
hopLine, ports := splitHysteria2Ports(line)
|
||||
urlHysteria2, err := url.Parse(hopLine)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
@@ -87,6 +89,9 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||
} else {
|
||||
hysteria2["port"] = "443"
|
||||
}
|
||||
if ports != "" {
|
||||
hysteria2["ports"] = ports
|
||||
}
|
||||
hysteria2["obfs"] = query.Get("obfs")
|
||||
hysteria2["obfs-password"] = query.Get("obfs-password")
|
||||
hysteria2["sni"] = query.Get("sni")
|
||||
@@ -94,12 +99,19 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||
if alpn := query.Get("alpn"); alpn != "" {
|
||||
hysteria2["alpn"] = strings.Split(alpn, ",")
|
||||
}
|
||||
if auth := urlHysteria2.User.String(); auth != "" {
|
||||
hysteria2["password"] = auth
|
||||
}
|
||||
hysteria2["fingerprint"] = query.Get("pinSHA256")
|
||||
hysteria2["down"] = query.Get("down")
|
||||
hysteria2["up"] = query.Get("up")
|
||||
if realmMode {
|
||||
token, _ := url.PathUnescape(urlHysteria2.User.String())
|
||||
realmID, _ := url.PathUnescape(strings.TrimPrefix(urlHysteria2.EscapedPath(), "/"))
|
||||
hysteria2["realm-opts"] = buildRealmOpts("https://"+urlHysteria2.Host, token, realmID, query["stun"])
|
||||
if auth := query.Get("auth"); auth != "" {
|
||||
hysteria2["password"] = auth
|
||||
}
|
||||
} else if auth := urlHysteria2.User.String(); auth != "" {
|
||||
hysteria2["password"] = auth
|
||||
}
|
||||
|
||||
proxies = append(proxies, hysteria2)
|
||||
|
||||
|
||||
@@ -40,6 +40,37 @@ func TestConvertsV2Ray_normal(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestConvertsV2Ray_hysteria2PortHopping(t *testing.T) {
|
||||
uri := "hysteria2://letmein@example.com:443,5000-6000/?sni=example.com#hop"
|
||||
proxies, err := ConvertsV2Ray([]byte(uri))
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, "example.com", proxies[0]["server"])
|
||||
assert.Equal(t, "443", proxies[0]["port"])
|
||||
assert.Equal(t, "443,5000-6000", proxies[0]["ports"])
|
||||
|
||||
_, err = adapter.ParseProxy(proxies[0])
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestConvertsV2Ray_hysteria2RealmScheme(t *testing.T) {
|
||||
uri := "hysteria2+realm://tok3n@rendezvous.example.com:8443/rid42?auth=letmein&stun=stun1:3478&stun=stun2:3478&sni=example.com#realm"
|
||||
proxies, err := ConvertsV2Ray([]byte(uri))
|
||||
assert.Nil(t, err)
|
||||
p := proxies[0]
|
||||
assert.Equal(t, "hysteria2", p["type"])
|
||||
assert.Equal(t, "letmein", p["password"])
|
||||
assert.Equal(t, map[string]any{
|
||||
"enable": true,
|
||||
"server-url": "https://rendezvous.example.com:8443",
|
||||
"token": "tok3n",
|
||||
"realm-id": "rid42",
|
||||
"stun-servers": []string{"stun1:3478", "stun2:3478"},
|
||||
}, p["realm-opts"])
|
||||
|
||||
_, err = adapter.ParseProxy(p)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestConvertsV2RayMieru(t *testing.T) {
|
||||
mierusTest := "mierus://user:pass@1.2.3.4?handshake-mode=HANDSHAKE_NO_WAIT&mtu=1400&multiplexing=MULTIPLEXING_HIGH&port=6666&port=9998-9999&port=6489&port=4896&profile=default&protocol=TCP&protocol=TCP&protocol=UDP&protocol=UDP&traffic-pattern=CCoQARoECAEQCiIYCAMQASoIMDAwMTAyMDMqCDA0MDUwNjA3"
|
||||
|
||||
|
||||
+65
-2
@@ -222,12 +222,26 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
|
||||
opts["uplink-http-method"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["sessionPlacement"].(string); ok && v != "" {
|
||||
if v, ok := extra["sessionIDPlacement"].(string); ok && v != "" {
|
||||
opts["session-placement"] = v
|
||||
} else if v, ok := extra["sessionPlacement"].(string); ok && v != "" {
|
||||
opts["session-placement"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["sessionKey"].(string); ok && v != "" {
|
||||
if v, ok := extra["sessionIDKey"].(string); ok && v != "" {
|
||||
opts["session-key"] = v
|
||||
} else if v, ok := extra["sessionKey"].(string); ok && v != "" {
|
||||
opts["session-key"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["sessionIDTable"].(string); ok && v != "" {
|
||||
opts["session-table"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["sessionIDLength"].(string); ok && v != "" {
|
||||
opts["session-length"] = v
|
||||
} else if v, ok := extra["sessionIDLength"].(float64); ok {
|
||||
opts["session-length"] = strconv.FormatInt(int64(v), 10)
|
||||
}
|
||||
|
||||
if v, ok := extra["seqPlacement"].(string); ok && v != "" {
|
||||
@@ -349,3 +363,52 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func buildRealmOpts(serverURL, token, realmID string, stunServers []string) map[string]any {
|
||||
opts := map[string]any{"enable": true, "server-url": serverURL}
|
||||
if token != "" {
|
||||
opts["token"] = token
|
||||
}
|
||||
if realmID != "" {
|
||||
opts["realm-id"] = realmID
|
||||
}
|
||||
if len(stunServers) > 0 {
|
||||
opts["stun-servers"] = stunServers
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
func splitHysteria2Ports(line string) (string, string) {
|
||||
i := strings.Index(line, "://")
|
||||
if i < 0 {
|
||||
return line, ""
|
||||
}
|
||||
head, rest := line[:i+3], line[i+3:]
|
||||
auth, tail := rest, ""
|
||||
if j := strings.IndexAny(rest, "/?#"); j >= 0 {
|
||||
auth, tail = rest[:j], rest[j:]
|
||||
}
|
||||
userinfo := ""
|
||||
if at := strings.LastIndex(auth, "@"); at >= 0 {
|
||||
userinfo, auth = auth[:at+1], auth[at+1:]
|
||||
}
|
||||
if strings.Contains(auth, "]") {
|
||||
return line, ""
|
||||
}
|
||||
colon := strings.LastIndex(auth, ":")
|
||||
if colon < 0 {
|
||||
return line, ""
|
||||
}
|
||||
host, ports := auth[:colon], auth[colon+1:]
|
||||
if !strings.ContainsAny(ports, ",-") {
|
||||
return line, ""
|
||||
}
|
||||
first := ports
|
||||
if k := strings.IndexAny(ports, ",-"); k >= 0 {
|
||||
first = ports[:k]
|
||||
}
|
||||
if first == "" {
|
||||
return line, ""
|
||||
}
|
||||
return head + userinfo + host + ":" + first + tail, ports
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// Copyright 2025 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package maphash
|
||||
|
||||
// A Hasher defines the interface between a hash-based container and its elements.
|
||||
// It provides a hash function and an equivalence relation over values
|
||||
// of type T, enabling those values to be inserted in hash tables
|
||||
// and similar data structures.
|
||||
//
|
||||
// Of course, comparable types can already be used as keys of Go's
|
||||
// built-in map type, but a Hasher enables non-comparable types to be
|
||||
// used as keys of a suitable hash table too.
|
||||
// Hashers may be useful even for comparable types, to define an
|
||||
// equivalence relation that differs from the usual one (==), such as a
|
||||
// field-based comparison for a pointer-to-struct type, or a
|
||||
// case-insensitive comparison for strings, as in this example:
|
||||
//
|
||||
// // CaseInsensitive is a Hasher[string] whose
|
||||
// // equivalence relation ignores letter case.
|
||||
// type CaseInsensitive struct{}
|
||||
//
|
||||
// func (CaseInsensitive) Hash(h *Hash, s string) {
|
||||
// h.WriteString(strings.ToLower(s))
|
||||
// }
|
||||
//
|
||||
// func (CaseInsensitive) Equal(x, y string) bool {
|
||||
// // (We avoid strings.EqualFold as it is not
|
||||
// // consistent with ToLower for all values.)
|
||||
// return strings.ToLower(x) == strings.ToLower(y)
|
||||
// }
|
||||
//
|
||||
// A Hasher also permits values to be used with other hash-based data
|
||||
// structures such as a Bloom filter.
|
||||
// The [ComparableHasher] type makes it convenient to enable comparable
|
||||
// types to be used in such data structures under their usual (==)
|
||||
// equivalence relation.
|
||||
//
|
||||
// # Hash invariants
|
||||
//
|
||||
// If two values are equal as defined by Equal(x, y), then they must
|
||||
// have the same hash as defined by the effects of Hash(h, x) on h.
|
||||
//
|
||||
// Hashers must be logically stateless: the behavior of the Hash and
|
||||
// Equal methods depends only on the arguments.
|
||||
//
|
||||
// # Writing a good function
|
||||
//
|
||||
// When defining a hash function and equivalence relation for a data
|
||||
// type, it may help to first define a canonical encoding for values
|
||||
// of that type as a sequence of elements, each being a number,
|
||||
// string, boolean, or pointer.
|
||||
// An encoding is canonical if two values that are logically equal
|
||||
// have the same encoding, even if they are represented differently.
|
||||
// For example, a canonical case-insensitive encoding of a string is
|
||||
// [strings.ToLower].
|
||||
//
|
||||
// Once you have defined the encoding, the Hasher's Hash method should
|
||||
// encode a value into the [Hash] using a sequence of calls to
|
||||
// [Hash.Write] for byte slices, [Hash.WriteString] for strings,
|
||||
// [Hash.WriteByte] for bytes, and [WriteComparable] for elements of
|
||||
// other types. The Hasher's Equal method should compute the
|
||||
// encodings of two values, then compare their corresponding
|
||||
// elements, returning false at the first mismatch.
|
||||
//
|
||||
// A Hash method may discard information so long as it remains
|
||||
// consistent with the Equal method as defined above.
|
||||
// For example, valid implementations of CaseInsensitive.Hash might inspect
|
||||
// only the first letter of the string, or even use a constant value.
|
||||
// However, the lossier the hash function, the more frequent
|
||||
// the hash collisions and the slower the hash table.
|
||||
//
|
||||
// Some data types, such as sets, are inherently unordered: the set
|
||||
// {a, b, c} is equal to the set {c, b, a}.
|
||||
// In some cases it is possible to define a canonical encoding for a
|
||||
// set by sorting the elements into some order.
|
||||
// In other cases this may inefficient, since it may require allocating
|
||||
// memory, or infeasible, as when there is no convenient order.
|
||||
// Another way to hash an unordered set is to compute the hash
|
||||
// for each element separately, then combine all the element hashes
|
||||
// using a commutative (order-independent) operator such as + or ^.
|
||||
//
|
||||
// The Hash method below, for a hypothetical Set type, illustrates
|
||||
// this approach:
|
||||
//
|
||||
// type Set[T comparable] struct{ ... }
|
||||
//
|
||||
// type setHasher[T comparable] struct{}
|
||||
//
|
||||
// func (setHasher[T]) Hash(hash *maphash.Hash, set *Set[T]) {
|
||||
// var accum uint64
|
||||
// for elem := range set.Elements() {
|
||||
// // Initialize a hasher for the element,
|
||||
// // using same seed as the outer hash.
|
||||
// var sub maphash.Hash
|
||||
// sub.SetSeed(hash.Seed())
|
||||
//
|
||||
// // Hash the element.
|
||||
// maphash.WriteComparable(&sub, elem)
|
||||
//
|
||||
// // Mix the element's hash into the set's hash.
|
||||
// accum ^= sub.Sum64()
|
||||
// }
|
||||
// maphash.WriteComparable(hash, accum)
|
||||
// }
|
||||
//
|
||||
// In many languages, a data type's hash operation simply returns an
|
||||
// integer value.
|
||||
// However, that makes it possible for an adversary to systematically
|
||||
// construct a large number of values that all have the same hash,
|
||||
// degrading the asymptotic performance of hash tables in a
|
||||
// denial-of-service attack known as "hash flooding".
|
||||
// By contrast, computing hashes as a sequence of values emitted into
|
||||
// a [Hash] with an unpredictable [Seed] that varies from one hash
|
||||
// table to another mitigates this attack.
|
||||
//
|
||||
// In effect, the Seed chooses one of 2⁶⁴ different hash functions.
|
||||
// The code example above calls SetSeed on the element's sub-Hasher
|
||||
// so that it uses the same hash function as for the Set itself, and
|
||||
// not a random one.
|
||||
type Hasher[T any] interface {
|
||||
Hash(*Hash, T)
|
||||
Equal(x, y T) bool
|
||||
}
|
||||
|
||||
// ComparableHasher is an implementation of [Hasher] whose
|
||||
// Equal(x, y) method is consistent with x == y.
|
||||
//
|
||||
// ComparableHasher is defined only for comparable types.
|
||||
// The type system will not prevent you from instantiating a type
|
||||
// such as ComparableHasher[any]; nonetheless you must not pass
|
||||
// non-comparable argument values to its Hash or Equal methods.
|
||||
type ComparableHasher[T comparable] struct {
|
||||
_ [0]func(T) // disallow comparison, and conversion between ComparableHasher[X] and ComparableHasher[Y]
|
||||
}
|
||||
|
||||
func (ComparableHasher[T]) Hash(h *Hash, v T) { WriteComparable(h, v) }
|
||||
func (ComparableHasher[T]) Equal(x, y T) bool { return x == y }
|
||||
@@ -0,0 +1,15 @@
|
||||
package sockopt
|
||||
|
||||
import "syscall"
|
||||
|
||||
func RawConnMark(rc syscall.RawConn, mark int) (err error) {
|
||||
var innerErr error
|
||||
err = rc.Control(func(fd uintptr) {
|
||||
innerErr = markControl(fd, mark)
|
||||
})
|
||||
|
||||
if innerErr != nil {
|
||||
err = innerErr
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package sockopt
|
||||
|
||||
import "syscall"
|
||||
|
||||
func markControl(fd uintptr, mark int) error {
|
||||
return syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build !linux
|
||||
|
||||
package sockopt
|
||||
|
||||
func markControl(fd uintptr, mark int) error { return nil }
|
||||
@@ -0,0 +1,46 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
||||
|
||||
func StringToBps(s string) uint64 {
|
||||
if s == "" {
|
||||
return 0
|
||||
}
|
||||
|
||||
// when have not unit, use Mbps
|
||||
if v, err := strconv.Atoi(s); err == nil {
|
||||
return StringToBps(fmt.Sprintf("%d Mbps", v))
|
||||
}
|
||||
|
||||
m := rateStringRegexp.FindStringSubmatch(s)
|
||||
if m == nil {
|
||||
return 0
|
||||
}
|
||||
var n uint64 = 1
|
||||
switch m[2] {
|
||||
case "T":
|
||||
n *= 1000
|
||||
fallthrough
|
||||
case "G":
|
||||
n *= 1000
|
||||
fallthrough
|
||||
case "M":
|
||||
n *= 1000
|
||||
fallthrough
|
||||
case "K":
|
||||
n *= 1000
|
||||
}
|
||||
v, _ := strconv.ParseUint(m[1], 10, 64)
|
||||
n *= v
|
||||
if m[3] == "b" {
|
||||
// Bits, need to convert to bytes
|
||||
n /= 8
|
||||
}
|
||||
return n
|
||||
}
|
||||
+380
-88
@@ -1,11 +1,12 @@
|
||||
package xsync
|
||||
|
||||
// copy and modified from https://github.com/puzpuzpuz/xsync/blob/v4.2.0/map.go
|
||||
// copy and modified from https://github.com/puzpuzpuz/xsync/blob/v4.5.0/map.go
|
||||
// which is licensed under Apache v2.
|
||||
//
|
||||
// mihomo modified:
|
||||
// 1. restore xsync/v3's LoadOrCompute api and rename to LoadOrStoreFn.
|
||||
// 2. the zero Map is ready for use.
|
||||
// 3. remove unnecessary member variables added by xsync/v3's "optimize Map for integer keys"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -37,11 +38,10 @@ const (
|
||||
// minimum counter stripes to use
|
||||
minMapCounterLen = 8
|
||||
// maximum counter stripes to use; stands for around 4KB of memory
|
||||
maxMapCounterLen = 32
|
||||
defaultMeta uint64 = 0x8080808080808080
|
||||
metaMask uint64 = 0xffffffffff
|
||||
defaultMetaMasked uint64 = defaultMeta & metaMask
|
||||
emptyMetaSlot uint8 = 0x80
|
||||
maxMapCounterLen = 32
|
||||
metaMask = 0xffffffffff
|
||||
occupiedMeta = 0x8080808080808080
|
||||
occupiedMetaMasked = occupiedMeta & metaMask
|
||||
// minimal number of buckets to transfer when participating in cooperative
|
||||
// resize; should be at least defaultMinMapTableLen
|
||||
minResizeTransferStride = 64
|
||||
@@ -212,7 +212,7 @@ func NewMap[K comparable, V any](options ...func(*MapConfig)) *Map[K, V] {
|
||||
|
||||
m := &Map[K, V]{}
|
||||
if c.sizeHint > defaultMinMapTableLen*entriesPerMapBucket {
|
||||
tableLen := nextPowOf2(uint32((float64(c.sizeHint) / entriesPerMapBucket) / mapLoadFactor))
|
||||
tableLen := nextPowOf2(uint64((float64(c.sizeHint) / entriesPerMapBucket) / mapLoadFactor))
|
||||
m.minTableLen = int(tableLen)
|
||||
}
|
||||
m.growOnly = c.growOnly
|
||||
@@ -229,11 +229,46 @@ func (m *Map[K, V]) init() {
|
||||
m.table.Store(table)
|
||||
}
|
||||
|
||||
// detectIntKey returns true if the key type is an integer type.
|
||||
func detectIntKey[K comparable]() bool {
|
||||
var zero K
|
||||
switch any(zero).(type) {
|
||||
case int, uint, uintptr, int64, uint64, int32, uint32, int16, uint16, int8, uint8:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// hashUint64 computes a hash for integer keys using two rounds of
|
||||
// multiply-xorshift mixing (wyhash-style).
|
||||
// This is significantly faster than maphash.Comparable for integer types.
|
||||
func hashUint64(seed maphash.Seed, v uint64) uint64 {
|
||||
// maphash.Seed is just a uint64, so we can convert it directly
|
||||
hi, lo := bits.Mul64(v^(*(*uint64)(unsafe.Pointer(&seed))), 0x2d358dccaa6c78a5)
|
||||
hi2, lo2 := bits.Mul64(hi^lo, 0x8bb84b93962eacc9)
|
||||
return hi2 ^ lo2
|
||||
}
|
||||
|
||||
// toUint64 reinterprets integer-like keys as uint64 for hashUint64.
|
||||
// The size switch is folded per instantiated K by the compiler.
|
||||
func toUint64[K any](k K) uint64 {
|
||||
switch unsafe.Sizeof(k) {
|
||||
case 8:
|
||||
return *(*uint64)(unsafe.Pointer(&k))
|
||||
case 4:
|
||||
return uint64(*(*uint32)(unsafe.Pointer(&k)))
|
||||
case 2:
|
||||
return uint64(*(*uint16)(unsafe.Pointer(&k)))
|
||||
case 1:
|
||||
return uint64(*(*uint8)(unsafe.Pointer(&k)))
|
||||
default:
|
||||
panic("unreachable")
|
||||
}
|
||||
}
|
||||
|
||||
func newMapTable[K comparable, V any](minTableLen int, seed maphash.Seed) *mapTable[K, V] {
|
||||
buckets := make([]bucketPadded, minTableLen)
|
||||
for i := range buckets {
|
||||
buckets[i].meta = defaultMeta
|
||||
}
|
||||
counterLen := minTableLen >> 10
|
||||
if counterLen < minMapCounterLen {
|
||||
counterLen = minMapCounterLen
|
||||
@@ -270,17 +305,33 @@ func ToPlainMap[K comparable, V any](m *Map[K, V]) map[K]V {
|
||||
func (m *Map[K, V]) Load(key K) (value V, ok bool) {
|
||||
m.initOnce.Do(m.init)
|
||||
table := m.table.Load()
|
||||
hash := maphash.Comparable(table.seed, key)
|
||||
var hash uint64
|
||||
if detectIntKey[K]() {
|
||||
hash = hashUint64(table.seed, toUint64(key))
|
||||
} else {
|
||||
hash = maphash.Comparable(table.seed, key)
|
||||
}
|
||||
h1 := h1(hash)
|
||||
h2w := broadcast(h2(hash))
|
||||
bidx := uint64(len(table.buckets)-1) & h1
|
||||
b := &table.buckets[bidx]
|
||||
// Same as: b := &table.buckets[bidx]
|
||||
// Inline bounds check elimination via unsafe pointer arithmetic.
|
||||
// Safety: bidx is always < len(table.buckets) since it's masked with (len-1).
|
||||
b := (*bucketPadded)(unsafe.Add(unsafe.Pointer(&table.buckets[0]),
|
||||
uintptr(bidx)*unsafe.Sizeof(bucketPadded{})))
|
||||
for {
|
||||
metaw := atomic.LoadUint64(&b.meta)
|
||||
markedw := markZeroBytes(metaw^h2w) & metaMask
|
||||
for markedw != 0 {
|
||||
idx := firstMarkedByteIndex(markedw)
|
||||
eptr := atomic.LoadPointer(&b.entries[idx])
|
||||
// Same as: eptr := atomic.LoadPointer(&b.entries[idx])
|
||||
// Inline bounds check elimination via unsafe pointer arithmetic.
|
||||
// Safety: idx is always < entriesPerMapBucket (5) since it comes from
|
||||
// firstMarkedByteIndex which returns index of a marked byte in the
|
||||
// 5-byte metadata mask (metaMask).
|
||||
eptr := atomic.LoadPointer((*unsafe.Pointer)(unsafe.Add(
|
||||
unsafe.Pointer(&b.entries[0]),
|
||||
uintptr(idx)*unsafe.Sizeof(b.entries[0]))))
|
||||
if eptr != nil {
|
||||
e := (*entry[K, V])(eptr)
|
||||
if e.key == key {
|
||||
@@ -299,14 +350,109 @@ func (m *Map[K, V]) Load(key K) (value V, ok bool) {
|
||||
|
||||
// Store sets the value for a key.
|
||||
func (m *Map[K, V]) Store(key K, value V) {
|
||||
m.doCompute(
|
||||
key,
|
||||
func(V, bool) (V, ComputeOp) {
|
||||
return value, UpdateOp
|
||||
},
|
||||
noLoadOp,
|
||||
false,
|
||||
)
|
||||
m.initOnce.Do(m.init)
|
||||
// Store is a popular operation, hence instead of using doCompute,
|
||||
// it uses a simplified and slightly faster version of it.
|
||||
for {
|
||||
store_attempt:
|
||||
var (
|
||||
emptyb *bucketPadded
|
||||
emptyidx int
|
||||
)
|
||||
table := m.table.Load()
|
||||
tableLen := len(table.buckets)
|
||||
var hash uint64
|
||||
if detectIntKey[K]() {
|
||||
hash = hashUint64(table.seed, toUint64(key))
|
||||
} else {
|
||||
hash = maphash.Comparable(table.seed, key)
|
||||
}
|
||||
h1 := h1(hash)
|
||||
h2 := h2(hash)
|
||||
h2w := broadcast(h2)
|
||||
bidx := uint64(len(table.buckets)-1) & h1
|
||||
rootb := &table.buckets[bidx]
|
||||
|
||||
rootb.mu.Lock()
|
||||
// The following two checks must go in reverse to what's
|
||||
// in the resize method.
|
||||
if seq := resizeSeq(m.resizeCtl.Load()); seq&1 == 1 {
|
||||
// Resize is in progress. Help with the transfer, then go for another attempt.
|
||||
rootb.mu.Unlock()
|
||||
m.helpResize(seq)
|
||||
goto store_attempt
|
||||
}
|
||||
if m.newerTableExists(table) {
|
||||
// Someone resized the table. Go for another attempt.
|
||||
rootb.mu.Unlock()
|
||||
goto store_attempt
|
||||
}
|
||||
b := rootb
|
||||
for {
|
||||
metaw := b.meta
|
||||
markedw := markZeroBytes(metaw^h2w) & metaMask
|
||||
for markedw != 0 {
|
||||
idx := firstMarkedByteIndex(markedw)
|
||||
eptr := b.entries[idx]
|
||||
if eptr != nil {
|
||||
e := (*entry[K, V])(eptr)
|
||||
if e.key == key {
|
||||
// In-place update.
|
||||
newe := new(entry[K, V])
|
||||
newe.key = key
|
||||
newe.value = value
|
||||
atomic.StorePointer(&b.entries[idx], unsafe.Pointer(newe))
|
||||
rootb.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
markedw &= markedw - 1
|
||||
}
|
||||
if emptyb == nil {
|
||||
// Search for empty entries (up to 5 per bucket).
|
||||
emptyw := ^metaw & occupiedMetaMasked
|
||||
if emptyw != 0 {
|
||||
idx := firstMarkedByteIndex(emptyw)
|
||||
emptyb = b
|
||||
emptyidx = idx
|
||||
}
|
||||
}
|
||||
if b.next == nil {
|
||||
if emptyb != nil {
|
||||
// Insertion into an existing bucket.
|
||||
newe := new(entry[K, V])
|
||||
newe.key = key
|
||||
newe.value = value
|
||||
// First we update meta, then the entry.
|
||||
atomic.StoreUint64(&emptyb.meta, setByte(emptyb.meta, h2, emptyidx))
|
||||
atomic.StorePointer(&emptyb.entries[emptyidx], unsafe.Pointer(newe))
|
||||
rootb.mu.Unlock()
|
||||
table.addSize(bidx, 1)
|
||||
return
|
||||
}
|
||||
growThreshold := float64(tableLen) * entriesPerMapBucket * mapLoadFactor
|
||||
if table.sumSize() > int64(growThreshold) {
|
||||
// Need to grow the table. Then go for another attempt.
|
||||
rootb.mu.Unlock()
|
||||
m.resize(table, mapGrowHint)
|
||||
goto store_attempt
|
||||
}
|
||||
// Insertion into a new bucket.
|
||||
// Create and append a bucket.
|
||||
newb := new(bucketPadded)
|
||||
newb.meta = setByte(0, h2, 0)
|
||||
newe := new(entry[K, V])
|
||||
newe.key = key
|
||||
newe.value = value
|
||||
newb.entries[0] = unsafe.Pointer(newe)
|
||||
atomic.StorePointer(&b.next, unsafe.Pointer(newb))
|
||||
rootb.mu.Unlock()
|
||||
table.addSize(bidx, 1)
|
||||
return
|
||||
}
|
||||
b = (*bucketPadded)(b.next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LoadOrStore returns the existing value for the key if present.
|
||||
@@ -436,7 +582,12 @@ func (m *Map[K, V]) doCompute(
|
||||
)
|
||||
table := m.table.Load()
|
||||
tableLen := len(table.buckets)
|
||||
hash := maphash.Comparable(table.seed, key)
|
||||
var hash uint64
|
||||
if detectIntKey[K]() {
|
||||
hash = hashUint64(table.seed, toUint64(key))
|
||||
} else {
|
||||
hash = maphash.Comparable(table.seed, key)
|
||||
}
|
||||
h1 := h1(hash)
|
||||
h2 := h2(hash)
|
||||
h2w := broadcast(h2)
|
||||
@@ -509,13 +660,13 @@ func (m *Map[K, V]) doCompute(
|
||||
case DeleteOp:
|
||||
// Deletion.
|
||||
// First we update the hash, then the entry.
|
||||
newmetaw := setByte(metaw, emptyMetaSlot, idx)
|
||||
newmetaw := setByte(metaw, 0, idx)
|
||||
atomic.StoreUint64(&b.meta, newmetaw)
|
||||
atomic.StorePointer(&b.entries[idx], nil)
|
||||
rootb.mu.Unlock()
|
||||
table.addSize(bidx, -1)
|
||||
// Might need to shrink the table if we left bucket empty.
|
||||
if newmetaw == defaultMeta {
|
||||
if newmetaw == 0 {
|
||||
m.resize(table, mapShrinkHint)
|
||||
}
|
||||
return oldv, !computeOnly
|
||||
@@ -540,7 +691,7 @@ func (m *Map[K, V]) doCompute(
|
||||
}
|
||||
if emptyb == nil {
|
||||
// Search for empty entries (up to 5 per bucket).
|
||||
emptyw := metaw & defaultMetaMasked
|
||||
emptyw := ^metaw & occupiedMetaMasked
|
||||
if emptyw != 0 {
|
||||
idx := firstMarkedByteIndex(emptyw)
|
||||
emptyb = b
|
||||
@@ -581,11 +732,11 @@ func (m *Map[K, V]) doCompute(
|
||||
switch op {
|
||||
case DeleteOp, CancelOp:
|
||||
rootb.mu.Unlock()
|
||||
return newValue, false
|
||||
return zeroV, false
|
||||
default:
|
||||
// Create and append a bucket.
|
||||
newb := new(bucketPadded)
|
||||
newb.meta = setByte(defaultMeta, h2, 0)
|
||||
newb.meta = setByte(0, h2, 0)
|
||||
newe := new(entry[K, V])
|
||||
newe.key = key
|
||||
newe.value = newValue
|
||||
@@ -655,10 +806,10 @@ func (m *Map[K, V]) resize(knownTable *mapTable[K, V], hint mapResizeHint) {
|
||||
shrinkThreshold := int64((tableLen * entriesPerMapBucket) / mapShrinkFraction)
|
||||
if tableLen > m.minTableLen && table.sumSize() <= shrinkThreshold {
|
||||
// Shrink the table with factor of 2.
|
||||
// It's fine to generate a new seed since full locking
|
||||
// is required anyway.
|
||||
// Analogous to growth, we must preserve the seed to ensure stable
|
||||
// hash mapping, enabling lock-free writes to destination buckets.
|
||||
m.totalShrinks.Add(1)
|
||||
newTable = newMapTable[K, V](tableLen>>1, maphash.MakeSeed())
|
||||
newTable = newMapTable[K, V](tableLen>>1, table.seed)
|
||||
} else {
|
||||
// No need to shrink. Wake up all waiters and give up.
|
||||
m.resizeMu.Lock()
|
||||
@@ -740,6 +891,20 @@ func (m *Map[K, V]) helpResize(seq uint64) {
|
||||
func (m *Map[K, V]) transfer(table, newTable *mapTable[K, V]) {
|
||||
tableLen := len(table.buckets)
|
||||
newTableLen := len(newTable.buckets)
|
||||
// Determines the concurrent task range for destination buckets.
|
||||
// We iterate based on these properties to avoid locking destination
|
||||
// buckets:
|
||||
// - Grow (Pow2): baseLen == tableLen
|
||||
// Entries from source bucket i move to dest buckets i and i+baseLen
|
||||
// - Shrink (Pow2): baseLen == newTableLen
|
||||
// Entries from source buckets i and i+baseLen move to dest bucket i
|
||||
// By iterating 0..baseLen and processing all possible source buckets
|
||||
// (srcIdx += baseLen) in the inner loop, a single goroutine exclusively
|
||||
// owns the write operations for its assigned destination buckets.
|
||||
baseLen := tableLen
|
||||
if baseLen > newTableLen {
|
||||
baseLen = newTableLen
|
||||
}
|
||||
stride := (tableLen >> 3) / int(maxResizeHelpers)
|
||||
if stride < minResizeTransferStride {
|
||||
stride = minResizeTransferStride
|
||||
@@ -751,27 +916,20 @@ func (m *Map[K, V]) transfer(table, newTable *mapTable[K, V]) {
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
if start > tableLen {
|
||||
if start >= baseLen {
|
||||
break
|
||||
}
|
||||
end := int(nextIdx)
|
||||
if end > tableLen {
|
||||
end = tableLen
|
||||
if end > baseLen {
|
||||
end = baseLen
|
||||
}
|
||||
// Transfer buckets in this range.
|
||||
total := 0
|
||||
if newTableLen > tableLen {
|
||||
// We're growing the table with 2x multiplier, so entries from a N bucket can
|
||||
// only be transferred to N and 2*N buckets in the new table. Thus, destination
|
||||
// buckets written by the resize helpers don't intersect, so we don't need to
|
||||
// acquire locks in the destination buckets.
|
||||
for i := start; i < end; i++ {
|
||||
total += transferBucketUnsafe(&table.buckets[i], newTable)
|
||||
}
|
||||
} else {
|
||||
// We're shrinking the table, so all locks must be acquired.
|
||||
for i := start; i < end; i++ {
|
||||
total += transferBucket(&table.buckets[i], newTable)
|
||||
for i := start; i < end; i++ {
|
||||
// Visit all source buckets that map to this destination bucket.
|
||||
// When growing, runs once. When shrinking, runs twice.
|
||||
for srcIdx := i; srcIdx < tableLen; srcIdx += baseLen {
|
||||
total += transferBucketUnsafe(&table.buckets[srcIdx], newTable)
|
||||
}
|
||||
}
|
||||
// The exact counter stripe doesn't matter here, so pick up the one
|
||||
@@ -791,7 +949,12 @@ func transferBucketUnsafe[K comparable, V any](
|
||||
for i := 0; i < entriesPerMapBucket; i++ {
|
||||
if eptr := b.entries[i]; eptr != nil {
|
||||
e := (*entry[K, V])(eptr)
|
||||
hash := maphash.Comparable(destTable.seed, e.key)
|
||||
var hash uint64
|
||||
if detectIntKey[K]() {
|
||||
hash = hashUint64(destTable.seed, toUint64(e.key))
|
||||
} else {
|
||||
hash = maphash.Comparable(destTable.seed, e.key)
|
||||
}
|
||||
bidx := uint64(len(destTable.buckets)-1) & h1(hash)
|
||||
destb := &destTable.buckets[bidx]
|
||||
appendToBucket(h2(hash), e, destb)
|
||||
@@ -806,33 +969,6 @@ func transferBucketUnsafe[K comparable, V any](
|
||||
}
|
||||
}
|
||||
|
||||
func transferBucket[K comparable, V any](
|
||||
b *bucketPadded,
|
||||
destTable *mapTable[K, V],
|
||||
) (copied int) {
|
||||
rootb := b
|
||||
rootb.mu.Lock()
|
||||
for {
|
||||
for i := 0; i < entriesPerMapBucket; i++ {
|
||||
if eptr := b.entries[i]; eptr != nil {
|
||||
e := (*entry[K, V])(eptr)
|
||||
hash := maphash.Comparable(destTable.seed, e.key)
|
||||
bidx := uint64(len(destTable.buckets)-1) & h1(hash)
|
||||
destb := &destTable.buckets[bidx]
|
||||
destb.mu.Lock()
|
||||
appendToBucket(h2(hash), e, destb)
|
||||
destb.mu.Unlock()
|
||||
copied++
|
||||
}
|
||||
}
|
||||
if b.next == nil {
|
||||
rootb.mu.Unlock()
|
||||
return
|
||||
}
|
||||
b = (*bucketPadded)(b.next)
|
||||
}
|
||||
}
|
||||
|
||||
// Range calls f sequentially for each key and value present in the
|
||||
// map. If f returns false, range stops the iteration.
|
||||
//
|
||||
@@ -846,6 +982,9 @@ func transferBucket[K comparable, V any](
|
||||
// creation, modification and deletion. However, the concurrent
|
||||
// modification rule apply, i.e. the changes may be not reflected
|
||||
// in the subsequently iterated entries.
|
||||
//
|
||||
// For a faster, lock-free alternative with relaxed consistency
|
||||
// guarantees, see [RangeRelaxed].
|
||||
func (m *Map[K, V]) Range(f func(key K, value V) bool) {
|
||||
m.initOnce.Do(m.init)
|
||||
// Pre-allocate array big enough to fit entries for most hash tables.
|
||||
@@ -882,6 +1021,167 @@ func (m *Map[K, V]) Range(f func(key K, value V) bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// All is similar to [Range], but returns an [iter.Seq2], so is compatible with
|
||||
// Go 1.23+ iterators. All of the same caveats and behaviour from [Range] apply
|
||||
// to All.
|
||||
//
|
||||
// For a faster, lock-free alternative with relaxed consistency
|
||||
// guarantees, see [AllRelaxed].
|
||||
func (m *Map[K, V]) All() func(func(key K, value V) bool) {
|
||||
return m.Range
|
||||
}
|
||||
|
||||
// RangeRelaxed calls f sequentially for each key and value present
|
||||
// in the map. If f returns false, range stops the iteration.
|
||||
//
|
||||
// RangeRelaxed is a faster, lock-free alternative to [Range]. Unlike
|
||||
// Range, it does not acquire bucket locks and does not allocate memory
|
||||
// for entry snapshots. Instead, it reads entries directly using atomic
|
||||
// loads.
|
||||
//
|
||||
// RangeRelaxed does not necessarily correspond to any consistent
|
||||
// snapshot of the Map's contents: if the value for any key is stored
|
||||
// or deleted concurrently, RangeRelaxed may reflect any mapping for
|
||||
// that key from any point during the RangeRelaxed call. Unlike [Range],
|
||||
// the same key may be visited more than once if it is concurrently
|
||||
// deleted and re-inserted during the iteration.
|
||||
//
|
||||
// It is safe to modify the map while iterating it, including entry
|
||||
// creation, modification and deletion. However, the concurrent
|
||||
// modification rule apply, i.e. the changes may be not reflected
|
||||
// in the subsequently iterated entries.
|
||||
//
|
||||
// For stronger consistency guarantees where each key is visited at
|
||||
// most once, see [Range].
|
||||
func (m *Map[K, V]) RangeRelaxed(f func(key K, value V) bool) {
|
||||
m.initOnce.Do(m.init)
|
||||
table := m.table.Load()
|
||||
for i := range table.buckets {
|
||||
b := &table.buckets[i]
|
||||
for {
|
||||
metaw := atomic.LoadUint64(&b.meta)
|
||||
markedw := metaw & occupiedMeta
|
||||
for markedw != 0 {
|
||||
idx := firstMarkedByteIndex(markedw)
|
||||
eptr := atomic.LoadPointer(&b.entries[idx])
|
||||
if eptr != nil {
|
||||
e := (*entry[K, V])(eptr)
|
||||
if !f(e.key, e.value) {
|
||||
return
|
||||
}
|
||||
}
|
||||
markedw &= markedw - 1
|
||||
}
|
||||
bptr := atomic.LoadPointer(&b.next)
|
||||
if bptr == nil {
|
||||
break
|
||||
}
|
||||
b = (*bucketPadded)(bptr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AllRelaxed is similar to [RangeRelaxed], but returns an [iter.Seq2],
|
||||
// so is compatible with Go 1.23+ iterators. All of the same caveats
|
||||
// and behaviour from [RangeRelaxed] apply to AllRelaxed.
|
||||
//
|
||||
// For stronger consistency guarantees where each key is visited at
|
||||
// most once, see [All].
|
||||
func (m *Map[K, V]) AllRelaxed() func(func(key K, value V) bool) {
|
||||
return m.RangeRelaxed
|
||||
}
|
||||
|
||||
// DeleteMatching deletes all entries for which the delete return
|
||||
// value of f is true. If the stop return value is true, the
|
||||
// iteration stops immediately. The function returns the number
|
||||
// of deleted entries.
|
||||
//
|
||||
// DeleteMatching does not necessarily correspond to any consistent
|
||||
// snapshot of the Map's contents: if the value for any key is stored
|
||||
// or deleted concurrently (including by a concurrent DeleteMatching
|
||||
// call), DeleteMatching may reflect any mapping for that key from
|
||||
// any point during the call. In particular, if the map is resized
|
||||
// during the call (for example, due to concurrent modifications),
|
||||
// the iteration restarts internally with the new table, which may
|
||||
// result in calling f with the same key more than once.
|
||||
//
|
||||
// This call locks a hash table bucket for the duration of
|
||||
// evaluating f for all entries in the bucket and performing
|
||||
// deletions. It means that modifications on other entries in
|
||||
// the bucket will be blocked until f executes. Consider this when
|
||||
// the function includes long-running operations.
|
||||
func (m *Map[K, V]) DeleteMatching(f func(key K, value V) (delete, stop bool)) int {
|
||||
m.initOnce.Do(m.init)
|
||||
var totalDeleted int
|
||||
var anyBucketEmptied bool
|
||||
delete_loop_attempt:
|
||||
table := m.table.Load()
|
||||
for bidx := range table.buckets {
|
||||
rootb := &table.buckets[bidx]
|
||||
rootb.mu.Lock()
|
||||
// The following two checks must go in reverse to what's
|
||||
// in the resize method.
|
||||
if seq := resizeSeq(m.resizeCtl.Load()); seq&1 == 1 {
|
||||
// Resize is in progress. Help with the transfer, then go for another attempt.
|
||||
rootb.mu.Unlock()
|
||||
m.helpResize(seq)
|
||||
goto delete_loop_attempt
|
||||
}
|
||||
if m.newerTableExists(table) {
|
||||
// Someone resized the table. Go for another attempt.
|
||||
rootb.mu.Unlock()
|
||||
goto delete_loop_attempt
|
||||
}
|
||||
|
||||
var bucketDeleted int
|
||||
b := rootb
|
||||
for {
|
||||
for i := 0; i < entriesPerMapBucket; i++ {
|
||||
eptr := b.entries[i]
|
||||
if eptr != nil {
|
||||
e := (*entry[K, V])(eptr)
|
||||
del, stop := f(e.key, e.value)
|
||||
if del {
|
||||
// Deletion.
|
||||
// First we update the meta, then the entry.
|
||||
newmetaw := setByte(b.meta, 0, i)
|
||||
atomic.StoreUint64(&b.meta, newmetaw)
|
||||
atomic.StorePointer(&b.entries[i], nil)
|
||||
bucketDeleted++
|
||||
if newmetaw == 0 {
|
||||
anyBucketEmptied = true
|
||||
}
|
||||
}
|
||||
if stop {
|
||||
rootb.mu.Unlock()
|
||||
totalDeleted += bucketDeleted
|
||||
if bucketDeleted > 0 {
|
||||
table.addSize(uint64(bidx), -bucketDeleted)
|
||||
}
|
||||
if anyBucketEmptied {
|
||||
m.resize(table, mapShrinkHint)
|
||||
}
|
||||
return totalDeleted
|
||||
}
|
||||
}
|
||||
}
|
||||
if b.next == nil {
|
||||
break
|
||||
}
|
||||
b = (*bucketPadded)(b.next)
|
||||
}
|
||||
rootb.mu.Unlock()
|
||||
if bucketDeleted > 0 {
|
||||
totalDeleted += bucketDeleted
|
||||
table.addSize(uint64(bidx), -bucketDeleted)
|
||||
}
|
||||
}
|
||||
if anyBucketEmptied {
|
||||
m.resize(table, mapShrinkHint)
|
||||
}
|
||||
return totalDeleted
|
||||
}
|
||||
|
||||
// Clear deletes all keys and values currently stored in the map.
|
||||
func (m *Map[K, V]) Clear() {
|
||||
m.initOnce.Do(m.init)
|
||||
@@ -907,7 +1207,7 @@ func appendToBucket[K comparable, V any](h2 uint8, e *entry[K, V], b *bucketPadd
|
||||
}
|
||||
if b.next == nil {
|
||||
newb := new(bucketPadded)
|
||||
newb.meta = setByte(defaultMeta, h2, 0)
|
||||
newb.meta = setByte(0, h2, 0)
|
||||
newb.entries[0] = unsafe.Pointer(e)
|
||||
b.next = unsafe.Pointer(newb)
|
||||
return
|
||||
@@ -917,7 +1217,7 @@ func appendToBucket[K comparable, V any](h2 uint8, e *entry[K, V], b *bucketPadd
|
||||
}
|
||||
|
||||
func (table *mapTable[K, V]) addSize(bucketIdx uint64, delta int) {
|
||||
cidx := uint64(len(table.size)-1) & bucketIdx
|
||||
cidx := bucketIdx & uint64(len(table.size)-1)
|
||||
atomic.AddInt64(&table.size[cidx].c, int64(delta))
|
||||
}
|
||||
|
||||
@@ -934,7 +1234,7 @@ func h1(h uint64) uint64 {
|
||||
}
|
||||
|
||||
func h2(h uint64) uint8 {
|
||||
return uint8(h & 0x7f)
|
||||
return 0x80 | uint8(h&0x7f)
|
||||
}
|
||||
|
||||
// MapStats is Map statistics.
|
||||
@@ -1052,20 +1352,12 @@ const (
|
||||
cacheLineSize = 64
|
||||
)
|
||||
|
||||
// nextPowOf2 computes the next highest power of 2 of 32-bit v.
|
||||
// Source: https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
|
||||
func nextPowOf2(v uint32) uint32 {
|
||||
if v == 0 {
|
||||
// nextPowOf2 computes the next highest power of 2 of 64-bit v.
|
||||
func nextPowOf2(v uint64) uint64 {
|
||||
if v <= 1 {
|
||||
return 1
|
||||
}
|
||||
v--
|
||||
v |= v >> 1
|
||||
v |= v >> 2
|
||||
v |= v >> 4
|
||||
v |= v >> 8
|
||||
v |= v >> 16
|
||||
v++
|
||||
return v
|
||||
return 1 << bits.Len64(v-1)
|
||||
}
|
||||
|
||||
func parallelism() uint32 {
|
||||
|
||||
+845
-341
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,250 @@
|
||||
package age
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/age"
|
||||
"github.com/metacubex/age/armor"
|
||||
)
|
||||
|
||||
const FileHeader = armor.Header
|
||||
|
||||
var globalSecretKeys []string
|
||||
|
||||
// parseIdentities parse age-secret-key to age.Identity
|
||||
func parseIdentities(secretKey string) ([]age.Identity, error) {
|
||||
return age.ParseIdentities(strings.NewReader(secretKey))
|
||||
}
|
||||
|
||||
// parseRecipients parse age-public-key to age.Recipient
|
||||
func parseRecipients(publicKey string) ([]age.Recipient, error) {
|
||||
return age.ParseRecipients(strings.NewReader(publicKey))
|
||||
}
|
||||
|
||||
// convertToRecipient convert age.Identity to age.Recipient
|
||||
func convertToRecipient(identity age.Identity) (age.Recipient, error) {
|
||||
switch identity := identity.(type) {
|
||||
case *age.X25519Identity:
|
||||
return identity.Recipient(), nil
|
||||
case *age.HybridIdentity:
|
||||
return identity.Recipient(), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected identity type: %T", identity)
|
||||
}
|
||||
}
|
||||
|
||||
// ToPublicKeys convert age-secret-key to age-public-key
|
||||
func ToPublicKeys(secretKeys ...string) (publicKeys []string, err error) {
|
||||
for _, secretKey := range secretKeys {
|
||||
identities, err := parseIdentities(secretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, identity := range identities {
|
||||
recipient, err := convertToRecipient(identity)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
publicKeys = append(publicKeys, fmt.Sprint(recipient))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// SetGlobalSecretKeys set global secret keys, which will be used when decrypting
|
||||
func SetGlobalSecretKeys(secretKeys ...string) {
|
||||
globalSecretKeys = append(globalSecretKeys[:0], secretKeys...)
|
||||
}
|
||||
|
||||
// VeritySecretKeys check if the secret key is valid
|
||||
func VeritySecretKeys(secretKeys ...string) error {
|
||||
for _, secretKey := range secretKeys {
|
||||
if _, err := parseIdentities(secretKey); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VerityPublicKeys check if the public key is valid
|
||||
func VerityPublicKeys(publicKeys ...string) error {
|
||||
for _, publicKey := range publicKeys {
|
||||
if _, err := parseRecipients(publicKey); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DecryptBytes decrypt age armor format encrypted data
|
||||
// if not the age armor format, return original data
|
||||
func DecryptBytes(data []byte, secretKeys ...string) ([]byte, error) {
|
||||
if !strings.HasPrefix(string(data), FileHeader) { // not age armor format
|
||||
return data, nil
|
||||
}
|
||||
var identities []age.Identity
|
||||
for _, secretKey := range secretKeys {
|
||||
identity, err := parseIdentities(secretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
identities = append(identities, identity...)
|
||||
}
|
||||
for _, secretKey := range globalSecretKeys {
|
||||
identity, err := parseIdentities(secretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
identities = append(identities, identity...)
|
||||
}
|
||||
|
||||
r, err := age.Decrypt(armor.NewReader(bytes.NewReader(data)), identities...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return io.ReadAll(r)
|
||||
}
|
||||
|
||||
// EncryptBytes encrypt data with age armor format
|
||||
func EncryptBytes(data []byte, publicKeys ...string) ([]byte, error) {
|
||||
var recipients []age.Recipient
|
||||
for _, publicKey := range publicKeys {
|
||||
recipient, err := parseRecipients(publicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recipients = append(recipients, recipient...)
|
||||
}
|
||||
buf := &bytes.Buffer{}
|
||||
armorWriter := armor.NewWriter(buf)
|
||||
w, err := age.Encrypt(armorWriter, recipients...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = w.Write(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = w.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = armorWriter.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// GenX25519KeyPair generate x25519 recipient type age-secret-key and age-public-key
|
||||
func GenX25519KeyPair() (secretKey string, publicKey string, err error) {
|
||||
identity, err := age.GenerateX25519Identity()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return identity.String(), identity.Recipient().String(), nil
|
||||
}
|
||||
|
||||
// GenHybridKeyPair generate mlkem768-x25519 hybrid post-quantum recipient type age-secret-key and age-public-key
|
||||
func GenHybridKeyPair() (secretKey string, publicKey string, err error) {
|
||||
identity, err := age.GenerateHybridIdentity()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return identity.String(), identity.Recipient().String(), nil
|
||||
}
|
||||
|
||||
func Main(args []string) {
|
||||
if len(args) < 1 {
|
||||
panic("Using: age keygen/keygen-pq/convert/decrypt/encrypt")
|
||||
}
|
||||
switch args[0] {
|
||||
case "keygen":
|
||||
secretKey, publicKey, err := GenX25519KeyPair()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("# created: %s\n", time.Now().Format(time.RFC3339))
|
||||
fmt.Printf("# public key: %s\n", publicKey)
|
||||
fmt.Printf("%s\n", secretKey)
|
||||
case "keygen-pq":
|
||||
secretKey, publicKey, err := GenHybridKeyPair()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("# created: %s\n", time.Now().Format(time.RFC3339))
|
||||
fmt.Printf("# public key: %s\n", publicKey)
|
||||
fmt.Printf("%s\n", secretKey)
|
||||
case "convert":
|
||||
if len(args) < 1 {
|
||||
panic("Using: age convert <secret_key>")
|
||||
}
|
||||
publicKeys, err := ToPublicKeys(args[1])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if len(publicKeys) == 0 {
|
||||
panic("no public keys found in the input")
|
||||
}
|
||||
for _, publicKey := range publicKeys {
|
||||
fmt.Println(publicKey)
|
||||
}
|
||||
case "decrypt":
|
||||
if len(args) < 3 {
|
||||
panic("Using: age decrypt <secret_key> <source_file> <target_file>")
|
||||
}
|
||||
var data []byte
|
||||
var err error
|
||||
if args[2] == "-" {
|
||||
data, err = io.ReadAll(os.Stdin)
|
||||
} else {
|
||||
data, err = os.ReadFile(args[2])
|
||||
}
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
result, err := DecryptBytes(data, args[1])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if args[3] == "-" {
|
||||
_, err = os.Stdout.Write(result)
|
||||
} else {
|
||||
err = os.WriteFile(args[3], result, 0644)
|
||||
}
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
case "encrypt":
|
||||
if len(args) < 3 {
|
||||
panic("Using: age encrypt <public_key> <source_file> <target_file>")
|
||||
}
|
||||
var data []byte
|
||||
var err error
|
||||
if args[2] == "-" {
|
||||
data, err = io.ReadAll(os.Stdin)
|
||||
} else {
|
||||
data, err = os.ReadFile(args[2])
|
||||
}
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
result, err := EncryptBytes(data, args[1])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if args[3] == "-" {
|
||||
_, err = os.Stdout.Write(result)
|
||||
} else {
|
||||
err = os.WriteFile(args[3], result, 0644)
|
||||
}
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package age_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/metacubex/mihomo/component/age"
|
||||
)
|
||||
|
||||
func TestAge(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
gen func() (string, string, error)
|
||||
}{
|
||||
{"X25519", age.GenX25519KeyPair},
|
||||
{"MLKEM768X25519", age.GenHybridKeyPair},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
secretKey, publicKey, err := tc.gen()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(secretKey, publicKey)
|
||||
publicKeys, err := age.ToPublicKeys(secretKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(publicKeys) != 1 {
|
||||
t.Fatal("public keys length is not equal to 1")
|
||||
}
|
||||
if publicKeys[0] != publicKey {
|
||||
t.Fatal("public key is not equal")
|
||||
}
|
||||
rawData := []byte("hello world")
|
||||
encryptData, err := age.EncryptBytes(rawData, publicKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(string(encryptData))
|
||||
decryptData, err := age.DecryptBytes(encryptData, secretKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(decryptData) != string(rawData) {
|
||||
t.Fatal("decrypt data is not equal to raw data")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -272,6 +272,11 @@ loop:
|
||||
}
|
||||
if res.error == nil {
|
||||
if res.isPrimary {
|
||||
if fallback.error == nil && fallback.Conn != nil {
|
||||
go func() { // close fallback connection in new goroutine to avoid blocking
|
||||
_ = fallback.Conn.Close()
|
||||
}()
|
||||
}
|
||||
return res.Conn, nil
|
||||
}
|
||||
fallback = res
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"syscall"
|
||||
|
||||
"github.com/metacubex/mihomo/common/sockopt"
|
||||
)
|
||||
|
||||
func bindMarkToDialer(mark int, dialer *net.Dialer, _ string, _ netip.Addr) {
|
||||
@@ -19,19 +21,11 @@ func bindMarkToListenConfig(mark int, lc *net.ListenConfig, _, _ string) {
|
||||
|
||||
func bindMarkToControl(mark int) controlFn {
|
||||
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
||||
|
||||
addrPort, err := netip.ParseAddrPort(address)
|
||||
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
||||
return
|
||||
}
|
||||
|
||||
var innerErr error
|
||||
err = c.Control(func(fd uintptr) {
|
||||
innerErr = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
||||
})
|
||||
if innerErr != nil {
|
||||
err = innerErr
|
||||
}
|
||||
return
|
||||
return sockopt.RawConnMark(c, mark)
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ func createCachefileStore(options Options) (*Pool, string, error) {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
db, err := bbolt.Open(f.Name(), 0o666, &bbolt.Options{Timeout: time.Second})
|
||||
db, err := bbolt.Open(f.Name(), 0o666, &bbolt.Options{Timeout: time.Second, NoStatistics: true})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
+12
-2
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/metacubex/mihomo/component/ca"
|
||||
"github.com/metacubex/mihomo/component/dialer"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/listener/inner"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
@@ -74,11 +75,13 @@ func HttpRequest(ctx context.Context, url, method string, header map[string][]st
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if opt.dialer != nil {
|
||||
return opt.dialer.DialContext(ctx, network, address)
|
||||
}
|
||||
if conn, err := inner.HandleTcp(inner.GetTunnel(), address, opt.specialProxy); err == nil {
|
||||
return conn, nil
|
||||
} else {
|
||||
return dialer.DialContext(ctx, network, address)
|
||||
}
|
||||
return dialer.DialContext(ctx, network, address)
|
||||
},
|
||||
TLSClientConfig: tlsConfig,
|
||||
}
|
||||
@@ -91,6 +94,7 @@ type Option func(opt *option)
|
||||
|
||||
type option struct {
|
||||
specialProxy string
|
||||
dialer C.Dialer
|
||||
caOption ca.Option
|
||||
}
|
||||
|
||||
@@ -100,6 +104,12 @@ func WithSpecialProxy(name string) Option {
|
||||
}
|
||||
}
|
||||
|
||||
func WithDialer(dialer C.Dialer) Option {
|
||||
return func(opt *option) {
|
||||
opt.dialer = dialer
|
||||
}
|
||||
}
|
||||
|
||||
func WithCAOption(caOption ca.Option) Option {
|
||||
return func(opt *option) {
|
||||
opt.caOption = caOption
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package anet
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func IsForceAnet() bool {
|
||||
force, _ := strconv.ParseBool(os.Getenv("FORCE_ANET"))
|
||||
return force
|
||||
}
|
||||
@@ -21,11 +21,13 @@ type ifReq [40]byte
|
||||
|
||||
// Interfaces returns a list of the system's network interfaces.
|
||||
func Interfaces() ([]net.Interface, error) {
|
||||
ift, err := net.Interfaces()
|
||||
if err == nil {
|
||||
return ift, nil
|
||||
if !IsForceAnet() {
|
||||
ift, err := net.Interfaces()
|
||||
if err == nil {
|
||||
return ift, nil
|
||||
}
|
||||
}
|
||||
ift, err = interfaceTable(0)
|
||||
ift, err := interfaceTable(0)
|
||||
if err != nil {
|
||||
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
|
||||
}
|
||||
@@ -38,11 +40,13 @@ func Interfaces() ([]net.Interface, error) {
|
||||
// The returned list does not identify the associated interface; use
|
||||
// Interfaces and Interface.Addrs for more detail.
|
||||
func InterfaceAddrs() ([]net.Addr, error) {
|
||||
ifat, err := net.InterfaceAddrs()
|
||||
if err == nil {
|
||||
return ifat, nil
|
||||
if !IsForceAnet() {
|
||||
ifat, err := net.InterfaceAddrs()
|
||||
if err == nil {
|
||||
return ifat, nil
|
||||
}
|
||||
}
|
||||
ifat, err = interfaceAddrTable(nil)
|
||||
ifat, err := interfaceAddrTable(nil)
|
||||
if err != nil {
|
||||
err = &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
|
||||
}
|
||||
@@ -55,9 +59,11 @@ func InterfaceAddrs() ([]net.Addr, error) {
|
||||
// sharing the logical data link; for more precision use
|
||||
// InterfaceByName.
|
||||
func InterfaceByIndex(index int) (*net.Interface, error) {
|
||||
ifi, err := net.InterfaceByIndex(index)
|
||||
if err == nil {
|
||||
return ifi, nil
|
||||
if !IsForceAnet() {
|
||||
ifi, err := net.InterfaceByIndex(index)
|
||||
if err == nil {
|
||||
return ifi, nil
|
||||
}
|
||||
}
|
||||
if index <= 0 {
|
||||
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: errInvalidInterfaceIndex}
|
||||
@@ -66,7 +72,7 @@ func InterfaceByIndex(index int) (*net.Interface, error) {
|
||||
if err != nil {
|
||||
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
|
||||
}
|
||||
ifi, err = interfaceByIndex(ift, index)
|
||||
ifi, err := interfaceByIndex(ift, index)
|
||||
if err != nil {
|
||||
err = &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: err}
|
||||
}
|
||||
@@ -75,9 +81,11 @@ func InterfaceByIndex(index int) (*net.Interface, error) {
|
||||
|
||||
// InterfaceByName returns the interface specified by name.
|
||||
func InterfaceByName(name string) (*net.Interface, error) {
|
||||
ifi, err := net.InterfaceByName(name)
|
||||
if err == nil {
|
||||
return ifi, nil
|
||||
if !IsForceAnet() {
|
||||
ifi, err := net.InterfaceByName(name)
|
||||
if err == nil {
|
||||
return ifi, nil
|
||||
}
|
||||
}
|
||||
if name == "" {
|
||||
return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: errInvalidInterfaceName}
|
||||
|
||||
@@ -6,15 +6,12 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/atomic"
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
)
|
||||
|
||||
var (
|
||||
keepAliveIdle = atomic.NewInt64(0)
|
||||
keepAliveInterval = atomic.NewInt64(0)
|
||||
disableKeepAlive = atomic.NewBool(false)
|
||||
|
||||
SetDisableKeepAliveCallback = utils.NewCallback[bool]()
|
||||
)
|
||||
|
||||
func SetKeepAliveIdle(t time.Duration) {
|
||||
@@ -43,7 +40,6 @@ func SetDisableKeepAlive(disable bool) {
|
||||
|
||||
func setDisableKeepAlive(disable bool) {
|
||||
disableKeepAlive.Store(disable)
|
||||
SetDisableKeepAliveCallback.Emit(disable)
|
||||
}
|
||||
|
||||
func DisableKeepAlive() bool {
|
||||
|
||||
@@ -78,7 +78,7 @@ func (c *CacheFile) Close() error {
|
||||
}
|
||||
|
||||
func initCache() {
|
||||
options := bbolt.Options{Timeout: time.Second}
|
||||
options := bbolt.Options{Timeout: time.Second, NoStatistics: true}
|
||||
db, err := bbolt.Open(C.Path.Cache(), fileMode, &options)
|
||||
switch err {
|
||||
case bbolt.ErrInvalid, bbolt.ErrChecksum, bbolt.ErrVersionMismatch:
|
||||
|
||||
@@ -7,14 +7,23 @@ import (
|
||||
"net/netip"
|
||||
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/tunnel"
|
||||
)
|
||||
|
||||
type Tunnel interface {
|
||||
C.Tunnel
|
||||
Proxies() map[string]C.Proxy
|
||||
}
|
||||
|
||||
type byNameProxyDialer struct {
|
||||
proxyName string
|
||||
tunnel C.Tunnel
|
||||
}
|
||||
|
||||
func (d byNameProxyDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
tunnel, _ := d.tunnel.(Tunnel)
|
||||
if tunnel == nil {
|
||||
return nil, fmt.Errorf("tunnel is invalid, must be proxydialer.Tunnel, but got: %T", d.tunnel)
|
||||
}
|
||||
proxies := tunnel.Proxies()
|
||||
proxy, ok := proxies[d.proxyName]
|
||||
if !ok {
|
||||
@@ -24,6 +33,10 @@ func (d byNameProxyDialer) DialContext(ctx context.Context, network, address str
|
||||
}
|
||||
|
||||
func (d byNameProxyDialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
||||
tunnel, _ := d.tunnel.(Tunnel)
|
||||
if tunnel == nil {
|
||||
return nil, fmt.Errorf("tunnel is invalid, must be proxydialer.Tunnel, but got: %T", d.tunnel)
|
||||
}
|
||||
proxies := tunnel.Proxies()
|
||||
proxy, ok := proxies[d.proxyName]
|
||||
if !ok {
|
||||
@@ -32,6 +45,6 @@ func (d byNameProxyDialer) ListenPacket(ctx context.Context, network, address st
|
||||
return New(proxy, true).ListenPacket(ctx, network, address, rAddrPort)
|
||||
}
|
||||
|
||||
func NewByName(proxyName string) C.Dialer {
|
||||
return byNameProxyDialer{proxyName: proxyName}
|
||||
func NewByName(proxyName string, tunnel C.Tunnel) C.Dialer {
|
||||
return byNameProxyDialer{proxyName: proxyName, tunnel: tunnel}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package proxydialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
@@ -50,6 +51,9 @@ func (p proxyDialer) DialContext(ctx context.Context, network, address string) (
|
||||
}
|
||||
|
||||
func (p proxyDialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
||||
if !strings.HasPrefix(network, "udp") {
|
||||
return nil, fmt.Errorf("proxyDialer only support udp network, but got: %s", network)
|
||||
}
|
||||
currentMeta := &C.Metadata{Type: C.INNER, DstIP: rAddrPort.Addr(), DstPort: rAddrPort.Port()}
|
||||
return p.listenPacket(ctx, currentMeta)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package resource
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -16,6 +18,7 @@ import (
|
||||
)
|
||||
|
||||
type Parser[V any] func([]byte) (V, error)
|
||||
type BundleFile func() (fs.File, error)
|
||||
|
||||
type Fetcher[V any] struct {
|
||||
ctx context.Context
|
||||
@@ -23,6 +26,7 @@ type Fetcher[V any] struct {
|
||||
resourceType string
|
||||
name string
|
||||
vehicle P.Vehicle
|
||||
bundleFile BundleFile
|
||||
updatedAt time.Time
|
||||
hash utils.HashType
|
||||
parser Parser[V]
|
||||
@@ -66,6 +70,33 @@ func (f *Fetcher[V]) Initial() (V, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// parse local file error, fallback to bundle file
|
||||
if f.bundleFile != nil {
|
||||
// bundle file exists, use it first
|
||||
if file, fErr := f.bundleFile(); fErr == nil {
|
||||
defer file.Close()
|
||||
buf, err := io.ReadAll(file)
|
||||
var modTime time.Time
|
||||
if stat, sErr := file.Stat(); sErr == nil {
|
||||
modTime = stat.ModTime()
|
||||
}
|
||||
contents, _, err := f.loadBuf(buf, utils.MakeHash(buf), true)
|
||||
f.updatedAt = modTime // reset updatedAt to file's modTime
|
||||
|
||||
if err == nil {
|
||||
log.Infoln("[Provider] %s extract successful from bundle file", f.Name())
|
||||
err = f.startPullLoop(time.Since(modTime) > f.interval)
|
||||
if err != nil {
|
||||
return lo.Empty[V](), err
|
||||
}
|
||||
return contents, nil
|
||||
}
|
||||
log.Warnln("[Provider] %s read bundle file error: %s", f.Name(), err.Error())
|
||||
} else {
|
||||
log.Warnln("[Provider] %s read bundle file error: %s", f.Name(), fErr.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// parse local file error, fallback to remote
|
||||
contents, _, updateErr := f.Update()
|
||||
|
||||
@@ -218,20 +249,21 @@ func (f *Fetcher[V]) updateWithLog() {
|
||||
return
|
||||
}
|
||||
|
||||
func NewFetcher[V any](name string, interval time.Duration, vehicle P.Vehicle, parser Parser[V], onUpdate func(V)) *Fetcher[V] {
|
||||
func NewFetcher[V any](name string, interval time.Duration, vehicle P.Vehicle, bundleFile BundleFile, parser Parser[V], onUpdate func(V)) *Fetcher[V] {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
minBackoff := 10 * time.Second
|
||||
if interval < minBackoff {
|
||||
minBackoff = interval
|
||||
}
|
||||
return &Fetcher[V]{
|
||||
ctx: ctx,
|
||||
ctxCancel: cancel,
|
||||
name: name,
|
||||
vehicle: vehicle,
|
||||
parser: parser,
|
||||
onUpdate: onUpdate,
|
||||
interval: interval,
|
||||
ctx: ctx,
|
||||
ctxCancel: cancel,
|
||||
name: name,
|
||||
bundleFile: bundleFile,
|
||||
vehicle: vehicle,
|
||||
parser: parser,
|
||||
onUpdate: onUpdate,
|
||||
interval: interval,
|
||||
backoff: slowdown.Backoff{
|
||||
Factor: 2,
|
||||
Jitter: false,
|
||||
|
||||
@@ -236,6 +236,10 @@ func (q *quicPacketSender) readQuicData(b []byte) error {
|
||||
cache := buf.NewPacket()
|
||||
defer cache.Release()
|
||||
|
||||
if hdrLen+4+16 > len(b) {
|
||||
return errNotQuic
|
||||
}
|
||||
|
||||
mask := cache.Extend(block.BlockSize())
|
||||
block.Encrypt(mask, b[hdrLen+4:hdrLen+4+16])
|
||||
firstByte := b[0]
|
||||
|
||||
@@ -40,9 +40,6 @@ func NewListener(inner net.Listener, config *Config) net.Listener {
|
||||
}
|
||||
|
||||
func GetFingerprint(clientFingerprint string) (UClientHelloID, bool) {
|
||||
if len(clientFingerprint) == 0 {
|
||||
clientFingerprint = globalFingerprint
|
||||
}
|
||||
if len(clientFingerprint) == 0 || clientFingerprint == "none" {
|
||||
return UClientHelloID{}, false
|
||||
}
|
||||
@@ -319,13 +316,3 @@ func GetTLSConnectionState(conn net.Conn) (tlsState tls.ConnectionState) {
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var globalFingerprint string
|
||||
|
||||
func SetGlobalFingerprint(fingerprint string) {
|
||||
globalFingerprint = fingerprint
|
||||
}
|
||||
|
||||
func GetGlobalFingerprint() string {
|
||||
return globalFingerprint
|
||||
}
|
||||
+143
-117
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/metacubex/mihomo/common/orderedmap"
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"github.com/metacubex/mihomo/common/yaml"
|
||||
"github.com/metacubex/mihomo/component/age"
|
||||
"github.com/metacubex/mihomo/component/auth"
|
||||
"github.com/metacubex/mihomo/component/cidr"
|
||||
"github.com/metacubex/mihomo/component/fakeip"
|
||||
@@ -34,6 +35,7 @@ import (
|
||||
LC "github.com/metacubex/mihomo/listener/config"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
R "github.com/metacubex/mihomo/rules"
|
||||
RB "github.com/metacubex/mihomo/rules/bundle"
|
||||
RC "github.com/metacubex/mihomo/rules/common"
|
||||
RP "github.com/metacubex/mihomo/rules/provider"
|
||||
RW "github.com/metacubex/mihomo/rules/wrapper"
|
||||
@@ -45,27 +47,26 @@ import (
|
||||
// General config
|
||||
type General struct {
|
||||
Inbound
|
||||
Mode T.TunnelMode `json:"mode"`
|
||||
UnifiedDelay bool `json:"unified-delay"`
|
||||
LogLevel log.LogLevel `json:"log-level"`
|
||||
IPv6 bool `json:"ipv6"`
|
||||
Interface string `json:"interface-name"`
|
||||
RoutingMark int `json:"routing-mark"`
|
||||
GeoXUrl GeoXUrl `json:"geox-url"`
|
||||
GeoAutoUpdate bool `json:"geo-auto-update"`
|
||||
GeoUpdateInterval int `json:"geo-update-interval"`
|
||||
GeodataMode bool `json:"geodata-mode"`
|
||||
GeodataLoader string `json:"geodata-loader"`
|
||||
GeositeMatcher string `json:"geosite-matcher"`
|
||||
TCPConcurrent bool `json:"tcp-concurrent"`
|
||||
FindProcessMode process.FindProcessMode `json:"find-process-mode"`
|
||||
Sniffing bool `json:"sniffing"`
|
||||
GlobalClientFingerprint string `json:"global-client-fingerprint"`
|
||||
GlobalUA string `json:"global-ua"`
|
||||
ETagSupport bool `json:"etag-support"`
|
||||
KeepAliveIdle int `json:"keep-alive-idle"`
|
||||
KeepAliveInterval int `json:"keep-alive-interval"`
|
||||
DisableKeepAlive bool `json:"disable-keep-alive"`
|
||||
Mode T.TunnelMode `json:"mode"`
|
||||
UnifiedDelay bool `json:"unified-delay"`
|
||||
LogLevel log.LogLevel `json:"log-level"`
|
||||
IPv6 bool `json:"ipv6"`
|
||||
Interface string `json:"interface-name"`
|
||||
RoutingMark int `json:"routing-mark"`
|
||||
GeoXUrl GeoXUrl `json:"geox-url"`
|
||||
GeoAutoUpdate bool `json:"geo-auto-update"`
|
||||
GeoUpdateInterval int `json:"geo-update-interval"`
|
||||
GeodataMode bool `json:"geodata-mode"`
|
||||
GeodataLoader string `json:"geodata-loader"`
|
||||
GeositeMatcher string `json:"geosite-matcher"`
|
||||
TCPConcurrent bool `json:"tcp-concurrent"`
|
||||
FindProcessMode process.FindProcessMode `json:"find-process-mode"`
|
||||
Sniffing bool `json:"sniffing"`
|
||||
GlobalUA string `json:"global-ua"`
|
||||
ETagSupport bool `json:"etag-support"`
|
||||
KeepAliveIdle int `json:"keep-alive-idle"`
|
||||
KeepAliveInterval int `json:"keep-alive-interval"`
|
||||
DisableKeepAlive bool `json:"disable-keep-alive"`
|
||||
}
|
||||
|
||||
// Inbound config
|
||||
@@ -99,16 +100,17 @@ type GeoXUrl struct {
|
||||
|
||||
// Controller config
|
||||
type Controller struct {
|
||||
ExternalController string
|
||||
ExternalControllerTLS string
|
||||
ExternalControllerUnix string
|
||||
ExternalControllerPipe string
|
||||
ExternalUI string
|
||||
ExternalUIURL string
|
||||
ExternalUIName string
|
||||
ExternalDohServer string
|
||||
Secret string
|
||||
Cors Cors
|
||||
ExternalController string
|
||||
ExternalControllerTLS string
|
||||
ExternalControllerUnix string
|
||||
ExternalControllerPipe string
|
||||
ExternalControllerRoutingMark int
|
||||
ExternalUI string
|
||||
ExternalUIURL string
|
||||
ExternalUIName string
|
||||
ExternalDohServer string
|
||||
Secret string
|
||||
Cors Cors
|
||||
}
|
||||
|
||||
type Cors struct {
|
||||
@@ -153,7 +155,9 @@ type DNS struct {
|
||||
Fallback []dns.NameServer
|
||||
FallbackIPFilter []C.IpMatcher
|
||||
FallbackDomainFilter []C.DomainMatcher
|
||||
FallbackLazyQuery bool
|
||||
Listen string
|
||||
ListenRoutingMark int
|
||||
EnhancedMode C.DNSMode
|
||||
DefaultNameserver []dns.NameServer
|
||||
CacheAlgorithm string
|
||||
@@ -225,7 +229,9 @@ type RawDNS struct {
|
||||
NameServer []string `yaml:"nameserver" json:"nameserver"`
|
||||
Fallback []string `yaml:"fallback" json:"fallback"`
|
||||
FallbackFilter RawFallbackFilter `yaml:"fallback-filter" json:"fallback-filter"`
|
||||
FallbackLazyQuery bool `yaml:"fallback-lazy-query" json:"fallback-lazy-query"`
|
||||
Listen string `yaml:"listen" json:"listen"`
|
||||
ListenRoutingMark int `yaml:"listen-routing-mark" json:"listen-routing-mark"`
|
||||
EnhancedMode C.DNSMode `yaml:"enhanced-mode" json:"enhanced-mode"`
|
||||
FakeIPRange string `yaml:"fake-ip-range" json:"fake-ip-range"`
|
||||
FakeIPRange6 string `yaml:"fake-ip-range6" json:"fake-ip-range6"`
|
||||
@@ -270,7 +276,7 @@ type RawTun struct {
|
||||
Stack C.TUNStack `yaml:"stack" json:"stack"`
|
||||
DNSHijack []string `yaml:"dns-hijack" json:"dns-hijack"`
|
||||
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
||||
AutoDetectInterface bool `yaml:"auto-detect-interface"`
|
||||
AutoDetectInterface bool `yaml:"auto-detect-interface" json:"auto-detect-interface"`
|
||||
|
||||
MTU uint32 `yaml:"mtu" json:"mtu,omitempty"`
|
||||
GSO bool `yaml:"gso" json:"gso,omitempty"`
|
||||
@@ -306,6 +312,7 @@ type RawTun struct {
|
||||
ExcludeMACAddress []string `yaml:"exclude-mac-address" json:"exclude-mac-address,omitempty"`
|
||||
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
|
||||
ICMPTimeout int64 `yaml:"icmp-timeout" json:"icmp-timeout,omitempty"`
|
||||
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
|
||||
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
|
||||
|
||||
@@ -342,10 +349,10 @@ type RawIPTables struct {
|
||||
}
|
||||
|
||||
type RawExperimental struct {
|
||||
Fingerprints []string `yaml:"fingerprints"`
|
||||
QUICGoDisableGSO bool `yaml:"quic-go-disable-gso"`
|
||||
QUICGoDisableECN bool `yaml:"quic-go-disable-ecn"`
|
||||
IP4PEnable bool `yaml:"dialer-ip4p-convert"`
|
||||
Fingerprints []string `yaml:"fingerprints" json:"fingerprints"`
|
||||
QUICGoDisableGSO bool `yaml:"quic-go-disable-gso" json:"quic-go-disable-gso"`
|
||||
QUICGoDisableECN bool `yaml:"quic-go-disable-ecn" json:"quic-go-disable-ecn"`
|
||||
IP4PEnable bool `yaml:"dialer-ip4p-convert" json:"dialer-ip4p-convert"`
|
||||
}
|
||||
|
||||
type RawProfile struct {
|
||||
@@ -390,51 +397,52 @@ type RawTLS struct {
|
||||
}
|
||||
|
||||
type RawConfig struct {
|
||||
Port int `yaml:"port" json:"port"`
|
||||
SocksPort int `yaml:"socks-port" json:"socks-port"`
|
||||
RedirPort int `yaml:"redir-port" json:"redir-port"`
|
||||
TProxyPort int `yaml:"tproxy-port" json:"tproxy-port"`
|
||||
MixedPort int `yaml:"mixed-port" json:"mixed-port"`
|
||||
ShadowSocksConfig string `yaml:"ss-config" json:"ss-config"`
|
||||
VmessConfig string `yaml:"vmess-config" json:"vmess-config"`
|
||||
InboundTfo bool `yaml:"inbound-tfo" json:"inbound-tfo"`
|
||||
InboundMPTCP bool `yaml:"inbound-mptcp" json:"inbound-mptcp"`
|
||||
Authentication []string `yaml:"authentication" json:"authentication"`
|
||||
SkipAuthPrefixes []netip.Prefix `yaml:"skip-auth-prefixes" json:"skip-auth-prefixes"`
|
||||
LanAllowedIPs []netip.Prefix `yaml:"lan-allowed-ips" json:"lan-allowed-ips"`
|
||||
LanDisAllowedIPs []netip.Prefix `yaml:"lan-disallowed-ips" json:"lan-disallowed-ips"`
|
||||
AllowLan bool `yaml:"allow-lan" json:"allow-lan"`
|
||||
BindAddress string `yaml:"bind-address" json:"bind-address"`
|
||||
Mode T.TunnelMode `yaml:"mode" json:"mode"`
|
||||
UnifiedDelay bool `yaml:"unified-delay" json:"unified-delay"`
|
||||
LogLevel log.LogLevel `yaml:"log-level" json:"log-level"`
|
||||
IPv6 bool `yaml:"ipv6" json:"ipv6"`
|
||||
ExternalController string `yaml:"external-controller" json:"external-controller"`
|
||||
ExternalControllerPipe string `yaml:"external-controller-pipe" json:"external-controller-pipe"`
|
||||
ExternalControllerUnix string `yaml:"external-controller-unix" json:"external-controller-unix"`
|
||||
ExternalControllerTLS string `yaml:"external-controller-tls" json:"external-controller-tls"`
|
||||
ExternalControllerCors RawCors `yaml:"external-controller-cors" json:"external-controller-cors"`
|
||||
ExternalUI string `yaml:"external-ui" json:"external-ui"`
|
||||
ExternalUIURL string `yaml:"external-ui-url" json:"external-ui-url"`
|
||||
ExternalUIName string `yaml:"external-ui-name" json:"external-ui-name"`
|
||||
ExternalDohServer string `yaml:"external-doh-server" json:"external-doh-server"`
|
||||
Secret string `yaml:"secret" json:"secret"`
|
||||
Interface string `yaml:"interface-name" json:"interface-name"`
|
||||
RoutingMark int `yaml:"routing-mark" json:"routing-mark"`
|
||||
Tunnels []LC.Tunnel `yaml:"tunnels" json:"tunnels"`
|
||||
GeoAutoUpdate bool `yaml:"geo-auto-update" json:"geo-auto-update"`
|
||||
GeoUpdateInterval int `yaml:"geo-update-interval" json:"geo-update-interval"`
|
||||
GeodataMode bool `yaml:"geodata-mode" json:"geodata-mode"`
|
||||
GeodataLoader string `yaml:"geodata-loader" json:"geodata-loader"`
|
||||
GeositeMatcher string `yaml:"geosite-matcher" json:"geosite-matcher"`
|
||||
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
|
||||
FindProcessMode process.FindProcessMode `yaml:"find-process-mode" json:"find-process-mode"`
|
||||
GlobalClientFingerprint string `yaml:"global-client-fingerprint" json:"global-client-fingerprint"`
|
||||
GlobalUA string `yaml:"global-ua" json:"global-ua"`
|
||||
ETagSupport bool `yaml:"etag-support" json:"etag-support"`
|
||||
KeepAliveIdle int `yaml:"keep-alive-idle" json:"keep-alive-idle"`
|
||||
KeepAliveInterval int `yaml:"keep-alive-interval" json:"keep-alive-interval"`
|
||||
DisableKeepAlive bool `yaml:"disable-keep-alive" json:"disable-keep-alive"`
|
||||
Port int `yaml:"port" json:"port"`
|
||||
SocksPort int `yaml:"socks-port" json:"socks-port"`
|
||||
RedirPort int `yaml:"redir-port" json:"redir-port"`
|
||||
TProxyPort int `yaml:"tproxy-port" json:"tproxy-port"`
|
||||
MixedPort int `yaml:"mixed-port" json:"mixed-port"`
|
||||
ShadowSocksConfig string `yaml:"ss-config" json:"ss-config"`
|
||||
VmessConfig string `yaml:"vmess-config" json:"vmess-config"`
|
||||
InboundTfo bool `yaml:"inbound-tfo" json:"inbound-tfo"`
|
||||
InboundMPTCP bool `yaml:"inbound-mptcp" json:"inbound-mptcp"`
|
||||
Authentication []string `yaml:"authentication" json:"authentication"`
|
||||
SkipAuthPrefixes []netip.Prefix `yaml:"skip-auth-prefixes" json:"skip-auth-prefixes"`
|
||||
LanAllowedIPs []netip.Prefix `yaml:"lan-allowed-ips" json:"lan-allowed-ips"`
|
||||
LanDisAllowedIPs []netip.Prefix `yaml:"lan-disallowed-ips" json:"lan-disallowed-ips"`
|
||||
AllowLan bool `yaml:"allow-lan" json:"allow-lan"`
|
||||
BindAddress string `yaml:"bind-address" json:"bind-address"`
|
||||
Mode T.TunnelMode `yaml:"mode" json:"mode"`
|
||||
UnifiedDelay bool `yaml:"unified-delay" json:"unified-delay"`
|
||||
LogLevel log.LogLevel `yaml:"log-level" json:"log-level"`
|
||||
IPv6 bool `yaml:"ipv6" json:"ipv6"`
|
||||
ExternalController string `yaml:"external-controller" json:"external-controller"`
|
||||
ExternalControllerRoutingMark int `yaml:"external-controller-routing-mark" json:"external-controller-routing-mark"`
|
||||
ExternalControllerPipe string `yaml:"external-controller-pipe" json:"external-controller-pipe"`
|
||||
ExternalControllerUnix string `yaml:"external-controller-unix" json:"external-controller-unix"`
|
||||
ExternalControllerTLS string `yaml:"external-controller-tls" json:"external-controller-tls"`
|
||||
ExternalControllerCors RawCors `yaml:"external-controller-cors" json:"external-controller-cors"`
|
||||
ExternalUI string `yaml:"external-ui" json:"external-ui"`
|
||||
ExternalUIURL string `yaml:"external-ui-url" json:"external-ui-url"`
|
||||
ExternalUIName string `yaml:"external-ui-name" json:"external-ui-name"`
|
||||
ExternalDohServer string `yaml:"external-doh-server" json:"external-doh-server"`
|
||||
Secret string `yaml:"secret" json:"secret"`
|
||||
Interface string `yaml:"interface-name" json:"interface-name"`
|
||||
RoutingMark int `yaml:"routing-mark" json:"routing-mark"`
|
||||
Tunnels []LC.Tunnel `yaml:"tunnels" json:"tunnels"`
|
||||
GeoAutoUpdate bool `yaml:"geo-auto-update" json:"geo-auto-update"`
|
||||
GeoUpdateInterval int `yaml:"geo-update-interval" json:"geo-update-interval"`
|
||||
GeodataMode bool `yaml:"geodata-mode" json:"geodata-mode"`
|
||||
GeodataLoader string `yaml:"geodata-loader" json:"geodata-loader"`
|
||||
GeositeMatcher string `yaml:"geosite-matcher" json:"geosite-matcher"`
|
||||
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
|
||||
FindProcessMode process.FindProcessMode `yaml:"find-process-mode" json:"find-process-mode"`
|
||||
GlobalClientFingerprint string `yaml:"global-client-fingerprint" json:"global-client-fingerprint"`
|
||||
GlobalUA string `yaml:"global-ua" json:"global-ua"`
|
||||
ETagSupport bool `yaml:"etag-support" json:"etag-support"`
|
||||
KeepAliveIdle int `yaml:"keep-alive-idle" json:"keep-alive-idle"`
|
||||
KeepAliveInterval int `yaml:"keep-alive-interval" json:"keep-alive-interval"`
|
||||
DisableKeepAlive bool `yaml:"disable-keep-alive" json:"disable-keep-alive"`
|
||||
|
||||
ProxyProvider map[string]map[string]any `yaml:"proxy-providers" json:"proxy-providers"`
|
||||
RuleProvider map[string]map[string]any `yaml:"rule-providers" json:"rule-providers"`
|
||||
@@ -595,6 +603,12 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
||||
// config with default value
|
||||
rawCfg := DefaultRawConfig()
|
||||
|
||||
// decrypt config
|
||||
buf, err := age.DecryptBytes(buf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt config error: %w", err)
|
||||
}
|
||||
|
||||
if err := yaml.Unmarshal(buf, rawCfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -739,6 +753,9 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
||||
func temporaryUpdateGeneral(general *General) func()
|
||||
|
||||
func parseGeneral(cfg *RawConfig) (*General, error) {
|
||||
if cfg.GlobalClientFingerprint != "" {
|
||||
log.Errorln("The `global-client-fingerprint` configuration is removed, please set `client-fingerprint` directly on the proxy instead")
|
||||
}
|
||||
return &General{
|
||||
Inbound: Inbound{
|
||||
Port: cfg.Port,
|
||||
@@ -768,19 +785,18 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
||||
ASN: cfg.GeoXUrl.ASN,
|
||||
GeoSite: cfg.GeoXUrl.GeoSite,
|
||||
},
|
||||
GeoAutoUpdate: cfg.GeoAutoUpdate,
|
||||
GeoUpdateInterval: cfg.GeoUpdateInterval,
|
||||
GeodataMode: cfg.GeodataMode,
|
||||
GeodataLoader: cfg.GeodataLoader,
|
||||
GeositeMatcher: cfg.GeositeMatcher,
|
||||
TCPConcurrent: cfg.TCPConcurrent,
|
||||
FindProcessMode: cfg.FindProcessMode,
|
||||
GlobalClientFingerprint: cfg.GlobalClientFingerprint,
|
||||
GlobalUA: cfg.GlobalUA,
|
||||
ETagSupport: cfg.ETagSupport,
|
||||
KeepAliveIdle: cfg.KeepAliveIdle,
|
||||
KeepAliveInterval: cfg.KeepAliveInterval,
|
||||
DisableKeepAlive: cfg.DisableKeepAlive,
|
||||
GeoAutoUpdate: cfg.GeoAutoUpdate,
|
||||
GeoUpdateInterval: cfg.GeoUpdateInterval,
|
||||
GeodataMode: cfg.GeodataMode,
|
||||
GeodataLoader: cfg.GeodataLoader,
|
||||
GeositeMatcher: cfg.GeositeMatcher,
|
||||
TCPConcurrent: cfg.TCPConcurrent,
|
||||
FindProcessMode: cfg.FindProcessMode,
|
||||
GlobalUA: cfg.GlobalUA,
|
||||
ETagSupport: cfg.ETagSupport,
|
||||
KeepAliveIdle: cfg.KeepAliveIdle,
|
||||
KeepAliveInterval: cfg.KeepAliveInterval,
|
||||
DisableKeepAlive: cfg.DisableKeepAlive,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -792,15 +808,16 @@ func parseController(cfg *RawConfig) (*Controller, error) {
|
||||
return nil, fmt.Errorf("external UI name is not local: %s", uiName)
|
||||
}
|
||||
return &Controller{
|
||||
ExternalController: cfg.ExternalController,
|
||||
ExternalUI: cfg.ExternalUI,
|
||||
ExternalUIURL: cfg.ExternalUIURL,
|
||||
ExternalUIName: cfg.ExternalUIName,
|
||||
Secret: cfg.Secret,
|
||||
ExternalControllerPipe: cfg.ExternalControllerPipe,
|
||||
ExternalControllerUnix: cfg.ExternalControllerUnix,
|
||||
ExternalControllerTLS: cfg.ExternalControllerTLS,
|
||||
ExternalDohServer: cfg.ExternalDohServer,
|
||||
ExternalController: cfg.ExternalController,
|
||||
ExternalUI: cfg.ExternalUI,
|
||||
ExternalUIURL: cfg.ExternalUIURL,
|
||||
ExternalUIName: cfg.ExternalUIName,
|
||||
Secret: cfg.Secret,
|
||||
ExternalControllerRoutingMark: cfg.ExternalControllerRoutingMark,
|
||||
ExternalControllerPipe: cfg.ExternalControllerPipe,
|
||||
ExternalControllerUnix: cfg.ExternalControllerUnix,
|
||||
ExternalControllerTLS: cfg.ExternalControllerTLS,
|
||||
ExternalDohServer: cfg.ExternalDohServer,
|
||||
Cors: Cors{
|
||||
AllowOrigins: cfg.ExternalControllerCors.AllowOrigins,
|
||||
AllowPrivateNetwork: cfg.ExternalControllerCors.AllowPrivateNetwork,
|
||||
@@ -872,6 +889,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
||||
proxies["REJECT-DROP"] = adapter.NewProxy(outbound.NewRejectDrop())
|
||||
proxies["COMPATIBLE"] = adapter.NewProxy(outbound.NewCompatible())
|
||||
proxies["PASS"] = adapter.NewProxy(outbound.NewPass())
|
||||
proxies["PASS-RULE"] = adapter.NewProxy(outbound.NewPassRule())
|
||||
proxyList = append(proxyList, "DIRECT", "REJECT")
|
||||
|
||||
// parse proxy
|
||||
@@ -942,7 +960,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
||||
|
||||
var ps []C.Proxy
|
||||
for _, v := range proxyList {
|
||||
if proxies[v].Type() == C.Pass {
|
||||
if proxies[v].Type() == C.Pass || proxies[v].Type() == C.PassRule {
|
||||
continue
|
||||
}
|
||||
ps = append(ps, proxies[v])
|
||||
@@ -952,12 +970,17 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
||||
providersMap[provider.ReservedName] = pd
|
||||
|
||||
if !hasGlobal {
|
||||
global := outboundgroup.NewSelector(
|
||||
&outboundgroup.GroupCommonOption{
|
||||
global, err := outboundgroup.NewSelector(
|
||||
outboundgroup.GroupCommonOption{
|
||||
Name: "GLOBAL",
|
||||
},
|
||||
outboundgroup.SelectorOption{},
|
||||
proxies["COMPATIBLE"],
|
||||
[]P.ProxyProvider{pd},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("new GLOBAL proxy group error: %w", err)
|
||||
}
|
||||
proxies["GLOBAL"] = adapter.NewProxy(global)
|
||||
}
|
||||
|
||||
@@ -993,7 +1016,7 @@ func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]P.RuleProvider
|
||||
ruleProviders = map[string]P.RuleProvider{}
|
||||
// parse rule provider
|
||||
for name, mapping := range cfg.RuleProvider {
|
||||
rp, err := RP.ParseRuleProvider(name, mapping, R.ParseRule)
|
||||
rp, err := RP.ParseRuleProvider(name, mapping, R.ParseRule, RB.MakeBundleFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1386,16 +1409,17 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
|
||||
}
|
||||
|
||||
dnsCfg := &DNS{
|
||||
Enable: cfg.Enable,
|
||||
Listen: cfg.Listen,
|
||||
PreferH3: cfg.PreferH3,
|
||||
IPv6Timeout: cfg.IPv6Timeout,
|
||||
IPv6: cfg.IPv6,
|
||||
UseHosts: cfg.UseHosts,
|
||||
UseSystemHosts: cfg.UseSystemHosts,
|
||||
EnhancedMode: cfg.EnhancedMode,
|
||||
CacheAlgorithm: cfg.CacheAlgorithm,
|
||||
CacheMaxSize: cfg.CacheMaxSize,
|
||||
Enable: cfg.Enable,
|
||||
Listen: cfg.Listen,
|
||||
ListenRoutingMark: cfg.ListenRoutingMark,
|
||||
PreferH3: cfg.PreferH3,
|
||||
IPv6Timeout: cfg.IPv6Timeout,
|
||||
IPv6: cfg.IPv6,
|
||||
UseHosts: cfg.UseHosts,
|
||||
UseSystemHosts: cfg.UseSystemHosts,
|
||||
EnhancedMode: cfg.EnhancedMode,
|
||||
CacheAlgorithm: cfg.CacheAlgorithm,
|
||||
CacheMaxSize: cfg.CacheMaxSize,
|
||||
}
|
||||
var err error
|
||||
if dnsCfg.NameServer, err = parseNameServer(cfg.NameServer, cfg.RespectRules, cfg.PreferH3); err != nil {
|
||||
@@ -1572,6 +1596,7 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
|
||||
dnsCfg.FallbackDomainFilter = append(dnsCfg.FallbackDomainFilter, matcher)
|
||||
}
|
||||
}
|
||||
dnsCfg.FallbackLazyQuery = cfg.FallbackLazyQuery
|
||||
}
|
||||
|
||||
return dnsCfg, nil
|
||||
@@ -1692,6 +1717,7 @@ func parseTun(rawTun RawTun, dns *DNS, general *General) error {
|
||||
ExcludeMACAddress: rawTun.ExcludeMACAddress,
|
||||
EndpointIndependentNat: rawTun.EndpointIndependentNat,
|
||||
UDPTimeout: rawTun.UDPTimeout,
|
||||
ICMPTimeout: rawTun.ICMPTimeout,
|
||||
DisableICMPForwarding: rawTun.DisableICMPForwarding,
|
||||
FileDescriptor: rawTun.FileDescriptor,
|
||||
|
||||
|
||||
@@ -21,6 +21,8 @@ const (
|
||||
RejectDrop
|
||||
Compatible
|
||||
Pass
|
||||
PassRule
|
||||
Rematch
|
||||
Dns
|
||||
|
||||
Relay
|
||||
@@ -183,6 +185,10 @@ func (at AdapterType) String() string {
|
||||
return "Compatible"
|
||||
case Pass:
|
||||
return "Pass"
|
||||
case PassRule:
|
||||
return "PassRule"
|
||||
case Rematch:
|
||||
return "Rematch"
|
||||
case Dns:
|
||||
return "Dns"
|
||||
case Shadowsocks:
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package constant
|
||||
|
||||
import "net"
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
)
|
||||
|
||||
type Listener interface {
|
||||
RawAddress() string
|
||||
@@ -27,3 +30,8 @@ type InboundConfig interface {
|
||||
Name() string
|
||||
Equal(config InboundConfig) bool
|
||||
}
|
||||
|
||||
type InboundListenConfig interface {
|
||||
Listen(ctx context.Context, network, address string) (net.Listener, error)
|
||||
ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error)
|
||||
}
|
||||
@@ -28,6 +28,7 @@ const (
|
||||
SOCKS4
|
||||
SOCKS5
|
||||
SHADOWSOCKS
|
||||
SNELL
|
||||
VMESS
|
||||
VLESS
|
||||
REDIR
|
||||
@@ -92,6 +93,8 @@ func (t Type) String() string {
|
||||
return "Socks5"
|
||||
case SHADOWSOCKS:
|
||||
return "ShadowSocks"
|
||||
case SNELL:
|
||||
return "Snell"
|
||||
case VMESS:
|
||||
return "Vmess"
|
||||
case VLESS:
|
||||
@@ -138,6 +141,8 @@ func ParseType(t string) (*Type, error) {
|
||||
res = SOCKS5
|
||||
case "SHADOWSOCKS":
|
||||
res = SHADOWSOCKS
|
||||
case "SNELL":
|
||||
res = SNELL
|
||||
case "VMESS":
|
||||
res = VMESS
|
||||
case "VLESS":
|
||||
@@ -192,6 +197,7 @@ type Metadata struct {
|
||||
InPort uint16 `json:"inboundPort,string"` // `,string` is used to compatible with old version json output
|
||||
InName string `json:"inboundName"`
|
||||
InUser string `json:"inboundUser"`
|
||||
RematchName string `json:"rematchName"`
|
||||
Host string `json:"host"`
|
||||
DNSMode DNSMode `json:"dnsMode"`
|
||||
Uid uint32 `json:"uid"`
|
||||
|
||||
+23
-3
@@ -15,9 +15,10 @@ import (
|
||||
const Name = "mihomo"
|
||||
|
||||
var (
|
||||
GeositeName = "GeoSite.dat"
|
||||
GeoipName = "GeoIP.dat"
|
||||
ASNName = "ASN.mmdb"
|
||||
GeositeName = "GeoSite.dat"
|
||||
GeoipName = "GeoIP.dat"
|
||||
ASNName = "ASN.mmdb"
|
||||
BundleMRSName = "BundleMRS.7z"
|
||||
)
|
||||
|
||||
// Path is used to get the configuration path
|
||||
@@ -162,6 +163,25 @@ func (p *path) ASN() string {
|
||||
return P.Join(p.homeDir, ASNName)
|
||||
}
|
||||
|
||||
func (p *path) BundleMRS() string {
|
||||
files, err := os.ReadDir(p.homeDir)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, fi := range files {
|
||||
if fi.IsDir() {
|
||||
// 目录则直接跳过
|
||||
continue
|
||||
} else {
|
||||
if strings.EqualFold(fi.Name(), "BundleMRS.7z") {
|
||||
BundleMRSName = fi.Name()
|
||||
return P.Join(p.homeDir, fi.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
return P.Join(p.homeDir, BundleMRSName)
|
||||
}
|
||||
|
||||
func (p *path) OldCache() string {
|
||||
return P.Join(p.homeDir, ".cache")
|
||||
}
|
||||
|
||||
+6
-2
@@ -31,6 +31,7 @@ const (
|
||||
ProcessPathRegex
|
||||
ProcessNameWildcard
|
||||
ProcessPathWildcard
|
||||
RematchName
|
||||
RuleSet
|
||||
Network
|
||||
Uid
|
||||
@@ -97,6 +98,8 @@ func (rt RuleType) String() string {
|
||||
return "ProcessNameWildcard"
|
||||
case ProcessPathWildcard:
|
||||
return "ProcessPathWildcard"
|
||||
case RematchName:
|
||||
return "RematchName"
|
||||
case MATCH:
|
||||
return "Match"
|
||||
case RuleSet:
|
||||
@@ -150,8 +153,9 @@ type RuleWrapper interface {
|
||||
}
|
||||
|
||||
type RuleMatchHelper struct {
|
||||
ResolveIP func()
|
||||
FindProcess func()
|
||||
ResolveIP func()
|
||||
FindProcess func()
|
||||
CheckPassRule func(adapterName string) bool
|
||||
}
|
||||
|
||||
type RuleGroup interface {
|
||||
|
||||
+2
-1
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
@@ -87,7 +88,7 @@ func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error)
|
||||
|
||||
func (c *client) ResetConnection() {}
|
||||
|
||||
func newClient(addr string, resolver *Resolver, netType string, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *client {
|
||||
func newClient(addr string, resolver resolver.Resolver, netType string, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *client {
|
||||
host, port, _ := net.SplitHostPort(addr)
|
||||
c := &client{
|
||||
port: port,
|
||||
|
||||
+2
-1
@@ -14,6 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/component/ca"
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
@@ -74,7 +75,7 @@ type dnsOverHTTPS struct {
|
||||
var _ dnsClient = (*dnsOverHTTPS)(nil)
|
||||
|
||||
// newDoH returns the DNS-over-HTTPS Upstream.
|
||||
func newDoHClient(urlString string, r *Resolver, preferH3 bool, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) dnsClient {
|
||||
func newDoHClient(urlString string, r resolver.Resolver, preferH3 bool, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) dnsClient {
|
||||
u, _ := url.Parse(urlString)
|
||||
httpVersions := DefaultHTTPVersions
|
||||
if preferH3 {
|
||||
|
||||
+49
-41
@@ -5,14 +5,17 @@ import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/contextutils"
|
||||
"github.com/metacubex/mihomo/common/pool"
|
||||
"github.com/metacubex/mihomo/component/ca"
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
@@ -65,7 +68,7 @@ type dnsOverQUIC struct {
|
||||
var _ dnsClient = (*dnsOverQUIC)(nil)
|
||||
|
||||
// newDoQ returns the DNS-over-QUIC Upstream.
|
||||
func newDoQ(addr string, resolver *Resolver, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *dnsOverQUIC {
|
||||
func newDoQ(addr string, resolver resolver.Resolver, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *dnsOverQUIC {
|
||||
doq := &dnsOverQUIC{
|
||||
addr: addr,
|
||||
dialer: newDNSDialer(resolver, proxyAdapter, proxyName),
|
||||
@@ -112,7 +115,7 @@ func (doq *dnsOverQUIC) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.M
|
||||
// make DoQ usable. We need to make 2 attempts in the case when the
|
||||
// connection was closed (due to inactivity for example) AND the server
|
||||
// refuses to open a 0-RTT connection.
|
||||
for i := 0; hasConnection && doq.shouldRetry(err) && i < 2; i++ {
|
||||
for i := 0; hasConnection && doq.shouldRetry(err) && ctx.Err() == nil && i < 2; i++ {
|
||||
log.Debugln("re-creating the QUIC connection and retrying due to %v", err)
|
||||
|
||||
// Close the active connection to make sure we'll try to re-connect.
|
||||
@@ -152,25 +155,39 @@ func (doq *dnsOverQUIC) ResetConnection() {
|
||||
// exchangeQUIC attempts to open a QUIC connection, send the DNS message
|
||||
// through it and return the response it got from the server.
|
||||
func (doq *dnsOverQUIC) exchangeQUIC(ctx context.Context, msg *D.Msg) (resp *D.Msg, err error) {
|
||||
// All DNS messages (queries and responses) sent over DoQ connections MUST
|
||||
// be encoded as a 2-octet length field followed by the message content as
|
||||
// specified in [RFC1035].
|
||||
// Note: we do not support receiving multiple messages over a single connection.
|
||||
buf := pool.Get(2 + MaxMsgSize)
|
||||
defer pool.Put(buf)
|
||||
b, err := msg.PackBuffer(buf[2:])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to pack DNS message for DoQ: %w", err)
|
||||
}
|
||||
if len(b) > MaxMsgSize {
|
||||
return nil, fmt.Errorf("DNS message is too large: %d > %d", len(b), MaxMsgSize)
|
||||
}
|
||||
binary.BigEndian.PutUint16(buf, uint16(len(b)))
|
||||
|
||||
var conn *quic.Conn
|
||||
conn, err = doq.getConnection(ctx, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var buf []byte
|
||||
buf, err = msg.Pack()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to pack DNS message for DoQ: %w", err)
|
||||
}
|
||||
|
||||
var stream *quic.Stream
|
||||
stream, err = doq.openStream(ctx, conn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = stream.Write(AddPrefix(buf))
|
||||
stop := contextutils.AfterFunc(ctx, func() {
|
||||
_ = stream.SetDeadline(time.Now()) // cancel any read or write operation on this stream
|
||||
})
|
||||
defer stop()
|
||||
|
||||
_, err = stream.Write(buf[:2+len(b)])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to write to a QUIC stream: %w", err)
|
||||
}
|
||||
@@ -181,16 +198,31 @@ func (doq *dnsOverQUIC) exchangeQUIC(ctx context.Context, msg *D.Msg) (resp *D.M
|
||||
// write-direction of the stream, but does not prevent reading from it.
|
||||
_ = stream.Close()
|
||||
|
||||
return doq.readMsg(stream)
|
||||
}
|
||||
// -- reading the response ---
|
||||
var respLen uint16
|
||||
err = binary.Read(stream, binary.BigEndian, &respLen)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading response length from %s: %w", doq.Address(), err)
|
||||
}
|
||||
if respLen == 0 {
|
||||
return nil, fmt.Errorf("received empty response from %s", doq.Address())
|
||||
}
|
||||
if respLen > MaxMsgSize {
|
||||
return nil, fmt.Errorf("received response that is too large: %d > %d", respLen, MaxMsgSize)
|
||||
}
|
||||
|
||||
// AddPrefix adds a 2-byte prefix with the DNS message length.
|
||||
func AddPrefix(b []byte) (m []byte) {
|
||||
m = make([]byte, 2+len(b))
|
||||
binary.BigEndian.PutUint16(m, uint16(len(b)))
|
||||
copy(m[2:], b)
|
||||
_, err = io.ReadFull(stream, buf[:respLen])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading response from %s: %w", doq.Address(), err)
|
||||
}
|
||||
|
||||
return m
|
||||
resp = new(D.Msg)
|
||||
err = resp.Unpack(buf[:respLen])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unpacking response from %s: %w", doq.Address(), err)
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// shouldRetry checks what error we received and decides whether it is required
|
||||
@@ -363,30 +395,6 @@ func (doq *dnsOverQUIC) closeConnWithError(err error) {
|
||||
doq.conn = nil
|
||||
}
|
||||
|
||||
// readMsg reads the incoming DNS message from the QUIC stream.
|
||||
func (doq *dnsOverQUIC) readMsg(stream *quic.Stream) (m *D.Msg, err error) {
|
||||
respBuf := pool.Get(MaxMsgSize)
|
||||
defer pool.Put(respBuf)
|
||||
|
||||
n, err := stream.Read(respBuf)
|
||||
if err != nil && n == 0 {
|
||||
return nil, fmt.Errorf("reading response from %s: %w", doq.Address(), err)
|
||||
}
|
||||
|
||||
// All DNS messages (queries and responses) sent over DoQ connections MUST
|
||||
// be encoded as a 2-octet length field followed by the message content as
|
||||
// specified in [RFC1035].
|
||||
// IMPORTANT: Note, that we ignore this prefix here as this implementation
|
||||
// does not support receiving multiple messages over a single connection.
|
||||
m = new(D.Msg)
|
||||
err = m.Unpack(respBuf[2:])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unpacking response from %s: %w", doq.Address(), err)
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// newQUICTokenStore creates a new quic.TokenStore that is necessary to have
|
||||
// in order to benefit from 0-RTT.
|
||||
func newQUICTokenStore() (s quic.TokenStore) {
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ package dns
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
"net"
|
||||
"runtime"
|
||||
"sync"
|
||||
@@ -159,7 +160,7 @@ func (t *dnsOverTLS) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func newDoTClient(addr string, resolver *Resolver, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *dnsOverTLS {
|
||||
func newDoTClient(addr string, resolver resolver.Resolver, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *dnsOverTLS {
|
||||
host, port, _ := net.SplitHostPort(addr)
|
||||
c := &dnsOverTLS{
|
||||
port: port,
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
)
|
||||
|
||||
type ResolverEnhancer struct {
|
||||
ipv6 bool
|
||||
mode C.DNSMode
|
||||
fakeIPPool *fakeip.Pool
|
||||
fakeIPPool6 *fakeip.Pool
|
||||
@@ -169,6 +170,7 @@ type EnhancerConfig struct {
|
||||
|
||||
func NewEnhancer(cfg EnhancerConfig) *ResolverEnhancer {
|
||||
e := &ResolverEnhancer{
|
||||
ipv6: cfg.IPv6,
|
||||
mode: cfg.EnhancedMode,
|
||||
useHosts: cfg.UseHosts,
|
||||
}
|
||||
|
||||
+4
-4
@@ -196,14 +196,14 @@ func withFakeIP(skipper *fakeip.Skipper, fakePool *fakeip.Pool, fakePool6 *fakei
|
||||
}
|
||||
}
|
||||
|
||||
func withResolver(resolver *Resolver) handler {
|
||||
func withResolver(resolver resolver.Resolver, ipv6 bool) handler {
|
||||
return func(ctx *icontext.DNSContext, r *D.Msg) (*D.Msg, error) {
|
||||
ctx.SetType(icontext.DNSTypeRaw)
|
||||
|
||||
q := r.Question[0]
|
||||
|
||||
// return a empty AAAA msg when ipv6 disabled
|
||||
if !resolver.ipv6 && q.Qtype == D.TypeAAAA {
|
||||
if !ipv6 && q.Qtype == D.TypeAAAA {
|
||||
return handleMsgWithEmptyAnswer(r), nil
|
||||
}
|
||||
|
||||
@@ -230,7 +230,7 @@ func compose(middlewares []middleware, endpoint handler) handler {
|
||||
return h
|
||||
}
|
||||
|
||||
func newHandler(resolver *Resolver, mapper *ResolverEnhancer) handler {
|
||||
func newHandler(resolver resolver.Resolver, mapper *ResolverEnhancer) handler {
|
||||
var middlewares []middleware
|
||||
|
||||
if mapper.useHosts {
|
||||
@@ -245,5 +245,5 @@ func newHandler(resolver *Resolver, mapper *ResolverEnhancer) handler {
|
||||
middlewares = append(middlewares, withMapping(mapper.mapping))
|
||||
}
|
||||
|
||||
return compose(middlewares, withResolver(resolver))
|
||||
return compose(middlewares, withResolver(resolver, mapper.ipv6))
|
||||
}
|
||||
+12
-2
@@ -43,6 +43,7 @@ type Resolver struct {
|
||||
fallback []dnsClient
|
||||
fallbackDomainFilters []C.DomainMatcher
|
||||
fallbackIPFilters []C.IpMatcher
|
||||
fallbackLazyQuery bool
|
||||
group singleflight.Group[*D.Msg]
|
||||
cache dnsCache
|
||||
policy []dnsPolicy
|
||||
@@ -310,12 +311,16 @@ func (r *Resolver) ipExchange(ctx context.Context, m *D.Msg) (msg *D.Msg, err er
|
||||
|
||||
msgCh := r.asyncExchange(ctx, r.main, m)
|
||||
|
||||
if r.fallback == nil || len(r.fallback) == 0 { // directly return if no fallback servers are available
|
||||
if r.fallback == nil { // directly return if no fallback servers are available
|
||||
res := <-msgCh
|
||||
msg, err = res.Msg, res.Error
|
||||
return
|
||||
}
|
||||
|
||||
var fallbackMsg <-chan *result
|
||||
if !r.fallbackLazyQuery {
|
||||
fallbackMsg = r.asyncExchange(ctx, r.fallback, m)
|
||||
}
|
||||
res := <-msgCh
|
||||
if res.Error == nil {
|
||||
if ips := msgToIP(res.Msg); len(ips) != 0 {
|
||||
@@ -329,7 +334,10 @@ func (r *Resolver) ipExchange(ctx context.Context, m *D.Msg) (msg *D.Msg, err er
|
||||
}
|
||||
}
|
||||
|
||||
res = <-r.asyncExchange(ctx, r.fallback, m)
|
||||
if fallbackMsg == nil {
|
||||
fallbackMsg = r.asyncExchange(ctx, r.fallback, m)
|
||||
}
|
||||
res = <-fallbackMsg
|
||||
msg, err = res.Msg, res.Error
|
||||
return
|
||||
}
|
||||
@@ -443,6 +451,7 @@ type Config struct {
|
||||
IPv6Timeout uint
|
||||
FallbackIPFilter []C.IpMatcher
|
||||
FallbackDomainFilter []C.DomainMatcher
|
||||
FallbackLazyQuery bool
|
||||
Policy []Policy
|
||||
ProxyServerPolicy []Policy
|
||||
CacheAlgorithm string
|
||||
@@ -584,6 +593,7 @@ func NewResolver(config Config) (rs Resolvers) {
|
||||
r.fallback = cacheTransform(config.Fallback)
|
||||
r.fallbackIPFilters = config.FallbackIPFilter
|
||||
r.fallbackDomainFilters = config.FallbackDomainFilter
|
||||
r.fallbackLazyQuery = config.FallbackLazyQuery
|
||||
}
|
||||
|
||||
return
|
||||
|
||||
+5
-5
@@ -4,9 +4,9 @@ import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/metacubex/mihomo/adapter/inbound"
|
||||
"github.com/metacubex/mihomo/common/sockopt"
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
D "github.com/miekg/dns"
|
||||
@@ -43,7 +43,7 @@ func (s *Server) SetService(service resolver.Service) {
|
||||
s.service = service
|
||||
}
|
||||
|
||||
func ReCreateServer(addr string, service resolver.Service) {
|
||||
func ReCreateServer(addr string, lc C.InboundListenConfig, service resolver.Service) {
|
||||
if addr == address && service != nil {
|
||||
server.SetService(service)
|
||||
return
|
||||
@@ -62,7 +62,7 @@ func ReCreateServer(addr string, service resolver.Service) {
|
||||
server.service = nil
|
||||
address = ""
|
||||
|
||||
if addr == "" || service == nil {
|
||||
if addr == "" || lc == nil || service == nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ func ReCreateServer(addr string, service resolver.Service) {
|
||||
server = &Server{service: service}
|
||||
|
||||
go func() {
|
||||
p, err := inbound.ListenPacket("udp", addr)
|
||||
p, err := lc.ListenPacket(context.Background(), "udp", addr)
|
||||
if err != nil {
|
||||
log.Errorln("Start DNS server(UDP) error: %s", err.Error())
|
||||
return
|
||||
@@ -98,7 +98,7 @@ func ReCreateServer(addr string, service resolver.Service) {
|
||||
}()
|
||||
|
||||
go func() {
|
||||
l, err := inbound.Listen("tcp", addr)
|
||||
l, err := lc.Listen(context.Background(), "tcp", addr)
|
||||
if err != nil {
|
||||
log.Errorln("Start DNS server(TCP) error: %s", err.Error())
|
||||
return
|
||||
|
||||
+1
-1
@@ -24,6 +24,6 @@ func (s *Service) ServeMsg(ctx context.Context, msg *D.Msg) (*D.Msg, error) {
|
||||
|
||||
var _ resolver.Service = (*Service)(nil)
|
||||
|
||||
func NewService(resolver *Resolver, mapper *ResolverEnhancer) *Service {
|
||||
func NewService(resolver resolver.Resolver, mapper *ResolverEnhancer) *Service {
|
||||
return &Service{handler: newHandler(resolver, mapper)}
|
||||
}
|
||||
+1
-1
@@ -113,7 +113,7 @@ func isIPRequest(q D.Question) bool {
|
||||
return q.Qclass == D.ClassINET && (q.Qtype == D.TypeA || q.Qtype == D.TypeAAAA || q.Qtype == D.TypeCNAME)
|
||||
}
|
||||
|
||||
func transform(servers []NameServer, resolver *Resolver) []dnsClient {
|
||||
func transform(servers []NameServer, resolver resolver.Resolver) []dnsClient {
|
||||
ret := make([]dnsClient, 0, len(servers))
|
||||
for _, s := range servers {
|
||||
var c dnsClient
|
||||
|
||||
+264
-35
@@ -83,6 +83,9 @@ external-controller-unix: mihomo.sock
|
||||
# !!!注意: 从Windows namedpipe访问api接口不会验证secret, 如果开启请自行保证安全问题 !!!
|
||||
external-controller-pipe: \\.\pipe\mihomo
|
||||
|
||||
# 为 external-controller 和 external-controller-tls 的监听socket设置routing-mark(仅支持linux)
|
||||
external-controller-routing-mark: 0
|
||||
|
||||
# tcp-concurrent: true # TCP 并发连接所有 IP, 将使用最快握手的 TCP
|
||||
|
||||
# 配置 WEB UI 目录,使用 http://{{external-controller}}/ui 访问
|
||||
@@ -335,18 +338,20 @@ dns:
|
||||
|
||||
# 配置 fallback 使用条件
|
||||
# fallback-filter:
|
||||
# geoip: true # 配置是否使用 geoip
|
||||
# geoip-code: CN # 当 nameserver 域名的 IP 查询 geoip 库为 CN 时,不使用 fallback 中的 DNS 查询结果
|
||||
# 配置强制 fallback,优先于 IP 判断,具体分类自行查看 geosite 库
|
||||
# geosite:
|
||||
# - gfw
|
||||
# 如果不匹配 ipcidr 则使用 nameservers 中的结果
|
||||
# ipcidr:
|
||||
# geoip: true # 配置是否使用 geoip
|
||||
# geoip-code: CN # 当 nameserver 解析出域名的 IP 查询 geoip 库为 CN 时, 使用 nameserver 中的 DNS 查询结果
|
||||
# ipcidr: # 当 nameserver 解析出域名的 IP 匹配 ipcidr 时,使用 fallback 中的 DNS 查询结果
|
||||
# - 240.0.0.0/4
|
||||
# domain:
|
||||
# - 0.0.0.0/32
|
||||
# - 127.0.0.1/32
|
||||
# - 100.64.0.0/10
|
||||
# domain: # 匹配到这些域名,会直接使用 fallback 解析,不去使用 nameserver
|
||||
# - '+.google.com'
|
||||
# - '+.facebook.com'
|
||||
# - '+.youtube.com'
|
||||
# geosite: # 匹配到这些域名,会直接使用 fallback 解析,不去使用 nameserver(已废弃,请使用 nameserver-policy)
|
||||
# - gfw
|
||||
# fallback-lazy-query: false # 默认值为 false ,如果为 true 会先判断来自 nameserver 的结果是否满足 fallback-filter 后再发起查询
|
||||
|
||||
# 配置查询域名使用的 DNS 服务器
|
||||
nameserver-policy:
|
||||
@@ -394,16 +399,32 @@ proxies: # socks5
|
||||
# ip-version: dual
|
||||
|
||||
# Snell
|
||||
# Beware that there's currently no UDP support yet
|
||||
- name: "snell"
|
||||
type: snell
|
||||
server: server
|
||||
port: 44046
|
||||
psk: yourpsk
|
||||
# version: 2
|
||||
# version: 4 # support 1/2/3/4/5
|
||||
# udp: true # support UDP on version 3/4/5
|
||||
# reuse: false # v4/5 only
|
||||
# obfs-opts:
|
||||
# mode: http # or tls
|
||||
# host: bing.com
|
||||
# mode: http # or tls/shadow-tls
|
||||
|
||||
- name: "snell-shadow-tls"
|
||||
type: snell
|
||||
server: server
|
||||
port: 44046
|
||||
psk: yourpsk
|
||||
# version: 4 # support 1/2/3/4/5
|
||||
# udp: true # support UDP on version 3/4/5
|
||||
# reuse: false # v4/5 only
|
||||
# client-fingerprint: chrome
|
||||
obfs-opts:
|
||||
mode: shadow-tls
|
||||
host: bing.com
|
||||
password: "shadow_tls_password"
|
||||
version: 2 # support 1/2/3
|
||||
alpn: ["h2","http/1.1"]
|
||||
|
||||
# Shadowsocks
|
||||
# cipher支持:
|
||||
@@ -657,6 +678,31 @@ proxies: # socks5
|
||||
# client-fingerprint: chrome # Available: "chrome","firefox","safari","ios","random", currently only support TLS transport in TCP/GRPC/WS/HTTP for VLESS/Vmess and trojan.
|
||||
# skip-cert-verify: true
|
||||
# servername: example.com # priority over wss host
|
||||
# 如果填写 tlsmirror-opts 则开启 tlsmirror(当 tls: true 时),servername 和 alpn 使用上层配置
|
||||
# tlsmirror-opts:
|
||||
# primary-key: MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY= # 必填,32 字节主密钥的 base64 编码
|
||||
# explicit-nonce-ciphersuites: [156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 49195, 49196, 49197, 49198, 49199, 49200, 49201, 49202, 49290, 49291, 49293, 49316, 49317, 49318, 49319, 49320, 49321, 49322, 49323, 49324, 49325, 49326, 49327, 52392, 52393, 52394, 52395, 52396, 52397, 52398] # TLS 1.2 载体使用显式 nonce 的加密套件
|
||||
# defer-instance-derived-write-time: # 首次写入前的延迟
|
||||
# base-nanoseconds: 0 # 固定延迟,单位纳秒
|
||||
# uniform-random-multiplier-nanoseconds: 0 # 额外随机延迟上限,单位纳秒
|
||||
# transport-layer-padding: # 启用传输层填充
|
||||
# enabled: false
|
||||
# connection-enrolment: # 启用 v2ray 兼容的连接登记确认
|
||||
# primary-egress-outbound: "" # mihomo VMess outbound 保持为空;v2ray 可填写专用的控制出站 tag
|
||||
# sequence-watermarking-enabled: false # 启用序列水印
|
||||
# embedded-traffic-generator: # 生成额外的 HTTP 载体流量,协议由 alpn 决定
|
||||
# steps:
|
||||
# - host: example.com
|
||||
# path: /
|
||||
# method: GET
|
||||
# connection-ready: true # 此步骤完成后再交付代理连接
|
||||
# connection-recall-exit: true # 代理连接关闭后退出载体流量
|
||||
# h2-do-not-wait-for-download-finish: false # h2 下不等待响应体读取完成
|
||||
# wait-time:
|
||||
# base-nanoseconds: 1000000000
|
||||
# next-step:
|
||||
# - weight: 1
|
||||
# goto-location: 0
|
||||
# network: ws
|
||||
# ech-opts:
|
||||
# enable: true # 必须手动开启
|
||||
@@ -672,6 +718,51 @@ proxies: # socks5
|
||||
# v2ray-http-upgrade: false
|
||||
# v2ray-http-upgrade-fast-open: false
|
||||
|
||||
- name: "vmess-mkcp"
|
||||
type: vmess
|
||||
server: server
|
||||
port: 443
|
||||
uuid: uuid
|
||||
alterId: 32
|
||||
cipher: auto
|
||||
network: mkcp
|
||||
mkcp-opts:
|
||||
mtu: 1350 # 最大传输单元
|
||||
tti: 50 # 传输时间间隔,单位毫秒
|
||||
uplink-capacity: 5 # 上行容量,单位 MB/s
|
||||
downlink-capacity: 20 # 下行容量,单位 MB/s
|
||||
congestion: false # 是否启用拥塞控制
|
||||
write-buffer: 2097152 # 写缓冲区大小,单位字节
|
||||
read-buffer: 2097152 # 读缓冲区大小,单位字节
|
||||
seed: "" # 启用 AES-GCM 认证时使用的种子,留空使用默认认证
|
||||
header: "" # 伪装包头,可选:none/srtp/utp/wechat-video/dtls/wireguard
|
||||
|
||||
- name: "vmess-mekya"
|
||||
type: vmess
|
||||
server: server
|
||||
port: 443
|
||||
uuid: uuid
|
||||
alterId: 32
|
||||
cipher: auto
|
||||
network: mekya
|
||||
tls: true
|
||||
mekya-opts:
|
||||
url: https://server:443/mekya
|
||||
max-write-delay: 80 # 首包后的最大聚合等待时间,单位毫秒
|
||||
max-request-size: 96000 # 单次 HTTP 请求的最大负载大小,单位字节
|
||||
polling-interval-initial: 200 # 空轮询间隔,单位毫秒
|
||||
h2-pool-size: 8 # HTTP/2 连接池大小
|
||||
kcp:
|
||||
mtu: 1350 # 最大传输单元
|
||||
tti: 15 # 传输时间间隔,单位毫秒
|
||||
uplink-capacity: 40 # 上行容量,单位 MB/s
|
||||
downlink-capacity: 2000 # 下行容量,单位 MB/s
|
||||
congestion: false # 是否启用拥塞控制
|
||||
write-buffer: 67108864 # 写缓冲区大小,单位字节
|
||||
read-buffer: 67108864 # 读缓冲区大小,单位字节
|
||||
seed: "" # 启用 AES-GCM 认证时使用的种子,留空使用默认认证
|
||||
header: "" # 伪装包头,可选:none/srtp/utp/wechat-video/dtls/wireguard
|
||||
|
||||
- name: "vmess-h2"
|
||||
type: vmess
|
||||
server: server
|
||||
@@ -1054,8 +1145,10 @@ proxies: # socks5
|
||||
# down: "200 Mbps" # 若不写单位,默认为 Mbps
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
password: yourpassword
|
||||
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前仅支持 salamander
|
||||
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前支持 salamander 和 gecko
|
||||
# obfs-password: yourpassword
|
||||
# obfs-min-packet-size: 512 # 最小线上数据包大小(字节)。仅限 Gecko。
|
||||
# obfs-max-packet-size: 1200 # 最大线上数据包大小(字节)。仅限 Gecko。
|
||||
# sni: server.com
|
||||
# ech-opts:
|
||||
# enable: true # 必须手动开启
|
||||
@@ -1169,8 +1262,9 @@ proxies: # socks5
|
||||
port: 1194
|
||||
proto: udp # udp/tcp,默认 udp
|
||||
# dev: tun # 目前仅支持 tun,默认 tun
|
||||
# cipher: AES-128-GCM # 支持 AES-128-GCM / AES-256-GCM,默认 AES-128-GCM
|
||||
# auth: SHA256 # 目前仅支持 SHA256,默认 SHA256
|
||||
# cipher: AES-128-GCM # 支持 AES-128-GCM / AES-192-GCM / AES-256-GCM / AES-128-CBC / AES-192-CBC / AES-256-CBC / CHACHA20-POLY1305,默认 AES-128-GCM;AES-CBC 会按 AES-128-CBC 处理
|
||||
# auth: SHA256 # 支持 MD5 / SHA1 / SHA256 / SHA384 / SHA512,默认 SHA256;AEAD cipher 会忽略 auth
|
||||
# comp-lzo: "no" # 可选值:"yes", "no", "adaptive"
|
||||
# username / password: auth-user-pass 模式(与下方 cert+key 二选一,不能都不填)
|
||||
# username: "user"
|
||||
# password: "pass"
|
||||
@@ -1189,12 +1283,18 @@ proxies: # socks5
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIE...example
|
||||
-----END PRIVATE KEY-----
|
||||
# 从 .ovpn 中复制 <tls-crypt></tls-crypt> 内的内容,不需要保留 <tls-crypt> 标签
|
||||
tls-crypt: |
|
||||
-----BEGIN OpenVPN Static key V1-----
|
||||
00000000000000000000000000000000
|
||||
...
|
||||
-----END OpenVPN Static key V1-----
|
||||
# 从 .ovpn 中复制 <tls-crypt></tls-crypt> 内的内容,不需要保留 <tls-crypt> 标签;没有 tls-crypt 的配置可省略
|
||||
# tls-crypt: |
|
||||
# -----BEGIN OpenVPN Static key V1-----
|
||||
# 00000000000000000000000000000000
|
||||
# ...
|
||||
# -----END OpenVPN Static key V1-----
|
||||
# peer-info: # 透传给服务端的 peer-info 键值对,追加在内置 IV_VER/IV_PROTO/IV_CIPHERS 之后;用于服务端基于 peer-info 做准入决策
|
||||
# IV_HWADDR: "52:54:00:ff:72:87"
|
||||
# UV_DEVICE_ID: "laptop-001"
|
||||
# ping: 10 # 默认值为 0
|
||||
# ping-restart: 60 # 默认值为 0
|
||||
# handshake-timeout: 30 # 单位为秒;配置后握手时不受外层连接超时影响;默认值为 0,表示仅使用外层连接超时
|
||||
# mtu: 1500
|
||||
udp: true
|
||||
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
|
||||
@@ -1218,6 +1318,23 @@ proxies: # socks5
|
||||
# remote-dns-resolve: true # 强制 dns 远程解析,默认值为 false
|
||||
# dns: [ 1.1.1.1, 8.8.8.8 ] # 仅在 remote-dns-resolve 为 true 时生效
|
||||
# congestion-controller: bbr # 默认不开启
|
||||
# handshake-timeout: 30 # 单位为秒;配置后握手时不受外层连接超时影响;默认值为 0,表示仅使用外层连接超时
|
||||
|
||||
# masque-h3-l4proxy
|
||||
- name: "masque-h3-l4proxy"
|
||||
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==
|
||||
udp: false # 目前 l4proxy 模式不支持 udp
|
||||
network: h3-l4proxy
|
||||
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
|
||||
# dialer-proxy: "ss1"
|
||||
# remote-dns-resolve: true # 强制 dns 远程解析,默认值为 false
|
||||
# dns: [ tls://1.1.1.1, tls://1.0.0.1 ] # 仅在 remote-dns-resolve 为 true 时生效
|
||||
# congestion-controller: bbr # 默认不开启
|
||||
# handshake-timeout: 30 # 单位为秒;配置后握手时不受外层连接超时影响;默认值为 0,表示仅使用外层连接超时
|
||||
|
||||
# masque-h2
|
||||
- name: "masque-h2"
|
||||
@@ -1235,6 +1352,7 @@ proxies: # socks5
|
||||
# dialer-proxy: "ss1"
|
||||
# remote-dns-resolve: true # 强制 dns 远程解析,默认值为 false
|
||||
# dns: [ 1.1.1.1, 8.8.8.8 ] # 仅在 remote-dns-resolve 为 true 时生效
|
||||
# handshake-timeout: 30 # 单位为秒;配置后握手时不受外层连接超时影响;默认值为 0,表示仅使用外层连接超时
|
||||
|
||||
# tuic
|
||||
- name: tuic
|
||||
@@ -1384,23 +1502,17 @@ proxies: # socks5
|
||||
- name: "dns-out"
|
||||
type: dns
|
||||
|
||||
- name: "rematch"
|
||||
type: rematch
|
||||
target-rematch-name: "rematch1" # 如果填写则覆盖原始 metadata 中的 rematch-name(可用REMATCH-NAME规则匹配)
|
||||
target-sub-rule: "sub-rule1" # 如果填写则接下来会直接用指定的 sub-rule 匹配,如果名字不存在或为空会回退到主rules
|
||||
|
||||
# 配置指定 interface-name 和 fwmark 的 DIRECT
|
||||
- name: en1-direct
|
||||
type: direct
|
||||
interface-name: en1
|
||||
routing-mark: 6667
|
||||
proxy-groups:
|
||||
# 代理链,目前 relay 可以支持 udp 的只有 vmess/vless/trojan/ss/ssr/tuic
|
||||
# wireguard 目前不支持在 relay 中使用,请使用 proxy 中的 dialer-proxy 配置项
|
||||
# Traffic: mihomo <-> http <-> vmess <-> ss1 <-> ss2 <-> Internet
|
||||
- name: "relay"
|
||||
type: relay
|
||||
proxies:
|
||||
- http
|
||||
- vmess
|
||||
- ss1
|
||||
- ss2
|
||||
|
||||
# url-test 将按照 url 测试结果使用延迟最低节点
|
||||
- name: "auto"
|
||||
type: url-test
|
||||
@@ -1444,6 +1556,7 @@ proxy-groups:
|
||||
- ss2
|
||||
- vmess1
|
||||
- auto
|
||||
# default-selected: ss1 # 默认选择的节点(该项为空或者设置的节点名不存在时,默认选择组中第一个节点)
|
||||
|
||||
- name: UseProvider
|
||||
type: select
|
||||
@@ -1453,6 +1566,7 @@ proxy-groups:
|
||||
proxies:
|
||||
- Proxy
|
||||
- DIRECT
|
||||
# empty-fallback: COMPATIBLE # 设置当组为空时的回退proxy(这里不支持填写代理组,只支持填写proxy名称)
|
||||
|
||||
# Mihomo 格式的节点或支持 *ray 的分享格式
|
||||
proxy-providers:
|
||||
@@ -1463,6 +1577,22 @@ proxy-providers:
|
||||
path: ./provider1.yaml # 默认只允许存储在 mihomo 的 Home Dir,如果想存储到其他位置,请通过设置 SAFE_PATHS 环境变量指定额外的安全路径。该环境变量的语法同本操作系统的PATH环境变量解析规则(即Windows下以分号分割,其他系统下以冒号分割)
|
||||
proxy: DIRECT
|
||||
# size-limit: 10240 # 限制下载文件最大为10kb,默认为0即不限制文件大小
|
||||
# #
|
||||
# # 如果设置会age-secret-key尝试通过此secret解密age armor格式加密的配置文件
|
||||
# #
|
||||
# # 注意:
|
||||
# # 对于加密内容,目前仅支持 age-encryption.org/v1 的 official ASCII "armor" format
|
||||
# # 对于key格式,目前仅支持 age-encryption.org/v1 的 x25519 recipient type 和 The mlkem768-x25519 hybrid post-quantum recipient type
|
||||
# # 实用工具:
|
||||
# # 您可以通过 "mihomo age keygen" 生成符合要求的 x25519 key
|
||||
# # 您可以通过 "mihomo age keygen-pq" 生成符合要求的 mlkem768-x25519 key
|
||||
# # 您可以通过 "mihomo age convert <secret_key>" 从 age-secret-key 导出 age-public-key
|
||||
# # 您可以通过 "mihomo age decrypt <secret_key> <source_file> <target_file>" 将已加密文件解密,<source_file> 为 - 时会从标准输入读取,<target_file> 为 - 时会往标准输出写入
|
||||
# # 您可以通过 "mihomo age encrypt <public_key> <source_file> <target_file>" 将未加密文件加密,<source_file> 为 - 时会从标准输入读取,<target_file> 为 - 时会往标准输出写入
|
||||
# # 参考实现:
|
||||
# # https://github.com/FiloSottile/awesome-age#implementations
|
||||
# #
|
||||
# age-secret-key: AGE-SECRET-KEY-1ZTQLLN0A4U3ZTT3DCZKYN0CGZEZQLWX2DFTXUWMT4ZHR0N2UG6LSW9NT0N
|
||||
header:
|
||||
User-Agent:
|
||||
- "Clash/v1.18.0"
|
||||
@@ -1471,6 +1601,8 @@ proxy-providers:
|
||||
# - 'application/vnd.github.v3.raw'
|
||||
# Authorization:
|
||||
# - 'token 1231231'
|
||||
# X-Age-Public-Key:
|
||||
# - 'age1xh86kh9v23vattr58yedspm3f57sxvnswu9krr6ns438amekx5gsd09uma'
|
||||
health-check:
|
||||
enable: true
|
||||
interval: 600
|
||||
@@ -1545,6 +1677,7 @@ rule-providers:
|
||||
format: mrs
|
||||
behavior: domain
|
||||
path: /path/to/save/file.mrs
|
||||
# path-in-bundle: "geo/geosite/cn.mrs" # 当设置该选项时,如果本地文件不存在,会优先从 Home Dir的 BundleMRS.7z 中解压该文件,此项的值用于指定在 BundleMRS.7z 中的路径
|
||||
rule4:
|
||||
type: inline
|
||||
behavior: domain # classical / ipcidr
|
||||
@@ -1596,6 +1729,7 @@ listeners:
|
||||
type: socks
|
||||
port: 10808 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
#listen: 0.0.0.0 # 默认监听 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理
|
||||
# udp: false # 默认 true
|
||||
@@ -1620,6 +1754,7 @@ listeners:
|
||||
type: http
|
||||
port: 10809 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||
# users: # 如果不填写users项,则遵从全局authentication设置,如果填写会忽略全局设置, 如想跳过该入站的验证可填写 users: []
|
||||
@@ -1643,6 +1778,7 @@ listeners:
|
||||
type: mixed # HTTP(S) 和 SOCKS 代理混合
|
||||
port: 10810 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||
# udp: false # 默认 true
|
||||
@@ -1682,6 +1818,7 @@ listeners:
|
||||
type: shadowsocks
|
||||
port: 10813 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||
password: vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg=
|
||||
@@ -1698,6 +1835,13 @@ listeners:
|
||||
# password: password
|
||||
# handshake:
|
||||
# dest: test.com:443
|
||||
# res-tls:
|
||||
# enable: false # 设置为true时开启
|
||||
# dest: test.com:443
|
||||
# password: password
|
||||
# restls-script: ""
|
||||
# min-record-len: 0
|
||||
# proxy: ""
|
||||
# kcp-tun:
|
||||
# enable: false
|
||||
# key: it's a secrect # pre-shared secret between client and server
|
||||
@@ -1725,10 +1869,34 @@ listeners:
|
||||
# streambuf: 2097152 # per stream receive buffer in bytes, smux v2+
|
||||
# keepalive: 10 # seconds between heartbeats
|
||||
|
||||
- name: snell-in-1
|
||||
type: snell
|
||||
port: 10815 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
psk: your-password
|
||||
version: 4 # 支持 1/2/3/4/5
|
||||
udp: true # UDP over TCP tunnel,默认 true
|
||||
# obfs-opts:
|
||||
# mode: http # 可选:http / tls
|
||||
# host: bing.com
|
||||
# shadow-tls:
|
||||
# enable: false # 设置为true时开启
|
||||
# version: 3 # 支持v1/v2/v3
|
||||
# password: password # v2设置项
|
||||
# users: # v3设置项
|
||||
# - name: 1
|
||||
# password: password
|
||||
# handshake:
|
||||
# dest: test.com:443
|
||||
# rule: sub-rule-name1
|
||||
# proxy: proxy
|
||||
|
||||
- name: vmess-in-1
|
||||
type: vmess
|
||||
port: 10814 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||
users:
|
||||
@@ -1737,6 +1905,35 @@ listeners:
|
||||
alterId: 1
|
||||
# ws-path: "/" # 如果不为空则开启 websocket 传输层
|
||||
# grpc-service-name: "GunService" # 如果不为空则开启 grpc 传输层
|
||||
# 如果填写 mekya-config 并设置 enable: true 则启用 v2ray 兼容的 Mekya 入站监听(不可与 mkcp/ws/grpc 同时使用)
|
||||
# mekya-config:
|
||||
# enable: true
|
||||
# max-write-size: 10485760 # 单个响应写回的最大负载大小,单位字节
|
||||
# max-write-duration-ms: 5000 # 单个响应写回的最大持续时间,单位毫秒
|
||||
# max-simultaneous-write-connection: 128 # 同一会话允许同时等待写回的请求数
|
||||
# packet-writing-buffer: 65536 # 写包缓冲区大小
|
||||
# kcp:
|
||||
# mtu: 1350 # 最大传输单元
|
||||
# tti: 15 # 传输时间间隔,单位毫秒
|
||||
# uplink-capacity: 40 # 上行容量,单位 MB/s
|
||||
# downlink-capacity: 2000 # 下行容量,单位 MB/s
|
||||
# congestion: false # 是否启用拥塞控制
|
||||
# write-buffer: 67108864 # 写缓冲区大小,单位字节
|
||||
# read-buffer: 67108864 # 读缓冲区大小,单位字节
|
||||
# seed: "" # 启用 AES-GCM 认证时使用的种子,留空使用默认认证
|
||||
# header: "" # 伪装包头,可选:none/srtp/utp/wechat-video/dtls/wireguard
|
||||
# 如果填写 mkcp-config 并设置 enable: true 则启用 v2ray 兼容的 mKCP 入站监听
|
||||
# mkcp-config:
|
||||
# enable: true
|
||||
# mtu: 1350 # 最大传输单元
|
||||
# tti: 50 # 传输时间间隔,单位毫秒
|
||||
# uplink-capacity: 5 # 上行容量,单位 MB/s
|
||||
# downlink-capacity: 20 # 下行容量,单位 MB/s
|
||||
# congestion: false # 是否启用拥塞控制
|
||||
# write-buffer: 2097152 # 写缓冲区大小,单位字节
|
||||
# read-buffer: 2097152 # 读缓冲区大小,单位字节
|
||||
# seed: "" # 启用 AES-GCM 认证时使用的种子,留空使用默认认证
|
||||
# header: "" # 伪装包头,可选:none/srtp/utp/wechat-video/dtls/wireguard
|
||||
# 下面两项如果填写则开启 tls(需要同时填写)
|
||||
# certificate: ./server.crt # 证书 PEM 格式,或者 证书的路径
|
||||
# private-key: ./server.key # 证书对应的私钥 PEM 格式,或者私钥路径
|
||||
@@ -1768,11 +1965,26 @@ listeners:
|
||||
# after-bytes: 0 # 传输指定字节后开始限速
|
||||
# bytes-per-sec: 0 # 基准速率(字节/秒)
|
||||
# burst-bytes-per-sec: 0 # 突发速率(字节/秒),大于 bytesPerSec 时生效
|
||||
# 如果填写tlsmirror-config则开启tlsmirror(注意不可与certificate和private-key同时填写)
|
||||
# tlsmirror-config:
|
||||
# dest: test.com:443
|
||||
# primary-key: MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY= # 必填,32 字节主密钥的 base64 编码
|
||||
# proxy: ""
|
||||
# explicit-nonce-ciphersuites: [156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 49195, 49196, 49197, 49198, 49199, 49200, 49201, 49202, 49290, 49291, 49293, 49316, 49317, 49318, 49319, 49320, 49321, 49322, 49323, 49324, 49325, 49326, 49327, 52392, 52393, 52394, 52395, 52396, 52397, 52398] # TLS 1.2 载体使用显式 nonce 的加密套件
|
||||
# defer-instance-derived-write-time: # 首次写入前的延迟
|
||||
# base-nanoseconds: 0 # 固定延迟,单位纳秒
|
||||
# uniform-random-multiplier-nanoseconds: 0 # 额外随机延迟上限,单位纳秒
|
||||
# transport-layer-padding: # 启用传输层填充
|
||||
# enabled: false
|
||||
# connection-enrolment: # 启用 v2ray 兼容的连接登记确认
|
||||
# primary-ingress-outbound: "" # v2ray 兼容字段,建议和对端路由中的控制出站 tag 一致
|
||||
# sequence-watermarking-enabled: false # 启用序列水印
|
||||
|
||||
- name: tuic-in-1
|
||||
type: tuic
|
||||
port: 10815 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||
# token: # tuicV4 填写(可以同时填写 users)
|
||||
@@ -1804,6 +2016,7 @@ listeners:
|
||||
type: tunnel
|
||||
port: 10816 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||
network: [tcp, udp]
|
||||
@@ -1813,6 +2026,7 @@ listeners:
|
||||
type: vless
|
||||
port: 10817 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||
users:
|
||||
@@ -1835,6 +2049,8 @@ listeners:
|
||||
# uplink-http-method: POST # Available: POST, PUT, PATCH, DELETE
|
||||
# session-placement: path # Available: path, query, cookie, header
|
||||
# session-key: ""
|
||||
# session-table: "" # Available: "", "uuid", "ALPHABET", "Alphabet", "BASE36", "Base62", "HEX", "alphabet", "base36", "hex", "number"
|
||||
# session-length: "16-32" # 起始值不可为 0,总的 id 空间必须大于 21 亿,仅当session-table不为空或uuid时生效
|
||||
# seq-placement: path # Available: path, query, cookie, header
|
||||
# seq-key: ""
|
||||
# uplink-data-placement: body # Available: body, cookie, header
|
||||
@@ -1887,12 +2103,14 @@ listeners:
|
||||
after-bytes: 0 # 传输指定字节后开始限速
|
||||
bytes-per-sec: 0 # 基准速率(字节/秒)
|
||||
burst-bytes-per-sec: 0 # 突发速率(字节/秒),大于 bytesPerSec 时生效
|
||||
### 注意,对于vless listener, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “decryption” 的其中一项 ###
|
||||
### 注意,对于vless listener, 如果 "allow-insecure" 不为 true, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “decryption” 的其中一项 ###
|
||||
# allow-insecure: false # 是否允许不开启tls加密(注意:仅用于有 nginx, caddy 前置的情况)
|
||||
|
||||
- name: anytls-in-1
|
||||
type: anytls
|
||||
port: 10818 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
users:
|
||||
username1: password1
|
||||
username2: password2
|
||||
@@ -1909,12 +2127,15 @@ listeners:
|
||||
# madSJjYQIf9o1N5GXjkW4DEEeb17qMxHdwMdNnwADAABAAEAAQACAAEAAwAIdGVz
|
||||
# dC5jb20AAA==
|
||||
# -----END ECH KEYS-----
|
||||
### 注意,anytls listener, 如果 "allow-insecure" 不为 true, 必须填写 “certificate和private-key” ###
|
||||
# allow-insecure: false # 是否允许不开启tls加密(注意:仅用于有 nginx, caddy 前置的情况)
|
||||
# padding-scheme: "" # https://github.com/anytls/anytls-go/blob/main/docs/protocol.md#cmdupdatepaddingscheme
|
||||
|
||||
- name: mieru-in-1
|
||||
type: mieru
|
||||
port: 10818 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
transport: TCP # 支持 TCP 或者 UDP
|
||||
users:
|
||||
username1: password1
|
||||
@@ -1928,6 +2149,7 @@ listeners:
|
||||
type: sudoku
|
||||
port: 8443 # 仅支持单端口
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
key: "<server_key>" # 如果你使用sudoku生成的ED25519密钥对,此处是密钥对中的公钥,当然,你也可以仅仅使用任意uuid充当key
|
||||
aead-method: chacha20-poly1305 # 可选:chacha20-poly1305、aes-128-gcm、none(不建议;none 不提供 AEAD 保护)
|
||||
padding-min: 1 # 最小填充率(0-100)
|
||||
@@ -1951,6 +2173,7 @@ listeners:
|
||||
type: trojan
|
||||
port: 10819 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||
users:
|
||||
@@ -1993,12 +2216,14 @@ listeners:
|
||||
# enabled: false
|
||||
# method: aes-128-gcm # aes-128-gcm/aes-256-gcm/chacha20-ietf-poly1305
|
||||
# password: "example"
|
||||
### 注意,对于trojan listener, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “ss-option” 的其中一项 ###
|
||||
### 注意,对于trojan listener, 如果 "allow-insecure" 不为 true, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “ss-option” 的其中一项 ###
|
||||
# allow-insecure: false # 是否允许不开启tls加密(注意:仅用于有 nginx, caddy 前置的情况)
|
||||
|
||||
- name: hysteria2-in-1
|
||||
type: hysteria2
|
||||
port: 10820 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||
users:
|
||||
@@ -2019,8 +2244,10 @@ listeners:
|
||||
## up 和 down 均不写或为 0 则使用 BBR 流控
|
||||
# up: "30 Mbps" # 若不写单位,默认为 Mbps
|
||||
# down: "200 Mbps" # 若不写单位,默认为 Mbps
|
||||
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前仅支持 salamander
|
||||
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前支持 salamander 和 gecko
|
||||
# obfs-password: yourpassword
|
||||
# obfs-min-packet-size: 512 # 最小线上数据包大小(字节)。仅限 Gecko。
|
||||
# obfs-max-packet-size: 1200 # 最大线上数据包大小(字节)。仅限 Gecko。
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
# max-idle-time: 15000
|
||||
# alpn:
|
||||
@@ -2049,6 +2276,7 @@ listeners:
|
||||
type: hysteria2-realm
|
||||
port: 10820 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
token: public # hysteria2入站和出站通过 `Authorization: Bearer <token>` 出示的 Bearer 令牌。
|
||||
max-realms: 65536 # maximum total realms (0 = unlimited)
|
||||
max-realms-per-ip: 4 # maximum realms per client IP (0 = unlimited)
|
||||
@@ -2073,6 +2301,7 @@ listeners:
|
||||
type: trusttunnel
|
||||
port: 10821 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
|
||||
listen: 0.0.0.0
|
||||
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
|
||||
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
|
||||
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
|
||||
users:
|
||||
|
||||
@@ -6,16 +6,17 @@ require (
|
||||
github.com/bahlo/generic-list-go v0.2.0
|
||||
github.com/coreos/go-iptables v0.8.0
|
||||
github.com/dlclark/regexp2 v1.12.0
|
||||
github.com/enfein/mieru/v3 v3.31.0
|
||||
github.com/enfein/mieru/v3 v3.34.0
|
||||
github.com/gobwas/ws v1.4.0
|
||||
github.com/gofrs/uuid/v5 v5.4.0
|
||||
github.com/golang/snappy v1.0.0
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d
|
||||
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20260612143004-19b4f1cdd5ec
|
||||
github.com/metacubex/bart v0.26.0
|
||||
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b
|
||||
github.com/metacubex/bbolt v0.0.0-20260706163408-d4ec34ad7c48
|
||||
github.com/metacubex/blake3 v0.1.0
|
||||
github.com/metacubex/chacha v0.1.5
|
||||
github.com/metacubex/chi v0.1.0
|
||||
github.com/metacubex/chi v0.1.1
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260412152424-e1625567920a
|
||||
github.com/metacubex/cpu v0.1.1
|
||||
github.com/metacubex/edwards25519 v1.2.0
|
||||
@@ -25,27 +26,29 @@ require (
|
||||
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604
|
||||
github.com/metacubex/mhurl v0.1.0
|
||||
github.com/metacubex/mlkem v0.1.0
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260606115121-0662b57ad5bf
|
||||
github.com/metacubex/randv2 v0.2.0
|
||||
github.com/metacubex/restls-client-go v0.1.7
|
||||
github.com/metacubex/restls-client-go v0.1.8
|
||||
github.com/metacubex/sevenzip v1.6.4
|
||||
github.com/metacubex/sing v0.5.7
|
||||
github.com/metacubex/sing-mux v0.3.9
|
||||
github.com/metacubex/sing-quic v0.0.0-20260512151354-8475655be853
|
||||
github.com/metacubex/sing-mux v0.3.10
|
||||
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3
|
||||
github.com/metacubex/sing-shadowsocks v0.2.12
|
||||
github.com/metacubex/sing-shadowsocks2 v0.2.7
|
||||
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2
|
||||
github.com/metacubex/sing-tun v0.4.18
|
||||
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc
|
||||
github.com/metacubex/sing-tun v0.4.21
|
||||
github.com/metacubex/sing-vmess v0.2.5
|
||||
github.com/metacubex/sing-wireguard v0.0.0-20260507084707-690d479ec947
|
||||
github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c
|
||||
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141
|
||||
github.com/metacubex/ssh v0.1.0
|
||||
github.com/metacubex/tailscale v0.0.0-20260516120020-a21c2c99dcbe
|
||||
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443
|
||||
github.com/metacubex/tls v0.1.5
|
||||
github.com/metacubex/utls v1.8.4
|
||||
github.com/metacubex/tailscale v0.0.0-20260623094802-1ab893d4162c
|
||||
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c
|
||||
github.com/metacubex/tls v0.1.7
|
||||
github.com/metacubex/utls v1.8.7
|
||||
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f
|
||||
github.com/mroth/weightedrand/v2 v2.1.0
|
||||
github.com/openacid/low v0.1.21
|
||||
github.com/rasky/go-lzo v0.0.0-20200203143853-96a758eda86e
|
||||
github.com/samber/lo v1.53.0
|
||||
github.com/sirupsen/logrus v1.9.4
|
||||
github.com/stretchr/testify v1.11.1
|
||||
@@ -75,10 +78,12 @@ require (
|
||||
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/ajg/form v1.7.1 // indirect
|
||||
github.com/akutz/memconn v0.1.0 // indirect
|
||||
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa // indirect
|
||||
github.com/andybalholm/brotli v1.0.6 // indirect
|
||||
github.com/andybalholm/brotli v1.1.1 // indirect
|
||||
github.com/bodgit/plumbing v1.3.0 // indirect
|
||||
github.com/bodgit/windows v1.0.1 // indirect
|
||||
github.com/coder/websocket v1.8.12 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dunglas/httpsfv v1.0.2 // indirect
|
||||
@@ -97,6 +102,7 @@ require (
|
||||
github.com/google/btree v1.1.3 // indirect
|
||||
github.com/google/go-cmp v0.6.0 // indirect
|
||||
github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/huin/goupnp v1.3.0 // indirect
|
||||
github.com/josharian/native v1.1.0 // indirect
|
||||
github.com/jsimonetti/rtnetlink v1.4.0 // indirect
|
||||
@@ -108,14 +114,14 @@ require (
|
||||
github.com/metacubex/gvisor v0.0.0-20251227095601-261ec1326fe8 // indirect
|
||||
github.com/metacubex/hkdf v0.1.0 // indirect
|
||||
github.com/metacubex/hpke v0.1.0 // indirect
|
||||
github.com/metacubex/jsonv2 v0.0.0-20260513175203-1c6abea7534c // indirect
|
||||
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df // indirect
|
||||
github.com/metacubex/nftables v0.0.0-20260426003805-208c2c1ba2cb // indirect
|
||||
github.com/metacubex/qpack v0.6.0 // indirect
|
||||
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260513233728-8bc7ee255d04 // indirect
|
||||
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260623093519-06ea214022e4 // indirect
|
||||
github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49 // indirect
|
||||
github.com/mitchellh/go-ps v1.0.0 // indirect
|
||||
github.com/oasisprotocol/deoxysii v0.0.0-20220228165953-2091330c22b7 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.14 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.27 // indirect
|
||||
github.com/pires/go-proxyproto v0.8.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/safchain/ethtool v0.3.0 // indirect
|
||||
@@ -123,11 +129,13 @@ require (
|
||||
github.com/sina-ghaderi/poly1305 v0.0.0-20220724002748-c5926b03988b // indirect
|
||||
github.com/sina-ghaderi/rabaead v0.0.0-20220730151906-ab6e06b96e8c // indirect
|
||||
github.com/sina-ghaderi/rabbitio v0.0.0-20220730151941-9ce26f4f872e // indirect
|
||||
github.com/stangelandcl/ppmd v0.1.1 // indirect
|
||||
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d // indirect
|
||||
github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 // indirect
|
||||
github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a // indirect
|
||||
github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc // indirect
|
||||
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 // indirect
|
||||
github.com/ulikunitz/xz v0.5.15 // indirect
|
||||
github.com/vishvananda/netns v0.0.5 // indirect
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
|
||||
github.com/x448/float16 v0.8.4 // indirect
|
||||
|
||||
@@ -3,17 +3,21 @@ github.com/RyuaNerin/go-krypto v1.3.0/go.mod h1:9R9TU936laAIqAmjcHo/LsaXYOZlymud
|
||||
github.com/RyuaNerin/testingutil v0.1.0 h1:IYT6JL57RV3U2ml3dLHZsVtPOP6yNK7WUVdzzlpNrss=
|
||||
github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344 h1:cDVUiFo+npB0ZASqnw4q90ylaVAbnYyx0JYqK4YcGok=
|
||||
github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344/go.mod h1:9pIqrY6SXNL8vjRQE5Hd/OL5GyK/9MrGUWs87z/eFfk=
|
||||
github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=
|
||||
github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=
|
||||
github.com/ajg/form v1.7.1 h1:OsnBDzTkrWdrxvEnO68I72ZVGJGNaMwPhoAm0V+llgc=
|
||||
github.com/ajg/form v1.7.1/go.mod h1:HL757PzLyNkj5AIfptT6L+iGNeXTlnrr/oDePGc/y7Q=
|
||||
github.com/akutz/memconn v0.1.0 h1:NawI0TORU4hcOMsMr11g7vwlCdkYeLKXBcxWu2W/P8A=
|
||||
github.com/akutz/memconn v0.1.0/go.mod h1:Jo8rI7m0NieZyLI5e2CDlRdRqRRB4S7Xp77ukDjH+Fw=
|
||||
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI=
|
||||
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
|
||||
github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI=
|
||||
github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
||||
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
|
||||
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk=
|
||||
github.com/bodgit/plumbing v1.3.0 h1:pf9Itz1JOQgn7vEOE7v7nlEfBykYqvUYioC61TwWCFU=
|
||||
github.com/bodgit/plumbing v1.3.0/go.mod h1:JOTb4XiRu5xfnmdnDJo6GmSbSbtSyufrsyZFByMtKEs=
|
||||
github.com/bodgit/windows v1.0.1 h1:tF7K6KOluPYygXa3Z2594zxlkbKPAOvqr97etrGNIz4=
|
||||
github.com/bodgit/windows v1.0.1/go.mod h1:a6JLwrB4KrTR5hBpp8FI9/9W9jJfeQ2h4XDXU74ZCdM=
|
||||
github.com/cilium/ebpf v0.12.3 h1:8ht6F9MquybnY97at+VDZb3eQQr8ev79RueWeVaEcG4=
|
||||
github.com/coder/websocket v1.8.12 h1:5bUXkEPPIbewrnkU8LTCLVaxi4N4J8ahufH2vlo4NAo=
|
||||
github.com/coder/websocket v1.8.12/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
|
||||
@@ -27,8 +31,8 @@ github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz
|
||||
github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/dunglas/httpsfv v1.0.2 h1:iERDp/YAfnojSDJ7PW3dj1AReJz4MrwbECSSE59JWL0=
|
||||
github.com/dunglas/httpsfv v1.0.2/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg=
|
||||
github.com/enfein/mieru/v3 v3.31.0 h1:Fl2ocRCRXJzMygzdRjBHgqI996ZuIDHUmyQyovSf9sA=
|
||||
github.com/enfein/mieru/v3 v3.31.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
|
||||
github.com/enfein/mieru/v3 v3.34.0 h1:8yeaPORvfSQtdfEH+Arw9wttDyFxkik8My4zFdGu79Y=
|
||||
github.com/enfein/mieru/v3 v3.34.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
|
||||
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 h1:kXYqH/sL8dS/FdoFjr12ePjnLPorPo2FsnrHNuXSDyo=
|
||||
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358/go.mod h1:hkIFzoiIPZYxdFOOLyDho59b7SrDfo+w3h+yWdlg45I=
|
||||
github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 h1:8j2RH289RJplhA6WfdaPqzg1MjH2K8wX5e0uhAxrw2g=
|
||||
@@ -69,6 +73,8 @@ github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN
|
||||
github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8 h1:FKHo8hFI3A+7w0aUQuYXQ+6EN5stWmeY/AZqtM8xk9k=
|
||||
github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo=
|
||||
github.com/google/tink/go v1.6.1 h1:t7JHqO8Ath2w2ig5vjwQYJzhGEZymedQc90lQXUBa4I=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc=
|
||||
github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8=
|
||||
github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905 h1:q3OEI9RaN/wwcx+qgGo6ZaoJkCiDYe/gjDLfq7lQQF4=
|
||||
@@ -91,20 +97,22 @@ github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/
|
||||
github.com/mdlayher/netlink v1.7.2/go.mod h1:xraEF7uJbxLhc5fpHL4cPe221LI2bdttWlU+ZGLfQSw=
|
||||
github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
|
||||
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d h1:vAJ0ZT4aO803F1uw2roIA9yH7Sxzox34tVVyye1bz6c=
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d/go.mod h1:MsM/5czONyXMJ3PRr5DbQ4O/BxzAnJWOIcJdLzW6qHY=
|
||||
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78 h1:LqWr0vb9zDNuQS+jJd4fnRYk/SEI7KJ7TDe/L4WFK48=
|
||||
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78/go.mod h1:BTBG/iVY7rg3qq5WdVCg0GFk58CSvCDSbjy8I7kEx/c=
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20260612143004-19b4f1cdd5ec h1:nRHevF7PmvDKjkYPjQCU7NUfVrr3Sry4QOPxpqoyo8U=
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20260612143004-19b4f1cdd5ec/go.mod h1:MsM/5czONyXMJ3PRr5DbQ4O/BxzAnJWOIcJdLzW6qHY=
|
||||
github.com/metacubex/ascon v0.1.0 h1:6ZWxmXYszT1XXtwkf6nxfFhc/OTtQ9R3Vyj1jN32lGM=
|
||||
github.com/metacubex/ascon v0.1.0/go.mod h1:eV5oim4cVPPdEL8/EYaTZ0iIKARH9pnhAK/fcT5Kacc=
|
||||
github.com/metacubex/bart v0.26.0 h1:d/bBTvVatfVWGfQbiDpYKI1bXUJgjaabB2KpK1Tnk6w=
|
||||
github.com/metacubex/bart v0.26.0/go.mod h1:DCcyfP4MC+Zy7sLK7XeGuMw+P5K9mIRsYOBgiE8icsI=
|
||||
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b h1:j7dadXD8I2KTmMt8jg1JcaP1ANL3JEObJPdANKcSYPY=
|
||||
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b/go.mod h1:+WmP0VJZDkDszvpa83HzfUp6QzARl/IKkMorH4+nODw=
|
||||
github.com/metacubex/bbolt v0.0.0-20260706163408-d4ec34ad7c48 h1:D+AoQ7g/ZeZAHAapelrZB0xUNRcDGuoNLcGmHCnC9Ss=
|
||||
github.com/metacubex/bbolt v0.0.0-20260706163408-d4ec34ad7c48/go.mod h1:yOfzykxfYIEVOtEys6KOKwxy75M2I/KtOQ+p3Kzc8/k=
|
||||
github.com/metacubex/blake3 v0.1.0 h1:KGnjh/56REO7U+cgZA8dnBhxdP7jByrG7hTP+bu6cqY=
|
||||
github.com/metacubex/blake3 v0.1.0/go.mod h1:CCkLdzFrqf7xmxCdhQFvJsRRV2mwOLDoSPg6vUTB9Uk=
|
||||
github.com/metacubex/chacha v0.1.5 h1:fKWMb/5c7ZrY8Uoqi79PPFxl+qwR7X/q0OrsAubyX2M=
|
||||
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/chi v0.1.1 h1:GajmCIXSIPAZNxqTTYpkCrkY9suBz9wjIdgPcoQ5K1A=
|
||||
github.com/metacubex/chi v0.1.1/go.mod h1:/CvDXe8jZD/ecU8Y7fmS5XKLRR44UDmC6/IBkRIb6Z4=
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260412152424-e1625567920a h1:Ph5UfTWDsGruZ+v95Df1ycTflQFmpZBFg2LUvj2kx/M=
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260412152424-e1625567920a/go.mod h1:xYC8Ik7/rN6no+vTRuWMEziGwm3brA0wNM/zZP9qhOQ=
|
||||
github.com/metacubex/cpu v0.1.1 h1:rRV5HGmeuGzjiKI3hYbL0dCd0qGwM7VUtk4ICXD06mI=
|
||||
@@ -123,8 +131,8 @@ github.com/metacubex/hpke v0.1.0 h1:gu2jUNhraehWi0P/z5HX2md3d7L1FhPQE6/Q0E9r9xQ=
|
||||
github.com/metacubex/hpke v0.1.0/go.mod h1:vfDm6gfgrwlXUxKDkWbcE44hXtmc1uxLDm2BcR11b3U=
|
||||
github.com/metacubex/http v0.1.6 h1:xvXuvXMCMxCWMF5nEJF4yiKvXL+p2atWMzs37e80m1I=
|
||||
github.com/metacubex/http v0.1.6/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
|
||||
github.com/metacubex/jsonv2 v0.0.0-20260513175203-1c6abea7534c h1:KGhBHDe6FveU0ury+9RyX329nclM1CHODa0Fi+uOAYM=
|
||||
github.com/metacubex/jsonv2 v0.0.0-20260513175203-1c6abea7534c/go.mod h1:F4sVXat6QjPXkNsKRDyyG3BhSkxPFFnRPEIwmmyCgbg=
|
||||
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df h1:S0vBzqjXok24VopstOgPd1JdgglW9tXehrqvwpQWbQ8=
|
||||
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df/go.mod h1:F4sVXat6QjPXkNsKRDyyG3BhSkxPFFnRPEIwmmyCgbg=
|
||||
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604 h1:hJwCVlE3ojViC35MGHB+FBr8TuIf3BUFn2EQ1VIamsI=
|
||||
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604/go.mod h1:lpmN3m269b3V5jFCWtffqBLS4U3QQoIid9ugtO+OhVc=
|
||||
github.com/metacubex/mhurl v0.1.0 h1:ZdW4Zxe3j3uJ89gNytOazHu6kbHn5owutN/VfXOI8GE=
|
||||
@@ -137,44 +145,46 @@ github.com/metacubex/protobuf-go v0.0.0-20260306035419-7ceee0674686 h1:PIXmYT2an
|
||||
github.com/metacubex/protobuf-go v0.0.0-20260306035419-7ceee0674686/go.mod h1:eQV7juxFZIdRgjMxtVqP+6BssKoTZQ1RM0fc58BsCZY=
|
||||
github.com/metacubex/qpack v0.6.0 h1:YqClGIMOpiRYLjV1qOs483Od08MdPgRnHjt90FuaAKw=
|
||||
github.com/metacubex/qpack v0.6.0/go.mod h1:lKGSi7Xk94IMvHGOmxS9eIei3bvIqpOAImEBsaOwTkA=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306 h1:HlGLmLsWJMLSu0CMI9z/BmEnithB4oXM5Rom6/0Qxtg=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306/go.mod h1:oNzMrmylS897M3zSMuapIdwSwfq6F2qW01Z3NhVRJhk=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260606115121-0662b57ad5bf h1:WvIp5pF+LLZwg0I6555eMVlKFrLrqQqPKob6XW6niyo=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260606115121-0662b57ad5bf/go.mod h1:2YEQEvFrZ5V76oynMBDTlN+4fdnSHCa2uNJxv3cm1HU=
|
||||
github.com/metacubex/randv2 v0.2.0 h1:uP38uBvV2SxYfLj53kuvAjbND4RUDfFJjwr4UigMiLs=
|
||||
github.com/metacubex/randv2 v0.2.0/go.mod h1:kFi2SzrQ5WuneuoLLCMkABtiBu6VRrMrWFqSPyj2cxY=
|
||||
github.com/metacubex/restls-client-go v0.1.7 h1:eCwiXCTQb5WJu9IlgYvDBA1OgrINv58dEe7hcN5H15k=
|
||||
github.com/metacubex/restls-client-go v0.1.7/go.mod h1:BN/U52vPw7j8VTSh2vleD/MnmVKCov84mS5VcjVHH4g=
|
||||
github.com/metacubex/restls-client-go v0.1.8 h1:0kQ699TWnbK3bWLhCPE0oIiBJLN+errOLQ9Z3/P1lbA=
|
||||
github.com/metacubex/restls-client-go v0.1.8/go.mod h1:BN/U52vPw7j8VTSh2vleD/MnmVKCov84mS5VcjVHH4g=
|
||||
github.com/metacubex/sevenzip v1.6.4 h1:OIL+DeOeSAbKNsjqxcYUMiarRmX6Kaxakb0GT7E9Oik=
|
||||
github.com/metacubex/sevenzip v1.6.4/go.mod h1:FP3X9bzFKj9wPxifGN9B3w2fIEicMjzKYIGIhnu+1pw=
|
||||
github.com/metacubex/sing v0.5.7 h1:8OC+fhKFSv/l9ehEhJRaZZAOuthfZo68SteBVLe8QqM=
|
||||
github.com/metacubex/sing v0.5.7/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w=
|
||||
github.com/metacubex/sing-mux v0.3.9 h1:/aoBD2+sK2qsXDlNDe3hkR0GZuFDtwIZhOeGUx9W0Yk=
|
||||
github.com/metacubex/sing-mux v0.3.9/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260512151354-8475655be853 h1:nZ5WNU6kjj6kBu4+2eMySFkUVGCop64rZnLMm+HPh8w=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260512151354-8475655be853/go.mod h1:6ayFGfzzBE85csgQkM3gf4neFq6s0losHlPRSxY+nuk=
|
||||
github.com/metacubex/sing-mux v0.3.10 h1:r5CuZ/KuwFsEcRRwpLvzLncW4fDzNfmSEcBEWcy/+94=
|
||||
github.com/metacubex/sing-mux v0.3.10/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3 h1:PnMby5+kZXTl/CFDHfxMbMTaSRD+uMKMsrDYVQyAmX8=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3/go.mod h1:6ayFGfzzBE85csgQkM3gf4neFq6s0losHlPRSxY+nuk=
|
||||
github.com/metacubex/sing-shadowsocks v0.2.12 h1:Wqzo8bYXrK5aWqxu/TjlTnYZzAKtKsaFQBdr6IHFaBE=
|
||||
github.com/metacubex/sing-shadowsocks v0.2.12/go.mod h1:2e5EIaw0rxKrm1YTRmiMnDulwbGxH9hAFlrwQLQMQkU=
|
||||
github.com/metacubex/sing-shadowsocks2 v0.2.7 h1:hSuuc0YpsfiqYqt1o+fP4m34BQz4e6wVj3PPBVhor3A=
|
||||
github.com/metacubex/sing-shadowsocks2 v0.2.7/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE=
|
||||
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2 h1:gXU+MYPm7Wme3/OAY2FFzVq9d9GxPHOqu5AQfg/ddhI=
|
||||
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2/go.mod h1:mbfboaXauKJNIHJYxQRa+NJs4JU9NZfkA+I33dS2+9E=
|
||||
github.com/metacubex/sing-tun v0.4.18 h1:WRzAosG0YkT3aZq5RJWtF+RdCgeJ8EpooS5ZM1lkXo0=
|
||||
github.com/metacubex/sing-tun v0.4.18/go.mod h1:g4I/JNplDBhXLF+aQWgFbhNeJPSXQOWS9HvLeNvkgeA=
|
||||
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc h1:8wLoFfYQ88iGPL+krQ5tJsI8IAmkFjKpQL2q+y3pvss=
|
||||
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc/go.mod h1:mbfboaXauKJNIHJYxQRa+NJs4JU9NZfkA+I33dS2+9E=
|
||||
github.com/metacubex/sing-tun v0.4.21 h1:MjbPYytM240VH70lO182v2Sg/JthMmx6R6z6E2fCR2I=
|
||||
github.com/metacubex/sing-tun v0.4.21/go.mod h1:g4I/JNplDBhXLF+aQWgFbhNeJPSXQOWS9HvLeNvkgeA=
|
||||
github.com/metacubex/sing-vmess v0.2.5 h1:m9Zt5I27lB9fmLMZfism9sH2LcnAfShZfwSkf6/KJoE=
|
||||
github.com/metacubex/sing-vmess v0.2.5/go.mod h1:AwtlzUgf8COe9tRYAKqWZ+leDH7p5U98a0ZUpYehl8Q=
|
||||
github.com/metacubex/sing-wireguard v0.0.0-20260507084707-690d479ec947 h1:IB03BvRQtvjWScyOK5jSQVJYY8osmZXHL+4VCEFMWcM=
|
||||
github.com/metacubex/sing-wireguard v0.0.0-20260507084707-690d479ec947/go.mod h1:jpAkVLPnCpGSfNyVmj6Cq4YbuZsFepm/Dc+9BAOcR80=
|
||||
github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c h1:tH9FuQW357zp2xAGzkoZTGpNGMVmEFZov0iV5M2S5ew=
|
||||
github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c/go.mod h1:eQZDJTx+IH3k4mXqaOJ3VJ9h9ZqOl60F7TLi5wAU51Q=
|
||||
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141 h1:DK2l6m2Fc85H2BhiAPgbJygiWhesPlfGmF+9Vw6ARdk=
|
||||
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141/go.mod h1:/yI4OiGOSn0SURhZdJF3CbtPg3nwK700bG8TZLMBvAg=
|
||||
github.com/metacubex/ssh v0.1.0 h1:iGfr99qk/eMHzUnQ/0bTxXT8+8SWqLSHBWDHoAhngzw=
|
||||
github.com/metacubex/ssh v0.1.0/go.mod h1:NUtl0d+/f2cG9ECEpMM8iCVOpmggQlC13oLeDUONDlU=
|
||||
github.com/metacubex/tailscale v0.0.0-20260516120020-a21c2c99dcbe h1:ZdAKshacNruZGuKTE8WMTuxyGgpv/LySLoE/EEmgF9c=
|
||||
github.com/metacubex/tailscale v0.0.0-20260516120020-a21c2c99dcbe/go.mod h1:2G1V82OGXgxT7m7046GA80I9SlcvczljCK0C7NQ3c10=
|
||||
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260513233728-8bc7ee255d04 h1:zk+mDDSBl5lv80WWtaFUbpj8XLb7AhjCUbn2pB37N0U=
|
||||
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260513233728-8bc7ee255d04/go.mod h1:pKUKBy7IcQ5r0i66gWENHgxKvBn8tlgAGx0DZMq8h5M=
|
||||
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443 h1:H6TnfM12tOoTizYE/qBHH3nEuibIelmHI+BVSxVJr8o=
|
||||
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443/go.mod h1:l9oLnLoEXyGZ5RVLsh7QCC5XsouTUyKk4F2nLm2DHLw=
|
||||
github.com/metacubex/tls v0.1.5 h1:ECcB83dj+zadnhlKcLnUUf1Sq6+vU0f/zoyU0+9oPTc=
|
||||
github.com/metacubex/tls v0.1.5/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
|
||||
github.com/metacubex/utls v1.8.4 h1:HmL9nUApDdWSkgUyodfwF6hSjtiwCGGdyhaSpEejKpg=
|
||||
github.com/metacubex/utls v1.8.4/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
|
||||
github.com/metacubex/tailscale v0.0.0-20260623094802-1ab893d4162c h1:ACfYexFGGaObb80aq0IiG3oRjv4I1lCxf104cUsI0W8=
|
||||
github.com/metacubex/tailscale v0.0.0-20260623094802-1ab893d4162c/go.mod h1:rDpd7cy7itpPi3Kgb90fUgSnKwMXHYBk0R5DuNRiNNA=
|
||||
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260623093519-06ea214022e4 h1:ui12xOUPsCAYwzI7+7Hw2mVhrAbWDGNQZcrBiELhGk0=
|
||||
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260623093519-06ea214022e4/go.mod h1:W00EeoPdd2jbV3+ZUa0m2b7FdKx5B1LFsXvEpy7cToQ=
|
||||
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c h1:+2C1UshSLzaogLY/IDz1XhOLxjhs3rkhVHB4eCN9Zto=
|
||||
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c/go.mod h1:l9oLnLoEXyGZ5RVLsh7QCC5XsouTUyKk4F2nLm2DHLw=
|
||||
github.com/metacubex/tls v0.1.7 h1:7YW+7z2xGH1bozSg04q3gKNd7GBSiTSXIrQY2SMnfoE=
|
||||
github.com/metacubex/tls v0.1.7/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
|
||||
github.com/metacubex/utls v1.8.7 h1:Cp+yWkNTFkSihETgGWq34hlVFds5HpYWVOR1xovUVTs=
|
||||
github.com/metacubex/utls v1.8.7/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
|
||||
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f h1:FGBPRb1zUabhPhDrlKEjQ9lgIwQ6cHL4x8M9lrERhbk=
|
||||
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f/go.mod h1:oPGcV994OGJedmmxrcK9+ni7jUEMGhR+uVQAdaduIP4=
|
||||
github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49 h1:lhlqpYHopuTLx9xQt22kSA9HtnyTDmk5XjjQVCGHe2E=
|
||||
@@ -194,14 +204,17 @@ github.com/openacid/must v0.1.3/go.mod h1:luPiXCuJlEo3UUFQngVQokV0MPGryeYvtCbQPs
|
||||
github.com/openacid/testkeys v0.1.6/go.mod h1:MfA7cACzBpbiwekivj8StqX0WIRmqlMsci1c37CA3Do=
|
||||
github.com/oschwald/maxminddb-golang v1.12.0 h1:9FnTOD0YOhP7DGxGsq4glzpGy5+w7pq50AS6wALUMYs=
|
||||
github.com/oschwald/maxminddb-golang v1.12.0/go.mod h1:q0Nob5lTCqyQ8WT6FYgS1L7PXKVVbgiymefNwIjPzgY=
|
||||
github.com/pierrec/lz4/v4 v4.1.14 h1:+fL8AQEZtz/ijeNnpduH0bROTu0O3NZAlPjQxGn8LwE=
|
||||
github.com/pierrec/lz4/v4 v4.1.14/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
||||
github.com/pierrec/lz4/v4 v4.1.27 h1:+PhzhWDrjRj89TH2sw43nE3+4+W8lSxIuQadEHZyjUk=
|
||||
github.com/pierrec/lz4/v4 v4.1.27/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pires/go-proxyproto v0.8.0 h1:5unRmEAPbHXHuLjDg01CxJWf91cw3lKHc/0xzKpXEe0=
|
||||
github.com/pires/go-proxyproto v0.8.0/go.mod h1:iknsfgnH8EkjrMeMyvfKByp9TiBZCKZM0jx2xmKqnVY=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g=
|
||||
github.com/rasky/go-lzo v0.0.0-20200203143853-96a758eda86e h1:dCWirM5F3wMY+cmRda/B1BiPsFtmzXqV9b0hLWtVBMs=
|
||||
github.com/rasky/go-lzo v0.0.0-20200203143853-96a758eda86e/go.mod h1:9leZcVcItj6m9/CfHY5Em/iBrCz7js8LcRQGTKEEv2M=
|
||||
github.com/safchain/ethtool v0.3.0 h1:gimQJpsI6sc1yIqP/y8GYgiXn/NjgvpM0RNoWLVVmP0=
|
||||
github.com/safchain/ethtool v0.3.0/go.mod h1:SA9BwrgyAqNo7M+uaL6IYbxpm5wk3L7Mm6ocLW+CJUs=
|
||||
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a h1:ObwtHN2VpqE0ZNjr6sGeT00J8uU7JF4cNUdb44/Duis=
|
||||
@@ -216,10 +229,18 @@ github.com/sina-ghaderi/rabbitio v0.0.0-20220730151941-9ce26f4f872e h1:ur8uMsPIF
|
||||
github.com/sina-ghaderi/rabbitio v0.0.0-20220730151941-9ce26f4f872e/go.mod h1:+e5fBW3bpPyo+3uLo513gIUblc03egGjMM0+5GKbzK8=
|
||||
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
|
||||
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
|
||||
github.com/stangelandcl/ppmd v0.1.1 h1:c25QazhlWUn5nmR1QOzafKhQxBicAr7GGCKER2aJ8H8=
|
||||
github.com/stangelandcl/ppmd v0.1.1/go.mod h1:Rrv7M+/2P5jYr/GMLhBl7Ug3uJ1bUiVzr5LbbaV6xgY=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d h1:JcGKBZAL7ePLwOhUdN8qGQZlP5GueEiIZwY7R62pejE=
|
||||
@@ -232,6 +253,8 @@ github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc h1:24heQPtnFR+y
|
||||
github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc/go.mod h1:f93CXfllFsO9ZQVq+Zocb1Gp4G5Fz0b0rXHLOzt/Djc=
|
||||
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 h1:tHNk7XK9GkmKUR6Gh8gVBKXc2MVSZ4G/NnWLtzw4gNA=
|
||||
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923/go.mod h1:eLL9Nub3yfAho7qB0MzZizFhTU2QkLeoVsWdHtDW264=
|
||||
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
|
||||
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
|
||||
github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE=
|
||||
github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU=
|
||||
github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0=
|
||||
@@ -244,6 +267,8 @@ github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
gitlab.com/go-extension/aes-ccm v0.0.0-20230221065045-e58665ef23c7 h1:UNrDfkQqiEYzdMlNsVvBYOAJWZjdktqFE9tQh5BT2+4=
|
||||
|
||||
+21
-24
@@ -26,7 +26,6 @@ import (
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
"github.com/metacubex/mihomo/component/resource"
|
||||
"github.com/metacubex/mihomo/component/sniffer"
|
||||
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||
"github.com/metacubex/mihomo/component/trie"
|
||||
"github.com/metacubex/mihomo/component/updater"
|
||||
"github.com/metacubex/mihomo/config"
|
||||
@@ -166,20 +165,19 @@ func GetGeneral() *config.General {
|
||||
ASN: geodata.ASNUrl(),
|
||||
GeoSite: geodata.GeoSiteUrl(),
|
||||
},
|
||||
GeoAutoUpdate: updater.GeoAutoUpdate(),
|
||||
GeoUpdateInterval: updater.GeoUpdateInterval(),
|
||||
GeodataMode: geodata.GeodataMode(),
|
||||
GeodataLoader: geodata.LoaderName(),
|
||||
GeositeMatcher: geodata.SiteMatcherName(),
|
||||
TCPConcurrent: dialer.GetTcpConcurrent(),
|
||||
FindProcessMode: tunnel.FindProcessMode(),
|
||||
Sniffing: tunnel.IsSniffing(),
|
||||
GlobalClientFingerprint: tlsC.GetGlobalFingerprint(),
|
||||
GlobalUA: mihomoHttp.UA(),
|
||||
ETagSupport: resource.ETag(),
|
||||
KeepAliveInterval: int(keepalive.KeepAliveInterval() / time.Second),
|
||||
KeepAliveIdle: int(keepalive.KeepAliveIdle() / time.Second),
|
||||
DisableKeepAlive: keepalive.DisableKeepAlive(),
|
||||
GeoAutoUpdate: updater.GeoAutoUpdate(),
|
||||
GeoUpdateInterval: updater.GeoUpdateInterval(),
|
||||
GeodataMode: geodata.GeodataMode(),
|
||||
GeodataLoader: geodata.LoaderName(),
|
||||
GeositeMatcher: geodata.SiteMatcherName(),
|
||||
TCPConcurrent: dialer.GetTcpConcurrent(),
|
||||
FindProcessMode: tunnel.FindProcessMode(),
|
||||
Sniffing: tunnel.IsSniffing(),
|
||||
GlobalUA: mihomoHttp.UA(),
|
||||
ETagSupport: resource.ETag(),
|
||||
KeepAliveInterval: int(keepalive.KeepAliveInterval() / time.Second),
|
||||
KeepAliveIdle: int(keepalive.KeepAliveIdle() / time.Second),
|
||||
DisableKeepAlive: keepalive.DisableKeepAlive(),
|
||||
}
|
||||
|
||||
return general
|
||||
@@ -229,10 +227,11 @@ func updateNTP(c *config.NTP) {
|
||||
net.JoinHostPort(c.Server, strconv.Itoa(c.Port)),
|
||||
time.Duration(c.Interval),
|
||||
c.DialerProxy,
|
||||
tunnel.Tunnel,
|
||||
c.WriteToSystem,
|
||||
)
|
||||
} else {
|
||||
ntp.ReCreateNTPService("", 0, "", false)
|
||||
ntp.ReCreateNTPService("", 0, "", nil, false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,7 +242,7 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
|
||||
resolver.DefaultService = nil
|
||||
resolver.ProxyServerHostResolver = nil
|
||||
resolver.DirectHostResolver = nil
|
||||
dns.ReCreateServer("", nil)
|
||||
dns.ReCreateServer("", nil, nil)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -255,6 +254,7 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
|
||||
IPv6Timeout: c.IPv6Timeout,
|
||||
FallbackIPFilter: c.FallbackIPFilter,
|
||||
FallbackDomainFilter: c.FallbackDomainFilter,
|
||||
FallbackLazyQuery: c.FallbackLazyQuery,
|
||||
Default: c.DefaultNameserver,
|
||||
Policy: c.NameServerPolicy,
|
||||
ProxyServer: c.ProxyServerNameserver,
|
||||
@@ -279,7 +279,7 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
|
||||
m.PatchFrom(old.(*dns.ResolverEnhancer))
|
||||
}
|
||||
|
||||
s := dns.NewService(r.Resolver, m)
|
||||
s := dns.NewService(r, m)
|
||||
|
||||
resolver.DefaultResolver = r
|
||||
resolver.DefaultHostMapper = m
|
||||
@@ -298,7 +298,9 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
|
||||
resolver.DirectHostResolver = r.Resolver
|
||||
}
|
||||
|
||||
dns.ReCreateServer(c.Listen, s)
|
||||
lc := inbound.NewListenConfig()
|
||||
lc.SetRouteMark(c.ListenRoutingMark)
|
||||
dns.ReCreateServer(c.Listen, lc, s)
|
||||
}
|
||||
|
||||
func updateHosts(tree *trie.DomainTrie[resolver.HostValue]) {
|
||||
@@ -424,11 +426,6 @@ func updateGeneral(general *config.General, logging bool) {
|
||||
geodata.SetASNUrl(general.GeoXUrl.ASN)
|
||||
mihomoHttp.SetUA(general.GlobalUA)
|
||||
resource.SetETag(general.ETagSupport)
|
||||
|
||||
if general.GlobalClientFingerprint != "" {
|
||||
log.Warnln("The `global-client-fingerprint` configuration is deprecated, please set `client-fingerprint` directly on the proxy instead")
|
||||
}
|
||||
tlsC.SetGlobalFingerprint(general.GlobalClientFingerprint)
|
||||
}
|
||||
|
||||
func updateUsers(users []auth.AuthUser) {
|
||||
|
||||
+13
@@ -21,6 +21,12 @@ func WithExternalController(externalController string) Option {
|
||||
}
|
||||
}
|
||||
|
||||
func WithExternalControllerTLS(externalControllerTLS string) Option {
|
||||
return func(cfg *config.Config) {
|
||||
cfg.Controller.ExternalControllerTLS = externalControllerTLS
|
||||
}
|
||||
}
|
||||
|
||||
func WithExternalControllerUnix(externalControllerUnix string) Option {
|
||||
return func(cfg *config.Config) {
|
||||
cfg.Controller.ExternalControllerUnix = externalControllerUnix
|
||||
@@ -33,6 +39,12 @@ func WithExternalControllerPipe(externalControllerPipe string) Option {
|
||||
}
|
||||
}
|
||||
|
||||
func WithExternalControllerRoutingMark(externalControllerRoutingMark int) Option {
|
||||
return func(cfg *config.Config) {
|
||||
cfg.Controller.ExternalControllerRoutingMark = externalControllerRoutingMark
|
||||
}
|
||||
}
|
||||
|
||||
func WithSecret(secret string) Option {
|
||||
return func(cfg *config.Config) {
|
||||
cfg.Controller.Secret = secret
|
||||
@@ -54,6 +66,7 @@ func applyRoute(cfg *config.Config) {
|
||||
TLSAddr: cfg.Controller.ExternalControllerTLS,
|
||||
UnixAddr: cfg.Controller.ExternalControllerUnix,
|
||||
PipeAddr: cfg.Controller.ExternalControllerPipe,
|
||||
RoutingMark: cfg.Controller.ExternalControllerRoutingMark,
|
||||
Secret: cfg.Controller.Secret,
|
||||
Certificate: cfg.TLS.Certificate,
|
||||
PrivateKey: cfg.TLS.PrivateKey,
|
||||
|
||||
@@ -97,6 +97,7 @@ type tunSchema struct {
|
||||
ExcludeMACAddress *[]string `yaml:"exclude-mac-address" json:"exclude-mac-address,omitempty"`
|
||||
EndpointIndependentNat *bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout *int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
|
||||
ICMPTimeout *int64 `yaml:"icmp-timeout" json:"icmp-timeout,omitempty"`
|
||||
FileDescriptor *int `yaml:"file-descriptor" json:"file-descriptor"`
|
||||
|
||||
Inet4RouteAddress *[]netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
|
||||
@@ -257,6 +258,9 @@ func pointerOrDefaultTun(p *tunSchema, def LC.Tun) LC.Tun {
|
||||
if p.UDPTimeout != nil {
|
||||
def.UDPTimeout = *p.UDPTimeout
|
||||
}
|
||||
if p.ICMPTimeout != nil {
|
||||
def.ICMPTimeout = *p.ICMPTimeout
|
||||
}
|
||||
if p.FileDescriptor != nil {
|
||||
def.FileDescriptor = *p.FileDescriptor
|
||||
}
|
||||
|
||||
+2
-20
@@ -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 := proxiesWithProviders()
|
||||
proxies := tunnel.Proxies()
|
||||
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 := proxiesWithProviders()
|
||||
proxies := tunnel.Proxies()
|
||||
render.JSON(w, r, render.M{
|
||||
"proxies": proxies,
|
||||
})
|
||||
@@ -158,21 +158,3 @@ 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
|
||||
}
|
||||
+11
-3
@@ -2,6 +2,7 @@ package route
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"net"
|
||||
@@ -61,6 +62,7 @@ type Config struct {
|
||||
TLSAddr string
|
||||
UnixAddr string
|
||||
PipeAddr string
|
||||
RoutingMark int
|
||||
Secret string
|
||||
Certificate string
|
||||
PrivateKey string
|
||||
@@ -166,7 +168,9 @@ func start(cfg *Config) {
|
||||
|
||||
// handle addr
|
||||
if len(cfg.Addr) > 0 {
|
||||
l, err := inbound.Listen("tcp", cfg.Addr)
|
||||
lc := inbound.NewListenConfig()
|
||||
lc.SetRouteMark(cfg.RoutingMark)
|
||||
l, err := lc.Listen(context.Background(), "tcp", cfg.Addr)
|
||||
if err != nil {
|
||||
log.Errorln("External controller listen error: %s", err)
|
||||
return
|
||||
@@ -198,7 +202,9 @@ func startTLS(cfg *Config) {
|
||||
return
|
||||
}
|
||||
|
||||
l, err := inbound.Listen("tcp", cfg.TLSAddr)
|
||||
lc := inbound.NewListenConfig()
|
||||
lc.SetRouteMark(cfg.RoutingMark)
|
||||
l, err := lc.Listen(context.Background(), "tcp", cfg.TLSAddr)
|
||||
if err != nil {
|
||||
log.Errorln("External controller tls listen error: %s", err)
|
||||
return
|
||||
@@ -270,7 +276,9 @@ func startUnix(cfg *Config) {
|
||||
// should be used to delete the socket file prior to calling bind with the same path.
|
||||
_ = syscall.Unlink(addr)
|
||||
|
||||
l, err := inbound.Listen("unix", addr)
|
||||
lc := inbound.NewListenConfig()
|
||||
lc.SetRouteMark(0) // don't set route mark for unix socket
|
||||
l, err := lc.Listen(context.Background(), "unix", addr)
|
||||
if err != nil {
|
||||
log.Errorln("External controller unix listen error: %s", err)
|
||||
return
|
||||
|
||||
@@ -35,7 +35,7 @@ type Listener struct {
|
||||
padding atomic.Pointer[padding.PaddingFactory]
|
||||
}
|
||||
|
||||
func New(config LC.AnyTLSServer, tunnel C.Tunnel, additions ...inbound.Addition) (sl *Listener, err error) {
|
||||
func New(config LC.AnyTLSServer, lc C.InboundListenConfig, tunnel C.Tunnel, additions ...inbound.Addition) (sl *Listener, err error) {
|
||||
if len(additions) == 0 {
|
||||
additions = []inbound.Addition{
|
||||
inbound.WithInName("DEFAULT-ANYTLS"),
|
||||
@@ -106,14 +106,14 @@ func New(config LC.AnyTLSServer, tunnel C.Tunnel, additions ...inbound.Addition)
|
||||
addr := addr
|
||||
|
||||
//TCP
|
||||
l, err := inbound.Listen("tcp", addr)
|
||||
l, err := lc.Listen(context.Background(), "tcp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tlsConfig.GetCertificate != nil {
|
||||
l = tls.NewListener(l, tlsConfig)
|
||||
} else {
|
||||
return nil, errors.New("disallow using AnyTLS without certificates config")
|
||||
} else if !config.AllowInsecure {
|
||||
return nil, errors.New("disallow using AnyTLS without certificates/allow-insecure config")
|
||||
}
|
||||
sl.listeners = append(sl.listeners, l)
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ type AnyTLSServer struct {
|
||||
PrivateKey string `yaml:"private-key" json:"private-key"`
|
||||
ClientAuthType string `yaml:"client-auth-type" json:"client-auth-type,omitempty"`
|
||||
ClientAuthCert string `yaml:"client-auth-cert" json:"client-auth-cert,omitempty"`
|
||||
EchKey string `yaml:"ech-key" json:"ech-key"`
|
||||
EchKey string `yaml:"ech-key" json:"ech-key,omitempty"`
|
||||
AllowInsecure bool `yaml:"allow-insecure" json:"allow-insecure,omitempty"`
|
||||
PaddingScheme string `yaml:"padding-scheme" json:"padding-scheme,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ type Hysteria2Server struct {
|
||||
Users map[string]string `yaml:"users" json:"users,omitempty"`
|
||||
Obfs string `yaml:"obfs" json:"obfs,omitempty"`
|
||||
ObfsPassword string `yaml:"obfs-password" json:"obfs-password,omitempty"`
|
||||
ObfsMinPacketSize int `yaml:"obfs-min-packet-size" json:"obfs-min-packet-size,omitempty"`
|
||||
ObfsMaxPacketSize int `yaml:"obfs-max-packet-size" json:"obfs-max-packet-size,omitempty"`
|
||||
Certificate string `yaml:"certificate" json:"certificate"`
|
||||
PrivateKey string `yaml:"private-key" json:"private-key"`
|
||||
ClientAuthType string `yaml:"client-auth-type" json:"client-auth-type,omitempty"`
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package config
|
||||
|
||||
import "github.com/metacubex/mihomo/transport/mekya"
|
||||
|
||||
type MekyaConfig struct {
|
||||
Enable bool `yaml:"enable" json:"enable,omitempty"`
|
||||
URL string `yaml:"url" json:"url,omitempty"`
|
||||
H2PoolSize int `yaml:"h2-pool-size" json:"h2-pool-size,omitempty"`
|
||||
MaxWriteDelay int `yaml:"max-write-delay" json:"max-write-delay,omitempty"`
|
||||
MaxRequestSize int `yaml:"max-request-size" json:"max-request-size,omitempty"`
|
||||
PollingIntervalInitial int `yaml:"polling-interval-initial" json:"polling-interval-initial,omitempty"`
|
||||
MaxWriteSize int `yaml:"max-write-size" json:"max-write-size,omitempty"`
|
||||
MaxWriteDurationMs int `yaml:"max-write-duration-ms" json:"max-write-duration-ms,omitempty"`
|
||||
MaxSimultaneousWriteConnection int `yaml:"max-simultaneous-write-connection" json:"max-simultaneous-write-connection,omitempty"`
|
||||
PacketWritingBuffer int `yaml:"packet-writing-buffer" json:"packet-writing-buffer,omitempty"`
|
||||
KCP MKCPConfig `yaml:"kcp" json:"kcp,omitempty"`
|
||||
}
|
||||
|
||||
func (c MekyaConfig) Build() mekya.Config {
|
||||
return mekya.Config{
|
||||
KCP: c.KCP.Build(),
|
||||
URL: c.URL,
|
||||
H2PoolSize: c.H2PoolSize,
|
||||
MaxWriteDelay: c.MaxWriteDelay,
|
||||
MaxRequestSize: c.MaxRequestSize,
|
||||
PollingIntervalInitial: c.PollingIntervalInitial,
|
||||
MaxWriteSize: c.MaxWriteSize,
|
||||
MaxWriteDurationMs: c.MaxWriteDurationMs,
|
||||
MaxSimultaneousWriteConnection: c.MaxSimultaneousWriteConnection,
|
||||
PacketWritingBuffer: c.PacketWritingBuffer,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package config
|
||||
|
||||
import "github.com/metacubex/mihomo/transport/mkcp"
|
||||
|
||||
type MKCPConfig struct {
|
||||
Enable bool `yaml:"enable" json:"enable,omitempty"`
|
||||
MTU uint32 `yaml:"mtu" json:"mtu,omitempty"`
|
||||
TTI uint32 `yaml:"tti" json:"tti,omitempty"`
|
||||
UplinkCapacity uint32 `yaml:"uplink-capacity" json:"uplink-capacity,omitempty"`
|
||||
DownlinkCapacity uint32 `yaml:"downlink-capacity" json:"downlink-capacity,omitempty"`
|
||||
Congestion bool `yaml:"congestion" json:"congestion,omitempty"`
|
||||
WriteBuffer uint32 `yaml:"write-buffer" json:"write-buffer,omitempty"`
|
||||
ReadBuffer uint32 `yaml:"read-buffer" json:"read-buffer,omitempty"`
|
||||
Seed string `yaml:"seed" json:"seed,omitempty"`
|
||||
Header string `yaml:"header" json:"header,omitempty"`
|
||||
}
|
||||
|
||||
func (c MKCPConfig) Build() mkcp.Config {
|
||||
return mkcp.Config{
|
||||
MTU: c.MTU,
|
||||
TTI: c.TTI,
|
||||
UplinkCapacity: c.UplinkCapacity,
|
||||
DownlinkCapacity: c.DownlinkCapacity,
|
||||
Congestion: c.Congestion,
|
||||
WriteBuffer: c.WriteBuffer,
|
||||
ReadBuffer: c.ReadBuffer,
|
||||
Seed: c.Seed,
|
||||
Header: c.Header,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package config
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type ResTLS struct {
|
||||
Enable bool
|
||||
Dest string
|
||||
Password string
|
||||
RestlsScript string
|
||||
MinRecordLen int
|
||||
Proxy string
|
||||
}
|
||||
|
||||
func (r ResTLS) String() string {
|
||||
b, _ := json.Marshal(r)
|
||||
return string(b)
|
||||
}
|
||||
@@ -14,6 +14,7 @@ type ShadowsocksServer struct {
|
||||
Udp bool
|
||||
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
|
||||
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
|
||||
ResTLS ResTLS `yaml:"res-tls" json:"res-tls,omitempty"`
|
||||
KcpTun KcpTun `yaml:"kcp-tun" json:"kcp-tun,omitempty"`
|
||||
SimpleObfs SimpleObfs `yaml:"simple-obfs" json:"simple-obfs,omitempty"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package config
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type SnellServer struct {
|
||||
Listen string
|
||||
Psk string
|
||||
Version int
|
||||
UDP bool
|
||||
ObfsMode string
|
||||
ObfsHost string
|
||||
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
|
||||
}
|
||||
|
||||
func (c SnellServer) String() string {
|
||||
b, _ := json.Marshal(c)
|
||||
return string(b)
|
||||
}
|
||||
@@ -23,6 +23,7 @@ type TrojanServer struct {
|
||||
ClientAuthType string
|
||||
ClientAuthCert string
|
||||
EchKey string
|
||||
AllowInsecure bool
|
||||
RealityConfig reality.Config
|
||||
MuxOption sing.MuxOption
|
||||
TrojanSSOption TrojanSSOption
|
||||
|
||||
@@ -51,6 +51,7 @@ type Tun struct {
|
||||
ExcludeMACAddress []string `yaml:"exclude-mac-address" json:"exclude-mac-address,omitempty"`
|
||||
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
|
||||
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
|
||||
ICMPTimeout int64 `yaml:"icmp-timeout" json:"icmp-timeout,omitempty"`
|
||||
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
|
||||
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
|
||||
|
||||
@@ -201,6 +202,9 @@ func (t *Tun) Equal(other Tun) bool {
|
||||
if t.UDPTimeout != other.UDPTimeout {
|
||||
return false
|
||||
}
|
||||
if t.ICMPTimeout != other.ICMPTimeout {
|
||||
return false
|
||||
}
|
||||
if t.DisableICMPForwarding != other.DisableICMPForwarding {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -9,10 +9,10 @@ import (
|
||||
)
|
||||
|
||||
type tunnel struct {
|
||||
Network []string `yaml:"network"`
|
||||
Address string `yaml:"address"`
|
||||
Target string `yaml:"target"`
|
||||
Proxy string `yaml:"proxy"`
|
||||
Network []string `yaml:"network" json:"network"`
|
||||
Address string `yaml:"address" json:"address"`
|
||||
Target string `yaml:"target" json:"target"`
|
||||
Proxy string `yaml:"proxy" json:"proxy"`
|
||||
}
|
||||
|
||||
type Tunnel tunnel
|
||||
|
||||
Loaded 100 of 245 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user