Compare commits

..
64 Commits
Author SHA1 Message Date
Peter Solomon cbd11db1e1 chore: converter map hysteria2 port hopping and realm URI (#2947) 2026-07-08 07:33:49 +08:00
wwqgtxx f62ebd0d04 chore: cleanup interop test code 2026-07-07 23:35:21 +08:00
wwqgtxx e10a1a707f feat: support mekya for vmess 2026-07-07 23:35:20 +08:00
wwqgtxx de51c4b840 chore: cleanup interop test code 2026-07-07 18:46:33 +08:00
wwqgtxx a198581333 feat: support mkcp for vmess 2026-07-07 18:35:42 +08:00
Aaron Chen e3972e78fa fix: apply TUIC v5 UDP relay size clamp when building server options (#2943) 2026-07-07 16:21:46 +08:00
wwqgtxx d41d75795e chore: rename listener config to tlsmirror-config 2026-07-07 15:40:00 +08:00
Aaron Chen 63e4d5a312 fix: TUIC v5 fragmented UDP reads in quicStreamPacketConn.ReadFrom (#2942) 2026-07-07 14:19:30 +08:00
wwqgtxx 2f510e86ad feat: support tlsmirror for vmess 2026-07-07 10:48:02 +08:00
wwqgtxx 3b85577f20 chore: make bbolt work on non-mmap supported platforms 2026-07-07 00:35:01 +08:00
wwqgtxx dc5c2ecc00 chore: change http method from GET to POST in listener test 2026-07-06 20:38:27 +08:00
Chenx Dust 578b88190a fix: add missing json tags to raw config structs (#2939) 2026-07-06 17:57:59 +08:00
wwqgtxx 5ab5eb31f6 fix: snell v2 listener can't pass test 2026-07-05 22:51:55 +08:00
wwqgtxx 1f93334106 fix: udp WriteTo returned wrong count 2026-07-05 22:29:19 +08:00
wwqgtxx 02dd143fbb chore: relax version restrictions for the snell listener 2026-07-05 22:29:18 +08:00
wwqgtxx a1c09adb91 feat: support restls for shadowsocks listener 2026-07-05 18:14:26 +08:00
wwqgtxx 6414c563dd chore: reduce one unnecessary slice copy operation 2026-07-03 17:49:28 +08:00
xream 45ca4ae12a fix: preserve shadow-tls in-user for snell listeners (#2934) 2026-07-03 17:40:52 +08:00
wwqgtxx 01111ffac1 feat: add handshake-timeout for masque 2026-07-03 17:00:20 +08:00
wwqgtxx 7870f8f839 feat: add handshake-timeout for OpenVPN 2026-07-03 16:37:10 +08:00
rumianoesa 73740c771c fix: wrong realm resolver when only IPv6 is requested 2026-07-03 08:26:59 +08:00
wwqgtxx bcfd434df3 chore: update chi to 5.3.0 2026-07-02 22:15:31 +08:00
xishang0128 85c1798f7d break: restore original Clash /proxies behavior
Do not merge proxy-provider nodes into the /proxies response. The original Clash API keeps runtime proxies and proxy-provider entries separate; clients that need provider nodes should call /providers/proxies.
2026-07-02 21:30:26 +08:00
wwqgtxx d924f1ca62 fix: CVE-2026-42505 for crypto/tls 2026-07-02 08:59:41 +08:00
wwqgtxx 1c4f7c4de6 feat: support shadow-tls for snell 2026-07-01 18:30:20 +08:00
kasumikira 26edbaae0b fix: dualStackDialContext not close the fallback connection when the preferred IP family won 2026-06-30 18:56:53 +08:00
wwqgtxx 27efee2dc7 chore: cleanup unused code in OpenVPN 2026-06-29 14:11:46 +08:00
Easy-Ez d20e85081a feat: support custom peer-info for openvpn outbound (#2926) 2026-06-29 13:44:12 +08:00
wwqgtxx 1095055136 chore: upgrade bbolt to 1.5.0 2026-06-28 22:46:16 +08:00
wwqgtxx 24b6de71fc chore: lazy init reality server cert 2026-06-26 17:09:57 +08:00
wwqgtxx 93d33faa4f chore: increase REALITY target TLS record buffer to 16 KiB 2026-06-26 16:31:00 +08:00
wwqgtxx 85c2f6a773 chore: change the type of the internal value being passed 2026-06-24 15:42:45 +08:00
wwqgtxx 59ffb63734 fix: scStreamUpServerSecs not working when xPaddingObfsMode is true 2026-06-23 18:37:42 +08:00
wwqgtxx 26e3d220a5 chore: peer should set to expire unconditionally in tailscale-wireguard-go 2026-06-23 17:56:53 +08:00
wwqgtxx 38fd8974b6 chore: sync common/maphash code 2026-06-23 12:00:17 +08:00
wwqgtxx eca44d08d7 chore: update tfo-go ready for go1.27 2026-06-23 10:18:47 +08:00
wwqgtxx 5b54b3ad46 fix: panic when dial failed in masque 2026-06-22 15:13:55 +08:00
wwqgtxx 76bf840121 chore: code cleanup 2026-06-22 10:23:43 +08:00
wwqgtxx 8c40e36087 feat: support fallback-lazy-query for dns section 2026-06-21 14:05:41 +08:00
wwqgtxx 42810015f9 fix: restore the original fallback concurrency behavior 2026-06-21 13:33:42 +08:00
wwqgtxx e64f58f333 fix: panic when rand.IntN calling on a nil slice 2026-06-20 17:06:24 +08:00
wwqgtxx 94a7a3f3c0 fix: udp write in sing-mux 2026-06-20 16:34:56 +08:00
wwqgtxx 174cba4cce chore: update sing-tun 2026-06-20 15:52:37 +08:00
wwqgtxx be9164e55f feat: add default-selected for select group 2026-06-19 11:21:14 +08:00
wwqgtxx 1e76df7377 chore: better group config parsing 2026-06-19 11:21:13 +08:00
wwqgtxx e68eca6c3d doc: remove outdate item 2026-06-19 11:21:12 +08:00
wwqgtxx 8e2aba40fc feat: support network: h3-l4proxy for masque outbound 2026-06-17 10:01:07 +08:00
enfein 2c6ff7251d chore: bump mieru version to 3.34.0 (#2899) 2026-06-15 15:59:42 +08:00
xream 2cd1443c04 fix: prevent snell pool from reusing unready connections (#2878) 2026-06-13 20:49:07 +08:00
wwqgtxx 793f61ec67 fix: crash in AmneziaWG receive path with slice bounds out of range when S4 is larger than incoming packet 2026-06-12 22:48:43 +08:00
Peter Solomon ea19cda0c9 feat: add rematch outbound type and REMATCH-NAME rule type (#2862) 2026-06-12 22:13:32 +08:00
wwqgtxx da28fe33c8 chore: more code sharing 2026-06-12 15:43:17 +08:00
wwqgtxx acbc92f021 chore: better mieru inbound test implementation 2026-06-12 11:05:19 +08:00
wwqgtxx 0daa3ff722 chore: allow overriding inbound listen config for api user 2026-06-12 10:50:42 +08:00
wwqgtxx aff8dc73e1 chore: adjust struct name 2026-06-12 10:35:35 +08:00
wwqgtxx ad730ae974 feat: support listen-routing-mark for dns section 2026-06-12 10:12:04 +08:00
wwqgtxx d67572bbae feat: support routing-mark for listeners except tun/redir/tproxy and top-level external-controller-routing-mark 2026-06-12 10:05:53 +08:00
wwqgtxx 084a09e4af chore: export internal function for api user 2026-06-11 08:21:34 +08:00
legiz-ru 1686d5633f feat: convert support session-table and session-length for xhttp-opts fields (#2889) 2026-06-10 15:52:32 +08:00
wwqgtxx f74bd8badc chore: adjust internal function return type 2026-06-10 14:30:08 +08:00
wwqgtxx e3d67b3227 chore: strictly forbidden to fill in a proxy group for empty-fallback 2026-06-10 13:15:44 +08:00
wwqgtxx 1f80d91552 feat: support session-table and session-length for xhttp client 2026-06-10 07:57:14 +08:00
roy.lieu d08c8853e3 fix: writeSem initiation in OpenVPN 2026-06-07 12:45:17 +08:00
wwqgtxx 7031b75698 chore: update quic-go to 0.60.0 2026-06-06 19:59:46 +08:00
180 changed files with 10583 additions and 806 deletions

No files matched your search

+1
View File
@@ -221,6 +221,7 @@ jobs:
if: ${{ matrix.jobs.test == 'test' }}
run: |
export SKIP_CONCURRENT_TEST=1
export SKIP_INTEROP_TEST=1
go test ./...
echo "---test with_gvisor---"
go test ./... -tags "with_gvisor" -count=1
+2
View File
@@ -42,6 +42,8 @@ jobs:
GOTOOLCHAIN: local
# Fix mingw trying to be smart and converting paths https://github.com/moby/moby/issues/24029#issuecomment-250412919
MSYS_NO_PATHCONV: true
# Skip mihomo inbound interop test
SKIP_INTEROP_TEST: 1
steps:
- uses: actions/checkout@v6
+53 -55
View File
@@ -5,8 +5,10 @@ import (
"fmt"
"net"
"net/netip"
"sync"
"syscall"
"github.com/metacubex/mihomo/common/atomic"
"github.com/metacubex/mihomo/common/sockopt"
"github.com/metacubex/mihomo/component/keepalive"
"github.com/metacubex/mihomo/component/mptcp"
@@ -14,34 +16,68 @@ import (
)
var (
lc = tfo.ListenConfig{
DisableTFO: true,
}
mutex sync.RWMutex
globalTFO = atomic.NewBool(false)
globalMPTCP = atomic.NewBool(false)
)
func SetTfo(open bool) {
mutex.Lock()
defer mutex.Unlock()
lc.DisableTFO = !open
globalTFO.Store(open)
}
func Tfo() bool {
mutex.RLock()
defer mutex.RUnlock()
return !lc.DisableTFO
return globalTFO.Load()
}
func SetMPTCP(open bool) {
mutex.Lock()
defer mutex.Unlock()
mptcp.SetNetListenConfig(&lc.ListenConfig, open)
globalMPTCP.Store(open)
}
func MPTCP() bool {
mutex.RLock()
defer mutex.RUnlock()
return mptcp.GetNetListenConfig(&lc.ListenConfig)
return globalMPTCP.Load()
}
type ListenConfig struct {
routeMark int
}
func NewListenConfig() *ListenConfig {
return &ListenConfig{}
}
func (l *ListenConfig) SetRouteMark(mark int) {
l.routeMark = mark
}
func (l ListenConfig) newListenConfig() *tfo.ListenConfig {
lc := tfo.ListenConfig{DisableTFO: !Tfo()}
keepalive.SetNetListenConfig(&lc.ListenConfig)
mptcp.SetNetListenConfig(&lc.ListenConfig, MPTCP())
lc.Control = func(network, address string, c syscall.RawConn) error {
if l.routeMark != 0 {
err := sockopt.RawConnMark(c, l.routeMark)
if err != nil {
return err
}
}
return nil
}
return &lc
}
func (l ListenConfig) Listen(ctx context.Context, network, address string) (net.Listener, error) {
address, err := preResolve(network, address)
if err != nil {
return nil, err
}
return l.newListenConfig().Listen(ctx, network, address)
}
func (l ListenConfig) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
address, err := preResolve(network, address)
if err != nil {
return nil, err
}
return l.newListenConfig().ListenPacket(ctx, network, address)
}
func preResolve(network, address string) (string, error) {
@@ -67,41 +103,3 @@ func preResolve(network, address string) (string, error) {
}
return address, nil
}
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
address, err := preResolve(network, address)
if err != nil {
return nil, err
}
mutex.RLock()
defer mutex.RUnlock()
return lc.Listen(ctx, network, address)
}
func Listen(network, address string) (net.Listener, error) {
return ListenContext(context.Background(), network, address)
}
func ListenPacketContext(ctx context.Context, network, address string) (net.PacketConn, error) {
address, err := preResolve(network, address)
if err != nil {
return nil, err
}
mutex.RLock()
defer mutex.RUnlock()
return lc.ListenPacket(ctx, network, address)
}
func ListenPacket(network, address string) (net.PacketConn, error) {
return ListenPacketContext(context.Background(), network, address)
}
func init() {
keepalive.SetDisableKeepAliveCallback.Register(func(b bool) {
mutex.Lock()
defer mutex.Unlock()
keepalive.SetNetListenConfig(&lc.ListenConfig)
})
}
+1 -1
View File
@@ -63,7 +63,7 @@ func (t *AnyTLS) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
// create uot on tcp
destination := M.SocksaddrFromNet(metadata.UDPAddr())
return newPacketConn(N.NewThreadSafePacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination})), t), nil
return NewPacketConn(N.NewThreadSafePacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination})), t), nil
}
// SupportUOT implements C.ProxyAdapter
+1 -1
View File
@@ -339,7 +339,7 @@ func (c *packetConn) AddRef(ref any) {
c.EnhancePacketConn = N.NewRefPacketConn(c.EnhancePacketConn, ref) // add ref for autoCloseProxyAdapter
}
func newPacketConn(pc net.PacketConn, a ProxyAdapter) C.PacketConn {
func NewPacketConn(pc net.PacketConn, a ProxyAdapter) C.PacketConn {
epc := N.NewEnhancePacketConn(pc)
if _, ok := pc.(syscall.Conn); !ok { // exclusion system conn like *net.UDPConn
epc = N.NewDeadlineEnhancePacketConn(epc) // most conn from outbound can't handle readDeadline correctly
+1 -1
View File
@@ -46,7 +46,7 @@ func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
if err != nil {
return nil, err
}
return d.loopBack.NewPacketConn(newPacketConn(pc, d)), nil
return d.loopBack.NewPacketConn(NewPacketConn(pc, d)), nil
}
func (d *Direct) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
+1 -1
View File
@@ -38,7 +38,7 @@ func (d *Dns) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.
ctx, cancel := context.WithCancel(context.Background())
return newPacketConn(&dnsPacketConn{
return NewPacketConn(&dnsPacketConn{
response: make(chan dnsPacket, 1),
ctx: ctx,
cancel: cancel,
+1 -1
View File
@@ -58,7 +58,7 @@ func (g *GostRelay) ListenPacketContext(ctx context.Context, metadata *C.Metadat
return nil, fmt.Errorf("%s udp connect error: %w", g.addr, err)
}
return newPacketConn(pc, g), nil
return NewPacketConn(pc, g), nil
}
func (g *GostRelay) ProxyInfo() C.ProxyInfo {
+1 -1
View File
@@ -67,7 +67,7 @@ func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata
if err != nil {
return nil, err
}
return newPacketConn(&hyPacketConn{udpConn}, h), nil
return NewPacketConn(&hyPacketConn{udpConn}, h), nil
}
func (h *Hysteria) genHdc(ctx context.Context) hyUtils.PacketDialer {
+2 -2
View File
@@ -105,7 +105,7 @@ func (h *Hysteria2) ListenPacketContext(ctx context.Context, metadata *C.Metadat
if pc == nil {
return nil, errors.New("packetConn is nil")
}
return newPacketConn(N.NewThreadSafePacketConn(pc), h), nil
return NewPacketConn(N.NewThreadSafePacketConn(pc), h), nil
}
// Close implements C.ProxyAdapter
@@ -297,7 +297,7 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
if ipv4 && !ipv6 {
return resolver.LookupIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
} else if ipv6 && !ipv4 {
return resolver.LookupIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
return resolver.LookupIPv6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
}
return resolver.LookupIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
},
+136 -36
View File
@@ -12,7 +12,6 @@ import (
"net/netip"
"strconv"
"strings"
"sync"
"time"
"github.com/metacubex/mihomo/common/atomic"
@@ -31,6 +30,7 @@ import (
wireguard "github.com/metacubex/sing-wireguard"
M "github.com/metacubex/sing/common/metadata"
"github.com/metacubex/tls"
"golang.org/x/sync/semaphore"
)
type Masque struct {
@@ -41,10 +41,11 @@ type Masque struct {
resolver resolver.Resolver
uri string
h2Transport *http.Transport
l4Client *masque.L4Client
runCtx context.Context
runCancel context.CancelFunc
runMutex sync.Mutex
runLock *semaphore.Weighted
running atomic.Bool
runDevice atomic.Bool
@@ -53,19 +54,20 @@ type Masque struct {
type MasqueOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
PrivateKey string `proxy:"private-key"`
PublicKey string `proxy:"public-key"`
Ip string `proxy:"ip,omitempty"`
Ipv6 string `proxy:"ipv6,omitempty"`
URI string `proxy:"uri,omitempty"`
SNI string `proxy:"sni,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Network string `proxy:"network,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
PrivateKey string `proxy:"private-key"`
PublicKey string `proxy:"public-key"`
Ip string `proxy:"ip,omitempty"`
Ipv6 string `proxy:"ipv6,omitempty"`
URI string `proxy:"uri,omitempty"`
SNI string `proxy:"sni,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
HandshakeTimeout int `proxy:"handshake-timeout,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Network string `proxy:"network,omitempty"`
CongestionController string `proxy:"congestion-controller,omitempty"`
CWND int `proxy:"cwnd,omitempty"`
@@ -104,6 +106,9 @@ func (option MasqueOption) Prefixes() ([]netip.Prefix, error) {
}
func NewMasque(option MasqueOption) (*Masque, error) {
if option.HandshakeTimeout < 0 {
return nil, errors.New("masque handshake timeout must be non-negative")
}
outbound := &Masque{
Base: NewBase(BaseOption{
Name: option.Name,
@@ -115,6 +120,7 @@ func NewMasque(option MasqueOption) (*Masque, error) {
RoutingMark: option.RoutingMark,
Prefer: option.IPVersion,
}),
runLock: semaphore.NewWeighted(1),
}
outbound.dialer = option.NewDialer(outbound.DialOptions())
@@ -144,6 +150,8 @@ func NewMasque(option MasqueOption) (*Masque, error) {
return nil, fmt.Errorf("failed to assert public key as ECDSA")
}
l4proxy := option.Network == "h3-l4proxy"
uri := option.URI
if uri == "" {
uri = masque.ConnectURI
@@ -153,6 +161,9 @@ func NewMasque(option MasqueOption) (*Masque, error) {
sni := option.SNI
if sni == "" {
sni = masque.ConnectSNI
if l4proxy {
sni = masque.L4ConnectSNI
}
}
tlsConfig, err := masque.PrepareTlsConfig(privKey, ecPubKey, sni, option.SkipCertVerify)
@@ -197,30 +208,39 @@ func NewMasque(option MasqueOption) (*Masque, error) {
KeepAlivePeriod: 30 * time.Second,
}
prefixes, err := option.Prefixes()
if err != nil {
return nil, err
}
outbound.option = option
mtu := option.MTU
if mtu == 0 {
mtu = 1280
}
if len(prefixes) == 0 {
return nil, errors.New("missing local address")
}
outbound.tunDevice, err = wireguard.NewStackDevice(prefixes, uint32(mtu))
if err != nil {
return nil, fmt.Errorf("create device: %w", err)
}
var has6 bool
for _, address := range prefixes {
if !address.Addr().Unmap().Is4() {
has6 = true
break
if l4proxy {
outbound.l4Client = masque.NewL4Client(outbound.runCtx, outbound.dialQuic)
if outbound.udp {
log.Warnln("[Masque](%s) L4 proxy mode is not supported for UDP", outbound.name)
outbound.udp = false
}
has6 = true // l4 proxy mode always has ipv6
} else {
prefixes, err := option.Prefixes()
if err != nil {
return nil, err
}
if len(prefixes) == 0 {
return nil, errors.New("missing local address")
}
outbound.tunDevice, err = wireguard.NewStackDevice(prefixes, uint32(mtu))
if err != nil {
return nil, fmt.Errorf("create device: %w", err)
}
for _, address := range prefixes {
if !address.Addr().Unmap().Is4() {
has6 = true
break
}
}
}
@@ -241,12 +261,36 @@ func NewMasque(option MasqueOption) (*Masque, error) {
return outbound, nil
}
func (w *Masque) dialQuic(ctx context.Context) (net.PacketConn, *quic.Conn, error) {
pc, quicConn, err := common.DialQuic(ctx, w.addr, w.DialOptions(), w.dialer, w.tlsConfig, w.quicConfig, false)
if err != nil {
return nil, nil, err
}
common.SetCongestionController(quicConn, w.option.CongestionController, w.option.CWND, w.option.BBRProfile)
return pc, quicConn, nil
}
func (w *Masque) run(ctx context.Context) error {
if w.running.Load() {
return nil
}
w.runMutex.Lock()
defer w.runMutex.Unlock()
runCtx, cancel := context.WithCancel(ctx)
stop := contextutils.AfterFunc(w.runCtx, cancel)
defer func() {
stop()
cancel()
}()
if err := w.runLock.Acquire(runCtx, 1); err != nil {
return err
}
releaseRunLock := true
defer func() {
if releaseRunLock {
w.runLock.Release(1)
}
}()
// double-check like sync.Once
if w.running.Load() {
return nil
@@ -256,6 +300,31 @@ func (w *Masque) run(ctx context.Context) error {
return w.runCtx.Err()
}
if w.option.HandshakeTimeout > 0 {
resultCh := make(chan error, 1)
releaseRunLock = false
go func() {
defer w.runLock.Release(1)
handshakeTimeout := time.Duration(w.option.HandshakeTimeout) * time.Second
handshakeCtx, handshakeCancel := context.WithTimeout(w.runCtx, handshakeTimeout)
defer handshakeCancel()
resultCh <- w.startLocked(handshakeCtx)
}()
select {
case err := <-resultCh:
return err
case <-runCtx.Done():
return runCtx.Err()
}
}
return w.startLocked(runCtx)
}
func (w *Masque) startLocked(ctx context.Context) error {
if !w.runDevice.Load() {
err := w.tunDevice.Start()
if err != nil {
@@ -275,11 +344,10 @@ func (w *Masque) run(ctx context.Context) error {
}
} else {
var quicConn *quic.Conn
pc, quicConn, err = common.DialQuic(ctx, w.addr, w.DialOptions(), w.dialer, w.tlsConfig, w.quicConfig, false)
pc, quicConn, err = w.dialQuic(ctx)
if err != nil {
return err
}
common.SetCongestionController(quicConn, w.option.CongestionController, w.option.CWND, w.option.BBRProfile)
closer, ipConn, err = masque.ConnectTunnel(ctx, quicConn, w.uri)
if err != nil {
@@ -358,10 +426,39 @@ func (w *Masque) Close() error {
if w.tunDevice != nil {
w.tunDevice.Close()
}
if w.l4Client != nil {
w.l4Client.Close()
}
return nil
}
func (w *Masque) dialContextL4(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
var conn net.Conn
if !metadata.Resolved() || w.resolver != nil {
r := resolver.DefaultResolver
if w.resolver != nil {
r = w.resolver
}
options := w.DialOptions()
options = append(options, dialer.WithResolver(r))
options = append(options, dialer.WithNetDialer(w.l4Client))
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
} else {
conn, err = w.l4Client.DialContext(ctx, "tcp", metadata.AddrPort().String())
}
if err != nil {
return nil, err
}
if conn == nil {
return nil, errors.New("conn is nil")
}
return NewConn(conn, w), nil
}
func (w *Masque) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
if w.l4Client != nil {
return w.dialContextL4(ctx, metadata)
}
var conn net.Conn
if err = w.run(ctx); err != nil {
return nil, err
@@ -388,6 +485,9 @@ func (w *Masque) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Con
}
func (w *Masque) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
if w.l4Client != nil {
return nil, errors.New("masque L4 proxy mode is not supported for UDP")
}
var pc net.PacketConn
if err = w.run(ctx); err != nil {
return nil, err
@@ -402,7 +502,7 @@ func (w *Masque) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
if pc == nil {
return nil, errors.New("packetConn is nil")
}
return newPacketConn(pc, w), nil
return NewPacketConn(pc, w), nil
}
func (w *Masque) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
+1 -1
View File
@@ -96,7 +96,7 @@ func (m *Mieru) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (
if err != nil {
return nil, fmt.Errorf("dial to %s failed: %w", metadata.UDPAddr(), err)
}
return newPacketConn(N.NewThreadSafePacketConn(mierucommon.NewUDPAssociateWrapper(mierucommon.NewPacketOverStreamTunnel(c))), m), nil
return NewPacketConn(N.NewThreadSafePacketConn(mierucommon.NewUDPAssociateWrapper(mierucommon.NewPacketOverStreamTunnel(c))), m), nil
}
// SupportUOT implements C.ProxyAdapter
+75 -66
View File
@@ -19,7 +19,6 @@ import (
ovpn "github.com/metacubex/mihomo/transport/openvpn"
wireguard "github.com/metacubex/sing-wireguard"
E "github.com/metacubex/sing/common/exceptions"
M "github.com/metacubex/sing/common/metadata"
"golang.org/x/sync/semaphore"
)
@@ -42,30 +41,35 @@ 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"`
Ping int `proxy:"ping,omitempty"`
PingRestart int `proxy:"ping-restart,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Proto string `proxy:"proto,omitempty"`
Dev string `proxy:"dev,omitempty"`
Cipher string `proxy:"cipher,omitempty"`
Auth string `proxy:"auth,omitempty"`
CompLZO string `proxy:"comp-lzo,omitempty"`
CA string `proxy:"ca"`
Cert string `proxy:"cert,omitempty"`
Key string `proxy:"key,omitempty"`
TLSCrypt string `proxy:"tls-crypt,omitempty"`
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
PeerInfo map[string]string `proxy:"peer-info,omitempty"`
Ping int `proxy:"ping,omitempty"`
PingRestart int `proxy:"ping-restart,omitempty"`
HandshakeTimeout int `proxy:"handshake-timeout,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
Dns []string `proxy:"dns,omitempty"`
}
func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
if option.HandshakeTimeout < 0 {
return nil, errors.New("openvpn handshake timeout must be non-negative")
}
cfg := &ovpn.ClientConfig{
RemoteHost: option.Server,
RemotePort: uint16(option.Port),
@@ -80,6 +84,7 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
TLSCrypt: []byte(option.TLSCrypt),
Username: option.Username,
Password: option.Password,
PeerInfo: option.PeerInfo,
PingInterval: time.Duration(option.Ping) * time.Second,
PingRestart: time.Duration(option.PingRestart) * time.Second,
}
@@ -137,7 +142,7 @@ func (o *OpenVPN) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Co
return nil, err
}
if conn == nil {
return nil, E.New("conn is nil")
return nil, errors.New("conn is nil")
}
return NewConn(conn, o), nil
}
@@ -158,7 +163,7 @@ func (o *OpenVPN) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
if pc == nil {
return nil, errors.New("packetConn is nil")
}
return newPacketConn(pc, o), nil
return NewPacketConn(pc, o), nil
}
func (o *OpenVPN) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
@@ -215,10 +220,23 @@ func (o *OpenVPN) Close() error {
}
func (o *OpenVPN) run(ctx context.Context) (wireguard.Device, resolver.Resolver, error) {
if err := o.lockRun(ctx); err != nil {
runCtx, cancel := context.WithCancel(ctx)
stop := contextutils.AfterFunc(o.runCtx, cancel)
defer func() {
stop()
cancel()
}()
if err := o.runLock.Acquire(runCtx, 1); err != nil {
return nil, nil, err
}
defer o.runLock.Release(1)
releaseRunLock := true
defer func() {
if releaseRunLock {
o.runLock.Release(1)
}
}()
if o.running {
if o.tunDevice == nil {
return nil, nil, net.ErrClosed
@@ -229,15 +247,41 @@ func (o *OpenVPN) run(ctx context.Context) (wireguard.Device, resolver.Resolver,
return nil, nil, o.runCtx.Err()
}
handshakeCtx, cancel := o.handshakeContext(ctx)
defer cancel()
if o.option.HandshakeTimeout > 0 {
type runResult struct {
tunDevice wireguard.Device
resolver resolver.Resolver
err error
}
releaseRunLock = false
resultCh := make(chan runResult, 1)
go func() {
defer o.runLock.Release(1)
handshakeTimeout := time.Duration(o.option.HandshakeTimeout) * time.Second
handshakeCtx, handshakeCancel := context.WithTimeout(o.runCtx, handshakeTimeout)
defer handshakeCancel()
tunDevice, r, err := o.startLocked(handshakeCtx)
resultCh <- runResult{tunDevice: tunDevice, resolver: r, err: err}
}()
select {
case result := <-resultCh:
return result.tunDevice, result.resolver, result.err
case <-runCtx.Done():
return nil, nil, runCtx.Err()
}
}
return o.startLocked(runCtx)
}
func (o *OpenVPN) startLocked(handshakeCtx context.Context) (wireguard.Device, resolver.Resolver, error) {
packetIO, err := o.openPacketIO(handshakeCtx)
if err != nil {
if ctxErr := o.contextErr(ctx); ctxErr != nil {
return nil, nil, ctxErr
}
return nil, nil, E.Cause(err, "connect OpenVPN server")
return nil, nil, fmt.Errorf("connect OpenVPN server: %w", err)
}
client, err := ovpn.NewClient(o.config, packetIO)
if err != nil {
@@ -247,10 +291,7 @@ func (o *OpenVPN) run(ctx context.Context) (wireguard.Device, resolver.Resolver,
push, err := client.Handshake(handshakeCtx)
if err != nil {
_ = client.Close()
if ctxErr := o.contextErr(ctx); ctxErr != nil {
return nil, nil, ctxErr
}
return nil, nil, E.Cause(err, "OpenVPN handshake")
return nil, nil, fmt.Errorf("make OpenVPN handshake: %w", err)
}
log.Debugln("[OpenVPN](%s) handshake complete: prefixes=%v routes=%v peer-id=%d dns=%v redirect=%t block-ipv6=%t", o.name, push.Prefixes, push.Routes, push.PeerID, push.DNS, push.Redirect, push.BlockIPv6)
@@ -261,7 +302,7 @@ func (o *OpenVPN) run(ctx context.Context) (wireguard.Device, resolver.Resolver,
tunDevice, err := wireguard.NewStackDevice(push.Prefixes, uint32(mtu))
if err != nil {
_ = client.Close()
return nil, nil, E.Cause(err, "create OpenVPN stack device")
return nil, nil, fmt.Errorf("create OpenVPN stack device: %w", err)
}
if err := tunDevice.Start(); err != nil {
_ = client.Close()
@@ -285,38 +326,6 @@ func (o *OpenVPN) run(ctx context.Context) (wireguard.Device, resolver.Resolver,
return o.tunDevice, o.resolver, nil
}
func (o *OpenVPN) lockRun(ctx context.Context) error {
lockCtx, cancel := context.WithCancel(ctx)
stop := contextutils.AfterFunc(o.runCtx, cancel)
defer func() {
stop()
cancel()
}()
if err := o.runLock.Acquire(lockCtx, 1); err != nil {
if ctxErr := o.contextErr(ctx); ctxErr != nil {
return ctxErr
}
return err
}
return nil
}
func (o *OpenVPN) handshakeContext(ctx context.Context) (context.Context, context.CancelFunc) {
handshakeCtx, handshakeCancel := context.WithTimeout(ctx, ovpn.DefaultHandshakeTimeout)
stop := contextutils.AfterFunc(o.runCtx, handshakeCancel)
return handshakeCtx, func() {
stop()
handshakeCancel()
}
}
func (o *OpenVPN) contextErr(ctx context.Context) error {
if err := ctx.Err(); err != nil {
return err
}
return o.runCtx.Err()
}
func openVPNPrefixesHas6(prefixes []netip.Prefix) bool {
for _, prefix := range prefixes {
if !prefix.Addr().Unmap().Is4() {
+1 -1
View File
@@ -34,7 +34,7 @@ func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
if err := r.ResolveUDP(ctx, metadata); err != nil {
return nil, err
}
return newPacketConn(&nopPacketConn{}, r), nil
return NewPacketConn(&nopPacketConn{}, r), nil
}
func (r *Reject) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
+56
View File
@@ -0,0 +1,56 @@
package outbound
import (
"context"
"fmt"
C "github.com/metacubex/mihomo/constant"
)
type Rematch struct {
*Base
targetRematchName *string
targetSubRule *string
}
type RematchOption struct {
BasicOption
Name string `proxy:"name"`
TargetRematchName *string `proxy:"target-rematch-name,omitempty"`
TargetSubRule *string `proxy:"target-sub-rule,omitempty"`
}
func (l *Rematch) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
l.applyMetadata(metadata)
return NewConn(nopConn{}, l), nil
}
func (l *Rematch) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
l.applyMetadata(metadata)
return NewPacketConn(&nopPacketConn{}, l), nil
}
func (l *Rematch) applyMetadata(metadata *C.Metadata) {
if l.targetRematchName != nil {
metadata.RematchName = *l.targetRematchName
}
if l.targetSubRule != nil {
metadata.SpecialRules = *l.targetSubRule
}
}
func NewRematch(option RematchOption) (*Rematch, error) {
if option.TargetRematchName == nil && option.TargetSubRule == nil {
return nil, fmt.Errorf("rematch %s requires at least one of target-rematch-name or target-sub-rule", option.Name)
}
return &Rematch{
Base: NewBase(BaseOption{
Name: option.Name,
Type: C.Rematch,
ProviderName: option.ProviderName,
UDP: true,
}),
targetRematchName: option.TargetRematchName,
targetSubRule: option.TargetSubRule,
}, nil
}
+18 -8
View File
@@ -100,10 +100,13 @@ type shadowTLSOption struct {
}
type restlsOption struct {
Password string `obfs:"password"`
Host string `obfs:"host"`
VersionHint string `obfs:"version-hint"`
RestlsScript string `obfs:"restls-script,omitempty"`
Password string `obfs:"password"`
Host string `obfs:"host"`
VersionHint string `obfs:"version-hint"`
RestlsScript string `obfs:"restls-script,omitempty"`
Fingerprint string `obfs:"fingerprint,omitempty"`
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
ForceTLS12 bool `obfs:"force-tls12,omitempty"` // for test
}
type kcpTunOption struct {
@@ -240,9 +243,9 @@ func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Meta
}
destination := M.SocksaddrFromNet(metadata.UDPAddr())
if ss.option.UDPOverTCPVersion == uot.LegacyVersion {
return newPacketConn(N.NewThreadSafePacketConn(uot.NewConn(c, uot.Request{Destination: destination})), ss), nil
return NewPacketConn(N.NewThreadSafePacketConn(uot.NewConn(c, uot.Request{Destination: destination})), ss), nil
} else {
return newPacketConn(N.NewThreadSafePacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination})), ss), nil
return NewPacketConn(N.NewThreadSafePacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination})), ss), nil
}
}
if err := ss.ResolveUDP(ctx, metadata); err != nil {
@@ -254,7 +257,7 @@ func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Meta
return nil, err
}
pc = ss.method.DialPacketConn(bufio.NewBindPacketConn(pc, addr))
return newPacketConn(pc, ss), nil
return NewPacketConn(pc, ss), nil
}
// ProxyInfo implements C.ProxyAdapter
@@ -404,7 +407,14 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
if err != nil {
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
}
restlsConfig.InsecureSkipVerify = restlsOpt.SkipCertVerify
if restlsOpt.Fingerprint != "" {
err = restls.SetFingerprint(restlsConfig, restlsOpt.Fingerprint)
if err != nil {
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
}
}
restlsConfig.ForceTLS12 = restlsOpt.ForceTLS12
} else if option.Plugin == kcptun.Mode {
obfsMode = kcptun.Mode
kcptunOpt := &kcpTunOption{}
+7 -2
View File
@@ -96,7 +96,7 @@ func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Me
epc := ssr.cipher.PacketConn(N.NewEnhancePacketConn(pc))
epc = ssr.protocol.PacketConn(epc)
return newPacketConn(&ssrPacketConn{EnhancePacketConn: epc, rAddr: addr}, ssr), nil
return NewPacketConn(&ssrPacketConn{EnhancePacketConn: epc, rAddr: addr}, ssr), nil
}
// ProxyInfo implements C.ProxyAdapter
@@ -189,7 +189,12 @@ func (spc *ssrPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
if err != nil {
return
}
return spc.EnhancePacketConn.WriteTo(packet[3:], spc.rAddr)
packet = packet[3:]
_, err = spc.EnhancePacketConn.WriteTo(packet, spc.rAddr)
if err != nil {
return 0, err
}
return len(b), nil
}
func (spc *ssrPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
+1 -1
View File
@@ -60,7 +60,7 @@ func (s *SingMux) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
if pc == nil {
return nil, E.New("packetConn is nil")
}
return newPacketConn(N.NewThreadSafePacketConn(pc), s), nil
return NewPacketConn(N.NewThreadSafePacketConn(pc), s), nil
}
func (s *SingMux) SupportUDP() bool {
+70 -36
View File
@@ -10,53 +10,58 @@ import (
"github.com/metacubex/mihomo/common/structure"
C "github.com/metacubex/mihomo/constant"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
"github.com/metacubex/mihomo/transport/snell"
)
type Snell struct {
*Base
option *SnellOption
psk []byte
pool *snell.Pool
obfsOption *simpleObfsOption
version int
reuse bool
option *SnellOption
psk []byte
pool *snell.Pool
obfsOption *simpleObfsOption
shadowTLSOption *shadowtls.ShadowTLSOption
version int
reuse bool
}
type SnellOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Psk string `proxy:"psk"`
UDP bool `proxy:"udp,omitempty"`
Version int `proxy:"version,omitempty"`
Reuse bool `proxy:"reuse,omitempty"`
ObfsOpts map[string]any `proxy:"obfs-opts,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Psk string `proxy:"psk"`
UDP bool `proxy:"udp,omitempty"`
Version int `proxy:"version,omitempty"`
Reuse bool `proxy:"reuse,omitempty"`
ObfsOpts map[string]any `proxy:"obfs-opts,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
}
type streamOption struct {
psk []byte
version int
addr string
obfsOption *simpleObfsOption
}
func snellStreamConn(c net.Conn, option streamOption) *snell.Snell {
switch option.obfsOption.Mode {
func (s *Snell) streamConnContext(ctx context.Context, c net.Conn) (*snell.Snell, error) {
var err error
switch s.obfsOption.Mode {
case "tls":
c = obfs.NewTLSObfs(c, option.obfsOption.Host)
c = obfs.NewTLSObfs(c, s.obfsOption.Host)
case "http":
_, port, _ := net.SplitHostPort(option.addr)
c = obfs.NewHTTPObfs(c, option.obfsOption.Host, port)
_, port, _ := net.SplitHostPort(s.addr)
c = obfs.NewHTTPObfs(c, s.obfsOption.Host, port)
case shadowtls.Mode:
c, err = shadowtls.NewShadowTLS(ctx, c, s.shadowTLSOption)
if err != nil {
return nil, err
}
}
return snell.StreamConn(c, option.psk, option.version)
return snell.StreamConn(c, s.psk, s.version), nil
}
// StreamConnContext implements C.ProxyAdapter
func (s *Snell) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
c = snellStreamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
err := s.writeHeaderContext(ctx, c, metadata)
c, err := s.streamConnContext(ctx, c)
if err != nil {
return nil, err
}
err = s.writeHeaderContext(ctx, c, metadata)
return c, err
}
@@ -91,6 +96,9 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn
_ = c.Close()
return nil, err
}
if pc, ok := c.(*snell.PoolConn); ok {
pc.MarkReusable()
}
return NewConn(c, s), err
}
@@ -127,7 +135,7 @@ func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (
}
pc := snell.PacketConn(c)
return newPacketConn(pc, s), nil
return NewPacketConn(pc, s), nil
}
// SupportUOT implements C.ProxyAdapter
@@ -152,9 +160,34 @@ func NewSnell(option SnellOption) (*Snell, error) {
return nil, fmt.Errorf("snell %s initialize obfs error: %w", addr, err)
}
var shadowTLSOpt *shadowtls.ShadowTLSOption
switch obfsOption.Mode {
case "tls", "http", "":
break
case shadowtls.Mode:
opt := &shadowTLSOption{
Version: 2,
}
if err := decoder.Decode(option.ObfsOpts, opt); err != nil {
return nil, fmt.Errorf("snell %s initialize shadow-tls-plugin error: %w", addr, err)
}
shadowTLSOpt = &shadowtls.ShadowTLSOption{
Password: opt.Password,
Host: opt.Host,
Fingerprint: opt.Fingerprint,
Certificate: opt.Certificate,
PrivateKey: opt.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
SkipCertVerify: opt.SkipCertVerify,
Version: opt.Version,
}
if opt.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
shadowTLSOpt.ALPN = opt.ALPN
} else {
shadowTLSOpt.ALPN = shadowtls.DefaultALPN
}
default:
return nil, fmt.Errorf("snell %s obfs mode error: %s", addr, obfsOption.Mode)
}
@@ -191,11 +224,12 @@ func NewSnell(option SnellOption) (*Snell, error) {
RoutingMark: option.RoutingMark,
Prefer: option.IPVersion,
}),
option: &option,
psk: psk,
obfsOption: obfsOption,
version: option.Version,
reuse: reuse,
option: &option,
psk: psk,
obfsOption: obfsOption,
shadowTLSOption: shadowTLSOpt,
version: option.Version,
reuse: reuse,
}
s.dialer = option.NewDialer(s.DialOptions())
@@ -206,7 +240,7 @@ func NewSnell(option SnellOption) (*Snell, error) {
return nil, err
}
return snellStreamConn(c, streamOption{psk, option.Version, addr, obfsOption}), nil
return s.streamConnContext(ctx, c)
})
}
return s, nil
+6 -2
View File
@@ -151,7 +151,7 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
pc.Close()
}()
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
return NewPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
}
// ProxyInfo implements C.ProxyAdapter
@@ -222,7 +222,11 @@ func (uc *socksPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
if err != nil {
return
}
return uc.PacketConn.WriteTo(packet, uc.rAddr)
_, err = uc.PacketConn.WriteTo(packet, uc.rAddr)
if err != nil {
return 0, err
}
return len(b), nil
}
func (uc *socksPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
+1 -1
View File
@@ -113,7 +113,7 @@ func (s *Sudoku) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
return nil, fmt.Errorf("start uot failed: %w", err)
}
return newPacketConn(N.NewThreadSafePacketConn(sudoku.NewUoTPacketConn(c)), s), nil
return NewPacketConn(N.NewThreadSafePacketConn(sudoku.NewUoTPacketConn(c)), s), nil
}
// SupportUOT implements C.ProxyAdapter
+1 -1
View File
@@ -399,7 +399,7 @@ func (t *Tailscale) ListenPacketContext(ctx context.Context, metadata *C.Metadat
if pc == nil {
return nil, errors.New("packetConn is nil")
}
return newPacketConn(pc, t), nil
return NewPacketConn(pc, t), nil
}
func (t *Tailscale) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
+142
View File
@@ -0,0 +1,142 @@
package outbound
import "github.com/metacubex/mihomo/transport/tlsmirror"
type TLSMirrorOptions struct {
PrimaryKey string `proxy:"primary-key,omitempty"`
ExplicitNonceCipherSuites []uint16 `proxy:"explicit-nonce-ciphersuites,omitempty"`
DeferInstanceDerivedWriteTime TLSMirrorTimeSpec `proxy:"defer-instance-derived-write-time,omitempty"`
TransportLayerPadding TLSMirrorTransportLayerPadding `proxy:"transport-layer-padding,omitempty"`
ConnectionEnrolment *TLSMirrorConnectionEnrolment `proxy:"connection-enrolment,omitempty"`
EmbeddedTrafficGenerator TLSMirrorTrafficGenerator `proxy:"embedded-traffic-generator,omitempty"`
SequenceWatermarkingEnabled bool `proxy:"sequence-watermarking-enabled,omitempty"`
}
type TLSMirrorConnectionEnrolment struct {
PrimaryIngressOutbound string `proxy:"primary-ingress-outbound,omitempty"`
PrimaryEgressOutbound string `proxy:"primary-egress-outbound,omitempty"`
}
func (e *TLSMirrorConnectionEnrolment) Build() *tlsmirror.ConnectionEnrolment {
if e == nil {
return nil
}
return &tlsmirror.ConnectionEnrolment{
PrimaryIngressOutbound: e.PrimaryIngressOutbound,
PrimaryEgressOutbound: e.PrimaryEgressOutbound,
}
}
type TLSMirrorTimeSpec struct {
BaseNanoseconds uint64 `proxy:"base-nanoseconds,omitempty"`
UniformRandomMultiplierNanoseconds uint64 `proxy:"uniform-random-multiplier-nanoseconds,omitempty"`
}
func (s TLSMirrorTimeSpec) Build() tlsmirror.TimeSpec {
return tlsmirror.TimeSpec{
BaseNanoseconds: s.BaseNanoseconds,
UniformRandomMultiplierNanoseconds: s.UniformRandomMultiplierNanoseconds,
}
}
type TLSMirrorTransportLayerPadding struct {
Enabled bool `proxy:"enabled,omitempty"`
}
func (p TLSMirrorTransportLayerPadding) Build() tlsmirror.TransportLayerPadding {
return tlsmirror.TransportLayerPadding{
Enabled: p.Enabled,
}
}
type TLSMirrorTrafficGenerator struct {
Steps []TLSMirrorTrafficStep `proxy:"steps,omitempty"`
}
func (g TLSMirrorTrafficGenerator) Build() *tlsmirror.TrafficGenerator {
if len(g.Steps) == 0 {
return nil
}
steps := make([]tlsmirror.TrafficStep, 0, len(g.Steps))
for _, step := range g.Steps {
steps = append(steps, step.Build())
}
return &tlsmirror.TrafficGenerator{Steps: steps}
}
type TLSMirrorTrafficStep struct {
Name string `proxy:"name,omitempty"`
Host string `proxy:"host,omitempty"`
Path string `proxy:"path,omitempty"`
Method string `proxy:"method,omitempty"`
Headers []TLSMirrorTrafficHeader `proxy:"headers,omitempty"`
NextStep []TLSMirrorTrafficTransferCandidate `proxy:"next-step,omitempty"`
ConnectionReady bool `proxy:"connection-ready,omitempty"`
ConnectionRecallExit bool `proxy:"connection-recall-exit,omitempty"`
WaitTime TLSMirrorTimeSpec `proxy:"wait-time,omitempty"`
H2DoNotWaitForDownloadFinish bool `proxy:"h2-do-not-wait-for-download-finish,omitempty"`
}
func (s TLSMirrorTrafficStep) Build() tlsmirror.TrafficStep {
headers := make([]tlsmirror.TrafficHeader, 0, len(s.Headers))
for _, header := range s.Headers {
headers = append(headers, header.Build())
}
nextStep := make([]tlsmirror.TrafficTransferCandidate, 0, len(s.NextStep))
for _, candidate := range s.NextStep {
nextStep = append(nextStep, candidate.Build())
}
return tlsmirror.TrafficStep{
Name: s.Name,
Host: s.Host,
Path: s.Path,
Method: s.Method,
Headers: headers,
NextStep: nextStep,
ConnectionReady: s.ConnectionReady,
ConnectionRecallExit: s.ConnectionRecallExit,
WaitTime: s.WaitTime.Build(),
H2DoNotWaitForDownloadFinish: s.H2DoNotWaitForDownloadFinish,
}
}
type TLSMirrorTrafficHeader struct {
Name string `proxy:"name,omitempty"`
Value string `proxy:"value,omitempty"`
Values []string `proxy:"values,omitempty"`
}
func (h TLSMirrorTrafficHeader) Build() tlsmirror.TrafficHeader {
return tlsmirror.TrafficHeader{
Name: h.Name,
Value: h.Value,
Values: h.Values,
}
}
type TLSMirrorTrafficTransferCandidate struct {
Weight int32 `proxy:"weight,omitempty"`
GotoLocation int `proxy:"goto-location,omitempty"`
}
func (c TLSMirrorTrafficTransferCandidate) Build() tlsmirror.TrafficTransferCandidate {
return tlsmirror.TrafficTransferCandidate{
Weight: c.Weight,
GotoLocation: c.GotoLocation,
}
}
func (o TLSMirrorOptions) Build() *tlsmirror.Config {
if o.PrimaryKey == "" {
return nil
}
return &tlsmirror.Config{
PrimaryKey: o.PrimaryKey,
ExplicitNonceCipherSuites: o.ExplicitNonceCipherSuites,
DeferInstanceDerivedWrite: o.DeferInstanceDerivedWriteTime.Build(),
TransportLayerPadding: o.TransportLayerPadding.Build(),
ConnectionEnrolment: o.ConnectionEnrolment.Build(),
SequenceWatermarkingEnabled: o.SequenceWatermarkingEnabled,
EmbeddedTrafficGenerator: o.EmbeddedTrafficGenerator.Build(),
}
}
+1 -1
View File
@@ -219,7 +219,7 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
}
pc := trojan.NewPacketConn(c)
return newPacketConn(pc, t), err
return NewPacketConn(pc, t), err
}
// SupportUOT implements C.ProxyAdapter
+1 -1
View File
@@ -63,7 +63,7 @@ func (t *TrustTunnel) ListenPacketContext(ctx context.Context, metadata *C.Metad
return nil, err
}
return newPacketConn(N.NewThreadSafePacketConn(pc), t), nil
return NewPacketConn(N.NewThreadSafePacketConn(pc), t), nil
}
// SupportUOT implements C.ProxyAdapter
+3 -3
View File
@@ -97,16 +97,16 @@ func (t *Tuic) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_
destination := M.SocksaddrFromNet(metadata.UDPAddr())
if t.option.UDPOverStreamVersion == uot.LegacyVersion {
return newPacketConn(uot.NewConn(c, uot.Request{Destination: destination}), t), nil
return NewPacketConn(uot.NewConn(c, uot.Request{Destination: destination}), t), nil
} else {
return newPacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination}), t), nil
return NewPacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination}), t), nil
}
}
pc, err := t.client.ListenPacket(ctx, metadata)
if err != nil {
return nil, err
}
return newPacketConn(pc, t), nil
return NewPacketConn(pc, t), nil
}
func (t *Tuic) dial(ctx context.Context) (quicConn *quic.Conn, err error) {
+7 -3
View File
@@ -93,6 +93,8 @@ type XHTTPOptions struct {
UplinkHTTPMethod string `proxy:"uplink-http-method,omitempty"`
SessionPlacement string `proxy:"session-placement,omitempty"`
SessionKey string `proxy:"session-key,omitempty"`
SessionTable string `proxy:"session-table,omitempty"`
SessionLength string `proxy:"session-length,omitempty"`
SeqPlacement string `proxy:"seq-placement,omitempty"`
SeqKey string `proxy:"seq-key,omitempty"`
UplinkDataPlacement string `proxy:"uplink-data-placement,omitempty"`
@@ -346,18 +348,18 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (
if metadata.SourceValid() {
globalID = utils.GlobalID(metadata.SourceAddress())
}
return newPacketConn(N.NewThreadSafePacketConn(
return NewPacketConn(N.NewThreadSafePacketConn(
vmessSing.NewXUDPConn(c,
globalID,
M.SocksaddrFromNet(metadata.UDPAddr())),
), v), nil
} else if v.option.PacketAddr {
return newPacketConn(N.NewThreadSafePacketConn(
return NewPacketConn(N.NewThreadSafePacketConn(
packetaddr.NewConn(v.client.PacketConn(c, metadata.UDPAddr()),
M.SocksaddrFromNet(metadata.UDPAddr())),
), v), nil
}
return newPacketConn(N.NewThreadSafePacketConn(v.client.PacketConn(c, metadata.UDPAddr())), v), nil
return NewPacketConn(N.NewThreadSafePacketConn(v.client.PacketConn(c, metadata.UDPAddr())), v), nil
}
// SupportUOT implements C.ProxyAdapter
@@ -569,6 +571,8 @@ func NewVless(option VlessOption) (*Vless, error) {
UplinkHTTPMethod: v.option.XHTTPOpts.UplinkHTTPMethod,
SessionPlacement: v.option.XHTTPOpts.SessionPlacement,
SessionKey: v.option.XHTTPOpts.SessionKey,
SessionTable: v.option.XHTTPOpts.SessionTable,
SessionLength: v.option.XHTTPOpts.SessionLength,
SeqPlacement: v.option.XHTTPOpts.SeqPlacement,
SeqKey: v.option.XHTTPOpts.SeqKey,
UplinkDataPlacement: v.option.XHTTPOpts.UplinkDataPlacement,
+158 -48
View File
@@ -13,10 +13,13 @@ import (
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/mihomo/component/ech"
"github.com/metacubex/mihomo/component/proxydialer"
tlsC "github.com/metacubex/mihomo/component/tls"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/mihomo/transport/gun"
"github.com/metacubex/mihomo/transport/mekya"
"github.com/metacubex/mihomo/transport/mkcp"
mihomoVMess "github.com/metacubex/mihomo/transport/vmess"
"github.com/metacubex/http"
@@ -34,7 +37,8 @@ type Vmess struct {
option *VmessOption
// for gun mux
gunClient *gun.Client
gunClient *gun.Client
mekyaClient *mekya.Client
realityConfig *tlsC.RealityConfig
echConfig *ech.Config
@@ -42,33 +46,90 @@ type Vmess struct {
type VmessOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
UUID string `proxy:"uuid"`
AlterID int `proxy:"alterId"`
Cipher string `proxy:"cipher"`
UDP bool `proxy:"udp,omitempty"`
Network string `proxy:"network,omitempty"`
TLS bool `proxy:"tls,omitempty"`
ALPN []string `proxy:"alpn,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
ServerName string `proxy:"servername,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
PacketAddr bool `proxy:"packet-addr,omitempty"`
XUDP bool `proxy:"xudp,omitempty"`
PacketEncoding string `proxy:"packet-encoding,omitempty"`
GlobalPadding bool `proxy:"global-padding,omitempty"`
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
UUID string `proxy:"uuid"`
AlterID int `proxy:"alterId"`
Cipher string `proxy:"cipher"`
UDP bool `proxy:"udp,omitempty"`
Network string `proxy:"network,omitempty"`
TLS bool `proxy:"tls,omitempty"`
ALPN []string `proxy:"alpn,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
ServerName string `proxy:"servername,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
TLSMirrorOpts TLSMirrorOptions `proxy:"tlsmirror-opts,omitempty"`
MekyaOpts MekyaOptions `proxy:"mekya-opts,omitempty"`
MKCPOpts MKCPOptions `proxy:"mkcp-opts,omitempty"`
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
PacketAddr bool `proxy:"packet-addr,omitempty"`
XUDP bool `proxy:"xudp,omitempty"`
PacketEncoding string `proxy:"packet-encoding,omitempty"`
GlobalPadding bool `proxy:"global-padding,omitempty"`
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
}
type MKCPOptions struct {
MTU uint32 `proxy:"mtu,omitempty"`
TTI uint32 `proxy:"tti,omitempty"`
UplinkCapacity uint32 `proxy:"uplink-capacity,omitempty"`
DownlinkCapacity uint32 `proxy:"downlink-capacity,omitempty"`
Congestion bool `proxy:"congestion,omitempty"`
WriteBuffer uint32 `proxy:"write-buffer,omitempty"`
ReadBuffer uint32 `proxy:"read-buffer,omitempty"`
Seed string `proxy:"seed,omitempty"`
Header string `proxy:"header,omitempty"`
}
func (o MKCPOptions) Build() mkcp.Config {
return mkcp.Config{
MTU: o.MTU,
TTI: o.TTI,
UplinkCapacity: o.UplinkCapacity,
DownlinkCapacity: o.DownlinkCapacity,
Congestion: o.Congestion,
WriteBuffer: o.WriteBuffer,
ReadBuffer: o.ReadBuffer,
Seed: o.Seed,
Header: o.Header,
}
}
type MekyaOptions struct {
URL string `proxy:"url,omitempty"`
H2PoolSize int `proxy:"h2-pool-size,omitempty"`
MaxWriteDelay int `proxy:"max-write-delay,omitempty"`
MaxRequestSize int `proxy:"max-request-size,omitempty"`
PollingIntervalInitial int `proxy:"polling-interval-initial,omitempty"`
MaxWriteSize int `proxy:"max-write-size,omitempty"`
MaxWriteDurationMs int `proxy:"max-write-duration-ms,omitempty"`
MaxSimultaneousWriteConnection int `proxy:"max-simultaneous-write-connection,omitempty"`
PacketWritingBuffer int `proxy:"packet-writing-buffer,omitempty"`
KCP MKCPOptions `proxy:"kcp,omitempty"`
}
func (o MekyaOptions) Build() mekya.Config {
return mekya.Config{
KCP: o.KCP.Build(),
URL: o.URL,
H2PoolSize: o.H2PoolSize,
MaxWriteDelay: o.MaxWriteDelay,
MaxRequestSize: o.MaxRequestSize,
PollingIntervalInitial: o.PollingIntervalInitial,
MaxWriteSize: o.MaxWriteSize,
MaxWriteDurationMs: o.MaxWriteDurationMs,
MaxSimultaneousWriteConnection: o.MaxSimultaneousWriteConnection,
PacketWritingBuffer: o.PacketWritingBuffer,
}
}
type HTTPOptions struct {
@@ -124,25 +185,32 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
}
if v.option.TLS {
wsOpts.TLS = true
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
TLSConfig: &tls.Config{
ServerName: host,
InsecureSkipVerify: v.option.SkipCertVerify,
NextProtos: []string{"http/1.1"},
},
Fingerprint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
})
if err != nil {
return nil, err
}
if v.option.TLSMirrorOpts.PrimaryKey != "" {
c, err = v.streamTLSConn(ctx, c, false)
if err != nil {
return nil, err
}
} else {
wsOpts.TLS = true
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
TLSConfig: &tls.Config{
ServerName: host,
InsecureSkipVerify: v.option.SkipCertVerify,
NextProtos: []string{"http/1.1"},
},
Fingerprint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
})
if err != nil {
return nil, err
}
if v.option.ServerName != "" {
wsOpts.TLSConfig.ServerName = v.option.ServerName
} else if host := wsOpts.Headers.Get("Host"); host != "" {
wsOpts.TLSConfig.ServerName = host
if v.option.ServerName != "" {
wsOpts.TLSConfig.ServerName = v.option.ServerName
} else if host := wsOpts.Headers.Get("Host"); host != "" {
wsOpts.TLSConfig.ServerName = host
}
}
}
c, err = mihomoVMess.StreamWebsocketConn(ctx, c, wsOpts)
@@ -176,6 +244,8 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
c, err = mihomoVMess.StreamH2Conn(ctx, c, h2Opts)
case "grpc":
break // already handle in dialContext
case "mekya":
break // already handle in dialContext
default:
// default tcp network
// handle TLS
@@ -258,6 +328,8 @@ func (v *Vmess) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (ne
ECH: v.echConfig,
Reality: v.realityConfig,
NextProtos: v.option.ALPN,
TLSMirror: v.option.TLSMirrorOpts.Build(),
TLSMirrorDialer: proxydialer.New(v, false).DialContext,
}
if isH2 {
@@ -278,6 +350,14 @@ func (v *Vmess) dialContext(ctx context.Context) (c net.Conn, err error) {
switch v.option.Network {
case "grpc": // gun transport
return v.gunClient.Dial()
case "mekya":
return v.mekyaClient.Dial(ctx)
case "mkcp", "kcp":
rawConn, err := v.dialer.DialContext(ctx, "udp", v.addr)
if err != nil {
return nil, err
}
return mkcp.Dial(ctx, rawConn, v.option.MKCPOpts.Build())
default:
}
return v.dialer.DialContext(ctx, "tcp", v.addr)
@@ -320,9 +400,9 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (
}
if pc, ok := c.(net.PacketConn); ok {
return newPacketConn(N.NewThreadSafePacketConn(pc), v), nil
return NewPacketConn(N.NewThreadSafePacketConn(pc), v), nil
}
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
return NewPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
}
// ProxyInfo implements C.ProxyAdapter
@@ -340,6 +420,11 @@ func (v *Vmess) Close() error {
errs = append(errs, err)
}
}
if v.mekyaClient != nil {
if err := v.mekyaClient.Close(); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
@@ -407,6 +492,29 @@ func NewVmess(option VmessOption) (*Vmess, error) {
if len(option.HTTP2Opts.Host) == 0 {
option.HTTP2Opts.Host = append(option.HTTP2Opts.Host, "www.example.com")
}
case "mekya":
if len(v.option.ALPN) == 0 {
v.option.ALPN = []string{"h2", "http/1.1"}
}
cfg := option.MekyaOpts.Build()
if cfg.URL == "" {
cfg.URL = "https://" + v.addr
}
v.mekyaClient, err = mekya.NewClient(context.Background(), func(ctx context.Context) (net.Conn, error) {
rawConn, err := v.dialer.DialContext(ctx, "tcp", v.addr)
if err != nil {
return nil, err
}
conn, err := v.streamTLSConn(ctx, rawConn, false)
if err != nil {
_ = rawConn.Close()
return nil, err
}
return conn, nil
}, cfg)
if err != nil {
return nil, err
}
case "grpc":
dialFn := func(ctx context.Context, network, addr string) (net.Conn, error) {
c, err := v.dialer.DialContext(ctx, "tcp", v.addr)
@@ -437,6 +545,8 @@ func NewVmess(option VmessOption) (*Vmess, error) {
NextProtos: []string{"h2"},
ECH: v.echConfig,
Reality: v.realityConfig,
TLSMirror: option.TLSMirrorOpts.Build(),
TLSMirrorDialer: proxydialer.New(v, false).DialContext,
}
if option.ServerName == "" {
host, _, _ := net.SplitHostPort(v.addr)
+1 -1
View File
@@ -591,7 +591,7 @@ func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadat
if pc == nil {
return nil, E.New("packetConn is nil")
}
return newPacketConn(pc, w), nil
return NewPacketConn(pc, w), nil
}
func (w *WireGuard) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
+4 -2
View File
@@ -13,6 +13,8 @@ import (
P "github.com/metacubex/mihomo/constant/provider"
)
type FallbackOption struct{}
type Fallback struct {
*GroupBase
disableUDP bool
@@ -157,7 +159,7 @@ func (f *Fallback) Proxies() []C.Proxy {
return f.GetProxies(false)
}
func NewFallback(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.ProxyProvider) *Fallback {
func NewFallback(option GroupCommonOption, fallbackOption FallbackOption, emptyFallback C.Proxy, providers []P.ProxyProvider) (*Fallback, error) {
return &Fallback{
GroupBase: NewGroupBase(GroupBaseOption{
Name: option.Name,
@@ -175,5 +177,5 @@ func NewFallback(option *GroupCommonOption, emptyFallback C.Proxy, providers []P
disableUDP: option.DisableUDP,
testUrl: option.URL,
expectedStatus: option.ExpectedStatus,
}
}, nil
}
+9 -12
View File
@@ -19,7 +19,9 @@ import (
"golang.org/x/net/publicsuffix"
)
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy
type LoadBalanceOption struct {
Strategy string `group:"strategy,omitempty"`
}
type LoadBalance struct {
*GroupBase
@@ -29,14 +31,9 @@ type LoadBalance struct {
expectedStatus string
}
var errStrategy = errors.New("unsupported strategy")
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy
func parseStrategy(config map[string]any) string {
if strategy, ok := config["strategy"].(string); ok {
return strategy
}
return "consistent-hashing"
}
var errStrategy = errors.New("unsupported strategy")
func getKey(metadata *C.Metadata) string {
if metadata == nil {
@@ -250,17 +247,17 @@ func (lb *LoadBalance) Now() string {
return ""
}
func NewLoadBalance(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
func NewLoadBalance(option GroupCommonOption, loadBalanceOption LoadBalanceOption, emptyFallback C.Proxy, providers []P.ProxyProvider) (lb *LoadBalance, err error) {
var strategyFn strategyFn
switch strategy {
case "consistent-hashing":
switch loadBalanceOption.Strategy {
case "", "consistent-hashing":
strategyFn = strategyConsistentHashing(option.URL)
case "round-robin":
strategyFn = strategyRoundRobin(option.URL)
case "sticky-sessions":
strategyFn = strategyStickySessions(option.URL)
default:
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
return nil, fmt.Errorf("%w: %s", errStrategy, loadBalanceOption.Strategy)
}
return &LoadBalance{
GroupBase: NewGroupBase(GroupBaseOption{
+30 -12
View File
@@ -45,13 +45,13 @@ type GroupCommonOption struct {
Icon string `group:"icon,omitempty"`
}
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]P.ProxyProvider, AllProxies []string, AllProviders []string) (C.ProxyAdapter, error) {
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]P.ProxyProvider, AllProxies []string, AllProviders []string) (ProxyGroup, error) {
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
groupOption := &GroupCommonOption{
groupOption := GroupCommonOption{
Lazy: true,
}
if err := decoder.Decode(config, groupOption); err != nil {
if err := decoder.Decode(config, &groupOption); err != nil {
return nil, errFormat
}
@@ -78,6 +78,9 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
if !ok {
return nil, fmt.Errorf("%s: empty fallback proxy '%s' not found", groupName, groupOption.EmptyFallback)
}
if _, ok := emptyFallback.Adapter().(ProxyGroup); ok { // strictly forbidden to fill in a proxy group for empty-fallback
return nil, fmt.Errorf("%s: empty fallback proxy '%s' not found", groupName, groupOption.EmptyFallback)
}
providers := []P.ProxyProvider{}
@@ -181,25 +184,40 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
providersMap[groupName] = pd
}
var group C.ProxyAdapter
switch groupOption.Type {
case "url-test":
opts := parseURLTestOption(config)
group = NewURLTest(groupOption, emptyFallback, providers, opts...)
opt := URLTestOption{}
err = decoder.Decode(config, &opt)
if err != nil {
return nil, err
}
return NewURLTest(groupOption, opt, emptyFallback, providers)
case "select":
group = NewSelector(groupOption, emptyFallback, providers)
opt := SelectorOption{}
err = decoder.Decode(config, &opt)
if err != nil {
return nil, err
}
return NewSelector(groupOption, opt, emptyFallback, providers)
case "fallback":
group = NewFallback(groupOption, emptyFallback, providers)
opt := FallbackOption{}
err = decoder.Decode(config, &opt)
if err != nil {
return nil, err
}
return NewFallback(groupOption, opt, emptyFallback, providers)
case "load-balance":
strategy := parseStrategy(config)
return NewLoadBalance(groupOption, emptyFallback, providers, strategy)
opt := LoadBalanceOption{}
err = decoder.Decode(config, &opt)
if err != nil {
return nil, err
}
return NewLoadBalance(groupOption, opt, emptyFallback, providers)
case "relay":
return nil, fmt.Errorf("%w: The group [%s] with relay type was removed, please using dialer-proxy instead", errType, groupName)
default:
return nil, fmt.Errorf("%w: %s", errType, groupOption.Type)
}
return group, nil
}
func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
+7 -3
View File
@@ -9,6 +9,10 @@ import (
P "github.com/metacubex/mihomo/constant/provider"
)
type SelectorOption struct {
DefaultSelected string `group:"default-selected,omitempty"`
}
type Selector struct {
*GroupBase
disableUDP bool
@@ -115,7 +119,7 @@ func (s *Selector) Proxies() []C.Proxy {
return s.GetProxies(false)
}
func NewSelector(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.ProxyProvider) *Selector {
func NewSelector(option GroupCommonOption, selectorOption SelectorOption, emptyFallback C.Proxy, providers []P.ProxyProvider) (*Selector, error) {
return &Selector{
GroupBase: NewGroupBase(GroupBaseOption{
Name: option.Name,
@@ -130,8 +134,8 @@ func NewSelector(option *GroupCommonOption, emptyFallback C.Proxy, providers []P
EmptyFallback: emptyFallback,
Providers: providers,
}),
selected: emptyFallback.Name(),
selected: selectorOption.DefaultSelected,
disableUDP: option.DisableUDP,
testUrl: option.URL,
}
}, nil
}
+7 -24
View File
@@ -14,12 +14,8 @@ import (
P "github.com/metacubex/mihomo/constant/provider"
)
type urlTestOption func(*URLTest)
func urlTestWithTolerance(tolerance uint16) urlTestOption {
return func(u *URLTest) {
u.tolerance = tolerance
}
type URLTestOption struct {
Tolerance uint16 `group:"tolerance,omitempty"`
}
type URLTest struct {
@@ -196,20 +192,10 @@ func (u *URLTest) URLTest(ctx context.Context, url string, expectedStatus utils.
return u.GroupBase.URLTest(ctx, u.testUrl, expectedStatus)
}
func parseURLTestOption(config map[string]any) []urlTestOption {
opts := []urlTestOption{}
// tolerance
if elm, ok := config["tolerance"]; ok {
if tolerance, ok := elm.(int); ok {
opts = append(opts, urlTestWithTolerance(uint16(tolerance)))
}
func NewURLTest(option GroupCommonOption, urlTestOption URLTestOption, emptyFallback C.Proxy, providers []P.ProxyProvider) (*URLTest, error) {
if emptyFallback == nil {
return nil, errors.New("empty fallback proxy not exist")
}
return opts
}
func NewURLTest(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.ProxyProvider, options ...urlTestOption) *URLTest {
urlTest := &URLTest{
GroupBase: NewGroupBase(GroupBaseOption{
Name: option.Name,
@@ -228,11 +214,8 @@ func NewURLTest(option *GroupCommonOption, emptyFallback C.Proxy, providers []P.
disableUDP: option.DisableUDP,
testUrl: option.URL,
expectedStatus: option.ExpectedStatus,
tolerance: urlTestOption.Tolerance,
}
for _, option := range options {
option(urlTest)
}
return urlTest
return urlTest, nil
}
+7
View File
@@ -139,6 +139,13 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error)
break
}
proxy = outbound.NewRejectWithOption(*rejectOption)
case "rematch":
rematchOption := &outbound.RematchOption{BasicOption: basicOption}
err = decoder.Decode(mapping, rematchOption)
if err != nil {
break
}
proxy, err = outbound.NewRematch(*rematchOption)
case "ssh":
sshOption := &outbound.SshOption{BasicOption: basicOption}
err = decoder.Decode(mapping, sshOption)
+17 -5
View File
@@ -69,8 +69,10 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
proxies = append(proxies, hysteria)
case "hysteria2", "hy2":
urlHysteria2, err := url.Parse(line)
case "hysteria2", "hy2", "hysteria2+realm", "hy2+realm":
realmMode := strings.HasSuffix(scheme, "+realm")
hopLine, ports := splitHysteria2Ports(line)
urlHysteria2, err := url.Parse(hopLine)
if err != nil {
continue
}
@@ -87,6 +89,9 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
} else {
hysteria2["port"] = "443"
}
if ports != "" {
hysteria2["ports"] = ports
}
hysteria2["obfs"] = query.Get("obfs")
hysteria2["obfs-password"] = query.Get("obfs-password")
hysteria2["sni"] = query.Get("sni")
@@ -94,12 +99,19 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
if alpn := query.Get("alpn"); alpn != "" {
hysteria2["alpn"] = strings.Split(alpn, ",")
}
if auth := urlHysteria2.User.String(); auth != "" {
hysteria2["password"] = auth
}
hysteria2["fingerprint"] = query.Get("pinSHA256")
hysteria2["down"] = query.Get("down")
hysteria2["up"] = query.Get("up")
if realmMode {
token, _ := url.PathUnescape(urlHysteria2.User.String())
realmID, _ := url.PathUnescape(strings.TrimPrefix(urlHysteria2.EscapedPath(), "/"))
hysteria2["realm-opts"] = buildRealmOpts("https://"+urlHysteria2.Host, token, realmID, query["stun"])
if auth := query.Get("auth"); auth != "" {
hysteria2["password"] = auth
}
} else if auth := urlHysteria2.User.String(); auth != "" {
hysteria2["password"] = auth
}
proxies = append(proxies, hysteria2)
+31
View File
@@ -40,6 +40,37 @@ func TestConvertsV2Ray_normal(t *testing.T) {
assert.NoError(t, err)
}
func TestConvertsV2Ray_hysteria2PortHopping(t *testing.T) {
uri := "hysteria2://letmein@example.com:443,5000-6000/?sni=example.com#hop"
proxies, err := ConvertsV2Ray([]byte(uri))
assert.Nil(t, err)
assert.Equal(t, "example.com", proxies[0]["server"])
assert.Equal(t, "443", proxies[0]["port"])
assert.Equal(t, "443,5000-6000", proxies[0]["ports"])
_, err = adapter.ParseProxy(proxies[0])
assert.NoError(t, err)
}
func TestConvertsV2Ray_hysteria2RealmScheme(t *testing.T) {
uri := "hysteria2+realm://tok3n@rendezvous.example.com:8443/rid42?auth=letmein&stun=stun1:3478&stun=stun2:3478&sni=example.com#realm"
proxies, err := ConvertsV2Ray([]byte(uri))
assert.Nil(t, err)
p := proxies[0]
assert.Equal(t, "hysteria2", p["type"])
assert.Equal(t, "letmein", p["password"])
assert.Equal(t, map[string]any{
"enable": true,
"server-url": "https://rendezvous.example.com:8443",
"token": "tok3n",
"realm-id": "rid42",
"stun-servers": []string{"stun1:3478", "stun2:3478"},
}, p["realm-opts"])
_, err = adapter.ParseProxy(p)
assert.NoError(t, err)
}
func TestConvertsV2RayMieru(t *testing.T) {
mierusTest := "mierus://user:pass@1.2.3.4?handshake-mode=HANDSHAKE_NO_WAIT&mtu=1400&multiplexing=MULTIPLEXING_HIGH&port=6666&port=9998-9999&port=6489&port=4896&profile=default&protocol=TCP&protocol=TCP&protocol=UDP&protocol=UDP&traffic-pattern=CCoQARoECAEQCiIYCAMQASoIMDAwMTAyMDMqCDA0MDUwNjA3"
+65 -2
View File
@@ -222,12 +222,26 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
opts["uplink-http-method"] = v
}
if v, ok := extra["sessionPlacement"].(string); ok && v != "" {
if v, ok := extra["sessionIDPlacement"].(string); ok && v != "" {
opts["session-placement"] = v
} else if v, ok := extra["sessionPlacement"].(string); ok && v != "" {
opts["session-placement"] = v
}
if v, ok := extra["sessionKey"].(string); ok && v != "" {
if v, ok := extra["sessionIDKey"].(string); ok && v != "" {
opts["session-key"] = v
} else if v, ok := extra["sessionKey"].(string); ok && v != "" {
opts["session-key"] = v
}
if v, ok := extra["sessionIDTable"].(string); ok && v != "" {
opts["session-table"] = v
}
if v, ok := extra["sessionIDLength"].(string); ok && v != "" {
opts["session-length"] = v
} else if v, ok := extra["sessionIDLength"].(float64); ok {
opts["session-length"] = strconv.FormatInt(int64(v), 10)
}
if v, ok := extra["seqPlacement"].(string); ok && v != "" {
@@ -349,3 +363,52 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
}
}
}
func buildRealmOpts(serverURL, token, realmID string, stunServers []string) map[string]any {
opts := map[string]any{"enable": true, "server-url": serverURL}
if token != "" {
opts["token"] = token
}
if realmID != "" {
opts["realm-id"] = realmID
}
if len(stunServers) > 0 {
opts["stun-servers"] = stunServers
}
return opts
}
func splitHysteria2Ports(line string) (string, string) {
i := strings.Index(line, "://")
if i < 0 {
return line, ""
}
head, rest := line[:i+3], line[i+3:]
auth, tail := rest, ""
if j := strings.IndexAny(rest, "/?#"); j >= 0 {
auth, tail = rest[:j], rest[j:]
}
userinfo := ""
if at := strings.LastIndex(auth, "@"); at >= 0 {
userinfo, auth = auth[:at+1], auth[at+1:]
}
if strings.Contains(auth, "]") {
return line, ""
}
colon := strings.LastIndex(auth, ":")
if colon < 0 {
return line, ""
}
host, ports := auth[:colon], auth[colon+1:]
if !strings.ContainsAny(ports, ",-") {
return line, ""
}
first := ports
if k := strings.IndexAny(ports, ",-"); k >= 0 {
first = ports[:k]
}
if first == "" {
return line, ""
}
return head + userinfo + host + ":" + first + tail, ports
}
+139
View File
@@ -0,0 +1,139 @@
// Copyright 2025 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package maphash
// A Hasher defines the interface between a hash-based container and its elements.
// It provides a hash function and an equivalence relation over values
// of type T, enabling those values to be inserted in hash tables
// and similar data structures.
//
// Of course, comparable types can already be used as keys of Go's
// built-in map type, but a Hasher enables non-comparable types to be
// used as keys of a suitable hash table too.
// Hashers may be useful even for comparable types, to define an
// equivalence relation that differs from the usual one (==), such as a
// field-based comparison for a pointer-to-struct type, or a
// case-insensitive comparison for strings, as in this example:
//
// // CaseInsensitive is a Hasher[string] whose
// // equivalence relation ignores letter case.
// type CaseInsensitive struct{}
//
// func (CaseInsensitive) Hash(h *Hash, s string) {
// h.WriteString(strings.ToLower(s))
// }
//
// func (CaseInsensitive) Equal(x, y string) bool {
// // (We avoid strings.EqualFold as it is not
// // consistent with ToLower for all values.)
// return strings.ToLower(x) == strings.ToLower(y)
// }
//
// A Hasher also permits values to be used with other hash-based data
// structures such as a Bloom filter.
// The [ComparableHasher] type makes it convenient to enable comparable
// types to be used in such data structures under their usual (==)
// equivalence relation.
//
// # Hash invariants
//
// If two values are equal as defined by Equal(x, y), then they must
// have the same hash as defined by the effects of Hash(h, x) on h.
//
// Hashers must be logically stateless: the behavior of the Hash and
// Equal methods depends only on the arguments.
//
// # Writing a good function
//
// When defining a hash function and equivalence relation for a data
// type, it may help to first define a canonical encoding for values
// of that type as a sequence of elements, each being a number,
// string, boolean, or pointer.
// An encoding is canonical if two values that are logically equal
// have the same encoding, even if they are represented differently.
// For example, a canonical case-insensitive encoding of a string is
// [strings.ToLower].
//
// Once you have defined the encoding, the Hasher's Hash method should
// encode a value into the [Hash] using a sequence of calls to
// [Hash.Write] for byte slices, [Hash.WriteString] for strings,
// [Hash.WriteByte] for bytes, and [WriteComparable] for elements of
// other types. The Hasher's Equal method should compute the
// encodings of two values, then compare their corresponding
// elements, returning false at the first mismatch.
//
// A Hash method may discard information so long as it remains
// consistent with the Equal method as defined above.
// For example, valid implementations of CaseInsensitive.Hash might inspect
// only the first letter of the string, or even use a constant value.
// However, the lossier the hash function, the more frequent
// the hash collisions and the slower the hash table.
//
// Some data types, such as sets, are inherently unordered: the set
// {a, b, c} is equal to the set {c, b, a}.
// In some cases it is possible to define a canonical encoding for a
// set by sorting the elements into some order.
// In other cases this may inefficient, since it may require allocating
// memory, or infeasible, as when there is no convenient order.
// Another way to hash an unordered set is to compute the hash
// for each element separately, then combine all the element hashes
// using a commutative (order-independent) operator such as + or ^.
//
// The Hash method below, for a hypothetical Set type, illustrates
// this approach:
//
// type Set[T comparable] struct{ ... }
//
// type setHasher[T comparable] struct{}
//
// func (setHasher[T]) Hash(hash *maphash.Hash, set *Set[T]) {
// var accum uint64
// for elem := range set.Elements() {
// // Initialize a hasher for the element,
// // using same seed as the outer hash.
// var sub maphash.Hash
// sub.SetSeed(hash.Seed())
//
// // Hash the element.
// maphash.WriteComparable(&sub, elem)
//
// // Mix the element's hash into the set's hash.
// accum ^= sub.Sum64()
// }
// maphash.WriteComparable(hash, accum)
// }
//
// In many languages, a data type's hash operation simply returns an
// integer value.
// However, that makes it possible for an adversary to systematically
// construct a large number of values that all have the same hash,
// degrading the asymptotic performance of hash tables in a
// denial-of-service attack known as "hash flooding".
// By contrast, computing hashes as a sequence of values emitted into
// a [Hash] with an unpredictable [Seed] that varies from one hash
// table to another mitigates this attack.
//
// In effect, the Seed chooses one of 2⁶⁴ different hash functions.
// The code example above calls SetSeed on the element's sub-Hasher
// so that it uses the same hash function as for the Set itself, and
// not a random one.
type Hasher[T any] interface {
Hash(*Hash, T)
Equal(x, y T) bool
}
// ComparableHasher is an implementation of [Hasher] whose
// Equal(x, y) method is consistent with x == y.
//
// ComparableHasher is defined only for comparable types.
// The type system will not prevent you from instantiating a type
// such as ComparableHasher[any]; nonetheless you must not pass
// non-comparable argument values to its Hash or Equal methods.
type ComparableHasher[T comparable] struct {
_ [0]func(T) // disallow comparison, and conversion between ComparableHasher[X] and ComparableHasher[Y]
}
func (ComparableHasher[T]) Hash(h *Hash, v T) { WriteComparable(h, v) }
func (ComparableHasher[T]) Equal(x, y T) bool { return x == y }
+15
View File
@@ -0,0 +1,15 @@
package sockopt
import "syscall"
func RawConnMark(rc syscall.RawConn, mark int) (err error) {
var innerErr error
err = rc.Control(func(fd uintptr) {
innerErr = markControl(fd, mark)
})
if innerErr != nil {
err = innerErr
}
return
}
+7
View File
@@ -0,0 +1,7 @@
package sockopt
import "syscall"
func markControl(fd uintptr, mark int) error {
return syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
}
+5
View File
@@ -0,0 +1,5 @@
//go:build !linux
package sockopt
func markControl(fd uintptr, mark int) error { return nil }
+5
View File
@@ -272,6 +272,11 @@ loop:
}
if res.error == nil {
if res.isPrimary {
if fallback.error == nil && fallback.Conn != nil {
go func() { // close fallback connection in new goroutine to avoid blocking
_ = fallback.Conn.Close()
}()
}
return res.Conn, nil
}
fallback = res
+3 -9
View File
@@ -7,6 +7,8 @@ import (
"net"
"net/netip"
"syscall"
"github.com/metacubex/mihomo/common/sockopt"
)
func bindMarkToDialer(mark int, dialer *net.Dialer, _ string, _ netip.Addr) {
@@ -19,19 +21,11 @@ func bindMarkToListenConfig(mark int, lc *net.ListenConfig, _, _ string) {
func bindMarkToControl(mark int) controlFn {
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
addrPort, err := netip.ParseAddrPort(address)
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
return
}
var innerErr error
err = c.Control(func(fd uintptr) {
innerErr = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
})
if innerErr != nil {
err = innerErr
}
return
return sockopt.RawConnMark(c, mark)
}
}
+1 -1
View File
@@ -36,7 +36,7 @@ func createCachefileStore(options Options) (*Pool, string, error) {
return nil, "", err
}
db, err := bbolt.Open(f.Name(), 0o666, &bbolt.Options{Timeout: time.Second})
db, err := bbolt.Open(f.Name(), 0o666, &bbolt.Options{Timeout: time.Second, NoStatistics: true})
if err != nil {
return nil, "", err
}
-4
View File
@@ -6,15 +6,12 @@ import (
"time"
"github.com/metacubex/mihomo/common/atomic"
"github.com/metacubex/mihomo/common/utils"
)
var (
keepAliveIdle = atomic.NewInt64(0)
keepAliveInterval = atomic.NewInt64(0)
disableKeepAlive = atomic.NewBool(false)
SetDisableKeepAliveCallback = utils.NewCallback[bool]()
)
func SetKeepAliveIdle(t time.Duration) {
@@ -43,7 +40,6 @@ func SetDisableKeepAlive(disable bool) {
func setDisableKeepAlive(disable bool) {
disableKeepAlive.Store(disable)
SetDisableKeepAliveCallback.Emit(disable)
}
func DisableKeepAlive() bool {
+1 -1
View File
@@ -78,7 +78,7 @@ func (c *CacheFile) Close() error {
}
func initCache() {
options := bbolt.Options{Timeout: time.Second}
options := bbolt.Options{Timeout: time.Second, NoStatistics: true}
db, err := bbolt.Open(C.Path.Cache(), fileMode, &options)
switch err {
case bbolt.ErrInvalid, bbolt.ErrChecksum, bbolt.ErrVersionMismatch:
+96 -81
View File
@@ -100,16 +100,17 @@ type GeoXUrl struct {
// Controller config
type Controller struct {
ExternalController string
ExternalControllerTLS string
ExternalControllerUnix string
ExternalControllerPipe string
ExternalUI string
ExternalUIURL string
ExternalUIName string
ExternalDohServer string
Secret string
Cors Cors
ExternalController string
ExternalControllerTLS string
ExternalControllerUnix string
ExternalControllerPipe string
ExternalControllerRoutingMark int
ExternalUI string
ExternalUIURL string
ExternalUIName string
ExternalDohServer string
Secret string
Cors Cors
}
type Cors struct {
@@ -154,7 +155,9 @@ type DNS struct {
Fallback []dns.NameServer
FallbackIPFilter []C.IpMatcher
FallbackDomainFilter []C.DomainMatcher
FallbackLazyQuery bool
Listen string
ListenRoutingMark int
EnhancedMode C.DNSMode
DefaultNameserver []dns.NameServer
CacheAlgorithm string
@@ -226,7 +229,9 @@ type RawDNS struct {
NameServer []string `yaml:"nameserver" json:"nameserver"`
Fallback []string `yaml:"fallback" json:"fallback"`
FallbackFilter RawFallbackFilter `yaml:"fallback-filter" json:"fallback-filter"`
FallbackLazyQuery bool `yaml:"fallback-lazy-query" json:"fallback-lazy-query"`
Listen string `yaml:"listen" json:"listen"`
ListenRoutingMark int `yaml:"listen-routing-mark" json:"listen-routing-mark"`
EnhancedMode C.DNSMode `yaml:"enhanced-mode" json:"enhanced-mode"`
FakeIPRange string `yaml:"fake-ip-range" json:"fake-ip-range"`
FakeIPRange6 string `yaml:"fake-ip-range6" json:"fake-ip-range6"`
@@ -271,7 +276,7 @@ type RawTun struct {
Stack C.TUNStack `yaml:"stack" json:"stack"`
DNSHijack []string `yaml:"dns-hijack" json:"dns-hijack"`
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
AutoDetectInterface bool `yaml:"auto-detect-interface"`
AutoDetectInterface bool `yaml:"auto-detect-interface" json:"auto-detect-interface"`
MTU uint32 `yaml:"mtu" json:"mtu,omitempty"`
GSO bool `yaml:"gso" json:"gso,omitempty"`
@@ -307,6 +312,7 @@ type RawTun struct {
ExcludeMACAddress []string `yaml:"exclude-mac-address" json:"exclude-mac-address,omitempty"`
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
ICMPTimeout int64 `yaml:"icmp-timeout" json:"icmp-timeout,omitempty"`
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
@@ -343,10 +349,10 @@ type RawIPTables struct {
}
type RawExperimental struct {
Fingerprints []string `yaml:"fingerprints"`
QUICGoDisableGSO bool `yaml:"quic-go-disable-gso"`
QUICGoDisableECN bool `yaml:"quic-go-disable-ecn"`
IP4PEnable bool `yaml:"dialer-ip4p-convert"`
Fingerprints []string `yaml:"fingerprints" json:"fingerprints"`
QUICGoDisableGSO bool `yaml:"quic-go-disable-gso" json:"quic-go-disable-gso"`
QUICGoDisableECN bool `yaml:"quic-go-disable-ecn" json:"quic-go-disable-ecn"`
IP4PEnable bool `yaml:"dialer-ip4p-convert" json:"dialer-ip4p-convert"`
}
type RawProfile struct {
@@ -391,51 +397,52 @@ type RawTLS struct {
}
type RawConfig struct {
Port int `yaml:"port" json:"port"`
SocksPort int `yaml:"socks-port" json:"socks-port"`
RedirPort int `yaml:"redir-port" json:"redir-port"`
TProxyPort int `yaml:"tproxy-port" json:"tproxy-port"`
MixedPort int `yaml:"mixed-port" json:"mixed-port"`
ShadowSocksConfig string `yaml:"ss-config" json:"ss-config"`
VmessConfig string `yaml:"vmess-config" json:"vmess-config"`
InboundTfo bool `yaml:"inbound-tfo" json:"inbound-tfo"`
InboundMPTCP bool `yaml:"inbound-mptcp" json:"inbound-mptcp"`
Authentication []string `yaml:"authentication" json:"authentication"`
SkipAuthPrefixes []netip.Prefix `yaml:"skip-auth-prefixes" json:"skip-auth-prefixes"`
LanAllowedIPs []netip.Prefix `yaml:"lan-allowed-ips" json:"lan-allowed-ips"`
LanDisAllowedIPs []netip.Prefix `yaml:"lan-disallowed-ips" json:"lan-disallowed-ips"`
AllowLan bool `yaml:"allow-lan" json:"allow-lan"`
BindAddress string `yaml:"bind-address" json:"bind-address"`
Mode T.TunnelMode `yaml:"mode" json:"mode"`
UnifiedDelay bool `yaml:"unified-delay" json:"unified-delay"`
LogLevel log.LogLevel `yaml:"log-level" json:"log-level"`
IPv6 bool `yaml:"ipv6" json:"ipv6"`
ExternalController string `yaml:"external-controller" json:"external-controller"`
ExternalControllerPipe string `yaml:"external-controller-pipe" json:"external-controller-pipe"`
ExternalControllerUnix string `yaml:"external-controller-unix" json:"external-controller-unix"`
ExternalControllerTLS string `yaml:"external-controller-tls" json:"external-controller-tls"`
ExternalControllerCors RawCors `yaml:"external-controller-cors" json:"external-controller-cors"`
ExternalUI string `yaml:"external-ui" json:"external-ui"`
ExternalUIURL string `yaml:"external-ui-url" json:"external-ui-url"`
ExternalUIName string `yaml:"external-ui-name" json:"external-ui-name"`
ExternalDohServer string `yaml:"external-doh-server" json:"external-doh-server"`
Secret string `yaml:"secret" json:"secret"`
Interface string `yaml:"interface-name" json:"interface-name"`
RoutingMark int `yaml:"routing-mark" json:"routing-mark"`
Tunnels []LC.Tunnel `yaml:"tunnels" json:"tunnels"`
GeoAutoUpdate bool `yaml:"geo-auto-update" json:"geo-auto-update"`
GeoUpdateInterval int `yaml:"geo-update-interval" json:"geo-update-interval"`
GeodataMode bool `yaml:"geodata-mode" json:"geodata-mode"`
GeodataLoader string `yaml:"geodata-loader" json:"geodata-loader"`
GeositeMatcher string `yaml:"geosite-matcher" json:"geosite-matcher"`
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
FindProcessMode process.FindProcessMode `yaml:"find-process-mode" json:"find-process-mode"`
GlobalClientFingerprint string `yaml:"global-client-fingerprint" json:"global-client-fingerprint"`
GlobalUA string `yaml:"global-ua" json:"global-ua"`
ETagSupport bool `yaml:"etag-support" json:"etag-support"`
KeepAliveIdle int `yaml:"keep-alive-idle" json:"keep-alive-idle"`
KeepAliveInterval int `yaml:"keep-alive-interval" json:"keep-alive-interval"`
DisableKeepAlive bool `yaml:"disable-keep-alive" json:"disable-keep-alive"`
Port int `yaml:"port" json:"port"`
SocksPort int `yaml:"socks-port" json:"socks-port"`
RedirPort int `yaml:"redir-port" json:"redir-port"`
TProxyPort int `yaml:"tproxy-port" json:"tproxy-port"`
MixedPort int `yaml:"mixed-port" json:"mixed-port"`
ShadowSocksConfig string `yaml:"ss-config" json:"ss-config"`
VmessConfig string `yaml:"vmess-config" json:"vmess-config"`
InboundTfo bool `yaml:"inbound-tfo" json:"inbound-tfo"`
InboundMPTCP bool `yaml:"inbound-mptcp" json:"inbound-mptcp"`
Authentication []string `yaml:"authentication" json:"authentication"`
SkipAuthPrefixes []netip.Prefix `yaml:"skip-auth-prefixes" json:"skip-auth-prefixes"`
LanAllowedIPs []netip.Prefix `yaml:"lan-allowed-ips" json:"lan-allowed-ips"`
LanDisAllowedIPs []netip.Prefix `yaml:"lan-disallowed-ips" json:"lan-disallowed-ips"`
AllowLan bool `yaml:"allow-lan" json:"allow-lan"`
BindAddress string `yaml:"bind-address" json:"bind-address"`
Mode T.TunnelMode `yaml:"mode" json:"mode"`
UnifiedDelay bool `yaml:"unified-delay" json:"unified-delay"`
LogLevel log.LogLevel `yaml:"log-level" json:"log-level"`
IPv6 bool `yaml:"ipv6" json:"ipv6"`
ExternalController string `yaml:"external-controller" json:"external-controller"`
ExternalControllerRoutingMark int `yaml:"external-controller-routing-mark" json:"external-controller-routing-mark"`
ExternalControllerPipe string `yaml:"external-controller-pipe" json:"external-controller-pipe"`
ExternalControllerUnix string `yaml:"external-controller-unix" json:"external-controller-unix"`
ExternalControllerTLS string `yaml:"external-controller-tls" json:"external-controller-tls"`
ExternalControllerCors RawCors `yaml:"external-controller-cors" json:"external-controller-cors"`
ExternalUI string `yaml:"external-ui" json:"external-ui"`
ExternalUIURL string `yaml:"external-ui-url" json:"external-ui-url"`
ExternalUIName string `yaml:"external-ui-name" json:"external-ui-name"`
ExternalDohServer string `yaml:"external-doh-server" json:"external-doh-server"`
Secret string `yaml:"secret" json:"secret"`
Interface string `yaml:"interface-name" json:"interface-name"`
RoutingMark int `yaml:"routing-mark" json:"routing-mark"`
Tunnels []LC.Tunnel `yaml:"tunnels" json:"tunnels"`
GeoAutoUpdate bool `yaml:"geo-auto-update" json:"geo-auto-update"`
GeoUpdateInterval int `yaml:"geo-update-interval" json:"geo-update-interval"`
GeodataMode bool `yaml:"geodata-mode" json:"geodata-mode"`
GeodataLoader string `yaml:"geodata-loader" json:"geodata-loader"`
GeositeMatcher string `yaml:"geosite-matcher" json:"geosite-matcher"`
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
FindProcessMode process.FindProcessMode `yaml:"find-process-mode" json:"find-process-mode"`
GlobalClientFingerprint string `yaml:"global-client-fingerprint" json:"global-client-fingerprint"`
GlobalUA string `yaml:"global-ua" json:"global-ua"`
ETagSupport bool `yaml:"etag-support" json:"etag-support"`
KeepAliveIdle int `yaml:"keep-alive-idle" json:"keep-alive-idle"`
KeepAliveInterval int `yaml:"keep-alive-interval" json:"keep-alive-interval"`
DisableKeepAlive bool `yaml:"disable-keep-alive" json:"disable-keep-alive"`
ProxyProvider map[string]map[string]any `yaml:"proxy-providers" json:"proxy-providers"`
RuleProvider map[string]map[string]any `yaml:"rule-providers" json:"rule-providers"`
@@ -801,15 +808,16 @@ func parseController(cfg *RawConfig) (*Controller, error) {
return nil, fmt.Errorf("external UI name is not local: %s", uiName)
}
return &Controller{
ExternalController: cfg.ExternalController,
ExternalUI: cfg.ExternalUI,
ExternalUIURL: cfg.ExternalUIURL,
ExternalUIName: cfg.ExternalUIName,
Secret: cfg.Secret,
ExternalControllerPipe: cfg.ExternalControllerPipe,
ExternalControllerUnix: cfg.ExternalControllerUnix,
ExternalControllerTLS: cfg.ExternalControllerTLS,
ExternalDohServer: cfg.ExternalDohServer,
ExternalController: cfg.ExternalController,
ExternalUI: cfg.ExternalUI,
ExternalUIURL: cfg.ExternalUIURL,
ExternalUIName: cfg.ExternalUIName,
Secret: cfg.Secret,
ExternalControllerRoutingMark: cfg.ExternalControllerRoutingMark,
ExternalControllerPipe: cfg.ExternalControllerPipe,
ExternalControllerUnix: cfg.ExternalControllerUnix,
ExternalControllerTLS: cfg.ExternalControllerTLS,
ExternalDohServer: cfg.ExternalDohServer,
Cors: Cors{
AllowOrigins: cfg.ExternalControllerCors.AllowOrigins,
AllowPrivateNetwork: cfg.ExternalControllerCors.AllowPrivateNetwork,
@@ -962,13 +970,17 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
providersMap[provider.ReservedName] = pd
if !hasGlobal {
global := outboundgroup.NewSelector(
&outboundgroup.GroupCommonOption{
global, err := outboundgroup.NewSelector(
outboundgroup.GroupCommonOption{
Name: "GLOBAL",
},
outboundgroup.SelectorOption{},
proxies["COMPATIBLE"],
[]P.ProxyProvider{pd},
)
if err != nil {
return nil, nil, fmt.Errorf("new GLOBAL proxy group error: %w", err)
}
proxies["GLOBAL"] = adapter.NewProxy(global)
}
@@ -1397,16 +1409,17 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
}
dnsCfg := &DNS{
Enable: cfg.Enable,
Listen: cfg.Listen,
PreferH3: cfg.PreferH3,
IPv6Timeout: cfg.IPv6Timeout,
IPv6: cfg.IPv6,
UseHosts: cfg.UseHosts,
UseSystemHosts: cfg.UseSystemHosts,
EnhancedMode: cfg.EnhancedMode,
CacheAlgorithm: cfg.CacheAlgorithm,
CacheMaxSize: cfg.CacheMaxSize,
Enable: cfg.Enable,
Listen: cfg.Listen,
ListenRoutingMark: cfg.ListenRoutingMark,
PreferH3: cfg.PreferH3,
IPv6Timeout: cfg.IPv6Timeout,
IPv6: cfg.IPv6,
UseHosts: cfg.UseHosts,
UseSystemHosts: cfg.UseSystemHosts,
EnhancedMode: cfg.EnhancedMode,
CacheAlgorithm: cfg.CacheAlgorithm,
CacheMaxSize: cfg.CacheMaxSize,
}
var err error
if dnsCfg.NameServer, err = parseNameServer(cfg.NameServer, cfg.RespectRules, cfg.PreferH3); err != nil {
@@ -1583,6 +1596,7 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
dnsCfg.FallbackDomainFilter = append(dnsCfg.FallbackDomainFilter, matcher)
}
}
dnsCfg.FallbackLazyQuery = cfg.FallbackLazyQuery
}
return dnsCfg, nil
@@ -1703,6 +1717,7 @@ func parseTun(rawTun RawTun, dns *DNS, general *General) error {
ExcludeMACAddress: rawTun.ExcludeMACAddress,
EndpointIndependentNat: rawTun.EndpointIndependentNat,
UDPTimeout: rawTun.UDPTimeout,
ICMPTimeout: rawTun.ICMPTimeout,
DisableICMPForwarding: rawTun.DisableICMPForwarding,
FileDescriptor: rawTun.FileDescriptor,
+3
View File
@@ -22,6 +22,7 @@ const (
Compatible
Pass
PassRule
Rematch
Dns
Relay
@@ -186,6 +187,8 @@ func (at AdapterType) String() string {
return "Pass"
case PassRule:
return "PassRule"
case Rematch:
return "Rematch"
case Dns:
return "Dns"
case Shadowsocks:
+9 -1
View File
@@ -1,6 +1,9 @@
package constant
import "net"
import (
"context"
"net"
)
type Listener interface {
RawAddress() string
@@ -27,3 +30,8 @@ type InboundConfig interface {
Name() string
Equal(config InboundConfig) bool
}
type InboundListenConfig interface {
Listen(ctx context.Context, network, address string) (net.Listener, error)
ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error)
}
+1
View File
@@ -197,6 +197,7 @@ type Metadata struct {
InPort uint16 `json:"inboundPort,string"` // `,string` is used to compatible with old version json output
InName string `json:"inboundName"`
InUser string `json:"inboundUser"`
RematchName string `json:"rematchName"`
Host string `json:"host"`
DNSMode DNSMode `json:"dnsMode"`
Uid uint32 `json:"uid"`
+5 -2
View File
@@ -31,6 +31,7 @@ const (
ProcessPathRegex
ProcessNameWildcard
ProcessPathWildcard
RematchName
RuleSet
Network
Uid
@@ -97,6 +98,8 @@ func (rt RuleType) String() string {
return "ProcessNameWildcard"
case ProcessPathWildcard:
return "ProcessPathWildcard"
case RematchName:
return "RematchName"
case MATCH:
return "Match"
case RuleSet:
@@ -150,8 +153,8 @@ type RuleWrapper interface {
}
type RuleMatchHelper struct {
ResolveIP func()
FindProcess func()
ResolveIP func()
FindProcess func()
CheckPassRule func(adapterName string) bool
}
+2 -1
View File
@@ -7,6 +7,7 @@ import (
"strings"
"time"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"
@@ -87,7 +88,7 @@ func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error)
func (c *client) ResetConnection() {}
func newClient(addr string, resolver *Resolver, netType string, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *client {
func newClient(addr string, resolver resolver.Resolver, netType string, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *client {
host, port, _ := net.SplitHostPort(addr)
c := &client{
port: port,
+2 -1
View File
@@ -14,6 +14,7 @@ import (
"time"
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"
@@ -74,7 +75,7 @@ type dnsOverHTTPS struct {
var _ dnsClient = (*dnsOverHTTPS)(nil)
// newDoH returns the DNS-over-HTTPS Upstream.
func newDoHClient(urlString string, r *Resolver, preferH3 bool, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) dnsClient {
func newDoHClient(urlString string, r resolver.Resolver, preferH3 bool, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) dnsClient {
u, _ := url.Parse(urlString)
httpVersions := DefaultHTTPVersions
if preferH3 {
+2 -1
View File
@@ -15,6 +15,7 @@ import (
"github.com/metacubex/mihomo/common/contextutils"
"github.com/metacubex/mihomo/common/pool"
"github.com/metacubex/mihomo/component/ca"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"
@@ -67,7 +68,7 @@ type dnsOverQUIC struct {
var _ dnsClient = (*dnsOverQUIC)(nil)
// newDoQ returns the DNS-over-QUIC Upstream.
func newDoQ(addr string, resolver *Resolver, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *dnsOverQUIC {
func newDoQ(addr string, resolver resolver.Resolver, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *dnsOverQUIC {
doq := &dnsOverQUIC{
addr: addr,
dialer: newDNSDialer(resolver, proxyAdapter, proxyName),
+2 -1
View File
@@ -3,6 +3,7 @@ package dns
import (
"context"
"fmt"
"github.com/metacubex/mihomo/component/resolver"
"net"
"runtime"
"sync"
@@ -159,7 +160,7 @@ func (t *dnsOverTLS) Close() error {
return nil
}
func newDoTClient(addr string, resolver *Resolver, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *dnsOverTLS {
func newDoTClient(addr string, resolver resolver.Resolver, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) *dnsOverTLS {
host, port, _ := net.SplitHostPort(addr)
c := &dnsOverTLS{
port: port,
+12 -2
View File
@@ -43,6 +43,7 @@ type Resolver struct {
fallback []dnsClient
fallbackDomainFilters []C.DomainMatcher
fallbackIPFilters []C.IpMatcher
fallbackLazyQuery bool
group singleflight.Group[*D.Msg]
cache dnsCache
policy []dnsPolicy
@@ -310,12 +311,16 @@ func (r *Resolver) ipExchange(ctx context.Context, m *D.Msg) (msg *D.Msg, err er
msgCh := r.asyncExchange(ctx, r.main, m)
if r.fallback == nil || len(r.fallback) == 0 { // directly return if no fallback servers are available
if r.fallback == nil { // directly return if no fallback servers are available
res := <-msgCh
msg, err = res.Msg, res.Error
return
}
var fallbackMsg <-chan *result
if !r.fallbackLazyQuery {
fallbackMsg = r.asyncExchange(ctx, r.fallback, m)
}
res := <-msgCh
if res.Error == nil {
if ips := msgToIP(res.Msg); len(ips) != 0 {
@@ -329,7 +334,10 @@ func (r *Resolver) ipExchange(ctx context.Context, m *D.Msg) (msg *D.Msg, err er
}
}
res = <-r.asyncExchange(ctx, r.fallback, m)
if fallbackMsg == nil {
fallbackMsg = r.asyncExchange(ctx, r.fallback, m)
}
res = <-fallbackMsg
msg, err = res.Msg, res.Error
return
}
@@ -443,6 +451,7 @@ type Config struct {
IPv6Timeout uint
FallbackIPFilter []C.IpMatcher
FallbackDomainFilter []C.DomainMatcher
FallbackLazyQuery bool
Policy []Policy
ProxyServerPolicy []Policy
CacheAlgorithm string
@@ -584,6 +593,7 @@ func NewResolver(config Config) (rs Resolvers) {
r.fallback = cacheTransform(config.Fallback)
r.fallbackIPFilters = config.FallbackIPFilter
r.fallbackDomainFilters = config.FallbackDomainFilter
r.fallbackLazyQuery = config.FallbackLazyQuery
}
return
+5 -5
View File
@@ -4,9 +4,9 @@ import (
"context"
"net"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/common/sockopt"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"
D "github.com/miekg/dns"
@@ -43,7 +43,7 @@ func (s *Server) SetService(service resolver.Service) {
s.service = service
}
func ReCreateServer(addr string, service resolver.Service) {
func ReCreateServer(addr string, lc C.InboundListenConfig, service resolver.Service) {
if addr == address && service != nil {
server.SetService(service)
return
@@ -62,7 +62,7 @@ func ReCreateServer(addr string, service resolver.Service) {
server.service = nil
address = ""
if addr == "" || service == nil {
if addr == "" || lc == nil || service == nil {
return
}
@@ -82,7 +82,7 @@ func ReCreateServer(addr string, service resolver.Service) {
server = &Server{service: service}
go func() {
p, err := inbound.ListenPacket("udp", addr)
p, err := lc.ListenPacket(context.Background(), "udp", addr)
if err != nil {
log.Errorln("Start DNS server(UDP) error: %s", err.Error())
return
@@ -98,7 +98,7 @@ func ReCreateServer(addr string, service resolver.Service) {
}()
go func() {
l, err := inbound.Listen("tcp", addr)
l, err := lc.Listen(context.Background(), "tcp", addr)
if err != nil {
log.Errorln("Start DNS server(TCP) error: %s", err.Error())
return
+1 -1
View File
@@ -113,7 +113,7 @@ func isIPRequest(q D.Question) bool {
return q.Qclass == D.ClassINET && (q.Qtype == D.TypeA || q.Qtype == D.TypeAAAA || q.Qtype == D.TypeCNAME)
}
func transform(servers []NameServer, resolver *Resolver) []dnsClient {
func transform(servers []NameServer, resolver resolver.Resolver) []dnsClient {
ret := make([]dnsClient, 0, len(servers))
for _, s := range servers {
var c dnsClient
+207 -23
View File
@@ -83,6 +83,9 @@ external-controller-unix: mihomo.sock
# !!!注意: 从Windows namedpipe访问api接口不会验证secret, 如果开启请自行保证安全问题 !!!
external-controller-pipe: \\.\pipe\mihomo
# 为 external-controller 和 external-controller-tls 的监听socket设置routing-mark(仅支持linux)
external-controller-routing-mark: 0
# tcp-concurrent: true # TCP 并发连接所有 IP, 将使用最快握手的 TCP
# 配置 WEB UI 目录,使用 http://{{external-controller}}/ui 访问
@@ -335,18 +338,20 @@ dns:
# 配置 fallback 使用条件
# fallback-filter:
# geoip: true # 配置是否使用 geoip
# geoip-code: CN # 当 nameserver 域名的 IP 查询 geoip 库为 CN 时,不使用 fallback 中的 DNS 查询结果
# 配置强制 fallback,优先于 IP 判断,具体分类自行查看 geosite 库
# geosite:
# - gfw
# 如果不匹配 ipcidr 则使用 nameservers 中的结果
# ipcidr:
# geoip: true # 配置是否使用 geoip
# geoip-code: CN # 当 nameserver 解析出域名的 IP 查询 geoip 库为 CN 时, 使用 nameserver 中的 DNS 查询结果
# ipcidr: # 当 nameserver 解析出域名的 IP 匹配 ipcidr 时,使用 fallback 中的 DNS 查询结果
# - 240.0.0.0/4
# domain:
# - 0.0.0.0/32
# - 127.0.0.1/32
# - 100.64.0.0/10
# domain: # 匹配到这些域名,会直接使用 fallback 解析,不去使用 nameserver
# - '+.google.com'
# - '+.facebook.com'
# - '+.youtube.com'
# geosite: # 匹配到这些域名,会直接使用 fallback 解析,不去使用 nameserver(已废弃,请使用 nameserver-policy)
# - gfw
# fallback-lazy-query: false # 默认值为 false ,如果为 true 会先判断来自 nameserver 的结果是否满足 fallback-filter 后再发起查询
# 配置查询域名使用的 DNS 服务器
nameserver-policy:
@@ -403,8 +408,23 @@ proxies: # socks5
# udp: true # support UDP on version 3/4/5
# reuse: false # v4/5 only
# obfs-opts:
# mode: http # or tls
# host: bing.com
# mode: http # or tls/shadow-tls
- name: "snell-shadow-tls"
type: snell
server: server
port: 44046
psk: yourpsk
# version: 4 # support 1/2/3/4/5
# udp: true # support UDP on version 3/4/5
# reuse: false # v4/5 only
# client-fingerprint: chrome
obfs-opts:
mode: shadow-tls
host: bing.com
password: "shadow_tls_password"
version: 2 # support 1/2/3
alpn: ["h2","http/1.1"]
# Shadowsocks
# cipher支持:
@@ -658,6 +678,31 @@ proxies: # socks5
# client-fingerprint: chrome # Available: "chrome","firefox","safari","ios","random", currently only support TLS transport in TCP/GRPC/WS/HTTP for VLESS/Vmess and trojan.
# skip-cert-verify: true
# servername: example.com # priority over wss host
# 如果填写 tlsmirror-opts 则开启 tlsmirror(当 tls: true 时),servername 和 alpn 使用上层配置
# tlsmirror-opts:
# primary-key: MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY= # 必填,32 字节主密钥的 base64 编码
# explicit-nonce-ciphersuites: [156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 49195, 49196, 49197, 49198, 49199, 49200, 49201, 49202, 49290, 49291, 49293, 49316, 49317, 49318, 49319, 49320, 49321, 49322, 49323, 49324, 49325, 49326, 49327, 52392, 52393, 52394, 52395, 52396, 52397, 52398] # TLS 1.2 载体使用显式 nonce 的加密套件
# defer-instance-derived-write-time: # 首次写入前的延迟
# base-nanoseconds: 0 # 固定延迟,单位纳秒
# uniform-random-multiplier-nanoseconds: 0 # 额外随机延迟上限,单位纳秒
# transport-layer-padding: # 启用传输层填充
# enabled: false
# connection-enrolment: # 启用 v2ray 兼容的连接登记确认
# primary-egress-outbound: "" # mihomo VMess outbound 保持为空;v2ray 可填写专用的控制出站 tag
# sequence-watermarking-enabled: false # 启用序列水印
# embedded-traffic-generator: # 生成额外的 HTTP 载体流量,协议由 alpn 决定
# steps:
# - host: example.com
# path: /
# method: GET
# connection-ready: true # 此步骤完成后再交付代理连接
# connection-recall-exit: true # 代理连接关闭后退出载体流量
# h2-do-not-wait-for-download-finish: false # h2 下不等待响应体读取完成
# wait-time:
# base-nanoseconds: 1000000000
# next-step:
# - weight: 1
# goto-location: 0
# network: ws
# ech-opts:
# enable: true # 必须手动开启
@@ -673,6 +718,51 @@ proxies: # socks5
# v2ray-http-upgrade: false
# v2ray-http-upgrade-fast-open: false
- name: "vmess-mkcp"
type: vmess
server: server
port: 443
uuid: uuid
alterId: 32
cipher: auto
network: mkcp
mkcp-opts:
mtu: 1350 # 最大传输单元
tti: 50 # 传输时间间隔,单位毫秒
uplink-capacity: 5 # 上行容量,单位 MB/s
downlink-capacity: 20 # 下行容量,单位 MB/s
congestion: false # 是否启用拥塞控制
write-buffer: 2097152 # 写缓冲区大小,单位字节
read-buffer: 2097152 # 读缓冲区大小,单位字节
seed: "" # 启用 AES-GCM 认证时使用的种子,留空使用默认认证
header: "" # 伪装包头,可选:none/srtp/utp/wechat-video/dtls/wireguard
- name: "vmess-mekya"
type: vmess
server: server
port: 443
uuid: uuid
alterId: 32
cipher: auto
network: mekya
tls: true
mekya-opts:
url: https://server:443/mekya
max-write-delay: 80 # 首包后的最大聚合等待时间,单位毫秒
max-request-size: 96000 # 单次 HTTP 请求的最大负载大小,单位字节
polling-interval-initial: 200 # 空轮询间隔,单位毫秒
h2-pool-size: 8 # HTTP/2 连接池大小
kcp:
mtu: 1350 # 最大传输单元
tti: 15 # 传输时间间隔,单位毫秒
uplink-capacity: 40 # 上行容量,单位 MB/s
downlink-capacity: 2000 # 下行容量,单位 MB/s
congestion: false # 是否启用拥塞控制
write-buffer: 67108864 # 写缓冲区大小,单位字节
read-buffer: 67108864 # 读缓冲区大小,单位字节
seed: "" # 启用 AES-GCM 认证时使用的种子,留空使用默认认证
header: "" # 伪装包头,可选:none/srtp/utp/wechat-video/dtls/wireguard
- name: "vmess-h2"
type: vmess
server: server
@@ -1199,8 +1289,12 @@ proxies: # socks5
# 00000000000000000000000000000000
# ...
# -----END OpenVPN Static key V1-----
# peer-info: # 透传给服务端的 peer-info 键值对,追加在内置 IV_VER/IV_PROTO/IV_CIPHERS 之后;用于服务端基于 peer-info 做准入决策
# IV_HWADDR: "52:54:00:ff:72:87"
# UV_DEVICE_ID: "laptop-001"
# ping: 10 # 默认值为 0
# ping-restart: 60 # 默认值为 0
# handshake-timeout: 30 # 单位为秒;配置后握手时不受外层连接超时影响;默认值为 0,表示仅使用外层连接超时
# mtu: 1500
udp: true
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
@@ -1224,6 +1318,23 @@ proxies: # socks5
# remote-dns-resolve: true # 强制 dns 远程解析,默认值为 false
# dns: [ 1.1.1.1, 8.8.8.8 ] # 仅在 remote-dns-resolve 为 true 时生效
# congestion-controller: bbr # 默认不开启
# handshake-timeout: 30 # 单位为秒;配置后握手时不受外层连接超时影响;默认值为 0,表示仅使用外层连接超时
# masque-h3-l4proxy
- name: "masque-h3-l4proxy"
type: masque
server: 162.159.198.1
port: 443
private-key: MHcCAQEEILI1eOtnbEIh89Fj4yNDuFR6UjayCKI3NdLl3DhetimWoAoGCCqGSM49AwEHoUQDQgAEgyXrE8v+hHsHy3ewSb3WcRjYgCrM9T9hiE0Uv6k2DZ1+4kefrDT9v1Q/8wdRigTf6t6gGNUV8W+IUMdrfUt+9g==
public-key: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIaU7MToJm9NKp8YfGxR6r+/h4mcG7SxI8tsW8OR1A5tv/zCzVbCRRh2t87/kxnP6lAy0lkr7qYwu+ox+k3dr6w==
udp: false # 目前 l4proxy 模式不支持 udp
network: h3-l4proxy
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
# dialer-proxy: "ss1"
# remote-dns-resolve: true # 强制 dns 远程解析,默认值为 false
# dns: [ tls://1.1.1.1, tls://1.0.0.1 ] # 仅在 remote-dns-resolve 为 true 时生效
# congestion-controller: bbr # 默认不开启
# handshake-timeout: 30 # 单位为秒;配置后握手时不受外层连接超时影响;默认值为 0,表示仅使用外层连接超时
# masque-h2
- name: "masque-h2"
@@ -1241,6 +1352,7 @@ proxies: # socks5
# dialer-proxy: "ss1"
# remote-dns-resolve: true # 强制 dns 远程解析,默认值为 false
# dns: [ 1.1.1.1, 8.8.8.8 ] # 仅在 remote-dns-resolve 为 true 时生效
# handshake-timeout: 30 # 单位为秒;配置后握手时不受外层连接超时影响;默认值为 0,表示仅使用外层连接超时
# tuic
- name: tuic
@@ -1390,23 +1502,17 @@ proxies: # socks5
- name: "dns-out"
type: dns
- name: "rematch"
type: rematch
target-rematch-name: "rematch1" # 如果填写则覆盖原始 metadata 中的 rematch-name(可用REMATCH-NAME规则匹配)
target-sub-rule: "sub-rule1" # 如果填写则接下来会直接用指定的 sub-rule 匹配,如果名字不存在或为空会回退到主rules
# 配置指定 interface-name 和 fwmark 的 DIRECT
- name: en1-direct
type: direct
interface-name: en1
routing-mark: 6667
proxy-groups:
# 代理链,目前 relay 可以支持 udp 的只有 vmess/vless/trojan/ss/ssr/tuic
# wireguard 目前不支持在 relay 中使用,请使用 proxy 中的 dialer-proxy 配置项
# Traffic: mihomo <-> http <-> vmess <-> ss1 <-> ss2 <-> Internet
- name: "relay"
type: relay
proxies:
- http
- vmess
- ss1
- ss2
# url-test 将按照 url 测试结果使用延迟最低节点
- name: "auto"
type: url-test
@@ -1450,6 +1556,7 @@ proxy-groups:
- ss2
- vmess1
- auto
# default-selected: ss1 # 默认选择的节点(该项为空或者设置的节点名不存在时,默认选择组中第一个节点)
- name: UseProvider
type: select
@@ -1459,7 +1566,7 @@ proxy-groups:
proxies:
- Proxy
- DIRECT
# empty-fallback: COMPATIBLE # 设置当组为空时的回退proxy
# empty-fallback: COMPATIBLE # 设置当组为空时的回退proxy(这里不支持填写代理组,只支持填写proxy名称)
# Mihomo 格式的节点或支持 *ray 的分享格式
proxy-providers:
@@ -1622,6 +1729,7 @@ listeners:
type: socks
port: 10808 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
#listen: 0.0.0.0 # 默认监听 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理
# udp: false # 默认 true
@@ -1646,6 +1754,7 @@ listeners:
type: http
port: 10809 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
# users: # 如果不填写users项,则遵从全局authentication设置,如果填写会忽略全局设置, 如想跳过该入站的验证可填写 users: []
@@ -1669,6 +1778,7 @@ listeners:
type: mixed # HTTP(S) 和 SOCKS 代理混合
port: 10810 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
# udp: false # 默认 true
@@ -1708,6 +1818,7 @@ listeners:
type: shadowsocks
port: 10813 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
password: vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg=
@@ -1724,6 +1835,13 @@ listeners:
# password: password
# handshake:
# dest: test.com:443
# res-tls:
# enable: false # 设置为true时开启
# dest: test.com:443
# password: password
# restls-script: ""
# min-record-len: 0
# proxy: ""
# kcp-tun:
# enable: false
# key: it's a secrect # pre-shared secret between client and server
@@ -1755,12 +1873,22 @@ listeners:
type: snell
port: 10815 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
psk: your-password
version: 4 # 仅支持 4/5
version: 4 # 支持 1/2/3/4/5
udp: true # UDP over TCP tunnel,默认 true
# obfs-opts:
# mode: http # 可选:http / tls
# host: bing.com
# shadow-tls:
# enable: false # 设置为true时开启
# version: 3 # 支持v1/v2/v3
# password: password # v2设置项
# users: # v3设置项
# - name: 1
# password: password
# handshake:
# dest: test.com:443
# rule: sub-rule-name1
# proxy: proxy
@@ -1768,6 +1896,7 @@ listeners:
type: vmess
port: 10814 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
users:
@@ -1776,6 +1905,35 @@ listeners:
alterId: 1
# ws-path: "/" # 如果不为空则开启 websocket 传输层
# grpc-service-name: "GunService" # 如果不为空则开启 grpc 传输层
# 如果填写 mekya-config 并设置 enable: true 则启用 v2ray 兼容的 Mekya 入站监听(不可与 mkcp/ws/grpc 同时使用)
# mekya-config:
# enable: true
# max-write-size: 10485760 # 单个响应写回的最大负载大小,单位字节
# max-write-duration-ms: 5000 # 单个响应写回的最大持续时间,单位毫秒
# max-simultaneous-write-connection: 128 # 同一会话允许同时等待写回的请求数
# packet-writing-buffer: 65536 # 写包缓冲区大小
# kcp:
# mtu: 1350 # 最大传输单元
# tti: 15 # 传输时间间隔,单位毫秒
# uplink-capacity: 40 # 上行容量,单位 MB/s
# downlink-capacity: 2000 # 下行容量,单位 MB/s
# congestion: false # 是否启用拥塞控制
# write-buffer: 67108864 # 写缓冲区大小,单位字节
# read-buffer: 67108864 # 读缓冲区大小,单位字节
# seed: "" # 启用 AES-GCM 认证时使用的种子,留空使用默认认证
# header: "" # 伪装包头,可选:none/srtp/utp/wechat-video/dtls/wireguard
# 如果填写 mkcp-config 并设置 enable: true 则启用 v2ray 兼容的 mKCP 入站监听
# mkcp-config:
# enable: true
# mtu: 1350 # 最大传输单元
# tti: 50 # 传输时间间隔,单位毫秒
# uplink-capacity: 5 # 上行容量,单位 MB/s
# downlink-capacity: 20 # 下行容量,单位 MB/s
# congestion: false # 是否启用拥塞控制
# write-buffer: 2097152 # 写缓冲区大小,单位字节
# read-buffer: 2097152 # 读缓冲区大小,单位字节
# seed: "" # 启用 AES-GCM 认证时使用的种子,留空使用默认认证
# header: "" # 伪装包头,可选:none/srtp/utp/wechat-video/dtls/wireguard
# 下面两项如果填写则开启 tls(需要同时填写)
# certificate: ./server.crt # 证书 PEM 格式,或者 证书的路径
# private-key: ./server.key # 证书对应的私钥 PEM 格式,或者私钥路径
@@ -1807,11 +1965,26 @@ listeners:
# after-bytes: 0 # 传输指定字节后开始限速
# bytes-per-sec: 0 # 基准速率(字节/秒)
# burst-bytes-per-sec: 0 # 突发速率(字节/秒),大于 bytesPerSec 时生效
# 如果填写tlsmirror-config则开启tlsmirror(注意不可与certificate和private-key同时填写)
# tlsmirror-config:
# dest: test.com:443
# primary-key: MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY= # 必填,32 字节主密钥的 base64 编码
# proxy: ""
# explicit-nonce-ciphersuites: [156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 49195, 49196, 49197, 49198, 49199, 49200, 49201, 49202, 49290, 49291, 49293, 49316, 49317, 49318, 49319, 49320, 49321, 49322, 49323, 49324, 49325, 49326, 49327, 52392, 52393, 52394, 52395, 52396, 52397, 52398] # TLS 1.2 载体使用显式 nonce 的加密套件
# defer-instance-derived-write-time: # 首次写入前的延迟
# base-nanoseconds: 0 # 固定延迟,单位纳秒
# uniform-random-multiplier-nanoseconds: 0 # 额外随机延迟上限,单位纳秒
# transport-layer-padding: # 启用传输层填充
# enabled: false
# connection-enrolment: # 启用 v2ray 兼容的连接登记确认
# primary-ingress-outbound: "" # v2ray 兼容字段,建议和对端路由中的控制出站 tag 一致
# sequence-watermarking-enabled: false # 启用序列水印
- name: tuic-in-1
type: tuic
port: 10815 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
# token: # tuicV4 填写(可以同时填写 users)
@@ -1843,6 +2016,7 @@ listeners:
type: tunnel
port: 10816 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
network: [tcp, udp]
@@ -1852,6 +2026,7 @@ listeners:
type: vless
port: 10817 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
users:
@@ -1874,6 +2049,8 @@ listeners:
# uplink-http-method: POST # Available: POST, PUT, PATCH, DELETE
# session-placement: path # Available: path, query, cookie, header
# session-key: ""
# session-table: "" # Available: "", "uuid", "ALPHABET", "Alphabet", "BASE36", "Base62", "HEX", "alphabet", "base36", "hex", "number"
# session-length: "16-32" # 起始值不可为 0,总的 id 空间必须大于 21 亿,仅当session-table不为空或uuid时生效
# seq-placement: path # Available: path, query, cookie, header
# seq-key: ""
# uplink-data-placement: body # Available: body, cookie, header
@@ -1933,6 +2110,7 @@ listeners:
type: anytls
port: 10818 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
users:
username1: password1
username2: password2
@@ -1957,6 +2135,7 @@ listeners:
type: mieru
port: 10818 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
transport: TCP # 支持 TCP 或者 UDP
users:
username1: password1
@@ -1970,6 +2149,7 @@ listeners:
type: sudoku
port: 8443 # 仅支持单端口
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
key: "<server_key>" # 如果你使用sudoku生成的ED25519密钥对,此处是密钥对中的公钥,当然,你也可以仅仅使用任意uuid充当key
aead-method: chacha20-poly1305 # 可选:chacha20-poly1305、aes-128-gcm、none(不建议;none 不提供 AEAD 保护)
padding-min: 1 # 最小填充率(0-100)
@@ -1993,6 +2173,7 @@ listeners:
type: trojan
port: 10819 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
users:
@@ -2042,6 +2223,7 @@ listeners:
type: hysteria2
port: 10820 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
users:
@@ -2094,6 +2276,7 @@ listeners:
type: hysteria2-realm
port: 10820 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
token: public # hysteria2入站和出站通过 `Authorization: Bearer <token>` 出示的 Bearer 令牌。
max-realms: 65536 # maximum total realms (0 = unlimited)
max-realms-per-ip: 4 # maximum realms per client IP (0 = unlimited)
@@ -2118,6 +2301,7 @@ listeners:
type: trusttunnel
port: 10821 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
# routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux)
# rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules
# proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错)
users:
+14 -14
View File
@@ -6,17 +6,17 @@ require (
github.com/bahlo/generic-list-go v0.2.0
github.com/coreos/go-iptables v0.8.0
github.com/dlclark/regexp2 v1.12.0
github.com/enfein/mieru/v3 v3.33.0
github.com/enfein/mieru/v3 v3.34.0
github.com/gobwas/ws v1.4.0
github.com/gofrs/uuid/v5 v5.4.0
github.com/golang/snappy v1.0.0
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d
github.com/metacubex/amneziawg-go v0.0.0-20260612143004-19b4f1cdd5ec
github.com/metacubex/bart v0.26.0
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b
github.com/metacubex/bbolt v0.0.0-20260706163408-d4ec34ad7c48
github.com/metacubex/blake3 v0.1.0
github.com/metacubex/chacha v0.1.5
github.com/metacubex/chi v0.1.0
github.com/metacubex/chi v0.1.1
github.com/metacubex/connect-ip-go v0.0.0-20260412152424-e1625567920a
github.com/metacubex/cpu v0.1.1
github.com/metacubex/edwards25519 v1.2.0
@@ -26,25 +26,25 @@ require (
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604
github.com/metacubex/mhurl v0.1.0
github.com/metacubex/mlkem v0.1.0
github.com/metacubex/quic-go v0.59.1-0.20260520020949-fcd18c7b6ace
github.com/metacubex/quic-go v0.59.1-0.20260606115121-0662b57ad5bf
github.com/metacubex/randv2 v0.2.0
github.com/metacubex/restls-client-go v0.1.7
github.com/metacubex/restls-client-go v0.1.8
github.com/metacubex/sevenzip v1.6.4
github.com/metacubex/sing v0.5.7
github.com/metacubex/sing-mux v0.3.9
github.com/metacubex/sing-mux v0.3.10
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3
github.com/metacubex/sing-shadowsocks v0.2.12
github.com/metacubex/sing-shadowsocks2 v0.2.7
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc
github.com/metacubex/sing-tun v0.4.20
github.com/metacubex/sing-tun v0.4.21
github.com/metacubex/sing-vmess v0.2.5
github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141
github.com/metacubex/ssh v0.1.0
github.com/metacubex/tailscale v0.0.0-20260520011538-f23132fac4b7
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443
github.com/metacubex/tls v0.1.6
github.com/metacubex/utls v1.8.4
github.com/metacubex/tailscale v0.0.0-20260623094802-1ab893d4162c
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c
github.com/metacubex/tls v0.1.7
github.com/metacubex/utls v1.8.7
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f
github.com/mroth/weightedrand/v2 v2.1.0
github.com/openacid/low v0.1.21
@@ -78,7 +78,7 @@ require (
require (
github.com/RyuaNerin/go-krypto v1.3.0 // indirect
github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344 // indirect
github.com/ajg/form v1.5.1 // indirect
github.com/ajg/form v1.7.1 // indirect
github.com/akutz/memconn v0.1.0 // indirect
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa // indirect
github.com/andybalholm/brotli v1.1.1 // indirect
@@ -117,7 +117,7 @@ require (
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df // indirect
github.com/metacubex/nftables v0.0.0-20260426003805-208c2c1ba2cb // indirect
github.com/metacubex/qpack v0.6.0 // indirect
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260521124654-e1bf77ef79af // indirect
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260623093519-06ea214022e4 // indirect
github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49 // indirect
github.com/mitchellh/go-ps v1.0.0 // indirect
github.com/oasisprotocol/deoxysii v0.0.0-20220228165953-2091330c22b7 // indirect
+28 -28
View File
@@ -3,8 +3,8 @@ github.com/RyuaNerin/go-krypto v1.3.0/go.mod h1:9R9TU936laAIqAmjcHo/LsaXYOZlymud
github.com/RyuaNerin/testingutil v0.1.0 h1:IYT6JL57RV3U2ml3dLHZsVtPOP6yNK7WUVdzzlpNrss=
github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344 h1:cDVUiFo+npB0ZASqnw4q90ylaVAbnYyx0JYqK4YcGok=
github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344/go.mod h1:9pIqrY6SXNL8vjRQE5Hd/OL5GyK/9MrGUWs87z/eFfk=
github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=
github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=
github.com/ajg/form v1.7.1 h1:OsnBDzTkrWdrxvEnO68I72ZVGJGNaMwPhoAm0V+llgc=
github.com/ajg/form v1.7.1/go.mod h1:HL757PzLyNkj5AIfptT6L+iGNeXTlnrr/oDePGc/y7Q=
github.com/akutz/memconn v0.1.0 h1:NawI0TORU4hcOMsMr11g7vwlCdkYeLKXBcxWu2W/P8A=
github.com/akutz/memconn v0.1.0/go.mod h1:Jo8rI7m0NieZyLI5e2CDlRdRqRRB4S7Xp77ukDjH+Fw=
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI=
@@ -31,8 +31,8 @@ github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz
github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dunglas/httpsfv v1.0.2 h1:iERDp/YAfnojSDJ7PW3dj1AReJz4MrwbECSSE59JWL0=
github.com/dunglas/httpsfv v1.0.2/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg=
github.com/enfein/mieru/v3 v3.33.0 h1:hv2jK8nqYHwpSG86U2rpZR2I8Aff1/J3ifRmd9NBbFc=
github.com/enfein/mieru/v3 v3.33.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
github.com/enfein/mieru/v3 v3.34.0 h1:8yeaPORvfSQtdfEH+Arw9wttDyFxkik8My4zFdGu79Y=
github.com/enfein/mieru/v3 v3.34.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 h1:kXYqH/sL8dS/FdoFjr12ePjnLPorPo2FsnrHNuXSDyo=
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358/go.mod h1:hkIFzoiIPZYxdFOOLyDho59b7SrDfo+w3h+yWdlg45I=
github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 h1:8j2RH289RJplhA6WfdaPqzg1MjH2K8wX5e0uhAxrw2g=
@@ -99,20 +99,20 @@ 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/amneziawg-go v0.0.0-20260612143004-19b4f1cdd5ec h1:nRHevF7PmvDKjkYPjQCU7NUfVrr3Sry4QOPxpqoyo8U=
github.com/metacubex/amneziawg-go v0.0.0-20260612143004-19b4f1cdd5ec/go.mod h1:MsM/5czONyXMJ3PRr5DbQ4O/BxzAnJWOIcJdLzW6qHY=
github.com/metacubex/ascon v0.1.0 h1:6ZWxmXYszT1XXtwkf6nxfFhc/OTtQ9R3Vyj1jN32lGM=
github.com/metacubex/ascon v0.1.0/go.mod h1:eV5oim4cVPPdEL8/EYaTZ0iIKARH9pnhAK/fcT5Kacc=
github.com/metacubex/bart v0.26.0 h1:d/bBTvVatfVWGfQbiDpYKI1bXUJgjaabB2KpK1Tnk6w=
github.com/metacubex/bart v0.26.0/go.mod h1:DCcyfP4MC+Zy7sLK7XeGuMw+P5K9mIRsYOBgiE8icsI=
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b h1:j7dadXD8I2KTmMt8jg1JcaP1ANL3JEObJPdANKcSYPY=
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b/go.mod h1:+WmP0VJZDkDszvpa83HzfUp6QzARl/IKkMorH4+nODw=
github.com/metacubex/bbolt v0.0.0-20260706163408-d4ec34ad7c48 h1:D+AoQ7g/ZeZAHAapelrZB0xUNRcDGuoNLcGmHCnC9Ss=
github.com/metacubex/bbolt v0.0.0-20260706163408-d4ec34ad7c48/go.mod h1:yOfzykxfYIEVOtEys6KOKwxy75M2I/KtOQ+p3Kzc8/k=
github.com/metacubex/blake3 v0.1.0 h1:KGnjh/56REO7U+cgZA8dnBhxdP7jByrG7hTP+bu6cqY=
github.com/metacubex/blake3 v0.1.0/go.mod h1:CCkLdzFrqf7xmxCdhQFvJsRRV2mwOLDoSPg6vUTB9Uk=
github.com/metacubex/chacha v0.1.5 h1:fKWMb/5c7ZrY8Uoqi79PPFxl+qwR7X/q0OrsAubyX2M=
github.com/metacubex/chacha v0.1.5/go.mod h1:Djn9bPZxLTXbJFSeyo0/qzEzQI+gUSSzttuzZM75GH8=
github.com/metacubex/chi v0.1.0 h1:rjNDyDj50nRpicG43CNkIw4ssiCbmDL8d7wJXKlUCsg=
github.com/metacubex/chi v0.1.0/go.mod h1:zM5u5oMQt8b2DjvDHvzadKrP6B2ztmasL1YHRMbVV+g=
github.com/metacubex/chi v0.1.1 h1:GajmCIXSIPAZNxqTTYpkCrkY9suBz9wjIdgPcoQ5K1A=
github.com/metacubex/chi v0.1.1/go.mod h1:/CvDXe8jZD/ecU8Y7fmS5XKLRR44UDmC6/IBkRIb6Z4=
github.com/metacubex/connect-ip-go v0.0.0-20260412152424-e1625567920a h1:Ph5UfTWDsGruZ+v95Df1ycTflQFmpZBFg2LUvj2kx/M=
github.com/metacubex/connect-ip-go v0.0.0-20260412152424-e1625567920a/go.mod h1:xYC8Ik7/rN6no+vTRuWMEziGwm3brA0wNM/zZP9qhOQ=
github.com/metacubex/cpu v0.1.1 h1:rRV5HGmeuGzjiKI3hYbL0dCd0qGwM7VUtk4ICXD06mI=
@@ -145,18 +145,18 @@ github.com/metacubex/protobuf-go v0.0.0-20260306035419-7ceee0674686 h1:PIXmYT2an
github.com/metacubex/protobuf-go v0.0.0-20260306035419-7ceee0674686/go.mod h1:eQV7juxFZIdRgjMxtVqP+6BssKoTZQ1RM0fc58BsCZY=
github.com/metacubex/qpack v0.6.0 h1:YqClGIMOpiRYLjV1qOs483Od08MdPgRnHjt90FuaAKw=
github.com/metacubex/qpack v0.6.0/go.mod h1:lKGSi7Xk94IMvHGOmxS9eIei3bvIqpOAImEBsaOwTkA=
github.com/metacubex/quic-go v0.59.1-0.20260520020949-fcd18c7b6ace h1:KXacx7dp1GYVMgxezwXRt5BMsEbvAYuA6rPFUmdAvcQ=
github.com/metacubex/quic-go v0.59.1-0.20260520020949-fcd18c7b6ace/go.mod h1:2YEQEvFrZ5V76oynMBDTlN+4fdnSHCa2uNJxv3cm1HU=
github.com/metacubex/quic-go v0.59.1-0.20260606115121-0662b57ad5bf h1:WvIp5pF+LLZwg0I6555eMVlKFrLrqQqPKob6XW6niyo=
github.com/metacubex/quic-go v0.59.1-0.20260606115121-0662b57ad5bf/go.mod h1:2YEQEvFrZ5V76oynMBDTlN+4fdnSHCa2uNJxv3cm1HU=
github.com/metacubex/randv2 v0.2.0 h1:uP38uBvV2SxYfLj53kuvAjbND4RUDfFJjwr4UigMiLs=
github.com/metacubex/randv2 v0.2.0/go.mod h1:kFi2SzrQ5WuneuoLLCMkABtiBu6VRrMrWFqSPyj2cxY=
github.com/metacubex/restls-client-go v0.1.7 h1:eCwiXCTQb5WJu9IlgYvDBA1OgrINv58dEe7hcN5H15k=
github.com/metacubex/restls-client-go v0.1.7/go.mod h1:BN/U52vPw7j8VTSh2vleD/MnmVKCov84mS5VcjVHH4g=
github.com/metacubex/restls-client-go v0.1.8 h1:0kQ699TWnbK3bWLhCPE0oIiBJLN+errOLQ9Z3/P1lbA=
github.com/metacubex/restls-client-go v0.1.8/go.mod h1:BN/U52vPw7j8VTSh2vleD/MnmVKCov84mS5VcjVHH4g=
github.com/metacubex/sevenzip v1.6.4 h1:OIL+DeOeSAbKNsjqxcYUMiarRmX6Kaxakb0GT7E9Oik=
github.com/metacubex/sevenzip v1.6.4/go.mod h1:FP3X9bzFKj9wPxifGN9B3w2fIEicMjzKYIGIhnu+1pw=
github.com/metacubex/sing v0.5.7 h1:8OC+fhKFSv/l9ehEhJRaZZAOuthfZo68SteBVLe8QqM=
github.com/metacubex/sing v0.5.7/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w=
github.com/metacubex/sing-mux v0.3.9 h1:/aoBD2+sK2qsXDlNDe3hkR0GZuFDtwIZhOeGUx9W0Yk=
github.com/metacubex/sing-mux v0.3.9/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
github.com/metacubex/sing-mux v0.3.10 h1:r5CuZ/KuwFsEcRRwpLvzLncW4fDzNfmSEcBEWcy/+94=
github.com/metacubex/sing-mux v0.3.10/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3 h1:PnMby5+kZXTl/CFDHfxMbMTaSRD+uMKMsrDYVQyAmX8=
github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3/go.mod h1:6ayFGfzzBE85csgQkM3gf4neFq6s0losHlPRSxY+nuk=
github.com/metacubex/sing-shadowsocks v0.2.12 h1:Wqzo8bYXrK5aWqxu/TjlTnYZzAKtKsaFQBdr6IHFaBE=
@@ -165,8 +165,8 @@ github.com/metacubex/sing-shadowsocks2 v0.2.7 h1:hSuuc0YpsfiqYqt1o+fP4m34BQz4e6w
github.com/metacubex/sing-shadowsocks2 v0.2.7/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE=
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc h1:8wLoFfYQ88iGPL+krQ5tJsI8IAmkFjKpQL2q+y3pvss=
github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc/go.mod h1:mbfboaXauKJNIHJYxQRa+NJs4JU9NZfkA+I33dS2+9E=
github.com/metacubex/sing-tun v0.4.20 h1:xdupzizRoZKyDzP0l68WAx5Sk4ooiuT1GiWsiJyOGPw=
github.com/metacubex/sing-tun v0.4.20/go.mod h1:g4I/JNplDBhXLF+aQWgFbhNeJPSXQOWS9HvLeNvkgeA=
github.com/metacubex/sing-tun v0.4.21 h1:MjbPYytM240VH70lO182v2Sg/JthMmx6R6z6E2fCR2I=
github.com/metacubex/sing-tun v0.4.21/go.mod h1:g4I/JNplDBhXLF+aQWgFbhNeJPSXQOWS9HvLeNvkgeA=
github.com/metacubex/sing-vmess v0.2.5 h1:m9Zt5I27lB9fmLMZfism9sH2LcnAfShZfwSkf6/KJoE=
github.com/metacubex/sing-vmess v0.2.5/go.mod h1:AwtlzUgf8COe9tRYAKqWZ+leDH7p5U98a0ZUpYehl8Q=
github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c h1:tH9FuQW357zp2xAGzkoZTGpNGMVmEFZov0iV5M2S5ew=
@@ -175,16 +175,16 @@ github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141 h1:DK2l6m2Fc85H2Bhi
github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141/go.mod h1:/yI4OiGOSn0SURhZdJF3CbtPg3nwK700bG8TZLMBvAg=
github.com/metacubex/ssh v0.1.0 h1:iGfr99qk/eMHzUnQ/0bTxXT8+8SWqLSHBWDHoAhngzw=
github.com/metacubex/ssh v0.1.0/go.mod h1:NUtl0d+/f2cG9ECEpMM8iCVOpmggQlC13oLeDUONDlU=
github.com/metacubex/tailscale v0.0.0-20260520011538-f23132fac4b7 h1:LoJR4NMyNKHeEJoeGDtcsao7sV0NRkzMeV5H/0J0MIE=
github.com/metacubex/tailscale v0.0.0-20260520011538-f23132fac4b7/go.mod h1:MAo3HhE7968rIwmDvYTYE8xCsV4x+hLnkChdXeP3X4c=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260521124654-e1bf77ef79af h1:c60IbBMUq2h1M2m7+grMJJmBmrObxL8SwvNtm6Ozbwk=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260521124654-e1bf77ef79af/go.mod h1:i3zLKytWkOnyT1i9OmiLevWvrN5J5HE1+yjE7UYNfcQ=
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443 h1:H6TnfM12tOoTizYE/qBHH3nEuibIelmHI+BVSxVJr8o=
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443/go.mod h1:l9oLnLoEXyGZ5RVLsh7QCC5XsouTUyKk4F2nLm2DHLw=
github.com/metacubex/tls v0.1.6 h1:t2ubLneYa4ceyIC++54a57BLqZFA/QYUrhdjLk2GPwo=
github.com/metacubex/tls v0.1.6/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
github.com/metacubex/utls v1.8.4 h1:HmL9nUApDdWSkgUyodfwF6hSjtiwCGGdyhaSpEejKpg=
github.com/metacubex/utls v1.8.4/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
github.com/metacubex/tailscale v0.0.0-20260623094802-1ab893d4162c h1:ACfYexFGGaObb80aq0IiG3oRjv4I1lCxf104cUsI0W8=
github.com/metacubex/tailscale v0.0.0-20260623094802-1ab893d4162c/go.mod h1:rDpd7cy7itpPi3Kgb90fUgSnKwMXHYBk0R5DuNRiNNA=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260623093519-06ea214022e4 h1:ui12xOUPsCAYwzI7+7Hw2mVhrAbWDGNQZcrBiELhGk0=
github.com/metacubex/tailscale-wireguard-go v0.0.0-20260623093519-06ea214022e4/go.mod h1:W00EeoPdd2jbV3+ZUa0m2b7FdKx5B1LFsXvEpy7cToQ=
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c h1:+2C1UshSLzaogLY/IDz1XhOLxjhs3rkhVHB4eCN9Zto=
github.com/metacubex/tfo-go v0.0.0-20260623020846-376a77860b8c/go.mod h1:l9oLnLoEXyGZ5RVLsh7QCC5XsouTUyKk4F2nLm2DHLw=
github.com/metacubex/tls v0.1.7 h1:7YW+7z2xGH1bozSg04q3gKNd7GBSiTSXIrQY2SMnfoE=
github.com/metacubex/tls v0.1.7/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM=
github.com/metacubex/utls v1.8.7 h1:Cp+yWkNTFkSihETgGWq34hlVFds5HpYWVOR1xovUVTs=
github.com/metacubex/utls v1.8.7/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f h1:FGBPRb1zUabhPhDrlKEjQ9lgIwQ6cHL4x8M9lrERhbk=
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f/go.mod h1:oPGcV994OGJedmmxrcK9+ni7jUEMGhR+uVQAdaduIP4=
github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49 h1:lhlqpYHopuTLx9xQt22kSA9HtnyTDmk5XjjQVCGHe2E=
+5 -2
View File
@@ -242,7 +242,7 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
resolver.DefaultService = nil
resolver.ProxyServerHostResolver = nil
resolver.DirectHostResolver = nil
dns.ReCreateServer("", nil)
dns.ReCreateServer("", nil, nil)
return
}
@@ -254,6 +254,7 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
IPv6Timeout: c.IPv6Timeout,
FallbackIPFilter: c.FallbackIPFilter,
FallbackDomainFilter: c.FallbackDomainFilter,
FallbackLazyQuery: c.FallbackLazyQuery,
Default: c.DefaultNameserver,
Policy: c.NameServerPolicy,
ProxyServer: c.ProxyServerNameserver,
@@ -297,7 +298,9 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
resolver.DirectHostResolver = r.Resolver
}
dns.ReCreateServer(c.Listen, s)
lc := inbound.NewListenConfig()
lc.SetRouteMark(c.ListenRoutingMark)
dns.ReCreateServer(c.Listen, lc, s)
}
func updateHosts(tree *trie.DomainTrie[resolver.HostValue]) {
+13
View File
@@ -21,6 +21,12 @@ func WithExternalController(externalController string) Option {
}
}
func WithExternalControllerTLS(externalControllerTLS string) Option {
return func(cfg *config.Config) {
cfg.Controller.ExternalControllerTLS = externalControllerTLS
}
}
func WithExternalControllerUnix(externalControllerUnix string) Option {
return func(cfg *config.Config) {
cfg.Controller.ExternalControllerUnix = externalControllerUnix
@@ -33,6 +39,12 @@ func WithExternalControllerPipe(externalControllerPipe string) Option {
}
}
func WithExternalControllerRoutingMark(externalControllerRoutingMark int) Option {
return func(cfg *config.Config) {
cfg.Controller.ExternalControllerRoutingMark = externalControllerRoutingMark
}
}
func WithSecret(secret string) Option {
return func(cfg *config.Config) {
cfg.Controller.Secret = secret
@@ -54,6 +66,7 @@ func applyRoute(cfg *config.Config) {
TLSAddr: cfg.Controller.ExternalControllerTLS,
UnixAddr: cfg.Controller.ExternalControllerUnix,
PipeAddr: cfg.Controller.ExternalControllerPipe,
RoutingMark: cfg.Controller.ExternalControllerRoutingMark,
Secret: cfg.Controller.Secret,
Certificate: cfg.TLS.Certificate,
PrivateKey: cfg.TLS.PrivateKey,
+4
View File
@@ -97,6 +97,7 @@ type tunSchema struct {
ExcludeMACAddress *[]string `yaml:"exclude-mac-address" json:"exclude-mac-address,omitempty"`
EndpointIndependentNat *bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
UDPTimeout *int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
ICMPTimeout *int64 `yaml:"icmp-timeout" json:"icmp-timeout,omitempty"`
FileDescriptor *int `yaml:"file-descriptor" json:"file-descriptor"`
Inet4RouteAddress *[]netip.Prefix `yaml:"inet4-route-address" json:"inet4-route-address,omitempty"`
@@ -257,6 +258,9 @@ func pointerOrDefaultTun(p *tunSchema, def LC.Tun) LC.Tun {
if p.UDPTimeout != nil {
def.UDPTimeout = *p.UDPTimeout
}
if p.ICMPTimeout != nil {
def.ICMPTimeout = *p.ICMPTimeout
}
if p.FileDescriptor != nil {
def.FileDescriptor = *p.FileDescriptor
}
+2 -20
View File
@@ -46,7 +46,7 @@ func parseProxyName(next http.Handler) http.Handler {
func findProxyByName(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name := r.Context().Value(CtxKeyProxyName).(string)
proxies := proxiesWithProviders()
proxies := tunnel.Proxies()
proxy, exist := proxies[name]
if !exist {
render.Status(r, http.StatusNotFound)
@@ -60,7 +60,7 @@ func findProxyByName(next http.Handler) http.Handler {
}
func getProxies(w http.ResponseWriter, r *http.Request) {
proxies := proxiesWithProviders()
proxies := tunnel.Proxies()
render.JSON(w, r, render.M{
"proxies": proxies,
})
@@ -158,21 +158,3 @@ func unfixedProxy(w http.ResponseWriter, r *http.Request) {
render.Status(r, http.StatusBadRequest)
render.JSON(w, r, ErrBadRequest)
}
// proxiesWithProviders merges all proxies from tunnel
//
// Deprecated: This function is poorly implemented and should not be called by any new code.
// It is left here only to ensure the compatibility of the output of the existing RESTful API.
func proxiesWithProviders() map[string]C.Proxy {
allProxies := make(map[string]C.Proxy)
for name, proxy := range tunnel.Proxies() {
allProxies[name] = proxy
}
for _, p := range tunnel.Providers() {
for _, proxy := range p.Proxies() {
name := proxy.Name()
allProxies[name] = proxy
}
}
return allProxies
}
+11 -3
View File
@@ -2,6 +2,7 @@ package route
import (
"bytes"
"context"
"crypto/subtle"
"encoding/json"
"net"
@@ -61,6 +62,7 @@ type Config struct {
TLSAddr string
UnixAddr string
PipeAddr string
RoutingMark int
Secret string
Certificate string
PrivateKey string
@@ -166,7 +168,9 @@ func start(cfg *Config) {
// handle addr
if len(cfg.Addr) > 0 {
l, err := inbound.Listen("tcp", cfg.Addr)
lc := inbound.NewListenConfig()
lc.SetRouteMark(cfg.RoutingMark)
l, err := lc.Listen(context.Background(), "tcp", cfg.Addr)
if err != nil {
log.Errorln("External controller listen error: %s", err)
return
@@ -198,7 +202,9 @@ func startTLS(cfg *Config) {
return
}
l, err := inbound.Listen("tcp", cfg.TLSAddr)
lc := inbound.NewListenConfig()
lc.SetRouteMark(cfg.RoutingMark)
l, err := lc.Listen(context.Background(), "tcp", cfg.TLSAddr)
if err != nil {
log.Errorln("External controller tls listen error: %s", err)
return
@@ -270,7 +276,9 @@ func startUnix(cfg *Config) {
// should be used to delete the socket file prior to calling bind with the same path.
_ = syscall.Unlink(addr)
l, err := inbound.Listen("unix", addr)
lc := inbound.NewListenConfig()
lc.SetRouteMark(0) // don't set route mark for unix socket
l, err := lc.Listen(context.Background(), "unix", addr)
if err != nil {
log.Errorln("External controller unix listen error: %s", err)
return
+2 -2
View File
@@ -35,7 +35,7 @@ type Listener struct {
padding atomic.Pointer[padding.PaddingFactory]
}
func New(config LC.AnyTLSServer, tunnel C.Tunnel, additions ...inbound.Addition) (sl *Listener, err error) {
func New(config LC.AnyTLSServer, lc C.InboundListenConfig, tunnel C.Tunnel, additions ...inbound.Addition) (sl *Listener, err error) {
if len(additions) == 0 {
additions = []inbound.Addition{
inbound.WithInName("DEFAULT-ANYTLS"),
@@ -106,7 +106,7 @@ func New(config LC.AnyTLSServer, tunnel C.Tunnel, additions ...inbound.Addition)
addr := addr
//TCP
l, err := inbound.Listen("tcp", addr)
l, err := lc.Listen(context.Background(), "tcp", addr)
if err != nil {
return nil, err
}
+32
View File
@@ -0,0 +1,32 @@
package config
import "github.com/metacubex/mihomo/transport/mekya"
type MekyaConfig struct {
Enable bool `yaml:"enable" json:"enable,omitempty"`
URL string `yaml:"url" json:"url,omitempty"`
H2PoolSize int `yaml:"h2-pool-size" json:"h2-pool-size,omitempty"`
MaxWriteDelay int `yaml:"max-write-delay" json:"max-write-delay,omitempty"`
MaxRequestSize int `yaml:"max-request-size" json:"max-request-size,omitempty"`
PollingIntervalInitial int `yaml:"polling-interval-initial" json:"polling-interval-initial,omitempty"`
MaxWriteSize int `yaml:"max-write-size" json:"max-write-size,omitempty"`
MaxWriteDurationMs int `yaml:"max-write-duration-ms" json:"max-write-duration-ms,omitempty"`
MaxSimultaneousWriteConnection int `yaml:"max-simultaneous-write-connection" json:"max-simultaneous-write-connection,omitempty"`
PacketWritingBuffer int `yaml:"packet-writing-buffer" json:"packet-writing-buffer,omitempty"`
KCP MKCPConfig `yaml:"kcp" json:"kcp,omitempty"`
}
func (c MekyaConfig) Build() mekya.Config {
return mekya.Config{
KCP: c.KCP.Build(),
URL: c.URL,
H2PoolSize: c.H2PoolSize,
MaxWriteDelay: c.MaxWriteDelay,
MaxRequestSize: c.MaxRequestSize,
PollingIntervalInitial: c.PollingIntervalInitial,
MaxWriteSize: c.MaxWriteSize,
MaxWriteDurationMs: c.MaxWriteDurationMs,
MaxSimultaneousWriteConnection: c.MaxSimultaneousWriteConnection,
PacketWritingBuffer: c.PacketWritingBuffer,
}
}
+30
View File
@@ -0,0 +1,30 @@
package config
import "github.com/metacubex/mihomo/transport/mkcp"
type MKCPConfig struct {
Enable bool `yaml:"enable" json:"enable,omitempty"`
MTU uint32 `yaml:"mtu" json:"mtu,omitempty"`
TTI uint32 `yaml:"tti" json:"tti,omitempty"`
UplinkCapacity uint32 `yaml:"uplink-capacity" json:"uplink-capacity,omitempty"`
DownlinkCapacity uint32 `yaml:"downlink-capacity" json:"downlink-capacity,omitempty"`
Congestion bool `yaml:"congestion" json:"congestion,omitempty"`
WriteBuffer uint32 `yaml:"write-buffer" json:"write-buffer,omitempty"`
ReadBuffer uint32 `yaml:"read-buffer" json:"read-buffer,omitempty"`
Seed string `yaml:"seed" json:"seed,omitempty"`
Header string `yaml:"header" json:"header,omitempty"`
}
func (c MKCPConfig) Build() mkcp.Config {
return mkcp.Config{
MTU: c.MTU,
TTI: c.TTI,
UplinkCapacity: c.UplinkCapacity,
DownlinkCapacity: c.DownlinkCapacity,
Congestion: c.Congestion,
WriteBuffer: c.WriteBuffer,
ReadBuffer: c.ReadBuffer,
Seed: c.Seed,
Header: c.Header,
}
}
+17
View File
@@ -0,0 +1,17 @@
package config
import "encoding/json"
type ResTLS struct {
Enable bool
Dest string
Password string
RestlsScript string
MinRecordLen int
Proxy string
}
func (r ResTLS) String() string {
b, _ := json.Marshal(r)
return string(b)
}
+1
View File
@@ -14,6 +14,7 @@ type ShadowsocksServer struct {
Udp bool
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
ResTLS ResTLS `yaml:"res-tls" json:"res-tls,omitempty"`
KcpTun KcpTun `yaml:"kcp-tun" json:"kcp-tun,omitempty"`
SimpleObfs SimpleObfs `yaml:"simple-obfs" json:"simple-obfs,omitempty"`
}
+18
View File
@@ -0,0 +1,18 @@
package config
import "encoding/json"
type SnellServer struct {
Listen string
Psk string
Version int
UDP bool
ObfsMode string
ObfsHost string
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
}
func (c SnellServer) String() string {
b, _ := json.Marshal(c)
return string(b)
}
+4
View File
@@ -51,6 +51,7 @@ type Tun struct {
ExcludeMACAddress []string `yaml:"exclude-mac-address" json:"exclude-mac-address,omitempty"`
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint-independent-nat,omitempty"`
UDPTimeout int64 `yaml:"udp-timeout" json:"udp-timeout,omitempty"`
ICMPTimeout int64 `yaml:"icmp-timeout" json:"icmp-timeout,omitempty"`
DisableICMPForwarding bool `yaml:"disable-icmp-forwarding" json:"disable-icmp-forwarding,omitempty"`
FileDescriptor int `yaml:"file-descriptor" json:"file-descriptor"`
@@ -201,6 +202,9 @@ func (t *Tun) Equal(other Tun) bool {
if t.UDPTimeout != other.UDPTimeout {
return false
}
if t.ICMPTimeout != other.ICMPTimeout {
return false
}
if t.DisableICMPForwarding != other.DisableICMPForwarding {
return false
}
+4 -4
View File
@@ -9,10 +9,10 @@ import (
)
type tunnel struct {
Network []string `yaml:"network"`
Address string `yaml:"address"`
Target string `yaml:"target"`
Proxy string `yaml:"proxy"`
Network []string `yaml:"network" json:"network"`
Address string `yaml:"address" json:"address"`
Target string `yaml:"target" json:"target"`
Proxy string `yaml:"proxy" json:"proxy"`
}
type Tunnel tunnel
+53 -1
View File
@@ -5,6 +5,7 @@ import (
"github.com/metacubex/mihomo/listener/reality"
"github.com/metacubex/mihomo/listener/sing"
"github.com/metacubex/mihomo/transport/tlsmirror"
)
type VmessUser struct {
@@ -25,7 +26,58 @@ type VmessServer struct {
ClientAuthCert string
EchKey string
RealityConfig reality.Config
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
TLSMirrorConfig TLSMirrorConfig `yaml:"tlsmirror-config" json:"tlsmirror-config,omitempty"`
MekyaConfig MekyaConfig `yaml:"mekya-config" json:"mekya-config,omitempty"`
MKCPConfig MKCPConfig `yaml:"mkcp-config" json:"mkcp-config,omitempty"`
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
}
type TLSMirrorConfig struct {
PrimaryKey string `yaml:"primary-key" json:"primary-key,omitempty"`
Dest string `yaml:"dest" json:"dest,omitempty"`
Proxy string `yaml:"proxy" json:"proxy,omitempty"`
ExplicitNonceCipherSuites []uint16 `yaml:"explicit-nonce-ciphersuites" json:"explicit-nonce-ciphersuites,omitempty"`
DeferInstanceDerivedWriteTime TLSMirrorTimeSpec `yaml:"defer-instance-derived-write-time" json:"defer-instance-derived-write-time,omitempty"`
TransportLayerPadding TLSMirrorTransportLayerPadding `yaml:"transport-layer-padding" json:"transport-layer-padding,omitempty"`
ConnectionEnrolment *TLSMirrorConnectionEnrolment `yaml:"connection-enrolment" json:"connection-enrolment,omitempty"`
SequenceWatermarkingEnabled bool `yaml:"sequence-watermarking-enabled" json:"sequence-watermarking-enabled,omitempty"`
}
type TLSMirrorConnectionEnrolment struct {
PrimaryIngressOutbound string `yaml:"primary-ingress-outbound" json:"primary-ingress-outbound,omitempty"`
PrimaryEgressOutbound string `yaml:"primary-egress-outbound" json:"primary-egress-outbound,omitempty"`
}
func (e *TLSMirrorConnectionEnrolment) Build() *tlsmirror.ConnectionEnrolment {
if e == nil {
return nil
}
return &tlsmirror.ConnectionEnrolment{
PrimaryIngressOutbound: e.PrimaryIngressOutbound,
PrimaryEgressOutbound: e.PrimaryEgressOutbound,
}
}
type TLSMirrorTimeSpec struct {
BaseNanoseconds uint64 `yaml:"base-nanoseconds" json:"base-nanoseconds,omitempty"`
UniformRandomMultiplierNanoseconds uint64 `yaml:"uniform-random-multiplier-nanoseconds" json:"uniform-random-multiplier-nanoseconds,omitempty"`
}
func (s TLSMirrorTimeSpec) Build() tlsmirror.TimeSpec {
return tlsmirror.TimeSpec{
BaseNanoseconds: s.BaseNanoseconds,
UniformRandomMultiplierNanoseconds: s.UniformRandomMultiplierNanoseconds,
}
}
type TLSMirrorTransportLayerPadding struct {
Enabled bool `yaml:"enabled" json:"enabled,omitempty"`
}
func (p TLSMirrorTransportLayerPadding) Build() tlsmirror.TransportLayerPadding {
return tlsmirror.TransportLayerPadding{
Enabled: p.Enabled,
}
}
func (t VmessServer) String() string {
+5 -4
View File
@@ -1,6 +1,7 @@
package http
import (
"context"
"errors"
"net"
@@ -39,7 +40,7 @@ func (l *Listener) Close() error {
}
func New(addr string, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
return NewWithConfig(LC.AuthServer{Enable: true, Listen: addr, AuthStore: authStore.Default}, tunnel, additions...)
return NewWithConfig(LC.AuthServer{Enable: true, Listen: addr, AuthStore: authStore.Default}, inbound.NewListenConfig(), tunnel, additions...)
}
// NewWithAuthenticate
@@ -49,10 +50,10 @@ func NewWithAuthenticate(addr string, tunnel C.Tunnel, authenticate bool, additi
if !authenticate {
store = authStore.Nil
}
return NewWithConfig(LC.AuthServer{Enable: true, Listen: addr, AuthStore: store}, tunnel, additions...)
return NewWithConfig(LC.AuthServer{Enable: true, Listen: addr, AuthStore: store}, inbound.NewListenConfig(), tunnel, additions...)
}
func NewWithConfig(config LC.AuthServer, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
func NewWithConfig(config LC.AuthServer, lc C.InboundListenConfig, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
isDefault := false
if len(additions) == 0 {
isDefault = true
@@ -62,7 +63,7 @@ func NewWithConfig(config LC.AuthServer, tunnel C.Tunnel, additions ...inbound.A
}
}
l, err := inbound.Listen("tcp", config.Listen)
l, err := lc.Listen(context.Background(), "tcp", config.Listen)
if err != nil {
return nil, err
}
+2 -2
View File
@@ -36,7 +36,7 @@ const (
func DefaultALPN() []string { return []string{"h2", "http/1.1"} }
func New(config LC.Hysteria2RealmServer, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
func New(config LC.Hysteria2RealmServer, lc C.InboundListenConfig, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
if len(additions) == 0 {
additions = []inbound.Addition{
inbound.WithInName("DEFAULT-HYSTERIA2-REALM"),
@@ -93,7 +93,7 @@ func New(config LC.Hysteria2RealmServer, tunnel C.Tunnel, additions ...inbound.A
addr := addr
//TCP
l, err := inbound.Listen("tcp", addr)
l, err := lc.Listen(context.Background(), "tcp", addr)
if err != nil {
return nil, err
}
+1 -1
View File
@@ -74,7 +74,7 @@ func (v *AnyTLS) Address() string {
// Listen implements constant.InboundListener
func (v *AnyTLS) Listen(tunnel C.Tunnel) error {
var err error
v.l, err = anytls.New(v.vs, tunnel, v.Additions()...)
v.l, err = anytls.New(v.vs, v.ListenConfig(), tunnel, v.Additions()...)
if err != nil {
return err
}
+19
View File
@@ -83,6 +83,10 @@ func (b *Base) Additions() []inbound.Addition {
return b.config.Additions()
}
func (b *Base) ListenConfig() C.InboundListenConfig {
return b.config.ListenConfig()
}
var _ C.InboundListener = (*Base)(nil)
type BaseOption struct {
@@ -91,6 +95,12 @@ type BaseOption struct {
Port string `inbound:"port,omitempty"`
SpecialRules string `inbound:"rule,omitempty"`
SpecialProxy string `inbound:"proxy,omitempty"`
RoutingMark int `inbound:"routing-mark,omitempty"`
//
// The following parameters are used internally, assign value by the structure decoder are disallowed
//
ListenConfigForAPI C.InboundListenConfig `inbound:"-"`
}
func (o BaseOption) Name() string {
@@ -109,6 +119,15 @@ func (o BaseOption) Additions() []inbound.Addition {
}
}
func (o BaseOption) ListenConfig() C.InboundListenConfig {
if o.ListenConfigForAPI != nil {
return o.ListenConfigForAPI
}
lc := inbound.NewListenConfig()
lc.SetRouteMark(o.RoutingMark)
return lc
}
var _ C.InboundConfig = (*BaseOption)(nil)
func optionToString(option any) string {
+2 -2
View File
@@ -175,7 +175,7 @@ func NewHttpTestTunnel() *TestTunnel {
ln := &TestTunnelListener{ch: make(chan net.Conn), ctx: ctx, cancel: cancel, addr: net.TCPAddrFromAddrPort(netip.AddrPortFrom(remoteAddr, 0))}
r := chi.NewRouter()
r.Get(httpPath, func(w http.ResponseWriter, r *http.Request) {
r.Post(httpPath, func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
size, err := strconv.Atoi(query.Get("size"))
if err != nil {
@@ -191,7 +191,7 @@ func NewHttpTestTunnel() *TestTunnel {
//_ = http.Http2ConfigureServer(&server, h2Server)
go server.Serve(ln)
testFn := func(t *testing.T, proxy C.ProxyAdapter, proto string, size int) {
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s://%s%s?size=%d", proto, remoteAddr, httpPath, size), bytes.NewReader(httpData[:size]))
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s://%s%s?size=%d", proto, remoteAddr, httpPath, size), bytes.NewReader(httpData[:size]))
if !assert.NoError(t, err) {
return
}
+2
View File
@@ -59,6 +59,7 @@ func (h *HTTP) Address() string {
// Listen implements constant.InboundListener
func (h *HTTP) Listen(tunnel C.Tunnel) error {
lc := h.ListenConfig()
for _, addr := range strings.Split(h.RawAddress(), ",") {
l, err := http.NewWithConfig(
LC.AuthServer{
@@ -72,6 +73,7 @@ func (h *HTTP) Listen(tunnel C.Tunnel) error {
EchKey: h.config.EchKey,
RealityConfig: h.config.RealityConfig.Build(),
},
lc,
tunnel,
h.Additions()...,
)
+1 -1
View File
@@ -146,7 +146,7 @@ func (t *Hysteria2) Address() string {
// Listen implements constant.InboundListener
func (t *Hysteria2) Listen(tunnel C.Tunnel) error {
var err error
t.l, err = sing_hysteria2.New(t.ts, tunnel, t.Additions()...)
t.l, err = sing_hysteria2.New(t.ts, t.ListenConfig(), tunnel, t.Additions()...)
if err != nil {
return err
}
+1 -1
View File
@@ -89,7 +89,7 @@ func (t *Hysteria2RealmServer) Address() string {
// Listen implements constant.InboundListener
func (t *Hysteria2RealmServer) Listen(tunnel C.Tunnel) error {
var err error
t.l, err = hysteria2_realm.New(t.ts, tunnel, t.Additions()...)
t.l, err = hysteria2_realm.New(t.ts, t.ListenConfig(), tunnel, t.Additions()...)
if err != nil {
return err
}
+33
View File
@@ -0,0 +1,33 @@
package inbound
import LC "github.com/metacubex/mihomo/listener/config"
type MekyaConfig struct {
Enable bool `inbound:"enable,omitempty"`
URL string `inbound:"url,omitempty"`
H2PoolSize int `inbound:"h2-pool-size,omitempty"`
MaxWriteDelay int `inbound:"max-write-delay,omitempty"`
MaxRequestSize int `inbound:"max-request-size,omitempty"`
PollingIntervalInitial int `inbound:"polling-interval-initial,omitempty"`
MaxWriteSize int `inbound:"max-write-size,omitempty"`
MaxWriteDurationMs int `inbound:"max-write-duration-ms,omitempty"`
MaxSimultaneousWriteConnection int `inbound:"max-simultaneous-write-connection,omitempty"`
PacketWritingBuffer int `inbound:"packet-writing-buffer,omitempty"`
KCP MKCPConfig `inbound:"kcp,omitempty"`
}
func (c MekyaConfig) Build() LC.MekyaConfig {
return LC.MekyaConfig{
Enable: c.Enable,
URL: c.URL,
H2PoolSize: c.H2PoolSize,
MaxWriteDelay: c.MaxWriteDelay,
MaxRequestSize: c.MaxRequestSize,
PollingIntervalInitial: c.PollingIntervalInitial,
MaxWriteSize: c.MaxWriteSize,
MaxWriteDurationMs: c.MaxWriteDurationMs,
MaxSimultaneousWriteConnection: c.MaxSimultaneousWriteConnection,
PacketWritingBuffer: c.PacketWritingBuffer,
KCP: c.KCP.Build(),
}
}
+3 -14
View File
@@ -1,9 +1,7 @@
package inbound
import (
"context"
"fmt"
"net"
"sync"
"github.com/metacubex/mihomo/adapter/inbound"
@@ -33,16 +31,6 @@ type MieruOption struct {
UserHintIsMandatory bool `inbound:"user-hint-is-mandatory,omitempty"`
}
type mieruListenerFactory struct{}
func (mieruListenerFactory) Listen(ctx context.Context, network, address string) (net.Listener, error) {
return inbound.ListenContext(ctx, network, address)
}
func (mieruListenerFactory) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
return inbound.ListenPacketContext(ctx, network, address)
}
func NewMieru(option *MieruOption) (*Mieru, error) {
base, err := NewBase(&option.BaseOption)
if err != nil {
@@ -165,6 +153,7 @@ func buildMieruServerConfig(option *MieruOption, ports utils.IntRanges[uint16])
UserHintIsMandatory: proto.Bool(true),
}
}
lc := option.ListenConfig()
return &mieruserver.ServerConfig{
Config: &mierupb.ServerConfig{
PortBindings: portBindings,
@@ -172,8 +161,8 @@ func buildMieruServerConfig(option *MieruOption, ports utils.IntRanges[uint16])
TrafficPattern: trafficPattern,
AdvancedSettings: advancedSettings,
},
StreamListenerFactory: mieruListenerFactory{},
PacketListenerFactory: mieruListenerFactory{},
StreamListenerFactory: lc,
PacketListenerFactory: lc,
}, nil
}
+42 -8
View File
@@ -1,6 +1,7 @@
package inbound_test
import (
"context"
"net"
"net/netip"
"strconv"
@@ -193,18 +194,28 @@ func TestInboundMieru(t *testing.T) {
func testInboundMieruTCP(t *testing.T, handshakeMode string) {
t.Parallel()
// mieru must listen on a specific port, so we first create a socket, get the port, and then inject it via ListenConfigForAPI
l, err := net.Listen("tcp", "127.0.0.1:0")
if !assert.NoError(t, err) {
return
}
port := l.Addr().(*net.TCPAddr).Port
l.Close()
defer l.Close()
lc := mieruTestInboundListenConfig{
ListenFn: func(ctx context.Context, network, address string) (net.Listener, error) {
return l, nil
},
ListenPacketFn: func(ctx context.Context, network, address string) (net.PacketConn, error) {
panic("should not be called")
},
}
inboundOptions := inbound.MieruOption{
BaseOption: inbound.BaseOption{
NameStr: "mieru_inbound_tcp",
Listen: "127.0.0.1",
Port: strconv.Itoa(port),
NameStr: "mieru_inbound_tcp",
Listen: "127.0.0.1",
Port: strconv.Itoa(port),
ListenConfigForAPI: lc,
},
Transport: "TCP",
Users: map[string]string{"test": "password"},
@@ -250,18 +261,28 @@ func testInboundMieruTCP(t *testing.T, handshakeMode string) {
func testInboundMieruUDP(t *testing.T, handshakeMode string) {
t.Parallel()
// mieru must listen on a specific port, so we first create a socket, get the port, and then inject it via ListenConfigForAPI
l, err := net.ListenPacket("udp", "127.0.0.1:0")
if !assert.NoError(t, err) {
return
}
port := l.LocalAddr().(*net.UDPAddr).Port
l.Close()
defer l.Close()
lc := mieruTestInboundListenConfig{
ListenFn: func(ctx context.Context, network, address string) (net.Listener, error) {
panic("should not be called")
},
ListenPacketFn: func(ctx context.Context, network, address string) (net.PacketConn, error) {
return l, nil
},
}
inboundOptions := inbound.MieruOption{
BaseOption: inbound.BaseOption{
NameStr: "mieru_inbound_udp",
Listen: "127.0.0.1",
Port: strconv.Itoa(port),
NameStr: "mieru_inbound_udp",
Listen: "127.0.0.1",
Port: strconv.Itoa(port),
ListenConfigForAPI: lc,
},
Transport: "UDP",
Users: map[string]string{"test": "password"},
@@ -303,3 +324,16 @@ func testInboundMieruUDP(t *testing.T, handshakeMode string) {
tunnel.DoSequentialTest(t, out)
}
type mieruTestInboundListenConfig struct {
ListenFn func(ctx context.Context, network, address string) (net.Listener, error)
ListenPacketFn func(ctx context.Context, network, address string) (net.PacketConn, error)
}
func (m mieruTestInboundListenConfig) Listen(ctx context.Context, network, address string) (net.Listener, error) {
return m.ListenFn(ctx, network, address)
}
func (m mieruTestInboundListenConfig) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
return m.ListenPacketFn(ctx, network, address)
}
+14 -16
View File
@@ -64,28 +64,26 @@ func (m *Mixed) Address() string {
// Listen implements constant.InboundListener
func (m *Mixed) Listen(tunnel C.Tunnel) error {
lc := m.ListenConfig()
for _, addr := range strings.Split(m.RawAddress(), ",") {
l, err := mixed.NewWithConfig(
LC.AuthServer{
Enable: true,
Listen: addr,
AuthStore: m.config.Users.GetAuthStore(),
Certificate: m.config.Certificate,
PrivateKey: m.config.PrivateKey,
ClientAuthType: m.config.ClientAuthType,
ClientAuthCert: m.config.ClientAuthCert,
EchKey: m.config.EchKey,
RealityConfig: m.config.RealityConfig.Build(),
},
tunnel,
m.Additions()...,
)
config := LC.AuthServer{
Enable: true,
Listen: addr,
AuthStore: m.config.Users.GetAuthStore(),
Certificate: m.config.Certificate,
PrivateKey: m.config.PrivateKey,
ClientAuthType: m.config.ClientAuthType,
ClientAuthCert: m.config.ClientAuthCert,
EchKey: m.config.EchKey,
RealityConfig: m.config.RealityConfig.Build(),
}
l, err := mixed.NewWithConfig(config, lc, tunnel, m.Additions()...)
if err != nil {
return err
}
m.l = append(m.l, l)
if m.udp {
lUDP, err := socks.NewUDP(addr, tunnel, m.Additions()...)
lUDP, err := socks.NewUDPWithConfig(config, lc, tunnel, m.Additions()...)
if err != nil {
return err
}
+31
View File
@@ -0,0 +1,31 @@
package inbound
import LC "github.com/metacubex/mihomo/listener/config"
type MKCPConfig struct {
Enable bool `inbound:"enable,omitempty"`
MTU uint32 `inbound:"mtu,omitempty"`
TTI uint32 `inbound:"tti,omitempty"`
UplinkCapacity uint32 `inbound:"uplink-capacity,omitempty"`
DownlinkCapacity uint32 `inbound:"downlink-capacity,omitempty"`
Congestion bool `inbound:"congestion,omitempty"`
WriteBuffer uint32 `inbound:"write-buffer,omitempty"`
ReadBuffer uint32 `inbound:"read-buffer,omitempty"`
Seed string `inbound:"seed,omitempty"`
Header string `inbound:"header,omitempty"`
}
func (c MKCPConfig) Build() LC.MKCPConfig {
return LC.MKCPConfig{
Enable: c.Enable,
MTU: c.MTU,
TTI: c.TTI,
UplinkCapacity: c.UplinkCapacity,
DownlinkCapacity: c.DownlinkCapacity,
Congestion: c.Congestion,
WriteBuffer: c.WriteBuffer,
ReadBuffer: c.ReadBuffer,
Seed: c.Seed,
Header: c.Header,
}
}
+25
View File
@@ -0,0 +1,25 @@
package inbound
import (
LC "github.com/metacubex/mihomo/listener/config"
)
type ResTLS struct {
Enable bool `inbound:"enable"`
Dest string `inbound:"dest"`
Password string `inbound:"password"`
RestlsScript string `inbound:"restls-script,omitempty"`
MinRecordLen int `inbound:"min-record-len,omitempty"`
Proxy string `inbound:"proxy,omitempty"`
}
func (r ResTLS) Build() LC.ResTLS {
return LC.ResTLS{
Enable: r.Enable,
Dest: r.Dest,
Password: r.Password,
RestlsScript: r.RestlsScript,
MinRecordLen: r.MinRecordLen,
Proxy: r.Proxy,
}
}
+3 -1
View File
@@ -16,6 +16,7 @@ type ShadowSocksOption struct {
UDP bool `inbound:"udp,omitempty"`
MuxOption MuxOption `inbound:"mux-option,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
ResTLS ResTLS `inbound:"res-tls,omitempty"`
KcpTun KcpTun `inbound:"kcp-tun,omitempty"`
SimpleObfs SimpleObfs `inbound:"simple-obfs,omitempty"`
}
@@ -59,6 +60,7 @@ func NewShadowSocks(options *ShadowSocksOption) (*ShadowSocks, error) {
Udp: options.UDP,
MuxOption: options.MuxOption.Build(),
ShadowTLS: options.ShadowTLS.Build(),
ResTLS: options.ResTLS.Build(),
KcpTun: options.KcpTun.Build(),
SimpleObfs: options.SimpleObfs.Build(),
},
@@ -84,7 +86,7 @@ func (s *ShadowSocks) Address() string {
// Listen implements constant.InboundListener
func (s *ShadowSocks) Listen(tunnel C.Tunnel) error {
var err error
s.l, err = sing_shadowsocks.New(s.ss, tunnel, s.Additions()...)
s.l, err = sing_shadowsocks.New(s.ss, s.ListenConfig(), tunnel, s.Additions()...)
if err != nil {
return err
}
+31
View File
@@ -12,6 +12,7 @@ import (
"github.com/metacubex/mihomo/adapter/outbound"
"github.com/metacubex/mihomo/listener/inbound"
"github.com/metacubex/mihomo/transport/kcptun"
"github.com/metacubex/mihomo/transport/restls"
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
shadowsocks "github.com/metacubex/sing-shadowsocks"
@@ -168,6 +169,36 @@ func TestInboundShadowSocks_ShadowTlsv3(t *testing.T) {
testInboundShadowSocksShadowTls(t, inboundOptions, outboundOptions)
}
func TestInboundShadowSocks_Restls_tls12(t *testing.T) {
inboundOptions := inbound.ShadowSocksOption{
ResTLS: inbound.ResTLS{
Enable: true,
Dest: net.JoinHostPort(realityDest, "443"),
Password: shadowsocksPassword16,
},
}
outboundOptions := outbound.ShadowSocksOption{
Plugin: restls.Mode,
PluginOpts: map[string]any{"host": realityDest, "password": shadowsocksPassword16, "fingerprint": tlsFingerprint, "version-hint": "tls12", "force-tls12": true},
}
testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherShortLists, false)
}
func TestInboundShadowSocks_Restls_tls13(t *testing.T) {
inboundOptions := inbound.ShadowSocksOption{
ResTLS: inbound.ResTLS{
Enable: true,
Dest: net.JoinHostPort(realityDest, "443"),
Password: shadowsocksPassword16,
},
}
outboundOptions := outbound.ShadowSocksOption{
Plugin: restls.Mode,
PluginOpts: map[string]any{"host": realityDest, "password": shadowsocksPassword16, "fingerprint": tlsFingerprint, "version-hint": "tls13"},
}
testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherShortLists, false)
}
func TestInboundShadowSocks_SimpleObfs_Http(t *testing.T) {
inboundOptions := inbound.ShadowSocksOption{
SimpleObfs: inbound.SimpleObfs{
+17 -14
View File
@@ -5,16 +5,18 @@ import (
"strings"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/snell"
"github.com/metacubex/mihomo/log"
)
type SnellOption struct {
BaseOption
Psk string `inbound:"psk"`
Version int `inbound:"version,omitempty"`
UDP bool `inbound:"udp,omitempty"`
ObfsOpts SnellObfsOption `inbound:"obfs-opts,omitempty"`
Psk string `inbound:"psk"`
Version int `inbound:"version,omitempty"`
UDP bool `inbound:"udp,omitempty"`
ObfsOpts SnellObfsOption `inbound:"obfs-opts,omitempty"`
ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"`
}
func (o SnellOption) Equal(config C.InboundConfig) bool {
@@ -30,7 +32,7 @@ type Snell struct {
*Base
config *SnellOption
l C.MultiAddrListener
snell snell.Config
snell LC.SnellServer
}
func NewSnell(options *SnellOption) (*Snell, error) {
@@ -41,20 +43,21 @@ func NewSnell(options *SnellOption) (*Snell, error) {
if options.Version == 0 {
options.Version = 4
}
if options.Version != 4 && options.Version != 5 {
if options.Version < 1 || options.Version > 5 {
return nil, fmt.Errorf("snell inbound version %d is not supported", options.Version)
}
return &Snell{
Base: base,
config: options,
snell: snell.Config{
Listen: base.RawAddress(),
Psk: options.Psk,
Version: options.Version,
UDP: options.UDP,
ObfsMode: options.ObfsOpts.Mode,
ObfsHost: options.ObfsOpts.Host,
snell: LC.SnellServer{
Listen: base.RawAddress(),
Psk: options.Psk,
Version: options.Version,
UDP: options.UDP,
ObfsMode: options.ObfsOpts.Mode,
ObfsHost: options.ObfsOpts.Host,
ShadowTLS: options.ShadowTLS.Build(),
},
}, nil
}
@@ -75,7 +78,7 @@ func (s *Snell) Address() string {
func (s *Snell) Listen(tunnel C.Tunnel) error {
var err error
s.l, err = snell.New(s.snell, tunnel, s.Additions()...)
s.l, err = snell.New(s.snell, s.ListenConfig(), tunnel, s.Additions()...)
if err != nil {
return err
}
+51
View File
@@ -1,11 +1,13 @@
package inbound_test
import (
"net"
"net/netip"
"testing"
"github.com/metacubex/mihomo/adapter/outbound"
"github.com/metacubex/mihomo/listener/inbound"
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
"github.com/stretchr/testify/assert"
)
@@ -58,6 +60,9 @@ func TestInboundSnell(t *testing.T) {
name string
version int
}{
{"v1", 1},
{"v2", 2},
{"v3", 3},
{"v4", 4},
{"v5", 5},
}
@@ -70,3 +75,49 @@ func TestInboundSnell(t *testing.T) {
})
}
}
func testInboundSnellShadowTls(t *testing.T, inboundOptions inbound.SnellOption, outboundOptions outbound.SnellOption) {
t.Parallel()
t.Run("Conn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
testInboundSnell(t, inboundOptions, outboundOptions)
})
t.Run("UConn", func(t *testing.T) {
inboundOptions, outboundOptions := inboundOptions, outboundOptions // don't modify outside options value
outboundOptions.ClientFingerprint = "chrome"
testInboundSnell(t, inboundOptions, outboundOptions)
})
}
func TestInboundSnell_ShadowTlsv2(t *testing.T) {
inboundOptions := inbound.SnellOption{
ShadowTLS: inbound.ShadowTLS{
Enable: true,
Version: 2,
Password: shadowsocksPassword16,
Handshake: inbound.ShadowTLSHandshakeOptions{Dest: net.JoinHostPort(realityDest, "443")},
},
}
outboundOptions := outbound.SnellOption{
Version: 5,
ObfsOpts: map[string]any{"mode": shadowtls.Mode, "host": realityDest, "password": shadowsocksPassword16, "fingerprint": tlsFingerprint, "version": 2},
}
outboundOptions.ObfsOpts["alpn"] = []string{"http/1.1"} // shadowtls v2 work confuse with http/2 server, so we set alpn to http/1.1 to pass the test
testInboundSnellShadowTls(t, inboundOptions, outboundOptions)
}
func TestInboundSnell_ShadowTlsv3(t *testing.T) {
inboundOptions := inbound.SnellOption{
ShadowTLS: inbound.ShadowTLS{
Enable: true,
Version: 3,
Users: []inbound.ShadowTLSUser{{Name: "test", Password: shadowsocksPassword16}},
Handshake: inbound.ShadowTLSHandshakeOptions{Dest: net.JoinHostPort(realityDest, "443")},
},
}
outboundOptions := outbound.SnellOption{
Version: 5,
ObfsOpts: map[string]any{"mode": shadowtls.Mode, "host": realityDest, "password": shadowsocksPassword16, "fingerprint": tlsFingerprint, "version": 3},
}
testInboundSnellShadowTls(t, inboundOptions, outboundOptions)
}
+14 -16
View File
@@ -84,28 +84,26 @@ func (s *Socks) Address() string {
// Listen implements constant.InboundListener
func (s *Socks) Listen(tunnel C.Tunnel) error {
lc := s.ListenConfig()
for _, addr := range strings.Split(s.RawAddress(), ",") {
stl, err := socks.NewWithConfig(
LC.AuthServer{
Enable: true,
Listen: addr,
AuthStore: s.config.Users.GetAuthStore(),
Certificate: s.config.Certificate,
PrivateKey: s.config.PrivateKey,
ClientAuthType: s.config.ClientAuthType,
ClientAuthCert: s.config.ClientAuthCert,
EchKey: s.config.EchKey,
RealityConfig: s.config.RealityConfig.Build(),
},
tunnel,
s.Additions()...,
)
config := LC.AuthServer{
Enable: true,
Listen: addr,
AuthStore: s.config.Users.GetAuthStore(),
Certificate: s.config.Certificate,
PrivateKey: s.config.PrivateKey,
ClientAuthType: s.config.ClientAuthType,
ClientAuthCert: s.config.ClientAuthCert,
EchKey: s.config.EchKey,
RealityConfig: s.config.RealityConfig.Build(),
}
stl, err := socks.NewWithConfig(config, lc, tunnel, s.Additions()...)
if err != nil {
return err
}
s.stl = append(s.stl, stl)
if s.udp {
sul, err := socks.NewUDP(addr, tunnel, s.Additions()...)
sul, err := socks.NewUDPWithConfig(config, lc, tunnel, s.Additions()...)
if err != nil {
return err
}
+2 -1
View File
@@ -114,11 +114,12 @@ func (s *Sudoku) Listen(tunnel C.Tunnel) error {
}
var errs []error
lc := s.ListenConfig()
for _, addr := range strings.Split(s.RawAddress(), ",") {
conf := s.serverConf
conf.Listen = addr
l, err := sudoku.New(conf, tunnel, s.Additions()...)
l, err := sudoku.New(conf, lc, tunnel, s.Additions()...)
if err != nil {
errs = append(errs, err)
continue
+66
View File
@@ -0,0 +1,66 @@
package inbound
import (
LC "github.com/metacubex/mihomo/listener/config"
)
type TLSMirrorConfig struct {
PrimaryKey string `inbound:"primary-key,omitempty"`
Dest string `inbound:"dest,omitempty"`
Proxy string `inbound:"proxy,omitempty"`
ExplicitNonceCipherSuites []uint16 `inbound:"explicit-nonce-ciphersuites,omitempty"`
DeferInstanceDerivedWriteTime TLSMirrorTimeSpec `inbound:"defer-instance-derived-write-time,omitempty"`
TransportLayerPadding TLSMirrorTransportLayerPadding `inbound:"transport-layer-padding,omitempty"`
ConnectionEnrolment *TLSMirrorConnectionEnrolment `inbound:"connection-enrolment,omitempty"`
SequenceWatermarkingEnabled bool `inbound:"sequence-watermarking-enabled,omitempty"`
}
type TLSMirrorConnectionEnrolment struct {
PrimaryIngressOutbound string `inbound:"primary-ingress-outbound,omitempty"`
PrimaryEgressOutbound string `inbound:"primary-egress-outbound,omitempty"`
}
func (e *TLSMirrorConnectionEnrolment) Build() *LC.TLSMirrorConnectionEnrolment {
if e == nil {
return nil
}
return &LC.TLSMirrorConnectionEnrolment{
PrimaryIngressOutbound: e.PrimaryIngressOutbound,
PrimaryEgressOutbound: e.PrimaryEgressOutbound,
}
}
type TLSMirrorTimeSpec struct {
BaseNanoseconds uint64 `inbound:"base-nanoseconds,omitempty"`
UniformRandomMultiplierNanoseconds uint64 `inbound:"uniform-random-multiplier-nanoseconds,omitempty"`
}
func (s TLSMirrorTimeSpec) Build() LC.TLSMirrorTimeSpec {
return LC.TLSMirrorTimeSpec{
BaseNanoseconds: s.BaseNanoseconds,
UniformRandomMultiplierNanoseconds: s.UniformRandomMultiplierNanoseconds,
}
}
type TLSMirrorTransportLayerPadding struct {
Enabled bool `inbound:"enabled,omitempty"`
}
func (p TLSMirrorTransportLayerPadding) Build() LC.TLSMirrorTransportLayerPadding {
return LC.TLSMirrorTransportLayerPadding{
Enabled: p.Enabled,
}
}
func (c TLSMirrorConfig) Build() LC.TLSMirrorConfig {
return LC.TLSMirrorConfig{
PrimaryKey: c.PrimaryKey,
Dest: c.Dest,
Proxy: c.Proxy,
ExplicitNonceCipherSuites: c.ExplicitNonceCipherSuites,
DeferInstanceDerivedWriteTime: c.DeferInstanceDerivedWriteTime.Build(),
TransportLayerPadding: c.TransportLayerPadding.Build(),
ConnectionEnrolment: c.ConnectionEnrolment.Build(),
SequenceWatermarkingEnabled: c.SequenceWatermarkingEnabled,
}
}
+1 -1
View File
@@ -105,7 +105,7 @@ func (v *Trojan) Address() string {
// Listen implements constant.InboundListener
func (v *Trojan) Listen(tunnel C.Tunnel) error {
var err error
v.l, err = trojan.New(v.vs, tunnel, v.Additions()...)
v.l, err = trojan.New(v.vs, v.ListenConfig(), tunnel, v.Additions()...)
if err != nil {
return err
}
+1 -1
View File
@@ -82,7 +82,7 @@ func (v *TrustTunnel) Address() string {
// Listen implements constant.InboundListener
func (v *TrustTunnel) Listen(tunnel C.Tunnel) error {
var err error
v.l, err = trusttunnel.New(v.vs, tunnel, v.Additions()...)
v.l, err = trusttunnel.New(v.vs, v.ListenConfig(), tunnel, v.Additions()...)
if err != nil {
return err
}
+1 -1
View File
@@ -88,7 +88,7 @@ func (t *Tuic) Address() string {
// Listen implements constant.InboundListener
func (t *Tuic) Listen(tunnel C.Tunnel) error {
var err error
t.l, err = tuic.New(t.ts, tunnel, t.Additions()...)
t.l, err = tuic.New(t.ts, t.ListenConfig(), tunnel, t.Additions()...)
if err != nil {
return err
}
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more