mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-12-01 08:28:31 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5184081ac3 | ||
|
|
dbaf85b71b | ||
|
|
5bdb1cc7e1 | ||
|
|
11848509fb | ||
|
|
ab56858d00 | ||
|
|
01edf45ce0 | ||
|
|
e928ef59c1 | ||
|
|
c710025559 | ||
|
|
dafdd06b30 | ||
|
|
fd2112ecbe | ||
|
|
9761bcd7f9 | ||
|
|
1e62d55418 | ||
|
|
1abd12619a | ||
|
|
f99d4e1be6 | ||
|
|
fb590a845f | ||
|
|
b60e687eb7 | ||
|
|
316f5df1f1 | ||
|
|
d7ac7b5239 | ||
|
|
358fa5eb24 | ||
|
|
90b1066e1a | ||
|
|
bd72c65b5e | ||
|
|
317bfc206a |
No files matched your search
@@ -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
|
||||
|
||||
+81
-29
@@ -8,6 +8,7 @@ import (
|
||||
"net/netip"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/contextutils"
|
||||
"github.com/metacubex/mihomo/component/dialer"
|
||||
@@ -41,22 +42,24 @@ type OpenVPN struct {
|
||||
|
||||
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"`
|
||||
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"`
|
||||
MTU int `proxy:"mtu,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Proto string `proxy:"proto,omitempty"`
|
||||
Dev string `proxy:"dev,omitempty"`
|
||||
Cipher string `proxy:"cipher,omitempty"`
|
||||
Auth string `proxy:"auth,omitempty"`
|
||||
CompLZO string `proxy:"comp-lzo,omitempty"`
|
||||
CA string `proxy:"ca"`
|
||||
Cert string `proxy:"cert,omitempty"`
|
||||
Key string `proxy:"key,omitempty"`
|
||||
TLSCrypt string `proxy:"tls-crypt,omitempty"`
|
||||
Username string `proxy:"username,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
Ping int `proxy:"ping,omitempty"`
|
||||
PingRestart int `proxy:"ping-restart,omitempty"`
|
||||
MTU int `proxy:"mtu,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
|
||||
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
||||
Dns []string `proxy:"dns,omitempty"`
|
||||
@@ -64,19 +67,21 @@ type OpenVPNOption struct {
|
||||
|
||||
func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
|
||||
cfg := &ovpn.ClientConfig{
|
||||
RemoteHost: option.Server,
|
||||
RemotePort: uint16(option.Port),
|
||||
Proto: option.Proto,
|
||||
Dev: option.Dev,
|
||||
Cipher: option.Cipher,
|
||||
Auth: option.Auth,
|
||||
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,
|
||||
RemoteHost: option.Server,
|
||||
RemotePort: uint16(option.Port),
|
||||
Proto: option.Proto,
|
||||
Dev: option.Dev,
|
||||
Cipher: option.Cipher,
|
||||
Auth: option.Auth,
|
||||
CompLZO: option.CompLZO,
|
||||
CA: []byte(option.CA),
|
||||
Cert: []byte(option.Cert),
|
||||
Key: []byte(option.Key),
|
||||
TLSCrypt: []byte(option.TLSCrypt),
|
||||
Username: option.Username,
|
||||
Password: option.Password,
|
||||
PingInterval: time.Duration(option.Ping) * time.Second,
|
||||
PingRestart: time.Duration(option.PingRestart) * time.Second,
|
||||
}
|
||||
if err := cfg.Prepare(); err != nil {
|
||||
return nil, err
|
||||
@@ -401,4 +406,51 @@ func (o *OpenVPN) startPacketLoops() {
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if o.config.PingInterval > 0 {
|
||||
go func() {
|
||||
defer stop()
|
||||
ticker := time.NewTicker(o.config.PingInterval)
|
||||
defer ticker.Stop()
|
||||
for runCtx.Err() == nil {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if sinceSend := client.SinceSend(); sinceSend >= o.config.PingInterval {
|
||||
if err := client.WritePing(runCtx); err != nil {
|
||||
if !errors.Is(err, context.Canceled) && !errors.Is(err, net.ErrClosed) {
|
||||
log.Warnln("[OpenVPN](%s) error writing ping packet: %v", o.name, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Debugln("[OpenVPN](%s) sent ping packet after %s idle", o.name, sinceSend.Round(time.Second))
|
||||
}
|
||||
case <-runCtx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
if o.config.PingRestart > 0 {
|
||||
go func() {
|
||||
defer stop()
|
||||
ticker := time.NewTicker(o.config.PingRestart)
|
||||
defer ticker.Stop()
|
||||
for runCtx.Err() == nil {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if sinceReceive := client.SinceReceive(); sinceReceive >= o.config.PingRestart {
|
||||
log.Warnln(
|
||||
"[OpenVPN](%s) ping-restart timeout: no packet received for %s",
|
||||
o.name,
|
||||
sinceReceive.Round(time.Second),
|
||||
)
|
||||
return
|
||||
}
|
||||
case <-runCtx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -90,6 +90,7 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||
"fixed": f.selected,
|
||||
"hidden": f.Hidden(),
|
||||
"icon": f.Icon(),
|
||||
"emptyFallback": f.EmptyFallback().Name(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -156,7 +157,7 @@ func (f *Fallback) Proxies() []C.Proxy {
|
||||
return f.GetProxies(false)
|
||||
}
|
||||
|
||||
func NewFallback(option *GroupCommonOption, providers []P.ProxyProvider) *Fallback {
|
||||
func NewFallback(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.ProxyProvider) *Fallback {
|
||||
return &Fallback{
|
||||
GroupBase: NewGroupBase(GroupBaseOption{
|
||||
Name: option.Name,
|
||||
@@ -168,6 +169,7 @@ func NewFallback(option *GroupCommonOption, providers []P.ProxyProvider) *Fallba
|
||||
ExcludeType: option.ExcludeType,
|
||||
TestTimeout: option.TestTimeout,
|
||||
MaxFailedTimes: option.MaxFailedTimes,
|
||||
EmptyFallback: emptyFallback,
|
||||
Providers: providers,
|
||||
}),
|
||||
disableUDP: option.DisableUDP,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -234,6 +234,7 @@ func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||
"expectedStatus": lb.expectedStatus,
|
||||
"hidden": lb.Hidden(),
|
||||
"icon": lb.Icon(),
|
||||
"emptyFallback": lb.EmptyFallback().Name(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -249,7 +250,7 @@ func (lb *LoadBalance) Now() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func NewLoadBalance(option *GroupCommonOption, providers []P.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
|
||||
func NewLoadBalance(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
|
||||
var strategyFn strategyFn
|
||||
switch strategy {
|
||||
case "consistent-hashing":
|
||||
@@ -272,6 +273,7 @@ func NewLoadBalance(option *GroupCommonOption, providers []P.ProxyProvider, stra
|
||||
ExcludeType: option.ExcludeType,
|
||||
TestTimeout: option.TestTimeout,
|
||||
MaxFailedTimes: option.MaxFailedTimes,
|
||||
EmptyFallback: emptyFallback,
|
||||
Providers: providers,
|
||||
}),
|
||||
strategyFn: strategyFn,
|
||||
|
||||
@@ -31,6 +31,7 @@ type GroupCommonOption struct {
|
||||
Interval int `group:"interval,omitempty"`
|
||||
TestTimeout int `group:"timeout,omitempty"`
|
||||
MaxFailedTimes int `group:"max-failed-times,omitempty"`
|
||||
EmptyFallback string `group:"empty-fallback,omitempty"`
|
||||
Lazy bool `group:"lazy,omitempty"`
|
||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||
Filter string `group:"filter,omitempty"`
|
||||
@@ -70,6 +71,14 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
||||
|
||||
groupName := groupOption.Name
|
||||
|
||||
if groupOption.EmptyFallback == "" {
|
||||
groupOption.EmptyFallback = "COMPATIBLE"
|
||||
}
|
||||
emptyFallback, ok := proxyMap[groupOption.EmptyFallback]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s: empty fallback proxy '%s' not found", groupName, groupOption.EmptyFallback)
|
||||
}
|
||||
|
||||
providers := []P.ProxyProvider{}
|
||||
|
||||
if groupOption.IncludeAll {
|
||||
@@ -98,7 +107,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
||||
groupOption.Proxies = append(groupOption.Proxies, AllProxies...)
|
||||
}
|
||||
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||
groupOption.Proxies = []string{"COMPATIBLE"}
|
||||
groupOption.Proxies = []string{groupOption.EmptyFallback}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,14 +185,14 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
||||
switch groupOption.Type {
|
||||
case "url-test":
|
||||
opts := parseURLTestOption(config)
|
||||
group = NewURLTest(groupOption, providers, opts...)
|
||||
group = NewURLTest(groupOption, emptyFallback, providers, opts...)
|
||||
case "select":
|
||||
group = NewSelector(groupOption, providers)
|
||||
group = NewSelector(groupOption, emptyFallback, providers)
|
||||
case "fallback":
|
||||
group = NewFallback(groupOption, providers)
|
||||
group = NewFallback(groupOption, emptyFallback, providers)
|
||||
case "load-balance":
|
||||
strategy := parseStrategy(config)
|
||||
return NewLoadBalance(groupOption, providers, strategy)
|
||||
return NewLoadBalance(groupOption, emptyFallback, providers, strategy)
|
||||
case "relay":
|
||||
return nil, fmt.Errorf("%w: The group [%s] with relay type was removed, please using dialer-proxy instead", errType, groupName)
|
||||
default:
|
||||
|
||||
@@ -62,12 +62,13 @@ func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||
}
|
||||
|
||||
return json.Marshal(map[string]any{
|
||||
"type": s.Type().String(),
|
||||
"now": s.Now(),
|
||||
"all": all,
|
||||
"testUrl": url,
|
||||
"hidden": s.Hidden(),
|
||||
"icon": s.Icon(),
|
||||
"type": s.Type().String(),
|
||||
"now": s.Now(),
|
||||
"all": all,
|
||||
"testUrl": url,
|
||||
"hidden": s.Hidden(),
|
||||
"icon": s.Icon(),
|
||||
"emptyFallback": s.EmptyFallback().Name(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -114,7 +115,7 @@ func (s *Selector) Proxies() []C.Proxy {
|
||||
return s.GetProxies(false)
|
||||
}
|
||||
|
||||
func NewSelector(option *GroupCommonOption, providers []P.ProxyProvider) *Selector {
|
||||
func NewSelector(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.ProxyProvider) *Selector {
|
||||
return &Selector{
|
||||
GroupBase: NewGroupBase(GroupBaseOption{
|
||||
Name: option.Name,
|
||||
@@ -126,9 +127,10 @@ func NewSelector(option *GroupCommonOption, providers []P.ProxyProvider) *Select
|
||||
ExcludeType: option.ExcludeType,
|
||||
TestTimeout: option.TestTimeout,
|
||||
MaxFailedTimes: option.MaxFailedTimes,
|
||||
EmptyFallback: emptyFallback,
|
||||
Providers: providers,
|
||||
}),
|
||||
selected: "COMPATIBLE",
|
||||
selected: emptyFallback.Name(),
|
||||
disableUDP: option.DisableUDP,
|
||||
testUrl: option.URL,
|
||||
}
|
||||
|
||||
@@ -180,6 +180,7 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||
"fixed": u.selected,
|
||||
"hidden": u.Hidden(),
|
||||
"icon": u.Icon(),
|
||||
"emptyFallback": u.EmptyFallback().Name(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -208,7 +209,7 @@ func parseURLTestOption(config map[string]any) []urlTestOption {
|
||||
return opts
|
||||
}
|
||||
|
||||
func NewURLTest(option *GroupCommonOption, providers []P.ProxyProvider, options ...urlTestOption) *URLTest {
|
||||
func NewURLTest(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.ProxyProvider, options ...urlTestOption) *URLTest {
|
||||
urlTest := &URLTest{
|
||||
GroupBase: NewGroupBase(GroupBaseOption{
|
||||
Name: option.Name,
|
||||
@@ -220,6 +221,7 @@ func NewURLTest(option *GroupCommonOption, providers []P.ProxyProvider, options
|
||||
ExcludeType: option.ExcludeType,
|
||||
TestTimeout: option.TestTimeout,
|
||||
MaxFailedTimes: option.MaxFailedTimes,
|
||||
EmptyFallback: emptyFallback,
|
||||
Providers: providers,
|
||||
}),
|
||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+47
-36
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/metacubex/mihomo/common/orderedmap"
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"github.com/metacubex/mihomo/common/yaml"
|
||||
"github.com/metacubex/mihomo/component/age"
|
||||
"github.com/metacubex/mihomo/component/auth"
|
||||
"github.com/metacubex/mihomo/component/cidr"
|
||||
"github.com/metacubex/mihomo/component/fakeip"
|
||||
@@ -34,6 +35,7 @@ import (
|
||||
LC "github.com/metacubex/mihomo/listener/config"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
R "github.com/metacubex/mihomo/rules"
|
||||
RB "github.com/metacubex/mihomo/rules/bundle"
|
||||
RC "github.com/metacubex/mihomo/rules/common"
|
||||
RP "github.com/metacubex/mihomo/rules/provider"
|
||||
RW "github.com/metacubex/mihomo/rules/wrapper"
|
||||
@@ -45,27 +47,26 @@ import (
|
||||
// General config
|
||||
type General struct {
|
||||
Inbound
|
||||
Mode T.TunnelMode `json:"mode"`
|
||||
UnifiedDelay bool `json:"unified-delay"`
|
||||
LogLevel log.LogLevel `json:"log-level"`
|
||||
IPv6 bool `json:"ipv6"`
|
||||
Interface string `json:"interface-name"`
|
||||
RoutingMark int `json:"routing-mark"`
|
||||
GeoXUrl GeoXUrl `json:"geox-url"`
|
||||
GeoAutoUpdate bool `json:"geo-auto-update"`
|
||||
GeoUpdateInterval int `json:"geo-update-interval"`
|
||||
GeodataMode bool `json:"geodata-mode"`
|
||||
GeodataLoader string `json:"geodata-loader"`
|
||||
GeositeMatcher string `json:"geosite-matcher"`
|
||||
TCPConcurrent bool `json:"tcp-concurrent"`
|
||||
FindProcessMode process.FindProcessMode `json:"find-process-mode"`
|
||||
Sniffing bool `json:"sniffing"`
|
||||
GlobalClientFingerprint string `json:"global-client-fingerprint"`
|
||||
GlobalUA string `json:"global-ua"`
|
||||
ETagSupport bool `json:"etag-support"`
|
||||
KeepAliveIdle int `json:"keep-alive-idle"`
|
||||
KeepAliveInterval int `json:"keep-alive-interval"`
|
||||
DisableKeepAlive bool `json:"disable-keep-alive"`
|
||||
Mode T.TunnelMode `json:"mode"`
|
||||
UnifiedDelay bool `json:"unified-delay"`
|
||||
LogLevel log.LogLevel `json:"log-level"`
|
||||
IPv6 bool `json:"ipv6"`
|
||||
Interface string `json:"interface-name"`
|
||||
RoutingMark int `json:"routing-mark"`
|
||||
GeoXUrl GeoXUrl `json:"geox-url"`
|
||||
GeoAutoUpdate bool `json:"geo-auto-update"`
|
||||
GeoUpdateInterval int `json:"geo-update-interval"`
|
||||
GeodataMode bool `json:"geodata-mode"`
|
||||
GeodataLoader string `json:"geodata-loader"`
|
||||
GeositeMatcher string `json:"geosite-matcher"`
|
||||
TCPConcurrent bool `json:"tcp-concurrent"`
|
||||
FindProcessMode process.FindProcessMode `json:"find-process-mode"`
|
||||
Sniffing bool `json:"sniffing"`
|
||||
GlobalUA string `json:"global-ua"`
|
||||
ETagSupport bool `json:"etag-support"`
|
||||
KeepAliveIdle int `json:"keep-alive-idle"`
|
||||
KeepAliveInterval int `json:"keep-alive-interval"`
|
||||
DisableKeepAlive bool `json:"disable-keep-alive"`
|
||||
}
|
||||
|
||||
// Inbound config
|
||||
@@ -595,6 +596,12 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
||||
// config with default value
|
||||
rawCfg := DefaultRawConfig()
|
||||
|
||||
// decrypt config
|
||||
buf, err := age.DecryptBytes(buf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt config error: %w", err)
|
||||
}
|
||||
|
||||
if err := yaml.Unmarshal(buf, rawCfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -739,6 +746,9 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
||||
func temporaryUpdateGeneral(general *General) func()
|
||||
|
||||
func parseGeneral(cfg *RawConfig) (*General, error) {
|
||||
if cfg.GlobalClientFingerprint != "" {
|
||||
log.Errorln("The `global-client-fingerprint` configuration is removed, please set `client-fingerprint` directly on the proxy instead")
|
||||
}
|
||||
return &General{
|
||||
Inbound: Inbound{
|
||||
Port: cfg.Port,
|
||||
@@ -768,19 +778,18 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
||||
ASN: cfg.GeoXUrl.ASN,
|
||||
GeoSite: cfg.GeoXUrl.GeoSite,
|
||||
},
|
||||
GeoAutoUpdate: cfg.GeoAutoUpdate,
|
||||
GeoUpdateInterval: cfg.GeoUpdateInterval,
|
||||
GeodataMode: cfg.GeodataMode,
|
||||
GeodataLoader: cfg.GeodataLoader,
|
||||
GeositeMatcher: cfg.GeositeMatcher,
|
||||
TCPConcurrent: cfg.TCPConcurrent,
|
||||
FindProcessMode: cfg.FindProcessMode,
|
||||
GlobalClientFingerprint: cfg.GlobalClientFingerprint,
|
||||
GlobalUA: cfg.GlobalUA,
|
||||
ETagSupport: cfg.ETagSupport,
|
||||
KeepAliveIdle: cfg.KeepAliveIdle,
|
||||
KeepAliveInterval: cfg.KeepAliveInterval,
|
||||
DisableKeepAlive: cfg.DisableKeepAlive,
|
||||
GeoAutoUpdate: cfg.GeoAutoUpdate,
|
||||
GeoUpdateInterval: cfg.GeoUpdateInterval,
|
||||
GeodataMode: cfg.GeodataMode,
|
||||
GeodataLoader: cfg.GeodataLoader,
|
||||
GeositeMatcher: cfg.GeositeMatcher,
|
||||
TCPConcurrent: cfg.TCPConcurrent,
|
||||
FindProcessMode: cfg.FindProcessMode,
|
||||
GlobalUA: cfg.GlobalUA,
|
||||
ETagSupport: cfg.ETagSupport,
|
||||
KeepAliveIdle: cfg.KeepAliveIdle,
|
||||
KeepAliveInterval: cfg.KeepAliveInterval,
|
||||
DisableKeepAlive: cfg.DisableKeepAlive,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -872,6 +881,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
||||
proxies["REJECT-DROP"] = adapter.NewProxy(outbound.NewRejectDrop())
|
||||
proxies["COMPATIBLE"] = adapter.NewProxy(outbound.NewCompatible())
|
||||
proxies["PASS"] = adapter.NewProxy(outbound.NewPass())
|
||||
proxies["PASS-RULE"] = adapter.NewProxy(outbound.NewPassRule())
|
||||
proxyList = append(proxyList, "DIRECT", "REJECT")
|
||||
|
||||
// parse proxy
|
||||
@@ -942,7 +952,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
||||
|
||||
var ps []C.Proxy
|
||||
for _, v := range proxyList {
|
||||
if proxies[v].Type() == C.Pass {
|
||||
if proxies[v].Type() == C.Pass || proxies[v].Type() == C.PassRule {
|
||||
continue
|
||||
}
|
||||
ps = append(ps, proxies[v])
|
||||
@@ -956,6 +966,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
||||
&outboundgroup.GroupCommonOption{
|
||||
Name: "GLOBAL",
|
||||
},
|
||||
proxies["COMPATIBLE"],
|
||||
[]P.ProxyProvider{pd},
|
||||
)
|
||||
proxies["GLOBAL"] = adapter.NewProxy(global)
|
||||
@@ -993,7 +1004,7 @@ func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]P.RuleProvider
|
||||
ruleProviders = map[string]P.RuleProvider{}
|
||||
// parse rule provider
|
||||
for name, mapping := range cfg.RuleProvider {
|
||||
rp, err := RP.ParseRuleProvider(name, mapping, R.ParseRule)
|
||||
rp, err := RP.ParseRuleProvider(name, mapping, R.ParseRule, RB.MakeBundleFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ const (
|
||||
RejectDrop
|
||||
Compatible
|
||||
Pass
|
||||
PassRule
|
||||
Dns
|
||||
|
||||
Relay
|
||||
@@ -183,6 +184,8 @@ func (at AdapterType) String() string {
|
||||
return "Compatible"
|
||||
case Pass:
|
||||
return "Pass"
|
||||
case PassRule:
|
||||
return "PassRule"
|
||||
case Dns:
|
||||
return "Dns"
|
||||
case Shadowsocks:
|
||||
|
||||
+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")
|
||||
}
|
||||
|
||||
@@ -152,6 +152,7 @@ type RuleWrapper interface {
|
||||
type RuleMatchHelper struct {
|
||||
ResolveIP func()
|
||||
FindProcess func()
|
||||
CheckPassRule func(adapterName string) bool
|
||||
}
|
||||
|
||||
type RuleGroup interface {
|
||||
|
||||
+47
-40
@@ -5,12 +5,14 @@ import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/contextutils"
|
||||
"github.com/metacubex/mihomo/common/pool"
|
||||
"github.com/metacubex/mihomo/component/ca"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
@@ -112,7 +114,7 @@ func (doq *dnsOverQUIC) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.M
|
||||
// make DoQ usable. We need to make 2 attempts in the case when the
|
||||
// connection was closed (due to inactivity for example) AND the server
|
||||
// refuses to open a 0-RTT connection.
|
||||
for i := 0; hasConnection && doq.shouldRetry(err) && i < 2; i++ {
|
||||
for i := 0; hasConnection && doq.shouldRetry(err) && ctx.Err() == nil && i < 2; i++ {
|
||||
log.Debugln("re-creating the QUIC connection and retrying due to %v", err)
|
||||
|
||||
// Close the active connection to make sure we'll try to re-connect.
|
||||
@@ -152,25 +154,39 @@ func (doq *dnsOverQUIC) ResetConnection() {
|
||||
// exchangeQUIC attempts to open a QUIC connection, send the DNS message
|
||||
// through it and return the response it got from the server.
|
||||
func (doq *dnsOverQUIC) exchangeQUIC(ctx context.Context, msg *D.Msg) (resp *D.Msg, err error) {
|
||||
// All DNS messages (queries and responses) sent over DoQ connections MUST
|
||||
// be encoded as a 2-octet length field followed by the message content as
|
||||
// specified in [RFC1035].
|
||||
// Note: we do not support receiving multiple messages over a single connection.
|
||||
buf := pool.Get(2 + MaxMsgSize)
|
||||
defer pool.Put(buf)
|
||||
b, err := msg.PackBuffer(buf[2:])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to pack DNS message for DoQ: %w", err)
|
||||
}
|
||||
if len(b) > MaxMsgSize {
|
||||
return nil, fmt.Errorf("DNS message is too large: %d > %d", len(b), MaxMsgSize)
|
||||
}
|
||||
binary.BigEndian.PutUint16(buf, uint16(len(b)))
|
||||
|
||||
var conn *quic.Conn
|
||||
conn, err = doq.getConnection(ctx, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var buf []byte
|
||||
buf, err = msg.Pack()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to pack DNS message for DoQ: %w", err)
|
||||
}
|
||||
|
||||
var stream *quic.Stream
|
||||
stream, err = doq.openStream(ctx, conn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = stream.Write(AddPrefix(buf))
|
||||
stop := contextutils.AfterFunc(ctx, func() {
|
||||
_ = stream.SetDeadline(time.Now()) // cancel any read or write operation on this stream
|
||||
})
|
||||
defer stop()
|
||||
|
||||
_, err = stream.Write(buf[:2+len(b)])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to write to a QUIC stream: %w", err)
|
||||
}
|
||||
@@ -181,16 +197,31 @@ func (doq *dnsOverQUIC) exchangeQUIC(ctx context.Context, msg *D.Msg) (resp *D.M
|
||||
// write-direction of the stream, but does not prevent reading from it.
|
||||
_ = stream.Close()
|
||||
|
||||
return doq.readMsg(stream)
|
||||
}
|
||||
// -- reading the response ---
|
||||
var respLen uint16
|
||||
err = binary.Read(stream, binary.BigEndian, &respLen)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading response length from %s: %w", doq.Address(), err)
|
||||
}
|
||||
if respLen == 0 {
|
||||
return nil, fmt.Errorf("received empty response from %s", doq.Address())
|
||||
}
|
||||
if respLen > MaxMsgSize {
|
||||
return nil, fmt.Errorf("received response that is too large: %d > %d", respLen, MaxMsgSize)
|
||||
}
|
||||
|
||||
// AddPrefix adds a 2-byte prefix with the DNS message length.
|
||||
func AddPrefix(b []byte) (m []byte) {
|
||||
m = make([]byte, 2+len(b))
|
||||
binary.BigEndian.PutUint16(m, uint16(len(b)))
|
||||
copy(m[2:], b)
|
||||
_, err = io.ReadFull(stream, buf[:respLen])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading response from %s: %w", doq.Address(), err)
|
||||
}
|
||||
|
||||
return m
|
||||
resp = new(D.Msg)
|
||||
err = resp.Unpack(buf[:respLen])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unpacking response from %s: %w", doq.Address(), err)
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// shouldRetry checks what error we received and decides whether it is required
|
||||
@@ -363,30 +394,6 @@ func (doq *dnsOverQUIC) closeConnWithError(err error) {
|
||||
doq.conn = nil
|
||||
}
|
||||
|
||||
// readMsg reads the incoming DNS message from the QUIC stream.
|
||||
func (doq *dnsOverQUIC) readMsg(stream *quic.Stream) (m *D.Msg, err error) {
|
||||
respBuf := pool.Get(MaxMsgSize)
|
||||
defer pool.Put(respBuf)
|
||||
|
||||
n, err := stream.Read(respBuf)
|
||||
if err != nil && n == 0 {
|
||||
return nil, fmt.Errorf("reading response from %s: %w", doq.Address(), err)
|
||||
}
|
||||
|
||||
// All DNS messages (queries and responses) sent over DoQ connections MUST
|
||||
// be encoded as a 2-octet length field followed by the message content as
|
||||
// specified in [RFC1035].
|
||||
// IMPORTANT: Note, that we ignore this prefix here as this implementation
|
||||
// does not support receiving multiple messages over a single connection.
|
||||
m = new(D.Msg)
|
||||
err = m.Unpack(respBuf[2:])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unpacking response from %s: %w", doq.Address(), err)
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// newQUICTokenStore creates a new quic.TokenStore that is necessary to have
|
||||
// in order to benefit from 0-RTT.
|
||||
func newQUICTokenStore() (s quic.TokenStore) {
|
||||
|
||||
+28
-2
@@ -1199,6 +1199,8 @@ proxies: # socks5
|
||||
# 00000000000000000000000000000000
|
||||
# ...
|
||||
# -----END OpenVPN Static key V1-----
|
||||
# ping: 10 # 默认值为 0
|
||||
# ping-restart: 60 # 默认值为 0
|
||||
# mtu: 1500
|
||||
udp: true
|
||||
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
|
||||
@@ -1457,6 +1459,7 @@ proxy-groups:
|
||||
proxies:
|
||||
- Proxy
|
||||
- DIRECT
|
||||
# empty-fallback: COMPATIBLE # 设置当组为空时的回退proxy
|
||||
|
||||
# Mihomo 格式的节点或支持 *ray 的分享格式
|
||||
proxy-providers:
|
||||
@@ -1467,6 +1470,22 @@ proxy-providers:
|
||||
path: ./provider1.yaml # 默认只允许存储在 mihomo 的 Home Dir,如果想存储到其他位置,请通过设置 SAFE_PATHS 环境变量指定额外的安全路径。该环境变量的语法同本操作系统的PATH环境变量解析规则(即Windows下以分号分割,其他系统下以冒号分割)
|
||||
proxy: DIRECT
|
||||
# size-limit: 10240 # 限制下载文件最大为10kb,默认为0即不限制文件大小
|
||||
# #
|
||||
# # 如果设置会age-secret-key尝试通过此secret解密age armor格式加密的配置文件
|
||||
# #
|
||||
# # 注意:
|
||||
# # 对于加密内容,目前仅支持 age-encryption.org/v1 的 official ASCII "armor" format
|
||||
# # 对于key格式,目前仅支持 age-encryption.org/v1 的 x25519 recipient type 和 The mlkem768-x25519 hybrid post-quantum recipient type
|
||||
# # 实用工具:
|
||||
# # 您可以通过 "mihomo age keygen" 生成符合要求的 x25519 key
|
||||
# # 您可以通过 "mihomo age keygen-pq" 生成符合要求的 mlkem768-x25519 key
|
||||
# # 您可以通过 "mihomo age convert <secret_key>" 从 age-secret-key 导出 age-public-key
|
||||
# # 您可以通过 "mihomo age decrypt <secret_key> <source_file> <target_file>" 将已加密文件解密,<source_file> 为 - 时会从标准输入读取,<target_file> 为 - 时会往标准输出写入
|
||||
# # 您可以通过 "mihomo age encrypt <public_key> <source_file> <target_file>" 将未加密文件加密,<source_file> 为 - 时会从标准输入读取,<target_file> 为 - 时会往标准输出写入
|
||||
# # 参考实现:
|
||||
# # https://github.com/FiloSottile/awesome-age#implementations
|
||||
# #
|
||||
# age-secret-key: AGE-SECRET-KEY-1ZTQLLN0A4U3ZTT3DCZKYN0CGZEZQLWX2DFTXUWMT4ZHR0N2UG6LSW9NT0N
|
||||
header:
|
||||
User-Agent:
|
||||
- "Clash/v1.18.0"
|
||||
@@ -1475,6 +1494,8 @@ proxy-providers:
|
||||
# - 'application/vnd.github.v3.raw'
|
||||
# Authorization:
|
||||
# - 'token 1231231'
|
||||
# X-Age-Public-Key:
|
||||
# - 'age1xh86kh9v23vattr58yedspm3f57sxvnswu9krr6ns438amekx5gsd09uma'
|
||||
health-check:
|
||||
enable: true
|
||||
interval: 600
|
||||
@@ -1549,6 +1570,7 @@ rule-providers:
|
||||
format: mrs
|
||||
behavior: domain
|
||||
path: /path/to/save/file.mrs
|
||||
# path-in-bundle: "geo/geosite/cn.mrs" # 当设置该选项时,如果本地文件不存在,会优先从 Home Dir的 BundleMRS.7z 中解压该文件,此项的值用于指定在 BundleMRS.7z 中的路径
|
||||
rule4:
|
||||
type: inline
|
||||
behavior: domain # classical / ipcidr
|
||||
@@ -1904,7 +1926,8 @@ listeners:
|
||||
after-bytes: 0 # 传输指定字节后开始限速
|
||||
bytes-per-sec: 0 # 基准速率(字节/秒)
|
||||
burst-bytes-per-sec: 0 # 突发速率(字节/秒),大于 bytesPerSec 时生效
|
||||
### 注意,对于vless listener, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “decryption” 的其中一项 ###
|
||||
### 注意,对于vless listener, 如果 "allow-insecure" 不为 true, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “decryption” 的其中一项 ###
|
||||
# allow-insecure: false # 是否允许不开启tls加密(注意:仅用于有 nginx, caddy 前置的情况)
|
||||
|
||||
- name: anytls-in-1
|
||||
type: anytls
|
||||
@@ -1926,6 +1949,8 @@ listeners:
|
||||
# madSJjYQIf9o1N5GXjkW4DEEeb17qMxHdwMdNnwADAABAAEAAQACAAEAAwAIdGVz
|
||||
# dC5jb20AAA==
|
||||
# -----END ECH KEYS-----
|
||||
### 注意,anytls listener, 如果 "allow-insecure" 不为 true, 必须填写 “certificate和private-key” ###
|
||||
# allow-insecure: false # 是否允许不开启tls加密(注意:仅用于有 nginx, caddy 前置的情况)
|
||||
# padding-scheme: "" # https://github.com/anytls/anytls-go/blob/main/docs/protocol.md#cmdupdatepaddingscheme
|
||||
|
||||
- name: mieru-in-1
|
||||
@@ -2010,7 +2035,8 @@ listeners:
|
||||
# enabled: false
|
||||
# method: aes-128-gcm # aes-128-gcm/aes-256-gcm/chacha20-ietf-poly1305
|
||||
# password: "example"
|
||||
### 注意,对于trojan listener, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “ss-option” 的其中一项 ###
|
||||
### 注意,对于trojan listener, 如果 "allow-insecure" 不为 true, 至少需要填写 “certificate和private-key” 或 “reality-config” 或 “ss-option” 的其中一项 ###
|
||||
# allow-insecure: false # 是否允许不开启tls加密(注意:仅用于有 nginx, caddy 前置的情况)
|
||||
|
||||
- name: hysteria2-in-1
|
||||
type: hysteria2
|
||||
|
||||
@@ -10,6 +10,7 @@ require (
|
||||
github.com/gobwas/ws v1.4.0
|
||||
github.com/gofrs/uuid/v5 v5.4.0
|
||||
github.com/golang/snappy v1.0.0
|
||||
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d
|
||||
github.com/metacubex/bart v0.26.0
|
||||
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b
|
||||
@@ -28,6 +29,7 @@ require (
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260520020949-fcd18c7b6ace
|
||||
github.com/metacubex/randv2 v0.2.0
|
||||
github.com/metacubex/restls-client-go v0.1.7
|
||||
github.com/metacubex/sevenzip v1.6.4
|
||||
github.com/metacubex/sing v0.5.7
|
||||
github.com/metacubex/sing-mux v0.3.9
|
||||
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3
|
||||
@@ -79,7 +81,9 @@ require (
|
||||
github.com/ajg/form v1.5.1 // indirect
|
||||
github.com/akutz/memconn v0.1.0 // indirect
|
||||
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa // indirect
|
||||
github.com/andybalholm/brotli v1.0.6 // indirect
|
||||
github.com/andybalholm/brotli v1.1.1 // indirect
|
||||
github.com/bodgit/plumbing v1.3.0 // indirect
|
||||
github.com/bodgit/windows v1.0.1 // indirect
|
||||
github.com/coder/websocket v1.8.12 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dunglas/httpsfv v1.0.2 // indirect
|
||||
@@ -98,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
|
||||
@@ -116,7 +121,7 @@ require (
|
||||
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
|
||||
@@ -124,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
|
||||
|
||||
@@ -9,11 +9,15 @@ github.com/akutz/memconn v0.1.0 h1:NawI0TORU4hcOMsMr11g7vwlCdkYeLKXBcxWu2W/P8A=
|
||||
github.com/akutz/memconn v0.1.0/go.mod h1:Jo8rI7m0NieZyLI5e2CDlRdRqRRB4S7Xp77ukDjH+Fw=
|
||||
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI=
|
||||
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
|
||||
github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI=
|
||||
github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
||||
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
|
||||
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk=
|
||||
github.com/bodgit/plumbing v1.3.0 h1:pf9Itz1JOQgn7vEOE7v7nlEfBykYqvUYioC61TwWCFU=
|
||||
github.com/bodgit/plumbing v1.3.0/go.mod h1:JOTb4XiRu5xfnmdnDJo6GmSbSbtSyufrsyZFByMtKEs=
|
||||
github.com/bodgit/windows v1.0.1 h1:tF7K6KOluPYygXa3Z2594zxlkbKPAOvqr97etrGNIz4=
|
||||
github.com/bodgit/windows v1.0.1/go.mod h1:a6JLwrB4KrTR5hBpp8FI9/9W9jJfeQ2h4XDXU74ZCdM=
|
||||
github.com/cilium/ebpf v0.12.3 h1:8ht6F9MquybnY97at+VDZb3eQQr8ev79RueWeVaEcG4=
|
||||
github.com/coder/websocket v1.8.12 h1:5bUXkEPPIbewrnkU8LTCLVaxi4N4J8ahufH2vlo4NAo=
|
||||
github.com/coder/websocket v1.8.12/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
|
||||
@@ -69,6 +73,8 @@ github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN
|
||||
github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8 h1:FKHo8hFI3A+7w0aUQuYXQ+6EN5stWmeY/AZqtM8xk9k=
|
||||
github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo=
|
||||
github.com/google/tink/go v1.6.1 h1:t7JHqO8Ath2w2ig5vjwQYJzhGEZymedQc90lQXUBa4I=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc=
|
||||
github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8=
|
||||
github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905 h1:q3OEI9RaN/wwcx+qgGo6ZaoJkCiDYe/gjDLfq7lQQF4=
|
||||
@@ -91,6 +97,8 @@ github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/
|
||||
github.com/mdlayher/netlink v1.7.2/go.mod h1:xraEF7uJbxLhc5fpHL4cPe221LI2bdttWlU+ZGLfQSw=
|
||||
github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
|
||||
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
|
||||
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78 h1:LqWr0vb9zDNuQS+jJd4fnRYk/SEI7KJ7TDe/L4WFK48=
|
||||
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78/go.mod h1:BTBG/iVY7rg3qq5WdVCg0GFk58CSvCDSbjy8I7kEx/c=
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d h1:vAJ0ZT4aO803F1uw2roIA9yH7Sxzox34tVVyye1bz6c=
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d/go.mod h1:MsM/5czONyXMJ3PRr5DbQ4O/BxzAnJWOIcJdLzW6qHY=
|
||||
github.com/metacubex/ascon v0.1.0 h1:6ZWxmXYszT1XXtwkf6nxfFhc/OTtQ9R3Vyj1jN32lGM=
|
||||
@@ -143,6 +151,8 @@ github.com/metacubex/randv2 v0.2.0 h1:uP38uBvV2SxYfLj53kuvAjbND4RUDfFJjwr4UigMiL
|
||||
github.com/metacubex/randv2 v0.2.0/go.mod h1:kFi2SzrQ5WuneuoLLCMkABtiBu6VRrMrWFqSPyj2cxY=
|
||||
github.com/metacubex/restls-client-go v0.1.7 h1:eCwiXCTQb5WJu9IlgYvDBA1OgrINv58dEe7hcN5H15k=
|
||||
github.com/metacubex/restls-client-go v0.1.7/go.mod h1:BN/U52vPw7j8VTSh2vleD/MnmVKCov84mS5VcjVHH4g=
|
||||
github.com/metacubex/sevenzip v1.6.4 h1:OIL+DeOeSAbKNsjqxcYUMiarRmX6Kaxakb0GT7E9Oik=
|
||||
github.com/metacubex/sevenzip v1.6.4/go.mod h1:FP3X9bzFKj9wPxifGN9B3w2fIEicMjzKYIGIhnu+1pw=
|
||||
github.com/metacubex/sing v0.5.7 h1:8OC+fhKFSv/l9ehEhJRaZZAOuthfZo68SteBVLe8QqM=
|
||||
github.com/metacubex/sing v0.5.7/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w=
|
||||
github.com/metacubex/sing-mux v0.3.9 h1:/aoBD2+sK2qsXDlNDe3hkR0GZuFDtwIZhOeGUx9W0Yk=
|
||||
@@ -194,8 +204,9 @@ 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=
|
||||
@@ -218,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=
|
||||
@@ -234,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=
|
||||
@@ -246,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=
|
||||
|
||||
+13
-20
@@ -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
|
||||
@@ -425,11 +423,6 @@ func updateGeneral(general *config.General, logging bool) {
|
||||
geodata.SetASNUrl(general.GeoXUrl.ASN)
|
||||
mihomoHttp.SetUA(general.GlobalUA)
|
||||
resource.SetETag(general.ETagSupport)
|
||||
|
||||
if general.GlobalClientFingerprint != "" {
|
||||
log.Warnln("The `global-client-fingerprint` configuration is deprecated, please set `client-fingerprint` directly on the proxy instead")
|
||||
}
|
||||
tlsC.SetGlobalFingerprint(general.GlobalClientFingerprint)
|
||||
}
|
||||
|
||||
func updateUsers(users []auth.AuthUser) {
|
||||
|
||||
@@ -112,8 +112,8 @@ func New(config LC.AnyTLSServer, tunnel C.Tunnel, additions ...inbound.Addition)
|
||||
}
|
||||
if tlsConfig.GetCertificate != nil {
|
||||
l = tls.NewListener(l, tlsConfig)
|
||||
} else {
|
||||
return nil, errors.New("disallow using AnyTLS without certificates config")
|
||||
} else if !config.AllowInsecure {
|
||||
return nil, errors.New("disallow using AnyTLS without certificates/allow-insecure config")
|
||||
}
|
||||
sl.listeners = append(sl.listeners, l)
|
||||
|
||||
|
||||
@@ -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"`
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ type TrojanServer struct {
|
||||
ClientAuthType string
|
||||
ClientAuthCert string
|
||||
EchKey string
|
||||
AllowInsecure bool
|
||||
RealityConfig reality.Config
|
||||
MuxOption sing.MuxOption
|
||||
TrojanSSOption TrojanSSOption
|
||||
|
||||
@@ -26,6 +26,7 @@ type VlessServer struct {
|
||||
ClientAuthType string
|
||||
ClientAuthCert string
|
||||
EchKey string
|
||||
AllowInsecure bool
|
||||
RealityConfig reality.Config
|
||||
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ type AnyTLSOption struct {
|
||||
ClientAuthType string `inbound:"client-auth-type,omitempty"`
|
||||
ClientAuthCert string `inbound:"client-auth-cert,omitempty"`
|
||||
EchKey string `inbound:"ech-key,omitempty"`
|
||||
AllowInsecure bool `inbound:"allow-insecure,omitempty"`
|
||||
PaddingScheme string `inbound:"padding-scheme,omitempty"`
|
||||
}
|
||||
|
||||
@@ -48,6 +49,7 @@ func NewAnyTLS(options *AnyTLSOption) (*AnyTLS, error) {
|
||||
ClientAuthType: options.ClientAuthType,
|
||||
ClientAuthCert: options.ClientAuthCert,
|
||||
EchKey: options.EchKey,
|
||||
AllowInsecure: options.AllowInsecure,
|
||||
PaddingScheme: options.PaddingScheme,
|
||||
},
|
||||
}, nil
|
||||
|
||||
@@ -19,6 +19,7 @@ type TrojanOption struct {
|
||||
ClientAuthType string `inbound:"client-auth-type,omitempty"`
|
||||
ClientAuthCert string `inbound:"client-auth-cert,omitempty"`
|
||||
EchKey string `inbound:"ech-key,omitempty"`
|
||||
AllowInsecure bool `inbound:"allow-insecure,omitempty"`
|
||||
RealityConfig RealityConfig `inbound:"reality-config,omitempty"`
|
||||
MuxOption MuxOption `inbound:"mux-option,omitempty"`
|
||||
SSOption TrojanSSOption `inbound:"ss-option,omitempty"`
|
||||
@@ -73,6 +74,7 @@ func NewTrojan(options *TrojanOption) (*Trojan, error) {
|
||||
ClientAuthType: options.ClientAuthType,
|
||||
ClientAuthCert: options.ClientAuthCert,
|
||||
EchKey: options.EchKey,
|
||||
AllowInsecure: options.AllowInsecure,
|
||||
RealityConfig: options.RealityConfig.Build(),
|
||||
MuxOption: options.MuxOption.Build(),
|
||||
TrojanSSOption: LC.TrojanSSOption{
|
||||
|
||||
@@ -21,6 +21,7 @@ type VlessOption struct {
|
||||
ClientAuthType string `inbound:"client-auth-type,omitempty"`
|
||||
ClientAuthCert string `inbound:"client-auth-cert,omitempty"`
|
||||
EchKey string `inbound:"ech-key,omitempty"`
|
||||
AllowInsecure bool `inbound:"allow-insecure,omitempty"`
|
||||
RealityConfig RealityConfig `inbound:"reality-config,omitempty"`
|
||||
MuxOption MuxOption `inbound:"mux-option,omitempty"`
|
||||
}
|
||||
@@ -121,6 +122,7 @@ func NewVless(options *VlessOption) (*Vless, error) {
|
||||
ClientAuthType: options.ClientAuthType,
|
||||
ClientAuthCert: options.ClientAuthCert,
|
||||
EchKey: options.EchKey,
|
||||
AllowInsecure: options.AllowInsecure,
|
||||
RealityConfig: options.RealityConfig.Build(),
|
||||
MuxOption: options.MuxOption.Build(),
|
||||
},
|
||||
|
||||
@@ -229,8 +229,8 @@ func New(config LC.VlessServer, tunnel C.Tunnel, additions ...inbound.Addition)
|
||||
l = realityBuilder.NewListener(l)
|
||||
} else if tlsConfig.GetCertificate != nil {
|
||||
l = tls.NewListener(l, tlsConfig)
|
||||
} else if sl.decryption == nil {
|
||||
return nil, errors.New("disallow using Vless without any certificates/reality/decryption config")
|
||||
} else if sl.decryption == nil && !config.AllowInsecure {
|
||||
return nil, errors.New("disallow using Vless without any certificates/reality/decryption/allow-insecure config")
|
||||
}
|
||||
sl.listeners = append(sl.listeners, l)
|
||||
|
||||
|
||||
@@ -168,8 +168,8 @@ func New(config LC.TrojanServer, tunnel C.Tunnel, additions ...inbound.Addition)
|
||||
l = realityBuilder.NewListener(l)
|
||||
} else if tlsConfig.GetCertificate != nil {
|
||||
l = tls.NewListener(l, tlsConfig)
|
||||
} else if !config.TrojanSSOption.Enabled {
|
||||
return nil, errors.New("disallow using Trojan without both certificates/reality/ss config")
|
||||
} else if !config.TrojanSSOption.Enabled && !config.AllowInsecure {
|
||||
return nil, errors.New("disallow using Trojan without both certificates/reality/ss/allow-insecure config")
|
||||
}
|
||||
sl.listeners = append(sl.listeners, l)
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"syscall"
|
||||
|
||||
"github.com/metacubex/mihomo/common/cmd"
|
||||
"github.com/metacubex/mihomo/component/age"
|
||||
"github.com/metacubex/mihomo/component/generator"
|
||||
"github.com/metacubex/mihomo/component/geodata"
|
||||
"github.com/metacubex/mihomo/component/updater"
|
||||
@@ -37,6 +38,7 @@ var (
|
||||
configFile string
|
||||
configString string
|
||||
configBytes []byte
|
||||
ageSecretKey string
|
||||
externalUI string
|
||||
externalController string
|
||||
externalControllerUnix string
|
||||
@@ -50,6 +52,7 @@ func init() {
|
||||
flag.StringVar(&homeDir, "d", os.Getenv("CLASH_HOME_DIR"), "set configuration directory")
|
||||
flag.StringVar(&configFile, "f", os.Getenv("CLASH_CONFIG_FILE"), "specify configuration file")
|
||||
flag.StringVar(&configString, "config", os.Getenv("CLASH_CONFIG_STRING"), "specify base64-encoded configuration string")
|
||||
flag.StringVar(&ageSecretKey, "age-secret-key", os.Getenv("CLASH_AGE_SECRET_KEY"), "specify age secret key to decrypt configuration")
|
||||
flag.StringVar(&externalUI, "ext-ui", os.Getenv("CLASH_OVERRIDE_EXTERNAL_UI_DIR"), "override external ui directory")
|
||||
flag.StringVar(&externalController, "ext-ctl", os.Getenv("CLASH_OVERRIDE_EXTERNAL_CONTROLLER"), "override external controller address")
|
||||
flag.StringVar(&externalControllerUnix, "ext-ctl-unix", os.Getenv("CLASH_OVERRIDE_EXTERNAL_CONTROLLER_UNIX"), "override external controller unix address")
|
||||
@@ -94,6 +97,11 @@ func main() {
|
||||
return
|
||||
}
|
||||
|
||||
if len(os.Args) > 1 && os.Args[1] == "age" {
|
||||
age.Main(os.Args[2:])
|
||||
return
|
||||
}
|
||||
|
||||
if version {
|
||||
fmt.Printf("Mihomo Meta %s %s %s with %s %s\n",
|
||||
C.Version, runtime.GOOS, runtime.GOARCH, runtime.Version(), C.BuildTime)
|
||||
@@ -116,6 +124,13 @@ func main() {
|
||||
geodata.SetGeodataMode(true)
|
||||
}
|
||||
|
||||
if ageSecretKey != "" {
|
||||
if err := age.VeritySecretKeys(ageSecretKey); err != nil {
|
||||
log.Errorln("Parse age-secret-key error: %s", err.Error())
|
||||
}
|
||||
age.SetGlobalSecretKeys(ageSecretKey)
|
||||
}
|
||||
|
||||
if configString != "" {
|
||||
var err error
|
||||
configBytes, err = base64.StdEncoding.DecodeString(configString)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package bundle
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
|
||||
"github.com/metacubex/mihomo/component/resource"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
|
||||
"github.com/metacubex/sevenzip"
|
||||
)
|
||||
|
||||
func MakeBundleFile(path string) resource.BundleFile {
|
||||
if path == "" {
|
||||
return nil
|
||||
}
|
||||
return func() (fs.File, error) {
|
||||
return Open(path)
|
||||
}
|
||||
}
|
||||
|
||||
func Open(path string) (fs.File, error) {
|
||||
r, err := sevenzip.OpenReader(C.Path.BundleMRS())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open bundle file error: %w", err)
|
||||
}
|
||||
f, err := r.Open(path)
|
||||
if err != nil {
|
||||
_ = r.Close()
|
||||
return nil, fmt.Errorf("open path in bundle file error: %w", err)
|
||||
}
|
||||
return file{f, r}, nil
|
||||
}
|
||||
|
||||
type file struct {
|
||||
fs.File
|
||||
closer io.Closer
|
||||
}
|
||||
|
||||
func (f file) Close() error {
|
||||
err1 := f.File.Close()
|
||||
err2 := f.closer.Close()
|
||||
return errors.Join(err1, err2)
|
||||
}
|
||||
@@ -180,10 +180,12 @@ func matchSubRules(metadata *C.Metadata, name string, subRules map[string][]C.Ru
|
||||
for _, rule := range subRules[name] {
|
||||
if m, a := rule.Match(metadata, helper); m {
|
||||
if rule.RuleType() == C.SubRules {
|
||||
return matchSubRules(metadata, rule.Adapter(), subRules, helper)
|
||||
} else {
|
||||
return m, a
|
||||
m, a = matchSubRules(metadata, rule.Adapter(), subRules, helper)
|
||||
}
|
||||
if m && (a == "PASS-RULE" || (helper.CheckPassRule != nil && helper.CheckPassRule(a))) {
|
||||
continue
|
||||
}
|
||||
return m, a
|
||||
}
|
||||
}
|
||||
return false, ""
|
||||
|
||||
+13
-12
@@ -12,19 +12,20 @@ import (
|
||||
)
|
||||
|
||||
type ruleProviderSchema struct {
|
||||
Type string `provider:"type"`
|
||||
Behavior string `provider:"behavior"`
|
||||
Path string `provider:"path,omitempty"`
|
||||
URL string `provider:"url,omitempty"`
|
||||
Proxy string `provider:"proxy,omitempty"`
|
||||
Format string `provider:"format,omitempty"`
|
||||
Interval int `provider:"interval,omitempty"`
|
||||
SizeLimit int64 `provider:"size-limit,omitempty"`
|
||||
Payload []string `provider:"payload,omitempty"`
|
||||
Header map[string][]string `provider:"header,omitempty"`
|
||||
Type string `provider:"type"`
|
||||
Behavior string `provider:"behavior"`
|
||||
Path string `provider:"path,omitempty"`
|
||||
URL string `provider:"url,omitempty"`
|
||||
Proxy string `provider:"proxy,omitempty"`
|
||||
Format string `provider:"format,omitempty"`
|
||||
Interval int `provider:"interval,omitempty"`
|
||||
SizeLimit int64 `provider:"size-limit,omitempty"`
|
||||
Payload []string `provider:"payload,omitempty"`
|
||||
Header map[string][]string `provider:"header,omitempty"`
|
||||
PathInBundle string `provider:"path-in-bundle,omitempty"`
|
||||
}
|
||||
|
||||
func ParseRuleProvider(name string, mapping map[string]any, parse common.ParseRuleFunc) (P.RuleProvider, error) {
|
||||
func ParseRuleProvider(name string, mapping map[string]any, parse common.ParseRuleFunc, makeBundleFile func(pathInBundle string) resource.BundleFile) (P.RuleProvider, error) {
|
||||
schema := &ruleProviderSchema{}
|
||||
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
||||
if err := decoder.Decode(mapping, schema); err != nil {
|
||||
@@ -64,5 +65,5 @@ func ParseRuleProvider(name string, mapping map[string]any, parse common.ParseRu
|
||||
|
||||
interval := time.Duration(uint(schema.Interval)) * time.Second
|
||||
|
||||
return NewRuleSetProvider(name, behavior, format, interval, vehicle, schema.Payload, parse), nil
|
||||
return NewRuleSetProvider(name, behavior, format, interval, vehicle, schema.Payload, makeBundleFile(schema.PathInBundle), parse), nil
|
||||
}
|
||||
@@ -122,7 +122,7 @@ func (rp *RuleSetProvider) Close() error {
|
||||
return rp.ruleSetProvider.Close()
|
||||
}
|
||||
|
||||
func NewRuleSetProvider(name string, behavior P.RuleBehavior, format P.RuleFormat, interval time.Duration, vehicle P.Vehicle, payload []string, parse common.ParseRuleFunc) P.RuleProvider {
|
||||
func NewRuleSetProvider(name string, behavior P.RuleBehavior, format P.RuleFormat, interval time.Duration, vehicle P.Vehicle, payload []string, bundleFile resource.BundleFile, parse common.ParseRuleFunc) P.RuleProvider {
|
||||
rp := &ruleSetProvider{
|
||||
baseProvider: baseProvider{
|
||||
behavior: behavior,
|
||||
@@ -139,7 +139,7 @@ func NewRuleSetProvider(name string, behavior P.RuleBehavior, format P.RuleForma
|
||||
if len(payload) > 0 { // using as fallback rules
|
||||
rp.strategy = rulesParseInline(payload, rp.strategy)
|
||||
}
|
||||
rp.Fetcher = resource.NewFetcher(name, interval, vehicle, func(bytes []byte) (ruleStrategy, error) {
|
||||
rp.Fetcher = resource.NewFetcher(name, interval, vehicle, bundleFile, func(bytes []byte) (ruleStrategy, error) {
|
||||
return rulesParse(bytes, newStrategy(behavior, parse), format)
|
||||
}, onUpdate)
|
||||
|
||||
|
||||
@@ -9,9 +9,11 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/tls"
|
||||
"golang.org/x/sync/semaphore"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -29,6 +31,11 @@ type Client struct {
|
||||
push *PushReply
|
||||
|
||||
cancel context.CancelFunc
|
||||
|
||||
writeSem semaphore.Weighted
|
||||
|
||||
lastSendNano atomic.Int64
|
||||
lastReceiveNano atomic.Int64
|
||||
}
|
||||
|
||||
func NewClient(config *ClientConfig, io PacketIO) (*Client, error) {
|
||||
@@ -53,12 +60,15 @@ func NewClient(config *ClientConfig, io PacketIO) (*Client, error) {
|
||||
runCtx, cancel := context.WithCancel(context.Background())
|
||||
mux := NewPacketMux(io)
|
||||
go mux.Run(runCtx)
|
||||
return &Client{
|
||||
client := &Client{
|
||||
config: config,
|
||||
mux: mux,
|
||||
control: NewControlChannel(mux, crypt, local),
|
||||
cancel: cancel,
|
||||
}, nil
|
||||
}
|
||||
client.markSend()
|
||||
client.markReceive()
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *Client) Handshake(ctx context.Context) (*PushReply, error) {
|
||||
@@ -126,22 +136,48 @@ func (c *Client) Handshake(ctx context.Context) (*PushReply, error) {
|
||||
return nil, err
|
||||
}
|
||||
c.push = push
|
||||
c.data, err = NewDataChannel(keys, c.config.Cipher, c.config.Auth, push.PeerID, c.config.CompLZO)
|
||||
c.data, err = NewDataChannel(keys, c.config.Cipher, c.config.Auth, push.PeerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.markSend()
|
||||
c.markReceive()
|
||||
return push, nil
|
||||
}
|
||||
|
||||
func (c *Client) WriteIPPacket(ctx context.Context, packet []byte) error {
|
||||
return c.writeDataPacket(ctx, packet, true)
|
||||
}
|
||||
|
||||
func (c *Client) WritePing(ctx context.Context) error {
|
||||
return c.writeDataPacket(ctx, openVPNPingPacket, false)
|
||||
}
|
||||
|
||||
func (c *Client) writeDataPacket(ctx context.Context, packet []byte, compress bool) error {
|
||||
if c.data == nil {
|
||||
return errors.New("openvpn data channel is not ready")
|
||||
}
|
||||
if err := c.writeSem.Acquire(ctx, 1); err != nil {
|
||||
return err
|
||||
}
|
||||
defer c.writeSem.Release(1)
|
||||
if compress && c.config.CompLZO == CompLzoYes {
|
||||
compressed, err := lzo1xCompressSafe(packet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
packet = compressed
|
||||
}
|
||||
encrypted, err := c.data.Encrypt(packet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.mux.WritePacket(ctx, encrypted)
|
||||
err = c.mux.WritePacket(ctx, encrypted)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.markSend()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) ReadIPPacket(ctx context.Context) ([]byte, error) {
|
||||
@@ -157,10 +193,38 @@ func (c *Client) ReadIPPacket(ctx context.Context) ([]byte, error) {
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
c.markReceive()
|
||||
if IsPingPacket(plain) {
|
||||
continue
|
||||
}
|
||||
if c.config.CompLZO == CompLzoYes && len(plain) > 0 {
|
||||
return lzo1xDecompressSafe(plain)
|
||||
}
|
||||
return plain, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) SinceSend() time.Duration {
|
||||
return time.Duration(int64(time.Since(start)) - c.lastSendNano.Load())
|
||||
}
|
||||
|
||||
func (c *Client) SinceReceive() time.Duration {
|
||||
return time.Duration(int64(time.Since(start)) - c.lastReceiveNano.Load())
|
||||
}
|
||||
|
||||
func (c *Client) markSend() {
|
||||
c.lastSendNano.Store(int64(time.Since(start)))
|
||||
}
|
||||
|
||||
func (c *Client) markReceive() {
|
||||
c.lastReceiveNano.Store(int64(time.Since(start)))
|
||||
}
|
||||
|
||||
// The absolute value doesn't matter, but it should be in the past,
|
||||
// so that every timestamp obtained with Now() is non-zero,
|
||||
// even on systems with low timer resolutions (e.g. Windows).
|
||||
var start = time.Now().Add(-time.Hour)
|
||||
|
||||
func (c *Client) Close() error {
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -50,6 +51,9 @@ type ClientConfig struct {
|
||||
Username string
|
||||
Password string
|
||||
|
||||
PingInterval time.Duration
|
||||
PingRestart time.Duration
|
||||
|
||||
TLSCryptKey []byte
|
||||
}
|
||||
|
||||
@@ -182,6 +186,12 @@ func (c *ClientConfig) ValidateInstallScriptSubset() error {
|
||||
} else if strings.TrimSpace(c.Username) == "" {
|
||||
return errors.New("openvpn requires either cert+key or username (auth-user-pass)")
|
||||
}
|
||||
if c.PingInterval < 0 {
|
||||
return errors.New("openvpn ping interval must be positive")
|
||||
}
|
||||
if c.PingRestart < 0 {
|
||||
return errors.New("openvpn ping restart must be positive")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+19
-32
@@ -1,6 +1,7 @@
|
||||
package openvpn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/hmac"
|
||||
@@ -28,6 +29,18 @@ const (
|
||||
PeerIDUnset uint32 = 0xffffff
|
||||
)
|
||||
|
||||
// OpenVPN data-channel ping payload, matching PING_STRING in upstream OpenVPN.
|
||||
var openVPNPingPacket = []byte{
|
||||
0x2a, 0x18, 0x7b, 0xf3,
|
||||
0x64, 0x1e, 0xb4, 0xcb,
|
||||
0x07, 0xed, 0x2d, 0x0a,
|
||||
0x98, 0x1f, 0xc7, 0x48,
|
||||
}
|
||||
|
||||
func IsPingPacket(packet []byte) bool {
|
||||
return bytes.Equal(packet, openVPNPingPacket)
|
||||
}
|
||||
|
||||
type DataChannel struct {
|
||||
sendAEAD cipher.AEAD
|
||||
recvAEAD cipher.AEAD
|
||||
@@ -44,10 +57,9 @@ type DataChannel struct {
|
||||
sendImplicitIV [DataChannelIVSize]byte
|
||||
recvImplicitIV [DataChannelIVSize]byte
|
||||
|
||||
keyID uint8
|
||||
peerID uint32
|
||||
header []byte
|
||||
compLZO string
|
||||
keyID uint8
|
||||
peerID uint32
|
||||
header []byte
|
||||
|
||||
mu sync.Mutex
|
||||
sendPacketID uint32
|
||||
@@ -60,7 +72,7 @@ type DataChannel struct {
|
||||
randOffset int
|
||||
}
|
||||
|
||||
func NewDataChannel(keys *KeyMaterial, cipherName, authName string, peerID uint32, compLZO string) (*DataChannel, error) {
|
||||
func NewDataChannel(keys *KeyMaterial, cipherName, authName string, peerID uint32) (*DataChannel, error) {
|
||||
if keys == nil {
|
||||
return nil, errors.New("nil openvpn key material")
|
||||
}
|
||||
@@ -81,7 +93,6 @@ func NewDataChannel(keys *KeyMaterial, cipherName, authName string, peerID uint3
|
||||
recvAEAD: recv,
|
||||
peerID: peerID,
|
||||
header: dataHeader(peerID, 0),
|
||||
compLZO: compLZO,
|
||||
}
|
||||
copy(d.sendImplicitIV[4:], keys.SendHMACKey[:DataChannelIVSize-4])
|
||||
copy(d.recvImplicitIV[4:], keys.RecvHMACKey[:DataChannelIVSize-4])
|
||||
@@ -112,7 +123,6 @@ func NewDataChannel(keys *KeyMaterial, cipherName, authName string, peerID uint3
|
||||
authSize: authSize,
|
||||
peerID: peerID,
|
||||
header: dataHeader(peerID, 0),
|
||||
compLZO: compLZO,
|
||||
}
|
||||
d.sendMACPool.New = func() any {
|
||||
return hmac.New(d.authHash, d.sendHMACKey)
|
||||
@@ -178,14 +188,6 @@ func (d *DataChannel) Encrypt(packet []byte) ([]byte, error) {
|
||||
return nil, errors.New("nil openvpn data channel")
|
||||
}
|
||||
|
||||
// Prepend comp-lzo header (0xfa = not compressed) to satisfy servers expecting the framing.
|
||||
if d.compLZO == CompLzoYes {
|
||||
lzoPacket := make([]byte, 1+len(packet))
|
||||
lzoPacket[0] = lzoCompressNone
|
||||
copy(lzoPacket[1:], packet)
|
||||
packet = lzoPacket
|
||||
}
|
||||
|
||||
packetID := d.nextPacketID()
|
||||
if d.sendAEAD != nil {
|
||||
return d.encryptAEAD(packet, packetID)
|
||||
@@ -245,25 +247,10 @@ func (d *DataChannel) Decrypt(packet []byte) ([]byte, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var plain []byte
|
||||
if d.recvAEAD != nil {
|
||||
plain, err = d.decryptAEAD(packet, headerSize)
|
||||
} else {
|
||||
plain, err = d.decryptCBC(packet, headerSize)
|
||||
return d.decryptAEAD(packet, headerSize)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.compLZO == CompLzoYes && len(plain) > 0 {
|
||||
decompressed, err := lzo1xDecompressSafe(plain)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(decompressed) > 0 {
|
||||
return decompressed, nil
|
||||
}
|
||||
}
|
||||
return plain, nil
|
||||
return d.decryptCBC(packet, headerSize)
|
||||
}
|
||||
|
||||
func (d *DataChannel) decryptAEAD(packet []byte, headerSize int) ([]byte, error) {
|
||||
|
||||
@@ -21,11 +21,11 @@ func TestDataChannelAESGCMV2RoundTrip(t *testing.T) {
|
||||
RecvCipherKey: clientKeys.SendCipherKey,
|
||||
RecvHMACKey: clientKeys.SendHMACKey,
|
||||
}
|
||||
client, err := NewDataChannel(clientKeys, CipherAES128GCM, AuthSHA256, 7, "")
|
||||
client, err := NewDataChannel(clientKeys, CipherAES128GCM, AuthSHA256, 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server, err := NewDataChannel(serverKeys, CipherAES128GCM, AuthSHA256, 7, "")
|
||||
server, err := NewDataChannel(serverKeys, CipherAES128GCM, AuthSHA256, 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -75,11 +75,11 @@ func TestDataChannelAcceptsOutOfOrderPacketsWithinReplayWindow(t *testing.T) {
|
||||
RecvCipherKey: clientKeys.SendCipherKey,
|
||||
RecvHMACKey: clientKeys.SendHMACKey,
|
||||
}
|
||||
client, err := NewDataChannel(clientKeys, CipherAES128GCM, AuthSHA256, 7, "")
|
||||
client, err := NewDataChannel(clientKeys, CipherAES128GCM, AuthSHA256, 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server, err := NewDataChannel(serverKeys, CipherAES128GCM, AuthSHA256, 7, "")
|
||||
server, err := NewDataChannel(serverKeys, CipherAES128GCM, AuthSHA256, 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -154,11 +154,11 @@ func TestDataChannelChaCha20Poly1305V2RoundTrip(t *testing.T) {
|
||||
RecvCipherKey: clientKeys.SendCipherKey,
|
||||
RecvHMACKey: clientKeys.SendHMACKey,
|
||||
}
|
||||
client, err := NewDataChannel(clientKeys, CipherChaCha20Poly1305, AuthSHA256, 7, "")
|
||||
client, err := NewDataChannel(clientKeys, CipherChaCha20Poly1305, AuthSHA256, 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server, err := NewDataChannel(serverKeys, CipherChaCha20Poly1305, AuthSHA256, 7, "")
|
||||
server, err := NewDataChannel(serverKeys, CipherChaCha20Poly1305, AuthSHA256, 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -194,11 +194,11 @@ func TestDataChannelAESCBCSHA1V2RoundTrip(t *testing.T) {
|
||||
RecvCipherKey: clientKeys.SendCipherKey,
|
||||
RecvHMACKey: clientKeys.SendHMACKey,
|
||||
}
|
||||
client, err := NewDataChannel(clientKeys, CipherAES128CBC, AuthSHA1, 7, "")
|
||||
client, err := NewDataChannel(clientKeys, CipherAES128CBC, AuthSHA1, 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server, err := NewDataChannel(serverKeys, CipherAES128CBC, AuthSHA1, 7, "")
|
||||
server, err := NewDataChannel(serverKeys, CipherAES128CBC, AuthSHA1, 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -41,3 +41,12 @@ func lzo1xDecompressSafe(src []byte) ([]byte, error) {
|
||||
return nil, ErrLZODecompress
|
||||
}
|
||||
}
|
||||
|
||||
// lzo1xCompressSafe handles OpenVPN comp-lzo data packets.
|
||||
// Prepend comp-lzo header (0xfa = not compressed) to satisfy servers expecting the framing.
|
||||
func lzo1xCompressSafe(src []byte) ([]byte, error) {
|
||||
lzoPacket := make([]byte, 1+len(src))
|
||||
lzoPacket[0] = lzoCompressNone
|
||||
copy(lzoPacket[1:], src)
|
||||
return lzoPacket, nil
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package openvpn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLzo1xSafe(t *testing.T) {
|
||||
data := make([]byte, 1024)
|
||||
rand.Read(data)
|
||||
compressed, err := lzo1xCompressSafe(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decompressed, err := lzo1xDecompressSafe(compressed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(data, decompressed) {
|
||||
t.Fatal("decompressed data is not equal to original")
|
||||
}
|
||||
}
|
||||
@@ -181,6 +181,7 @@ func isReservedIP(ip netip.Addr) bool {
|
||||
}
|
||||
|
||||
func readUntilNull(r io.Reader) ([]byte, error) {
|
||||
const maxLen = 256
|
||||
buf := &bytes.Buffer{}
|
||||
var data [1]byte
|
||||
|
||||
@@ -191,6 +192,9 @@ func readUntilNull(r io.Reader) ([]byte, error) {
|
||||
if data[0] == 0 {
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
if buf.Len() >= maxLen {
|
||||
return nil, errors.New("readUntilNull: data too long")
|
||||
}
|
||||
buf.WriteByte(data[0])
|
||||
}
|
||||
}
|
||||
@@ -96,9 +96,6 @@ func buildEarlyClientObfsConn(raw net.Conn, cfg EarlyCodecConfig, table *sudokuo
|
||||
func buildEarlyServerObfsConn(raw net.Conn, cfg EarlyCodecConfig, table *sudokuobfs.Table) net.Conn {
|
||||
uplink := sudokuobfs.NewConn(raw, table, cfg.PaddingMin, cfg.PaddingMax, false)
|
||||
downlinkWriter, closers := newServerDownlinkWriter(raw, table, cfg.PaddingMin, cfg.PaddingMax, cfg.EnablePureDownlink)
|
||||
if downlinkWriter == nil {
|
||||
return uplink
|
||||
}
|
||||
return newDirectionalConn(raw, uplink, downlinkWriter, closers...)
|
||||
}
|
||||
|
||||
|
||||
@@ -258,14 +258,7 @@ func newClientDownlinkReader(raw net.Conn, table *sudoku.Table, paddingMin, padd
|
||||
|
||||
func newServerDownlinkWriter(raw net.Conn, table *sudoku.Table, paddingMin, paddingMax int, pureDownlink bool) (io.Writer, []func() error) {
|
||||
downlinkTable := oppositeDirectionTable(table)
|
||||
if pureDownlink {
|
||||
if downlinkTable == table {
|
||||
return nil, nil
|
||||
}
|
||||
return sudoku.NewConn(raw, downlinkTable, paddingMin, paddingMax, false), nil
|
||||
}
|
||||
packed := sudoku.NewPackedConn(raw, downlinkTable, paddingMin, paddingMax)
|
||||
return packed, []func() error{packed.Flush}
|
||||
return sudoku.NewServerDownlinkWriter(raw, downlinkTable, paddingMin, paddingMax, pureDownlink)
|
||||
}
|
||||
|
||||
func buildClientObfsConn(raw net.Conn, cfg *ProtocolConfig, table *sudoku.Table) net.Conn {
|
||||
@@ -280,9 +273,6 @@ func buildClientObfsConn(raw net.Conn, cfg *ProtocolConfig, table *sudoku.Table)
|
||||
func buildServerObfsConn(raw net.Conn, cfg *ProtocolConfig, table *sudoku.Table, record bool) (*sudoku.Conn, net.Conn) {
|
||||
uplinkSudoku := sudoku.NewConn(raw, table, cfg.PaddingMin, cfg.PaddingMax, record)
|
||||
downlinkWriter, closers := newServerDownlinkWriter(raw, table, cfg.PaddingMin, cfg.PaddingMax, cfg.EnablePureDownlink)
|
||||
if downlinkWriter == nil {
|
||||
return uplinkSudoku, uplinkSudoku
|
||||
}
|
||||
return uplinkSudoku, newDirectionalConn(raw, uplinkSudoku, downlinkWriter, closers...)
|
||||
}
|
||||
|
||||
@@ -439,7 +429,7 @@ func ServerHandshake(rawConn net.Conn, cfg *ProtocolConfig) (net.Conn, *Handshak
|
||||
return nil, nil, &SuspiciousError{Err: fmt.Errorf("resolve table hint failed: %w", err), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
|
||||
}
|
||||
if resolvedTable != selectedTable {
|
||||
downlinkWriter, closers := newServerDownlinkWriter(baseConn, resolvedTable, cfg.PaddingMin, cfg.PaddingMax, cfg.EnablePureDownlink)
|
||||
downlinkWriter, closers := sudoku.NewServerDownlinkWriter(baseConn, resolvedTable.OppositeDirection(), cfg.PaddingMin, cfg.PaddingMax, cfg.EnablePureDownlink)
|
||||
switchable, ok := obfsConn.(*directionalConn)
|
||||
if !ok {
|
||||
return nil, nil, &SuspiciousError{Err: fmt.Errorf("switch downlink writer failed"), Conn: &prefixedRecorderConn{Conn: sConn, prefix: httpHeaderData}}
|
||||
|
||||
@@ -18,9 +18,12 @@ const (
|
||||
)
|
||||
|
||||
const (
|
||||
headerSize = 1 + 4 + 4
|
||||
maxFrameSize = 256 * 1024
|
||||
maxDataPayload = 32 * 1024
|
||||
headerSize = 1 + 4 + 4
|
||||
// maxQueuedBytesPerStream bounds unread payload retained by a single logical stream.
|
||||
// Backpressure is applied to the demux loop instead of dropping data.
|
||||
maxQueuedBytesPerStream = 4 * 1024 * 1024
|
||||
maxFrameSize = 256 * 1024
|
||||
maxDataPayload = 128 * 1024
|
||||
)
|
||||
|
||||
type acceptEvent struct {
|
||||
@@ -344,6 +347,8 @@ type stream struct {
|
||||
closeErr error
|
||||
readBuf []byte
|
||||
queue [][]byte
|
||||
// queuedBytes includes unread bytes in readBuf and queue.
|
||||
queuedBytes int
|
||||
|
||||
localAddr net.Addr
|
||||
remoteAddr net.Addr
|
||||
@@ -362,16 +367,20 @@ func newStream(session *Session, id uint32) *stream {
|
||||
|
||||
func (c *stream) enqueue(payload []byte) {
|
||||
c.mu.Lock()
|
||||
for !c.closed && c.queuedBytes+len(payload) > maxQueuedBytesPerStream {
|
||||
c.cond.Wait()
|
||||
}
|
||||
if c.closed {
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
c.queuedBytes += len(payload)
|
||||
if len(c.readBuf) == 0 && len(c.queue) == 0 {
|
||||
c.readBuf = payload
|
||||
} else {
|
||||
c.queue = append(c.queue, payload)
|
||||
}
|
||||
c.cond.Signal()
|
||||
c.cond.Broadcast()
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
@@ -413,7 +422,11 @@ func (c *stream) Read(p []byte) (int, error) {
|
||||
}
|
||||
if len(c.readBuf) == 0 && len(c.queue) > 0 {
|
||||
c.readBuf = c.queue[0]
|
||||
c.queue[0] = nil
|
||||
c.queue = c.queue[1:]
|
||||
if len(c.queue) == 0 {
|
||||
c.queue = nil
|
||||
}
|
||||
}
|
||||
if len(c.readBuf) == 0 && c.closed {
|
||||
if c.closeErr == nil {
|
||||
@@ -424,6 +437,14 @@ func (c *stream) Read(p []byte) (int, error) {
|
||||
|
||||
n := copy(p, c.readBuf)
|
||||
c.readBuf = c.readBuf[n:]
|
||||
if len(c.readBuf) == 0 {
|
||||
c.readBuf = nil
|
||||
}
|
||||
c.queuedBytes -= n
|
||||
if c.queuedBytes < 0 {
|
||||
c.queuedBytes = 0
|
||||
}
|
||||
c.cond.Broadcast()
|
||||
return n, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -514,6 +514,8 @@ type queuedConn struct {
|
||||
remoteAddr net.Addr
|
||||
}
|
||||
|
||||
const queuedConnPayloadQueueDepth = 64
|
||||
|
||||
func (c *queuedConn) CloseWrite() error {
|
||||
if c == nil || c.writeClosed == nil {
|
||||
return nil
|
||||
@@ -646,9 +648,9 @@ func newStreamSplitConnFromInfo(info *sessionDialInfo) *streamSplitConn {
|
||||
headerHost: info.headerHost,
|
||||
auth: info.auth,
|
||||
queuedConn: queuedConn{
|
||||
rxc: make(chan []byte, 256),
|
||||
rxc: make(chan []byte, queuedConnPayloadQueueDepth),
|
||||
closed: make(chan struct{}),
|
||||
writeCh: make(chan []byte, 256),
|
||||
writeCh: make(chan []byte, queuedConnPayloadQueueDepth),
|
||||
writeClosed: make(chan struct{}),
|
||||
localAddr: &net.TCPAddr{},
|
||||
remoteAddr: &net.TCPAddr{},
|
||||
@@ -1083,9 +1085,9 @@ func newPollConnFromInfo(info *sessionDialInfo) *pollConn {
|
||||
headerHost: info.headerHost,
|
||||
auth: info.auth,
|
||||
queuedConn: queuedConn{
|
||||
rxc: make(chan []byte, 128),
|
||||
rxc: make(chan []byte, queuedConnPayloadQueueDepth),
|
||||
closed: make(chan struct{}),
|
||||
writeCh: make(chan []byte, 256),
|
||||
writeCh: make(chan []byte, queuedConnPayloadQueueDepth),
|
||||
writeClosed: make(chan struct{}),
|
||||
localAddr: &net.TCPAddr{},
|
||||
remoteAddr: &net.TCPAddr{},
|
||||
|
||||
@@ -175,23 +175,42 @@ func (sc *Conn) Read(p []byte) (n int, err error) {
|
||||
sc.recordLock.Unlock()
|
||||
}
|
||||
|
||||
layout := sc.table.layout
|
||||
for _, b := range chunk {
|
||||
table := sc.table
|
||||
layout := table.layout
|
||||
for i := 0; i < len(chunk); {
|
||||
if sc.hintCount == 0 && outN < len(p) && i+3 < len(chunk) &&
|
||||
layout.hintTable[chunk[i]] &&
|
||||
layout.hintTable[chunk[i+1]] &&
|
||||
layout.hintTable[chunk[i+2]] &&
|
||||
layout.hintTable[chunk[i+3]] {
|
||||
val, ok := table.DecodeMap[packHintBytes(chunk[i], chunk[i+1], chunk[i+2], chunk[i+3])]
|
||||
if !ok {
|
||||
return 0, ErrInvalidSudokuMapMiss
|
||||
}
|
||||
p[outN] = val
|
||||
outN++
|
||||
i += 4
|
||||
continue
|
||||
}
|
||||
|
||||
b := chunk[i]
|
||||
i++
|
||||
if !layout.hintTable[b] {
|
||||
continue
|
||||
}
|
||||
|
||||
sc.hintBuf[sc.hintCount] = b
|
||||
sc.hintCount++
|
||||
if sc.hintCount == len(sc.hintBuf) {
|
||||
key := packHintsToKey(sc.hintBuf)
|
||||
val, ok := sc.table.DecodeMap[key]
|
||||
if !ok {
|
||||
return 0, ErrInvalidSudokuMapMiss
|
||||
}
|
||||
outN = appendDecodedByte(p, outN, &sc.pendingData, val)
|
||||
sc.hintCount = 0
|
||||
if sc.hintCount != len(sc.hintBuf) {
|
||||
continue
|
||||
}
|
||||
|
||||
val, ok := table.DecodeMap[packHintBytes(sc.hintBuf[0], sc.hintBuf[1], sc.hintBuf[2], sc.hintBuf[3])]
|
||||
if !ok {
|
||||
return 0, ErrInvalidSudokuMapMiss
|
||||
}
|
||||
outN = appendDecodedByte(p, outN, &sc.pendingData, val)
|
||||
sc.hintCount = 0
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package sudoku
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// DownlinkWriter encodes payload bytes with the selected downlink codec.
|
||||
type DownlinkWriter struct {
|
||||
dataWriter io.Writer
|
||||
writeMu sync.Mutex
|
||||
}
|
||||
|
||||
func NewDownlinkWriter(raw io.Writer, table *Table, pMin, pMax int) *DownlinkWriter {
|
||||
localRng := newSeededRand()
|
||||
return newDownlinkWriter(newSudokuDataWriter(raw, table, localRng, pMin, pMax))
|
||||
}
|
||||
|
||||
func NewPackedDownlinkWriter(raw net.Conn, table *Table, pMin, pMax int) (*PackedConn, *DownlinkWriter) {
|
||||
packed := NewPackedConn(raw, table, pMin, pMax)
|
||||
return packed, newDownlinkWriter(packed)
|
||||
}
|
||||
|
||||
func NewServerDownlinkWriter(raw net.Conn, table *Table, pMin, pMax int, pure bool) (io.Writer, []func() error) {
|
||||
if pure {
|
||||
return NewDownlinkWriter(raw, table, pMin, pMax), nil
|
||||
}
|
||||
|
||||
packed, writer := NewPackedDownlinkWriter(raw, table, pMin, pMax)
|
||||
return writer, []func() error{packed.Flush}
|
||||
}
|
||||
|
||||
func newDownlinkWriter(dataWriter io.Writer) *DownlinkWriter {
|
||||
return &DownlinkWriter{dataWriter: dataWriter}
|
||||
}
|
||||
|
||||
func (w *DownlinkWriter) Write(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if w == nil || w.dataWriter == nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
|
||||
w.writeMu.Lock()
|
||||
defer w.writeMu.Unlock()
|
||||
|
||||
return w.dataWriter.Write(p)
|
||||
}
|
||||
|
||||
type sudokuDataWriter struct {
|
||||
writer io.Writer
|
||||
table *Table
|
||||
rng *sudokuRand
|
||||
paddingThreshold uint64
|
||||
writeBuf []byte
|
||||
}
|
||||
|
||||
func newSudokuDataWriter(writer io.Writer, table *Table, rng *sudokuRand, pMin, pMax int) *sudokuDataWriter {
|
||||
return &sudokuDataWriter{
|
||||
writer: writer,
|
||||
table: table,
|
||||
rng: rng,
|
||||
paddingThreshold: pickPaddingThreshold(rng, pMin, pMax),
|
||||
writeBuf: make([]byte, 0, 4096),
|
||||
}
|
||||
}
|
||||
|
||||
func (w *sudokuDataWriter) Write(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if w == nil || w.writer == nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
if w.table == nil || w.table.layout == nil || w.rng == nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
|
||||
w.writeBuf = encodeSudokuPayload(w.writeBuf[:0], w.table, w.rng, w.paddingThreshold, p)
|
||||
return len(p), writeFull(w.writer, w.writeBuf)
|
||||
}
|
||||
@@ -16,8 +16,25 @@ func encodeSudokuPayload(dst []byte, table *Table, rng *sudokuRand, paddingThres
|
||||
pads := table.PaddingPool
|
||||
padLen := len(pads)
|
||||
|
||||
if paddingThreshold >= probOne {
|
||||
for _, b := range p {
|
||||
out = append(out, pads[rng.Intn(padLen)])
|
||||
|
||||
puzzles := table.EncodeTable[b]
|
||||
puzzle := puzzles[rng.Intn(len(puzzles))]
|
||||
|
||||
perm := perm4[rng.Intn(len(perm4))]
|
||||
for _, idx := range perm {
|
||||
out = append(out, pads[rng.Intn(padLen)], puzzle[idx])
|
||||
}
|
||||
}
|
||||
|
||||
out = append(out, pads[rng.Intn(padLen)])
|
||||
return out
|
||||
}
|
||||
|
||||
for _, b := range p {
|
||||
if shouldPad(rng, paddingThreshold) {
|
||||
if uint64(rng.Uint32()) < paddingThreshold {
|
||||
out = append(out, pads[rng.Intn(padLen)])
|
||||
}
|
||||
|
||||
@@ -25,14 +42,14 @@ func encodeSudokuPayload(dst []byte, table *Table, rng *sudokuRand, paddingThres
|
||||
puzzle := puzzles[rng.Intn(len(puzzles))]
|
||||
perm := perm4[rng.Intn(len(perm4))]
|
||||
for _, idx := range perm {
|
||||
if shouldPad(rng, paddingThreshold) {
|
||||
if uint64(rng.Uint32()) < paddingThreshold {
|
||||
out = append(out, pads[rng.Intn(padLen)])
|
||||
}
|
||||
out = append(out, puzzle[idx])
|
||||
}
|
||||
}
|
||||
|
||||
if shouldPad(rng, paddingThreshold) {
|
||||
if uint64(rng.Uint32()) < paddingThreshold {
|
||||
out = append(out, pads[rng.Intn(padLen)])
|
||||
}
|
||||
return out
|
||||
|
||||
@@ -192,23 +192,27 @@ func tableHintFingerprint(key string, mode string, uplinkPattern string, downlin
|
||||
}
|
||||
|
||||
func packHintsToKey(hints [4]byte) uint32 {
|
||||
return packHintBytes(hints[0], hints[1], hints[2], hints[3])
|
||||
}
|
||||
|
||||
func packHintBytes(h0, h1, h2, h3 byte) uint32 {
|
||||
// Sorting network for 4 elements (Bubble sort unrolled)
|
||||
// Swap if a > b
|
||||
if hints[0] > hints[1] {
|
||||
hints[0], hints[1] = hints[1], hints[0]
|
||||
if h0 > h1 {
|
||||
h0, h1 = h1, h0
|
||||
}
|
||||
if hints[2] > hints[3] {
|
||||
hints[2], hints[3] = hints[3], hints[2]
|
||||
if h2 > h3 {
|
||||
h2, h3 = h3, h2
|
||||
}
|
||||
if hints[0] > hints[2] {
|
||||
hints[0], hints[2] = hints[2], hints[0]
|
||||
if h0 > h2 {
|
||||
h0, h2 = h2, h0
|
||||
}
|
||||
if hints[1] > hints[3] {
|
||||
hints[1], hints[3] = hints[3], hints[1]
|
||||
if h1 > h3 {
|
||||
h1, h3 = h3, h1
|
||||
}
|
||||
if hints[1] > hints[2] {
|
||||
hints[1], hints[2] = hints[2], hints[1]
|
||||
if h1 > h2 {
|
||||
h1, h2 = h2, h1
|
||||
}
|
||||
|
||||
return uint32(hints[0])<<24 | uint32(hints[1])<<16 | uint32(hints[2])<<8 | uint32(hints[3])
|
||||
return uint32(h0)<<24 | uint32(h1)<<16 | uint32(h2)<<8 | uint32(h3)
|
||||
}
|
||||
@@ -202,6 +202,12 @@ func (pc *PacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, er
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
length := binary.BigEndian.Uint16(data)
|
||||
if length > maxLength {
|
||||
if put != nil {
|
||||
put()
|
||||
}
|
||||
return nil, nil, nil, errors.New("packet invalid")
|
||||
}
|
||||
|
||||
if length > 0 {
|
||||
data = data[:length]
|
||||
|
||||
@@ -43,7 +43,10 @@ func (vc *Conn) FilterTLS(buffer []byte) (index int) {
|
||||
vc.isTLS12orAbove = true
|
||||
if lenP-index >= 79 && vc.remainingServerHello >= 79 {
|
||||
sessionIDLen := int(buffer[index+43])
|
||||
vc.cipher = binary.BigEndian.Uint16(buffer[index+43+sessionIDLen+1:])
|
||||
cipherOffset := index + 43 + sessionIDLen + 1
|
||||
if cipherOffset+2 <= lenP {
|
||||
vc.cipher = binary.BigEndian.Uint16(buffer[cipherOffset:])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -374,6 +374,18 @@ func resolveMetadata(metadata *C.Metadata) (proxy C.Proxy, rule C.Rule, err erro
|
||||
}
|
||||
}
|
||||
},
|
||||
CheckPassRule: func(adapterName string) bool {
|
||||
adapter, ok := proxies[adapterName]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
for a := adapter; a != nil; a = a.Unwrap(metadata, false) {
|
||||
if a.Type() == C.PassRule {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
},
|
||||
}
|
||||
|
||||
switch FindProcessMode() {
|
||||
|
||||
Reference in new issue
Block a user