Compare commits

...
132 Commits
Author SHA1 Message Date
Lanlan13-14 e26714a181 feat: support TLS rekey fix, data-ciphers negotiation, tls-crypt-v2 for OpenVPN (#2989) 2026-07-18 19:18:54 +08:00
anytls bd749c65bc feat: sync anytls v0.0.13 (#2990) 2026-07-18 10:41:27 +08:00
wwqgtxx 9ae1cc2be2 fix: shadowquic JLS pre-flight fallback handle 2026-07-17 15:52:42 +08:00
wwqgtxx 1eb49e0571 doc: explain the flaws in the official Shadowquic implementation regarding JLS 0-RTT authentication 2026-07-17 08:39:14 +08:00
wwqgtxx a5167fa4ab fix: allow JLS fallback before the server flight
Decide whether fallback is safe based on bytes actually written instead of JLS authentication status. This allows authenticated preflight failures, including HRR and TLS configuration mismatches, to relay the untouched ClientHello to the camouflage target.

Keep rejecting fallback after a partial or complete server flight, update jls-tls for pre-write alert suppression, and add coverage for both sides of the write boundary.
2026-07-16 23:02:17 +08:00
wwqgtxx f86bc224dc fix: align HelloRetryRequest handling with JLS v3
JLS v3 does not permit HelloRetryRequest during JLS authentication. Keep the ClientHello random unchanged across HRR and make clients continue as ordinary TLS with certificate verification.

When an authenticated ClientHello would require HRR, fail before writing handshake data and wrap ErrJLSAuthFailed. This allows stream and QUIC callers to forward the untouched handshake to the camouflage fallback instead of accepting a non-standard JLS exchange.
2026-07-16 22:17:24 +08:00
wwqgtxx 423611628c chore: better UserFromConn implementation 2026-07-16 20:47:52 +08:00
freephilx 0ee584171e fix: reconnect OpenVPN on server soft reset (#2978) 2026-07-16 17:04:33 +08:00
wwqgtxx 9a7e726657 fix: performance regression caused by unnecessary wrapping in stream encryption 2026-07-16 16:27:34 +08:00
wwqgtxx a70af27451 fix: remove unnecessary quinn-jls compatibility behavior 2026-07-16 10:03:47 +08:00
wwqgtxx 5c1b8bfc31 chore: authenticate JLS ServerHello using its wire encoding
JLS authenticates the serialized ServerHello with only the random field zeroed. The previous marshalForJLS implementation reordered extensions to match rustls-jls's internal struct order, even when that order differed from the bytes sent on the wire.

That canonical order is not defined by TLS or the JLS specification and couples this package to a rustls-jls implementation detail. Use the normal marshal output when sending and the original wire bytes when receiving, preserving extension order and leaving the TLS transcript untouched.

This intentionally removes compatibility with rustls-jls clients that re-encode ServerHello extensions before JLS verification.
2026-07-16 09:04:31 +08:00
wwqgtxx e3c1ea06a4 chore: better handshakeRecorderConn impl 2026-07-16 08:40:18 +08:00
wwqgtxx e9119858b2 chore: change the brutal negotiation in shadowquic to be asynchronous 2026-07-16 00:02:50 +08:00
AaronChen0 c079b0cc12 fix: panic on full-width IP-SUFFIX rules (#2975) 2026-07-15 21:51:32 +08:00
wwqgtxx b75a776d39 chore: clean up duplicate helpers in tests 2026-07-15 18:29:59 +08:00
wwqgtxx 9ab75434a9 feat: support restls/jls for snell outbound and listener 2026-07-15 18:16:38 +08:00
wwqgtxx da5a3e52ae chore: rewrite the internal mutual exclusion logic of the outbound 2026-07-15 17:55:48 +08:00
wwqgtxx b6ed8e2643 chore: rewrite the internal mutual exclusion logic of the listener 2026-07-15 17:43:18 +08:00
wwqgtxx 8507c1e221 fix: missing override shadow-tls-opts and restls-opts in xhttp download-settings 2026-07-15 17:42:58 +08:00
wwqgtxx bc5976f4ed chore: sync internal logic 2026-07-15 16:59:59 +08:00
wwqgtxx 0e7c3c79e3 feat: support restls for anytls outbound and listener 2026-07-15 16:52:21 +08:00
wwqgtxx 769ea6f5b4 feat: support restls for vmess/vless/trojan outbound and listener 2026-07-15 16:49:02 +08:00
wwqgtxx bc0e5aa835 feat: support shadowtls for anytls outbound and listener 2026-07-15 16:18:37 +08:00
wwqgtxx c015694bf3 feat: support shadowtls for vmess/vless/trojan outbound and listener 2026-07-15 15:51:35 +08:00
wwqgtxx 8413f50407 chore: skip frequently failed tests on windows go1.20 2026-07-15 10:18:47 +08:00
wwqgtxx 86984831ed fix: the incorrect tls stack was used in shadowtls tests 2026-07-15 08:54:41 +08:00
wwqgtxx 2b0d8411fa fix: make shadowtls v2 read deadlines recoverable 2026-07-15 00:31:49 +08:00
wwqgtxx 7a3c37cb33 fix: make shadowtls v3 read deadlines recoverable 2026-07-15 00:31:14 +08:00
wwqgtxx 3f22309b51 chore: respect the incoming context during JLS fallback 2026-07-14 21:51:12 +08:00
wwqgtxx 4d7ef85adb chore: sync logic to legacy shadowsocks listener 2026-07-14 21:02:36 +08:00
wwqgtxx 44dd834fef chore: preserve jls in-user for shadowsocks listeners 2026-07-14 17:58:28 +08:00
wwqgtxx 309cfbd613 chore: reimplement shadowtls 2026-07-14 17:22:01 +08:00
wwqgtxx ba5c45b735 fix: anytls listener config parsing 2026-07-14 12:31:41 +08:00
wwqgtxx 94409eb659 chore: remove redundant writeFull in sudoku 2026-07-14 09:16:29 +08:00
wwqgtxx 1d1b370e4c chore: remove redundant writeFull in snell v4 2026-07-14 09:16:19 +08:00
wwqgtxx f23e43e68a chore: remove redundant writeFull in gost relay 2026-07-14 09:16:19 +08:00
wwqgtxx 95af34af06 chore: remove redundant writeFull in shadowquic 2026-07-14 09:16:19 +08:00
wwqgtxx bfa9ea1d2b feat: support brutal for shadowquic (mihomo private extension) 2026-07-14 08:49:22 +08:00
wwqgtxx 3b73922fb9 chore: cleanup shadowquic code 2026-07-14 00:28:24 +08:00
wwqgtxx cb8cde8da8 fix: missing override jls-opts in xhttp download-settings 2026-07-14 00:28:24 +08:00
wwqgtxx 8fe7f74811 feat: support jls for anytls outbound and listener 2026-07-13 23:50:40 +08:00
wwqgtxx 611a4481fa feat: support jls for vmess/vless/trojan outbound and listener 2026-07-13 18:49:53 +08:00
wwqgtxx dc4d4fcb8c chore: allow jls with utls client-fingerprint 2026-07-13 08:57:32 +08:00
wwqgtxx 2b2bdf6d22 feat: support jls for shadowsocks outbound and listener 2026-07-13 01:31:09 +08:00
wwqgtxx a35045d9f1 fix: consume CachedConn data in ReadCached 2026-07-13 00:39:52 +08:00
wwqgtxx aea5ce4142 feat: support shadowquic outbound and listener 2026-07-12 22:28:43 +08:00
wwqgtxx 46f9b78626 chore: export internal OverrideExpr for api user 2026-07-12 19:12:58 +08:00
wwqgtxx 5677fd3808 feat: add name-cert-verify to support separate certificate verification name 2026-07-12 18:12:59 +08:00
wwqgtxx 3766a08754 fix: set global CA pool and NTP time for restls 2026-07-12 17:53:03 +08:00
lyaaz 76d80883dd feat: add support for TLSAuth for Openvpn (#2969) 2026-07-12 16:33:45 +08:00
saba-futai 9729296862 chore: sync to sudoku v0.4.8 (#2966) 2026-07-12 08:16:44 +08:00
wwqgtxx 75eeba4292 chore: significantly trim unnecessary code from tailscale
reduced size by 2.3 MB on Windows/Linux build
2026-07-11 23:02:57 +08:00
AaronChen0 45f7930936 fix: CNAME query matching a hosts domain-entry returns an empty answer (#2965) 2026-07-11 19:14:42 +08:00
AaronChen0 41549236fe fix: stop reaper goroutine busy-looping after context cancel (#2964) 2026-07-11 17:47:56 +08:00
wwqgtxx 6d96163e6f feat: support override-expr for proxy provider override 2026-07-11 15:40:54 +08:00
wwqgtxx 975389a1e5 fix: intermittent timeouts during the soak test 2026-07-10 22:30:38 +08:00
AaronChen0 75a3ea8b2d fix: leaked openStreams on failure in TUIC client (#2959) 2026-07-10 21:36:51 +08:00
AaronChen0 12c30af92f fix: wireguard per-peer reserved ignored (#2958) 2026-07-10 20:35:23 +08:00
AaronChen0 c5834396c4 fix: DOMAIN-WILDCARD ignores sniffed hostname (#2956) 2026-07-10 19:29:08 +08:00
Medium1992 6a52d23a13 chore: do not force trailing path / when both sessionID and seq are placed elsewhere for xhttp 2026-07-09 07:35:14 +08:00
SaltyMonkey 02dfcf2b4d fix: incorrect alphabet size used in session-table for predefined tables in xhttp-config 2026-07-09 07:34:03 +08:00
wwqgtxx 5ec37681f9 doc: update doc 2026-07-08 22:02:47 +08:00
wwqgtxx e8ab2d047e fix: alpnAwareRoundTripper behavior in mekya client 2026-07-08 15:50:32 +08:00
wwqgtxx 9cece132be chore: add test for alpnAwareRoundTripper in mekya client 2026-07-08 15:50:32 +08:00
wwqgtxx 2d45f9ec16 chore: using new net/http api in mekya client 2026-07-08 15:50:32 +08:00
wwqgtxx cf8545dbd1 chore: stabilize traffic wait timing in tlsmirror test 2026-07-08 15:50:32 +08:00
wwqgtxx ee80e8d641 chore: more comprehensive interop test 2026-07-08 15:50:32 +08:00
AaronChen0 2c7309e2af fix: listener duplicate-name check (#2948) 2026-07-08 14:52:54 +08:00
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
293 changed files with 27396 additions and 1933 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)
})
}
+54 -17
View File
@@ -2,8 +2,10 @@ package outbound
import (
"context"
"errors"
"net"
"strconv"
"strings"
"time"
N "github.com/metacubex/mihomo/common/net"
@@ -24,22 +26,27 @@ type AnyTLS struct {
type AnyTLSOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Password string `proxy:"password"`
ALPN []string `proxy:"alpn,omitempty"`
SNI string `proxy:"sni,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
UDP bool `proxy:"udp,omitempty"`
IdleSessionCheckInterval int `proxy:"idle-session-check-interval,omitempty"`
IdleSessionTimeout int `proxy:"idle-session-timeout,omitempty"`
MinIdleSession int `proxy:"min-idle-session,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Password string `proxy:"password"`
ALPN []string `proxy:"alpn,omitempty"`
SNI string `proxy:"sni,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
ShadowTLSOpts ShadowTLSOptions `proxy:"shadow-tls-opts,omitempty"`
RestlsOpts RestlsOptions `proxy:"restls-opts,omitempty"`
JLSOpts JLSOptions `proxy:"jls-opts,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
UDP bool `proxy:"udp,omitempty"`
IdleSessionCheckInterval int `proxy:"idle-session-check-interval,omitempty"`
IdleSessionTimeout int `proxy:"idle-session-timeout,omitempty"`
MinIdleSession int `proxy:"min-idle-session,omitempty"`
DisableReuse bool `proxy:"disable-reuse,omitempty"`
}
func (t *AnyTLS) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
@@ -63,7 +70,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
@@ -110,20 +117,50 @@ func NewAnyTLS(option AnyTLSOption) (*AnyTLS, error) {
IdleSessionCheckInterval: time.Duration(option.IdleSessionCheckInterval) * time.Second,
IdleSessionTimeout: time.Duration(option.IdleSessionTimeout) * time.Second,
MinIdleSession: option.MinIdleSession,
DisableReuse: option.DisableReuse,
}
echConfig, err := option.ECHOpts.Parse()
if err != nil {
return nil, err
}
shadowTLSConfig, err := option.ShadowTLSOpts.Parse()
if err != nil {
return nil, err
}
restlsConfig, err := option.RestlsOpts.Parse(option.SNI, option.ClientFingerprint)
if err != nil {
return nil, err
}
jlsConfig, err := option.JLSOpts.Parse()
if err != nil {
return nil, err
}
securityModes := make([]string, 0, 3)
if shadowTLSConfig != nil {
securityModes = append(securityModes, "ShadowTLS")
}
if restlsConfig != nil {
securityModes = append(securityModes, "Restls")
}
if jlsConfig != nil {
securityModes = append(securityModes, "JLS")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
tlsConfig := &vmess.TLSConfig{
Host: option.SNI,
SkipCertVerify: option.SkipCertVerify,
NameCertVerify: option.NameCertVerify,
NextProtos: option.ALPN,
FingerPrint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
ECH: echConfig,
ShadowTLS: shadowTLSConfig,
Restls: restlsConfig,
JLS: jlsConfig,
}
if tlsConfig.Host == "" {
tlsConfig.Host = option.Server
+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,
+3 -1
View File
@@ -29,6 +29,7 @@ type GostRelayOption struct {
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -58,7 +59,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 {
@@ -100,6 +101,7 @@ func NewGostRelay(option GostRelayOption) (*GostRelay, error) {
Username: option.Username,
Password: option.Password,
SkipCertVerify: option.SkipCertVerify,
NameCertVerify: option.NameCertVerify,
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
+5 -3
View File
@@ -35,6 +35,7 @@ type HttpOption struct {
TLS bool `proxy:"tls,omitempty"`
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -157,9 +158,10 @@ func NewHttp(option HttpOption) (*Http, error) {
InsecureSkipVerify: option.SkipCertVerify,
ServerName: sni,
},
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
Fingerprint: option.Fingerprint,
NameCertVerify: option.NameCertVerify,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
})
if err != nil {
return nil, err
+6 -4
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 {
@@ -116,6 +116,7 @@ type HysteriaOption struct {
SNI string `proxy:"sni,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -158,9 +159,10 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
InsecureSkipVerify: option.SkipCertVerify,
MinVersion: tls.VersionTLS13,
},
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
Fingerprint: option.Fingerprint,
NameCertVerify: option.NameCertVerify,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
})
if err != nil {
return nil, err
+12 -8
View File
@@ -53,6 +53,7 @@ type Hysteria2Option struct {
SNI string `proxy:"sni,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -80,6 +81,7 @@ type Hysteria2RealmOption struct {
// for ServerURL
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -105,7 +107,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
@@ -170,9 +172,10 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
InsecureSkipVerify: option.SkipCertVerify,
MinVersion: tls.VersionTLS13,
},
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
Fingerprint: option.Fingerprint,
NameCertVerify: option.NameCertVerify,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
})
if err != nil {
return nil, err
@@ -269,9 +272,10 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
InsecureSkipVerify: option.RealmOpts.SkipCertVerify,
NextProtos: option.RealmOpts.ALPN,
},
Fingerprint: option.RealmOpts.Fingerprint,
Certificate: option.RealmOpts.Certificate,
PrivateKey: option.RealmOpts.PrivateKey,
Fingerprint: option.RealmOpts.Fingerprint,
NameCertVerify: option.RealmOpts.NameCertVerify,
Certificate: option.RealmOpts.Certificate,
PrivateKey: option.RealmOpts.PrivateKey,
})
if err != nil {
return nil, err
@@ -297,7 +301,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)
},
+15
View File
@@ -0,0 +1,15 @@
package outbound
import "github.com/metacubex/mihomo/transport/jls"
type JLSOptions struct {
Username string `proxy:"username"`
Password string `proxy:"password"`
}
func (o JLSOptions) Parse() (*jls.Config, error) {
if o.Username == "" && o.Password == "" {
return nil, nil
}
return jls.NewConfig(o.Username, o.Password)
}
+137 -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,21 @@ 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"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"` // placeholder; MASQUE does not verify certificate names
Network string `proxy:"network,omitempty"`
CongestionController string `proxy:"congestion-controller,omitempty"`
CWND int `proxy:"cwnd,omitempty"`
@@ -104,6 +107,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 +121,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 +151,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 +162,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 +209,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 +262,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 +301,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 +345,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 +427,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 +486,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 +503,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
+100 -81
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,46 +41,62 @@ 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"`
DataCiphers []string `proxy:"data-ciphers,omitempty"`
DataCipherFallback string `proxy:"data-ciphers-fallback,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"`
TLSAuth string `proxy:"tls-auth,omitempty"`
KeyDirection string `proxy:"key-direction,omitempty"`
TLSCrypt string `proxy:"tls-crypt,omitempty"`
TLSCryptV2 string `proxy:"tls-crypt-v2,omitempty"`
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
PeerInfo map[string]string `proxy:"peer-info,omitempty"`
Ping int `proxy:"ping,omitempty"`
PingRestart int `proxy:"ping-restart,omitempty"`
HandshakeTimeout int `proxy:"handshake-timeout,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
Dns []string `proxy:"dns,omitempty"`
}
func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
if option.HandshakeTimeout < 0 {
return nil, errors.New("openvpn handshake timeout must be non-negative")
}
cfg := &ovpn.ClientConfig{
RemoteHost: option.Server,
RemotePort: uint16(option.Port),
Proto: option.Proto,
Dev: option.Dev,
Cipher: option.Cipher,
Auth: option.Auth,
CompLZO: option.CompLZO,
CA: []byte(option.CA),
Cert: []byte(option.Cert),
Key: []byte(option.Key),
TLSCrypt: []byte(option.TLSCrypt),
Username: option.Username,
Password: option.Password,
PingInterval: time.Duration(option.Ping) * time.Second,
PingRestart: time.Duration(option.PingRestart) * time.Second,
RemoteHost: option.Server,
RemotePort: uint16(option.Port),
Proto: option.Proto,
Dev: option.Dev,
Cipher: option.Cipher,
DataCiphers: option.DataCiphers,
FallbackCipher: option.DataCipherFallback,
Auth: option.Auth,
CompLZO: option.CompLZO,
CA: []byte(option.CA),
Cert: []byte(option.Cert),
Key: []byte(option.Key),
TLSAuth: []byte(option.TLSAuth),
KeyDirection: option.KeyDirection,
TLSCrypt: []byte(option.TLSCrypt),
TLSCryptV2: []byte(option.TLSCryptV2),
Username: option.Username,
Password: option.Password,
PeerInfo: option.PeerInfo,
PingInterval: time.Duration(option.Ping) * time.Second,
PingRestart: time.Duration(option.PingRestart) * time.Second,
}
if err := cfg.Prepare(); err != nil {
return nil, err
@@ -137,7 +152,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 +173,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 +230,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 +257,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 +301,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 +312,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 +336,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
}
+16
View File
@@ -0,0 +1,16 @@
package outbound
import "github.com/metacubex/mihomo/transport/restls"
type RestlsOptions struct {
Password string `proxy:"password,omitempty"`
VersionHint string `proxy:"version-hint,omitempty"`
RestlsScript string `proxy:"restls-script,omitempty"`
}
func (o RestlsOptions) Parse(serverName, clientFingerprint string) (*restls.Config, error) {
if o.Password == "" && o.VersionHint == "" && o.RestlsScript == "" {
return nil, nil
}
return restls.NewRestlsConfig(serverName, o.Password, o.VersionHint, o.RestlsScript, clientFingerprint)
}
+193
View File
@@ -0,0 +1,193 @@
package outbound
import (
"context"
"net"
"strconv"
"time"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/ca"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/mihomo/transport/shadowquic"
"github.com/metacubex/mihomo/transport/tuic"
"github.com/metacubex/jls-quic-go"
"github.com/metacubex/jls-tls"
)
type ShadowQuic struct {
*Base
option *ShadowQuicOption
client *shadowquic.Client
quicConfig *quic.Config
tlsConfig *tls.Config
}
type ShadowQuicOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
SNI string `proxy:"sni,omitempty"`
ALPN []string `proxy:"alpn,omitempty"`
QUICVersions []string `proxy:"quic-versions,omitempty"`
UDPOverStream bool `proxy:"udp-over-stream,omitempty"`
ZeroRTT bool `proxy:"zero-rtt,omitempty"`
KeepAliveInterval int `proxy:"keep-alive-interval,omitempty"`
CongestionController string `proxy:"congestion-controller,omitempty"`
Up string `proxy:"up,omitempty"`
Down string `proxy:"down,omitempty"`
CWND int `proxy:"cwnd,omitempty"`
BBRProfile string `proxy:"bbr-profile,omitempty"`
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
ReceiveWindow int `proxy:"recv-window,omitempty"`
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
MaxDatagramFrameSize int `proxy:"max-datagram-frame-size,omitempty"`
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
}
func (s *ShadowQuic) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
conn, err := s.client.DialContext(ctx, metadata)
if err != nil {
return nil, err
}
return NewConn(conn, s), nil
}
func (s *ShadowQuic) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
if err := s.ResolveUDP(ctx, metadata); err != nil {
return nil, err
}
pc, err := s.client.ListenPacket(ctx, metadata)
if err != nil {
return nil, err
}
return NewPacketConn(pc, s), nil
}
func (s *ShadowQuic) Close() error {
if s.client != nil {
return s.client.Close()
}
return nil
}
func (s *ShadowQuic) ProxyInfo() C.ProxyInfo {
info := s.Base.ProxyInfo()
info.DialerProxy = s.option.DialerProxy
return info
}
func NewShadowQuic(option ShadowQuicOption) (*ShadowQuic, error) {
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
serverName := option.SNI
if serverName == "" {
serverName = option.Server
}
tlsConfig := &tls.Config{
ServerName: serverName,
MinVersion: tls.VersionTLS13,
Time: ntp.Now,
RootCAs: ca.GetCertPool(),
}
if option.ALPN != nil {
tlsConfig.NextProtos = option.ALPN
} else {
tlsConfig.NextProtos = []string{"h3"}
}
tlsConfig.JLSConfig = &tls.JLSConfig{
Enable: true,
User: tls.JLSUser{
Username: option.Username,
Password: option.Password,
},
}
if option.ZeroRTT {
// DialEarly can only send 0-RTT data after TLS has cached a session
// ticket from an earlier connection to this server.
tlsConfig.ClientSessionCache = tls.NewLRUClientSessionCache(1)
}
if option.MaxDatagramFrameSize == 0 {
option.MaxDatagramFrameSize = 1400
}
if option.MaxOpenStreams == 0 {
option.MaxOpenStreams = 1024
}
if option.CWND == 0 {
option.CWND = 32
}
quicVersions := shadowquic.DefaultQUICVersions()
if len(option.QUICVersions) > 0 {
parsedVersions, _, err := shadowquic.ParseQUICVersionProfile(option.QUICVersions)
if err != nil {
return nil, err
}
quicVersions = parsedVersions
}
quicConfig := &quic.Config{
Versions: quicVersions,
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
MaxIncomingStreams: int64(option.MaxOpenStreams),
MaxIncomingUniStreams: int64(option.MaxOpenStreams),
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
MaxDatagramFrameSize: int64(option.MaxDatagramFrameSize),
EnableDatagrams: true,
}
if option.KeepAliveInterval > 0 {
quicConfig.KeepAlivePeriod = time.Duration(option.KeepAliveInterval) * time.Millisecond
}
if option.ReceiveWindowConn == 0 {
quicConfig.InitialStreamReceiveWindow = tuic.DefaultStreamReceiveWindow / 10
quicConfig.MaxStreamReceiveWindow = tuic.DefaultStreamReceiveWindow
}
if option.ReceiveWindow == 0 {
quicConfig.InitialConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow / 10
quicConfig.MaxConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow
}
outbound := &ShadowQuic{
Base: NewBase(BaseOption{
Name: option.Name,
Addr: addr,
Type: C.ShadowQuic,
ProviderName: option.ProviderName,
UDP: true,
Interface: option.Interface,
RoutingMark: option.RoutingMark,
Prefer: option.IPVersion,
}),
option: &option,
quicConfig: quicConfig,
tlsConfig: tlsConfig,
}
outbound.dialer = option.NewDialer(outbound.DialOptions())
outbound.client = shadowquic.NewClient(&shadowquic.ClientOption{
UDPOverStream: option.UDPOverStream,
CongestionController: option.CongestionController,
SendBPS: utils.StringToBps(option.Up),
ReceiveBPS: utils.StringToBps(option.Down),
CWND: option.CWND,
BBRProfile: option.BBRProfile,
Dial: func(ctx context.Context) (*quic.Conn, error) {
_, quicConn, err := shadowquic.DialQuic(ctx, outbound.addr, outbound.DialOptions(), outbound.dialer, outbound.tlsConfig, outbound.quicConfig, option.ZeroRTT)
if err != nil {
return nil, err
}
return quicConn, nil
},
})
return outbound, nil
}
+56 -9
View File
@@ -11,10 +11,11 @@ import (
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/ntp"
gost "github.com/metacubex/mihomo/transport/gost"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/kcptun"
"github.com/metacubex/mihomo/transport/restls"
"github.com/metacubex/mihomo/transport/shadowtls"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
v2rayObfs "github.com/metacubex/mihomo/transport/v2ray-plugin"
shadowsocks "github.com/metacubex/sing-shadowsocks2"
@@ -35,6 +36,7 @@ type ShadowSocks struct {
gostOption *gost.Option
shadowTLSOption *shadowtls.ShadowTLSOption
restlsConfig *restls.Config
jlsConfig *jls.ClientConfig
kcptunClient *kcptun.Client
}
@@ -69,6 +71,7 @@ type v2rayObfsOption struct {
PrivateKey string `obfs:"private-key,omitempty"`
Headers map[string]string `obfs:"headers,omitempty"`
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
NameCertVerify string `obfs:"name-cert-verify,omitempty"`
Mux bool `obfs:"mux,omitempty"`
V2rayHttpUpgrade bool `obfs:"v2ray-http-upgrade,omitempty"`
V2rayHttpUpgradeFastOpen bool `obfs:"v2ray-http-upgrade-fast-open,omitempty"`
@@ -85,6 +88,7 @@ type gostObfsOption struct {
PrivateKey string `obfs:"private-key,omitempty"`
Headers map[string]string `obfs:"headers,omitempty"`
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
NameCertVerify string `obfs:"name-cert-verify,omitempty"`
Mux bool `obfs:"mux,omitempty"`
}
@@ -95,15 +99,27 @@ type shadowTLSOption struct {
Certificate string `obfs:"certificate,omitempty"`
PrivateKey string `obfs:"private-key,omitempty"`
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
NameCertVerify string `obfs:"name-cert-verify,omitempty"`
Version int `obfs:"version,omitempty"`
ALPN []string `obfs:"alpn,omitempty"`
}
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"`
NameCertVerify string `obfs:"name-cert-verify,omitempty"`
ForceTLS12 bool `obfs:"force-tls12,omitempty"` // for test
}
type jlsOption struct {
Host string `obfs:"host"`
Username string `obfs:"username"`
Password string `obfs:"password"`
ALPN []string `obfs:"alpn,omitempty"`
}
type kcpTunOption struct {
@@ -166,6 +182,12 @@ func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metada
return nil, fmt.Errorf("%s (restls) connect error: %w", ss.addr, err)
}
useEarly = true
case jls.Mode:
c, err = jls.NewClient(ctx, c, ss.jlsConfig)
if err != nil {
return nil, fmt.Errorf("%s (jls) connect error: %w", ss.addr, err)
}
useEarly = true
}
useEarly = useEarly || N.NeedHandshake(c)
if !useEarly {
@@ -240,9 +262,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 +276,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
@@ -291,6 +313,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
var obfsOption *simpleObfsOption
var shadowTLSOpt *shadowtls.ShadowTLSOption
var restlsConfig *restls.Config
var jlsConfig *jls.ClientConfig
var kcptunClient *kcptun.Client
obfsMode := ""
@@ -328,6 +351,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
if opts.TLS {
v2rayOption.TLS = true
v2rayOption.SkipCertVerify = opts.SkipCertVerify
v2rayOption.NameCertVerify = opts.NameCertVerify
v2rayOption.Fingerprint = opts.Fingerprint
v2rayOption.Certificate = opts.Certificate
v2rayOption.PrivateKey = opts.PrivateKey
@@ -358,6 +382,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
if opts.TLS {
gostOption.TLS = true
gostOption.SkipCertVerify = opts.SkipCertVerify
gostOption.NameCertVerify = opts.NameCertVerify
gostOption.Fingerprint = opts.Fingerprint
gostOption.Certificate = opts.Certificate
gostOption.PrivateKey = opts.PrivateKey
@@ -385,6 +410,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
PrivateKey: opt.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
SkipCertVerify: opt.SkipCertVerify,
NameCertVerify: opt.NameCertVerify,
Version: opt.Version,
}
@@ -404,7 +430,27 @@ 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, restlsOpt.NameCertVerify)
if err != nil {
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
}
} else if restlsOpt.NameCertVerify != "" {
restls.SetNameCertVerify(restlsConfig, restlsOpt.NameCertVerify)
}
restlsConfig.ForceTLS12 = restlsOpt.ForceTLS12
} else if option.Plugin == jls.Mode {
obfsMode = jls.Mode
jlsOpt := &jlsOption{}
if err := decoder.Decode(option.PluginOpts, jlsOpt); err != nil {
return nil, fmt.Errorf("ss %s initialize jls-plugin error: %w", addr, err)
}
jlsConfig, err = jls.NewClientConfig(jlsOpt.Host, jlsOpt.Username, jlsOpt.Password, jlsOpt.ALPN)
if err != nil {
return nil, fmt.Errorf("ss %s initialize jls-plugin error: %w", addr, err)
}
jlsConfig.ClientFingerprint = option.ClientFingerprint
} else if option.Plugin == kcptun.Mode {
obfsMode = kcptun.Mode
kcptunOpt := &kcpTunOption{}
@@ -471,6 +517,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
obfsOption: obfsOption,
shadowTLSOption: shadowTLSOpt,
restlsConfig: restlsConfig,
jlsConfig: jlsConfig,
kcptunClient: kcptunClient,
}
outbound.dialer = option.NewDialer(outbound.DialOptions())
+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) {
+15
View File
@@ -0,0 +1,15 @@
package outbound
import "github.com/metacubex/mihomo/transport/shadowtls"
type ShadowTLSOptions struct {
Password string `proxy:"password,omitempty"`
Version int `proxy:"version,omitempty"`
}
func (o ShadowTLSOptions) Parse() (*shadowtls.Config, error) {
if o.Password == "" && o.Version == 0 {
return nil, nil
}
return shadowtls.NewConfig(o.Password, o.Version)
}
+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 {
+121 -36
View File
@@ -9,54 +9,73 @@ import (
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/structure"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/restls"
"github.com/metacubex/mihomo/transport/shadowtls"
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
"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
restlsConfig *restls.Config
jlsConfig *jls.ClientConfig
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
}
case restls.Mode:
c, err = restls.NewRestls(ctx, c, s.restlsConfig)
if err != nil {
return nil, err
}
case jls.Mode:
c, err = jls.NewClient(ctx, c, s.jlsConfig)
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 +110,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 +149,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 +174,69 @@ func NewSnell(option SnellOption) (*Snell, error) {
return nil, fmt.Errorf("snell %s initialize obfs error: %w", addr, err)
}
var shadowTLSOpt *shadowtls.ShadowTLSOption
var restlsConfig *restls.Config
var jlsConfig *jls.ClientConfig
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,
NameCertVerify: opt.NameCertVerify,
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
}
case restls.Mode:
opt := &restlsOption{}
if err := decoder.Decode(option.ObfsOpts, opt); err != nil {
return nil, fmt.Errorf("snell %s initialize restls-plugin error: %w", addr, err)
}
var err error
restlsConfig, err = restls.NewRestlsConfig(opt.Host, opt.Password, opt.VersionHint, opt.RestlsScript, option.ClientFingerprint)
if err != nil {
return nil, fmt.Errorf("snell %s initialize restls-plugin error: %w", addr, err)
}
restlsConfig.InsecureSkipVerify = opt.SkipCertVerify
if opt.Fingerprint != "" {
if err = restls.SetFingerprint(restlsConfig, opt.Fingerprint, opt.NameCertVerify); err != nil {
return nil, fmt.Errorf("snell %s initialize restls-plugin error: %w", addr, err)
}
} else if opt.NameCertVerify != "" {
restls.SetNameCertVerify(restlsConfig, opt.NameCertVerify)
}
restlsConfig.ForceTLS12 = opt.ForceTLS12
case jls.Mode:
opt := &jlsOption{}
if err := decoder.Decode(option.ObfsOpts, opt); err != nil {
return nil, fmt.Errorf("snell %s initialize jls-plugin error: %w", addr, err)
}
var err error
jlsConfig, err = jls.NewClientConfig(opt.Host, opt.Username, opt.Password, opt.ALPN)
if err != nil {
return nil, fmt.Errorf("snell %s initialize jls-plugin error: %w", addr, err)
}
jlsConfig.ClientFingerprint = option.ClientFingerprint
default:
return nil, fmt.Errorf("snell %s obfs mode error: %s", addr, obfsOption.Mode)
}
@@ -191,11 +273,14 @@ 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,
restlsConfig: restlsConfig,
jlsConfig: jlsConfig,
version: option.Version,
reuse: reuse,
}
s.dialer = option.NewDialer(s.DialOptions())
@@ -206,7 +291,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
+11 -5
View File
@@ -37,6 +37,7 @@ type Socks5Option struct {
TLS bool `proxy:"tls,omitempty"`
UDP bool `proxy:"udp,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -151,7 +152,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
@@ -178,9 +179,10 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
InsecureSkipVerify: option.SkipCertVerify,
ServerName: option.Server,
},
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
Fingerprint: option.Fingerprint,
NameCertVerify: option.NameCertVerify,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
})
if err != nil {
return nil, err
@@ -222,7 +224,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) {
+33 -88
View File
@@ -19,8 +19,7 @@ type Sudoku struct {
option *SudokuOption
baseConf sudoku.ProtocolConfig
muxMu sync.Mutex
muxClient *sudoku.MultiplexClient
muxDialer *sudoku.MultiplexDialer
httpMaskMu sync.Mutex
httpMaskClient *httpmask.TunnelClient
@@ -43,7 +42,8 @@ type SudokuOption struct {
HTTPMaskTLS bool `proxy:"http-mask-tls,omitempty"` // only for http-mask-mode stream/poll/auto
HTTPMaskHost string `proxy:"http-mask-host,omitempty"` // optional Host/SNI override (domain or domain:port)
PathRoot string `proxy:"path-root,omitempty"` // optional first-level path prefix for HTTP tunnel endpoints
HTTPMaskMultiplex string `proxy:"http-mask-multiplex,omitempty"` // "off" (default), "auto" (reuse h1/h2), "on" (single tunnel, multi-target)
Multiplex string `proxy:"multiplex,omitempty"` // "off" (default), "auto" (HTTP reuse), "on" (session mux over raw TCP or HTTPMask)
HTTPMaskMultiplex string `proxy:"http-mask-multiplex,omitempty"` // legacy flat alias for multiplex
HTTPMaskOptions *SudokuHTTPMaskOptions `proxy:"httpmask,omitempty"`
CustomTable string `proxy:"custom-table,omitempty"` // optional custom byte layout, e.g. xpxvvpvv
CustomTables []string `proxy:"custom-tables,omitempty"` // optional table rotation patterns, overrides custom-table when non-empty
@@ -65,8 +65,7 @@ func (s *Sudoku) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Con
return nil, err
}
muxMode := normalizeHTTPMaskMultiplex(cfg.HTTPMaskMultiplex)
if muxMode == "on" {
if cfg.SessionMuxEnabled() {
stream, muxErr := s.dialMultiplex(ctx, cfg.TargetAddress)
if muxErr == nil {
return NewConn(stream, s), nil
@@ -113,7 +112,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
@@ -172,9 +171,12 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
httpMaskTLS := option.HTTPMaskTLS
httpMaskHost := option.HTTPMaskHost
pathRoot := strings.TrimSpace(option.PathRoot)
httpMaskMultiplex := defaultConf.HTTPMaskMultiplex
if option.HTTPMaskMultiplex != "" {
httpMaskMultiplex = option.HTTPMaskMultiplex
multiplex := defaultConf.Multiplex
if mode := strings.TrimSpace(option.Multiplex); mode != "" {
multiplex = mode
}
if mode := strings.TrimSpace(option.HTTPMaskMultiplex); mode != "" {
multiplex = mode
}
if hm := option.HTTPMaskOptions; hm != nil {
@@ -188,9 +190,7 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
pathRoot = pr
}
if mux := strings.TrimSpace(hm.Multiplex); mux != "" {
httpMaskMultiplex = mux
} else {
httpMaskMultiplex = defaultConf.HTTPMaskMultiplex
multiplex = mux
}
}
@@ -207,7 +207,7 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
HTTPMaskTLSEnabled: httpMaskTLS,
HTTPMaskHost: httpMaskHost,
HTTPMaskPathRoot: pathRoot,
HTTPMaskMultiplex: httpMaskMultiplex,
Multiplex: multiplex,
}
tables, err := sudoku.NewClientTablesWithCustomPatterns(sudoku.ClientAEADSeed(option.Key), tableType, option.CustomTable, option.CustomTables)
if err != nil {
@@ -221,6 +221,9 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
if option.AEADMethod != "" {
baseConf.AEADMethod = option.AEADMethod
}
if err := baseConf.Validate(); err != nil {
return nil, err
}
outbound := &Sudoku{
Base: NewBase(BaseOption{
@@ -239,28 +242,26 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
baseConf: baseConf,
}
outbound.dialer = option.NewDialer(outbound.DialOptions())
if baseConf.SessionMuxEnabled() {
outbound.muxDialer, err = sudoku.NewMultiplexDialer(func(ctx context.Context) (net.Conn, error) {
cfg := outbound.baseConf
return outbound.dialAndHandshake(ctx, &cfg)
})
if err != nil {
return nil, err
}
}
return outbound, nil
}
func (s *Sudoku) Close() error {
s.resetMuxClient()
if s.muxDialer != nil {
_ = s.muxDialer.Close()
}
s.resetHTTPMaskClient()
return s.Base.Close()
}
func normalizeHTTPMaskMultiplex(mode string) string {
switch strings.ToLower(strings.TrimSpace(mode)) {
case "", "off":
return "off"
case "auto":
return "auto"
case "on":
return "on"
default:
return "off"
}
}
func httpTunnelModeEnabled(mode string) bool {
switch strings.ToLower(strings.TrimSpace(mode)) {
case "stream", "poll", "auto", "ws":
@@ -289,7 +290,7 @@ func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfi
handshakeDone bool
)
if !cfg.DisableHTTPMask && httpTunnelModeEnabled(cfg.HTTPMaskMode) {
muxMode := normalizeHTTPMaskMultiplex(cfg.HTTPMaskMultiplex)
muxMode := cfg.MultiplexMode()
if muxMode == "auto" && strings.ToLower(strings.TrimSpace(cfg.HTTPMaskMode)) != "ws" {
if client, cerr := s.getOrCreateHTTPMaskClient(cfg); cerr == nil && client != nil {
c, err = client.DialTunnel(ctx, httpmask.TunnelDialOptions{
@@ -299,7 +300,7 @@ func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfi
PathRoot: cfg.HTTPMaskPathRoot,
AuthKey: sudoku.ClientAEADSeed(cfg.Key),
Upgrade: upgrade,
Multiplex: cfg.HTTPMaskMultiplex,
Multiplex: muxMode,
DialContext: s.dialer.DialContext,
})
if err != nil {
@@ -339,66 +340,10 @@ func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfi
}
func (s *Sudoku) dialMultiplex(ctx context.Context, targetAddress string) (net.Conn, error) {
for attempt := 0; attempt < 2; attempt++ {
client, err := s.getOrCreateMuxClient(ctx)
if err != nil {
return nil, err
}
stream, err := client.Dial(ctx, targetAddress)
if err != nil {
s.resetMuxClient()
continue
}
return stream, nil
}
return nil, fmt.Errorf("multiplex open stream failed")
}
func (s *Sudoku) getOrCreateMuxClient(ctx context.Context) (*sudoku.MultiplexClient, error) {
if s == nil {
return nil, fmt.Errorf("nil adapter")
}
s.muxMu.Lock()
if s.muxClient != nil && !s.muxClient.IsClosed() {
client := s.muxClient
s.muxMu.Unlock()
return client, nil
}
s.muxMu.Unlock()
s.muxMu.Lock()
defer s.muxMu.Unlock()
if s.muxClient != nil && !s.muxClient.IsClosed() {
return s.muxClient, nil
}
baseCfg := s.baseConf
baseConn, err := s.dialAndHandshake(ctx, &baseCfg)
if err != nil {
return nil, err
}
client, err := sudoku.StartMultiplexClient(baseConn)
if err != nil {
_ = baseConn.Close()
return nil, err
}
s.muxClient = client
return client, nil
}
func (s *Sudoku) resetMuxClient() {
s.muxMu.Lock()
defer s.muxMu.Unlock()
if s.muxClient != nil {
_ = s.muxClient.Close()
s.muxClient = nil
if s == nil || s.muxDialer == nil {
return nil, fmt.Errorf("multiplex dialer is unavailable")
}
return s.muxDialer.Dial(ctx, targetAddress)
}
func (s *Sudoku) resetHTTPMaskClient() {
+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(),
}
}
+105 -39
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"net"
"strconv"
"strings"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/component/ca"
@@ -13,7 +14,10 @@ import (
tlsC "github.com/metacubex/mihomo/component/tls"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/gun"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/restls"
"github.com/metacubex/mihomo/transport/shadowsocks/core"
"github.com/metacubex/mihomo/transport/shadowtls"
"github.com/metacubex/mihomo/transport/trojan"
"github.com/metacubex/mihomo/transport/vmess"
@@ -29,32 +33,39 @@ type Trojan struct {
// for gun mux
gunClient *gun.Client
realityConfig *tlsC.RealityConfig
echConfig *ech.Config
echConfig *ech.Config
shadowTLSConfig *shadowtls.Config
restlsConfig *restls.Config
jlsConfig *jls.Config
realityConfig *tlsC.RealityConfig
ssCipher core.Cipher
}
type TrojanOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Password string `proxy:"password"`
ALPN []string `proxy:"alpn,omitempty"`
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
UDP bool `proxy:"udp,omitempty"`
Network string `proxy:"network,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
SSOpts TrojanSSOption `proxy:"ss-opts,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Password string `proxy:"password"`
ALPN []string `proxy:"alpn,omitempty"`
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
UDP bool `proxy:"udp,omitempty"`
Network string `proxy:"network,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
ShadowTLSOpts ShadowTLSOptions `proxy:"shadow-tls-opts,omitempty"`
RestlsOpts RestlsOptions `proxy:"restls-opts,omitempty"`
JLSOpts JLSOptions `proxy:"jls-opts,omitempty"`
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
SSOpts TrojanSSOption `proxy:"ss-opts,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
}
// TrojanSSOption from https://github.com/p4gefau1t/trojan-go/blob/v0.10.6/tunnel/shadowsocks/config.go#L5
@@ -97,20 +108,40 @@ func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.
alpn = t.option.ALPN
}
wsOpts.TLS = true
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
TLSConfig: &tls.Config{
NextProtos: alpn,
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: t.option.SkipCertVerify,
ServerName: t.option.SNI,
},
Fingerprint: t.option.Fingerprint,
Certificate: t.option.Certificate,
PrivateKey: t.option.PrivateKey,
})
if err != nil {
return nil, err
if t.shadowTLSConfig != nil || t.restlsConfig != nil || t.jlsConfig != nil {
c, err = vmess.StreamTLSConn(ctx, c, &vmess.TLSConfig{
Host: t.option.SNI,
SkipCertVerify: t.option.SkipCertVerify,
NameCertVerify: t.option.NameCertVerify,
FingerPrint: t.option.Fingerprint,
Certificate: t.option.Certificate,
PrivateKey: t.option.PrivateKey,
ClientFingerprint: t.option.ClientFingerprint,
NextProtos: []string{"http/1.1"},
ShadowTLS: t.shadowTLSConfig,
Restls: t.restlsConfig,
JLS: t.jlsConfig,
})
if err != nil {
return nil, err
}
} else {
wsOpts.TLS = true
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
TLSConfig: &tls.Config{
NextProtos: alpn,
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: t.option.SkipCertVerify,
ServerName: t.option.SNI,
},
Fingerprint: t.option.Fingerprint,
NameCertVerify: t.option.NameCertVerify,
Certificate: t.option.Certificate,
PrivateKey: t.option.PrivateKey,
})
if err != nil {
return nil, err
}
}
c, err = vmess.StreamWebsocketConn(ctx, c, wsOpts)
@@ -126,12 +157,16 @@ func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.
c, err = vmess.StreamTLSConn(ctx, c, &vmess.TLSConfig{
Host: t.option.SNI,
SkipCertVerify: t.option.SkipCertVerify,
NameCertVerify: t.option.NameCertVerify,
FingerPrint: t.option.Fingerprint,
Certificate: t.option.Certificate,
PrivateKey: t.option.PrivateKey,
ClientFingerprint: t.option.ClientFingerprint,
NextProtos: alpn,
ECH: t.echConfig,
ShadowTLS: t.shadowTLSConfig,
Restls: t.restlsConfig,
JLS: t.jlsConfig,
Reality: t.realityConfig,
})
}
@@ -219,7 +254,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
@@ -271,14 +306,41 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
t.dialer = option.NewDialer(t.DialOptions())
var err error
t.echConfig, err = option.ECHOpts.Parse()
if err != nil {
return nil, err
}
t.shadowTLSConfig, err = option.ShadowTLSOpts.Parse()
if err != nil {
return nil, err
}
t.restlsConfig, err = option.RestlsOpts.Parse(option.SNI, option.ClientFingerprint)
if err != nil {
return nil, err
}
t.jlsConfig, err = option.JLSOpts.Parse()
if err != nil {
return nil, err
}
t.realityConfig, err = option.RealityOpts.Parse()
if err != nil {
return nil, err
}
t.echConfig, err = option.ECHOpts.Parse()
if err != nil {
return nil, err
securityModes := make([]string, 0, 4)
if t.shadowTLSConfig != nil {
securityModes = append(securityModes, "ShadowTLS")
}
if t.restlsConfig != nil {
securityModes = append(securityModes, "Restls")
}
if t.jlsConfig != nil {
securityModes = append(securityModes, "JLS")
}
if t.realityConfig != nil {
securityModes = append(securityModes, "REALITY")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
if option.SSOpts.Enabled {
@@ -307,12 +369,16 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
tlsConfig := &vmess.TLSConfig{
Host: option.SNI,
SkipCertVerify: option.SkipCertVerify,
NameCertVerify: option.NameCertVerify,
FingerPrint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
NextProtos: []string{"h2"},
ECH: t.echConfig,
ShadowTLS: t.shadowTLSConfig,
Restls: t.restlsConfig,
JLS: t.jlsConfig,
Reality: t.realityConfig,
}
+3 -1
View File
@@ -29,6 +29,7 @@ type TrustTunnelOption struct {
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -63,7 +64,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
@@ -124,6 +125,7 @@ func NewTrustTunnel(option TrustTunnelOption) (*TrustTunnel, error) {
tlsConfig := &vmess.TLSConfig{
Host: option.SNI,
SkipCertVerify: option.SkipCertVerify,
NameCertVerify: option.NameCertVerify,
NextProtos: option.ALPN,
FingerPrint: option.Fingerprint,
Certificate: option.Certificate,
+8 -6
View File
@@ -54,6 +54,7 @@ type TuicOption struct {
CWND int `proxy:"cwnd,omitempty"`
BBRProfile string `proxy:"bbr-profile,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -97,16 +98,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) {
@@ -138,9 +139,10 @@ func NewTuic(option TuicOption) (*Tuic, error) {
InsecureSkipVerify: option.SkipCertVerify,
MinVersion: tls.VersionTLS13,
},
Fingerprint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
Fingerprint: option.Fingerprint,
NameCertVerify: option.NameCertVerify,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
})
if err != nil {
return nil, err
+181 -48
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/metacubex/mihomo/common/convert"
@@ -16,6 +17,9 @@ import (
tlsC "github.com/metacubex/mihomo/component/tls"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/gun"
"github.com/metacubex/mihomo/transport/jls"
"github.com/metacubex/mihomo/transport/restls"
"github.com/metacubex/mihomo/transport/shadowtls"
"github.com/metacubex/mihomo/transport/tuic/common"
"github.com/metacubex/mihomo/transport/vless"
"github.com/metacubex/mihomo/transport/vless/encryption"
@@ -43,8 +47,11 @@ type Vless struct {
// for xhttp
xhttpClient *xhttp.Client
realityConfig *tlsC.RealityConfig
echConfig *ech.Config
echConfig *ech.Config
shadowTLSConfig *shadowtls.Config
restlsConfig *restls.Config
jlsConfig *jls.Config
realityConfig *tlsC.RealityConfig
}
type VlessOption struct {
@@ -63,6 +70,9 @@ type VlessOption struct {
Encryption string `proxy:"encryption,omitempty"`
Network string `proxy:"network,omitempty"`
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
ShadowTLSOpts ShadowTLSOptions `proxy:"shadow-tls-opts,omitempty"`
RestlsOpts RestlsOptions `proxy:"restls-opts,omitempty"`
JLSOpts JLSOptions `proxy:"jls-opts,omitempty"`
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
@@ -71,6 +81,7 @@ type VlessOption struct {
XHTTPOpts XHTTPOptions `proxy:"xhttp-opts,omitempty"`
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
@@ -93,6 +104,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"`
@@ -120,18 +133,22 @@ type XHTTPDownloadSettings struct {
Headers *map[string]string `proxy:"headers,omitempty"`
ReuseSettings *XHTTPReuseSettings `proxy:"reuse-settings,omitempty"` // aka XMUX
// proxy part
Server *string `proxy:"server,omitempty"`
Port *int `proxy:"port,omitempty"`
TLS *bool `proxy:"tls,omitempty"`
ALPN *[]string `proxy:"alpn,omitempty"`
ECHOpts *ECHOptions `proxy:"ech-opts,omitempty"`
RealityOpts *RealityOptions `proxy:"reality-opts,omitempty"`
SkipCertVerify *bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint *string `proxy:"fingerprint,omitempty"`
Certificate *string `proxy:"certificate,omitempty"`
PrivateKey *string `proxy:"private-key,omitempty"`
ServerName *string `proxy:"servername,omitempty"`
ClientFingerprint *string `proxy:"client-fingerprint,omitempty"`
Server *string `proxy:"server,omitempty"`
Port *int `proxy:"port,omitempty"`
TLS *bool `proxy:"tls,omitempty"`
ALPN *[]string `proxy:"alpn,omitempty"`
ECHOpts *ECHOptions `proxy:"ech-opts,omitempty"`
ShadowTLSOpts *ShadowTLSOptions `proxy:"shadow-tls-opts,omitempty"`
RestlsOpts *RestlsOptions `proxy:"restls-opts,omitempty"`
JLSOpts *JLSOptions `proxy:"jls-opts,omitempty"`
RealityOpts *RealityOptions `proxy:"reality-opts,omitempty"`
SkipCertVerify *bool `proxy:"skip-cert-verify,omitempty"`
NameCertVerify *string `proxy:"name-cert-verify,omitempty"`
Fingerprint *string `proxy:"fingerprint,omitempty"`
Certificate *string `proxy:"certificate,omitempty"`
PrivateKey *string `proxy:"private-key,omitempty"`
ServerName *string `proxy:"servername,omitempty"`
ClientFingerprint *string `proxy:"client-fingerprint,omitempty"`
}
func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) {
@@ -157,25 +174,46 @@ func (v *Vless) 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
serverName := host
if v.option.ServerName != "" {
serverName = v.option.ServerName
} else if host := wsOpts.Headers.Get("Host"); host != "" {
serverName = host
}
if v.option.ServerName != "" {
wsOpts.TLSConfig.ServerName = v.option.ServerName
} else if host := wsOpts.Headers.Get("Host"); host != "" {
wsOpts.TLSConfig.ServerName = host
if v.shadowTLSConfig != nil || v.restlsConfig != nil || v.jlsConfig != nil {
c, err = vmess.StreamTLSConn(ctx, c, &vmess.TLSConfig{
Host: serverName,
SkipCertVerify: v.option.SkipCertVerify,
NameCertVerify: v.option.NameCertVerify,
FingerPrint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
ClientFingerprint: v.option.ClientFingerprint,
NextProtos: []string{"http/1.1"},
ShadowTLS: v.shadowTLSConfig,
Restls: v.restlsConfig,
JLS: v.jlsConfig,
})
if err != nil {
return nil, err
}
} else {
wsOpts.TLS = true
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
TLSConfig: &tls.Config{
ServerName: serverName,
InsecureSkipVerify: v.option.SkipCertVerify,
NextProtos: []string{"http/1.1"},
},
Fingerprint: v.option.Fingerprint,
NameCertVerify: v.option.NameCertVerify,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
})
if err != nil {
return nil, err
}
}
} else {
if host := wsOpts.Headers.Get("Host"); host == "" {
@@ -271,11 +309,15 @@ func (v *Vless) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (ne
tlsOpts := vmess.TLSConfig{
Host: host,
SkipCertVerify: v.option.SkipCertVerify,
NameCertVerify: v.option.NameCertVerify,
FingerPrint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
ClientFingerprint: v.option.ClientFingerprint,
ECH: v.echConfig,
ShadowTLS: v.shadowTLSConfig,
Restls: v.restlsConfig,
JLS: v.jlsConfig,
Reality: v.realityConfig,
NextProtos: v.option.ALPN,
}
@@ -346,18 +388,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
@@ -470,14 +512,48 @@ func NewVless(option VlessOption) (*Vless, error) {
return nil, err
}
v.echConfig, err = v.option.ECHOpts.Parse()
if err != nil {
return nil, err
}
v.shadowTLSConfig, err = option.ShadowTLSOpts.Parse()
if err != nil {
return nil, err
}
v.restlsConfig, err = option.RestlsOpts.Parse(option.ServerName, option.ClientFingerprint)
if err != nil {
return nil, err
}
v.jlsConfig, err = option.JLSOpts.Parse()
if err != nil {
return nil, err
}
v.realityConfig, err = v.option.RealityOpts.Parse()
if err != nil {
return nil, err
}
v.echConfig, err = v.option.ECHOpts.Parse()
if err != nil {
return nil, err
securityModes := make([]string, 0, 4)
if v.shadowTLSConfig != nil {
securityModes = append(securityModes, "ShadowTLS")
}
if v.restlsConfig != nil {
securityModes = append(securityModes, "Restls")
}
if v.jlsConfig != nil {
securityModes = append(securityModes, "JLS")
}
if v.realityConfig != nil {
securityModes = append(securityModes, "REALITY")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
securityMode := ""
if len(securityModes) == 1 {
securityMode = securityModes[0]
}
if securityMode != "" && !option.TLS {
return nil, fmt.Errorf("%s requires TLS", securityMode)
}
switch option.Network {
@@ -508,12 +584,16 @@ func NewVless(option VlessOption) (*Vless, error) {
tlsConfig = &vmess.TLSConfig{
Host: option.ServerName,
SkipCertVerify: option.SkipCertVerify,
NameCertVerify: option.NameCertVerify,
FingerPrint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
NextProtos: []string{"h2"},
ECH: v.echConfig,
ShadowTLS: v.shadowTLSConfig,
Restls: v.restlsConfig,
JLS: v.jlsConfig,
Reality: v.realityConfig,
}
if option.ServerName == "" {
@@ -569,6 +649,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,
@@ -592,6 +674,7 @@ func NewVless(option VlessOption) (*Vless, error) {
tlsOpts := &vmess.TLSConfig{
Host: host,
SkipCertVerify: v.option.SkipCertVerify,
NameCertVerify: v.option.NameCertVerify,
FingerPrint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
@@ -606,8 +689,8 @@ func NewVless(option VlessOption) (*Vless, error) {
if !v.option.TLS {
return nil, errors.New("xhttp HTTP/3 requires TLS")
}
if v.realityConfig != nil {
return nil, errors.New("xhttp HTTP/3 does not support reality")
if securityMode != "" {
return nil, fmt.Errorf("xhttp HTTP/3 does not support %s", securityMode)
}
tlsConfig, err := tlsOpts.ToStdConfig()
if err != nil {
@@ -639,6 +722,13 @@ func NewVless(option VlessOption) (*Vless, error) {
downloadPort := lo.FromPtrOr(ds.Port, v.option.Port)
downloadTLS := lo.FromPtrOr(ds.TLS, v.option.TLS)
downloadALPN := lo.FromPtrOr(ds.ALPN, v.option.ALPN)
downloadSkipCertVerify := lo.FromPtrOr(ds.SkipCertVerify, v.option.SkipCertVerify)
downloadNameCertVerify := lo.FromPtrOr(ds.NameCertVerify, v.option.NameCertVerify)
downloadFingerprint := lo.FromPtrOr(ds.Fingerprint, v.option.Fingerprint)
downloadCertificate := lo.FromPtrOr(ds.Certificate, v.option.Certificate)
downloadPrivateKey := lo.FromPtrOr(ds.PrivateKey, v.option.PrivateKey)
downloadServerName := lo.FromPtrOr(ds.ServerName, v.option.ServerName)
downloadClientFingerprint := lo.FromPtrOr(ds.ClientFingerprint, v.option.ClientFingerprint)
downloadEchConfig := v.echConfig
if ds.ECHOpts != nil {
downloadEchConfig, err = ds.ECHOpts.Parse()
@@ -646,6 +736,27 @@ func NewVless(option VlessOption) (*Vless, error) {
return nil, err
}
}
downloadShadowTLSConfig := v.shadowTLSConfig
if ds.ShadowTLSOpts != nil {
downloadShadowTLSConfig, err = ds.ShadowTLSOpts.Parse()
if err != nil {
return nil, err
}
}
downloadRestlsConfig := v.restlsConfig
if ds.RestlsOpts != nil {
downloadRestlsConfig, err = ds.RestlsOpts.Parse(downloadServerName, downloadClientFingerprint)
if err != nil {
return nil, err
}
}
downloadJLSConfig := v.jlsConfig
if ds.JLSOpts != nil {
downloadJLSConfig, err = ds.JLSOpts.Parse()
if err != nil {
return nil, err
}
}
downloadRealityCfg := v.realityConfig
if ds.RealityOpts != nil {
downloadRealityCfg, err = ds.RealityOpts.Parse()
@@ -653,12 +764,29 @@ func NewVless(option VlessOption) (*Vless, error) {
return nil, err
}
}
downloadSkipCertVerify := lo.FromPtrOr(ds.SkipCertVerify, v.option.SkipCertVerify)
downloadFingerprint := lo.FromPtrOr(ds.Fingerprint, v.option.Fingerprint)
downloadCertificate := lo.FromPtrOr(ds.Certificate, v.option.Certificate)
downloadPrivateKey := lo.FromPtrOr(ds.PrivateKey, v.option.PrivateKey)
downloadServerName := lo.FromPtrOr(ds.ServerName, v.option.ServerName)
downloadClientFingerprint := lo.FromPtrOr(ds.ClientFingerprint, v.option.ClientFingerprint)
downloadSecurityModes := make([]string, 0, 4)
if downloadShadowTLSConfig != nil {
downloadSecurityModes = append(downloadSecurityModes, "ShadowTLS")
}
if downloadRestlsConfig != nil {
downloadSecurityModes = append(downloadSecurityModes, "Restls")
}
if downloadJLSConfig != nil {
downloadSecurityModes = append(downloadSecurityModes, "JLS")
}
if downloadRealityCfg != nil {
downloadSecurityModes = append(downloadSecurityModes, "REALITY")
}
if len(downloadSecurityModes) > 1 {
return nil, errors.New("xhttp download-settings security modes are mutually exclusive: " + strings.Join(downloadSecurityModes, ", "))
}
downloadSecurityMode := ""
if len(downloadSecurityModes) == 1 {
downloadSecurityMode = downloadSecurityModes[0]
}
if downloadSecurityMode != "" && !downloadTLS {
return nil, fmt.Errorf("xhttp download-settings: %s requires TLS", downloadSecurityMode)
}
downloadAddr := net.JoinHostPort(downloadServer, strconv.Itoa(downloadPort))
@@ -703,11 +831,15 @@ func NewVless(option VlessOption) (*Vless, error) {
tlsOpts := vmess.TLSConfig{
Host: host,
SkipCertVerify: downloadSkipCertVerify,
NameCertVerify: downloadNameCertVerify,
FingerPrint: downloadFingerprint,
Certificate: downloadCertificate,
PrivateKey: downloadPrivateKey,
ClientFingerprint: downloadClientFingerprint,
ECH: downloadEchConfig,
ShadowTLS: downloadShadowTLSConfig,
Restls: downloadRestlsConfig,
JLS: downloadJLSConfig,
Reality: downloadRealityCfg,
NextProtos: downloadALPN,
}
@@ -730,6 +862,7 @@ func NewVless(option VlessOption) (*Vless, error) {
tlsOpts := &vmess.TLSConfig{
Host: host,
SkipCertVerify: downloadSkipCertVerify,
NameCertVerify: downloadNameCertVerify,
FingerPrint: downloadFingerprint,
Certificate: downloadCertificate,
PrivateKey: downloadPrivateKey,
@@ -744,8 +877,8 @@ func NewVless(option VlessOption) (*Vless, error) {
if !downloadTLS {
return nil, errors.New("xhttp HTTP/3 requires TLS")
}
if downloadRealityCfg != nil {
return nil, errors.New("xhttp HTTP/3 does not support reality")
if downloadSecurityMode != "" {
return nil, fmt.Errorf("xhttp HTTP/3 does not support %s", downloadSecurityMode)
}
tlsConfig, err := tlsOpts.ToStdConfig()
if err != nil {
+243 -53
View File
@@ -13,10 +13,16 @@ 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/jls"
"github.com/metacubex/mihomo/transport/mekya"
"github.com/metacubex/mihomo/transport/mkcp"
"github.com/metacubex/mihomo/transport/restls"
"github.com/metacubex/mihomo/transport/shadowtls"
mihomoVMess "github.com/metacubex/mihomo/transport/vmess"
"github.com/metacubex/http"
@@ -34,41 +40,106 @@ type Vmess struct {
option *VmessOption
// for gun mux
gunClient *gun.Client
gunClient *gun.Client
mekyaClient *mekya.Client
realityConfig *tlsC.RealityConfig
echConfig *ech.Config
echConfig *ech.Config
shadowTLSConfig *shadowtls.Config
restlsConfig *restls.Config
jlsConfig *jls.Config
realityConfig *tlsC.RealityConfig
}
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"`
NameCertVerify string `proxy:"name-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"`
ShadowTLSOpts ShadowTLSOptions `proxy:"shadow-tls-opts,omitempty"`
RestlsOpts RestlsOptions `proxy:"restls-opts,omitempty"`
JLSOpts JLSOptions `proxy:"jls-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 +195,51 @@ 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
serverName := host
if v.option.ServerName != "" {
serverName = v.option.ServerName
} else if host := wsOpts.Headers.Get("Host"); host != "" {
serverName = host
}
if v.option.ServerName != "" {
wsOpts.TLSConfig.ServerName = v.option.ServerName
} else if host := wsOpts.Headers.Get("Host"); host != "" {
wsOpts.TLSConfig.ServerName = host
if v.shadowTLSConfig != nil || v.restlsConfig != nil || v.jlsConfig != nil {
c, err = mihomoVMess.StreamTLSConn(ctx, c, &mihomoVMess.TLSConfig{
Host: serverName,
SkipCertVerify: v.option.SkipCertVerify,
NameCertVerify: v.option.NameCertVerify,
FingerPrint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
ClientFingerprint: v.option.ClientFingerprint,
NextProtos: []string{"http/1.1"},
ShadowTLS: v.shadowTLSConfig,
Restls: v.restlsConfig,
JLS: v.jlsConfig,
})
if err != nil {
return nil, err
}
} else 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: serverName,
InsecureSkipVerify: v.option.SkipCertVerify,
NextProtos: []string{"http/1.1"},
},
Fingerprint: v.option.Fingerprint,
NameCertVerify: v.option.NameCertVerify,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
})
if err != nil {
return nil, err
}
}
}
c, err = mihomoVMess.StreamWebsocketConn(ctx, c, wsOpts)
@@ -176,6 +273,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
@@ -251,13 +350,19 @@ func (v *Vmess) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (ne
tlsOpts := mihomoVMess.TLSConfig{
Host: host,
SkipCertVerify: v.option.SkipCertVerify,
NameCertVerify: v.option.NameCertVerify,
FingerPrint: v.option.Fingerprint,
Certificate: v.option.Certificate,
PrivateKey: v.option.PrivateKey,
ClientFingerprint: v.option.ClientFingerprint,
ECH: v.echConfig,
ShadowTLS: v.shadowTLSConfig,
Restls: v.restlsConfig,
JLS: v.jlsConfig,
Reality: v.realityConfig,
NextProtos: v.option.ALPN,
TLSMirror: v.option.TLSMirrorOpts.Build(),
TLSMirrorDialer: proxydialer.New(v, false).DialContext,
}
if isH2 {
@@ -278,6 +383,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 +433,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 +453,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...)
}
@@ -392,14 +510,57 @@ func NewVmess(option VmessOption) (*Vmess, error) {
}
v.dialer = option.NewDialer(v.DialOptions())
v.echConfig, err = v.option.ECHOpts.Parse()
if err != nil {
return nil, err
}
v.shadowTLSConfig, err = option.ShadowTLSOpts.Parse()
if err != nil {
return nil, err
}
v.restlsConfig, err = option.RestlsOpts.Parse(option.ServerName, option.ClientFingerprint)
if err != nil {
return nil, err
}
v.jlsConfig, err = option.JLSOpts.Parse()
if err != nil {
return nil, err
}
v.realityConfig, err = v.option.RealityOpts.Parse()
if err != nil {
return nil, err
}
v.echConfig, err = v.option.ECHOpts.Parse()
if err != nil {
return nil, err
securityModes := make([]string, 0, 5)
if v.shadowTLSConfig != nil {
securityModes = append(securityModes, "ShadowTLS")
}
if v.restlsConfig != nil {
securityModes = append(securityModes, "Restls")
}
if v.jlsConfig != nil {
securityModes = append(securityModes, "JLS")
}
if v.realityConfig != nil {
securityModes = append(securityModes, "REALITY")
}
if option.TLSMirrorOpts.PrimaryKey != "" {
securityModes = append(securityModes, "TLSMirror")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
securityMode := ""
if len(securityModes) == 1 {
securityMode = securityModes[0]
}
if securityMode != "" && !option.TLS {
return nil, fmt.Errorf("%s requires TLS", securityMode)
}
if option.Network == "mkcp" || option.Network == "kcp" {
switch securityMode {
case "ShadowTLS", "Restls", "JLS":
return nil, fmt.Errorf("%s only supports TCP transports", securityMode)
}
}
switch option.Network {
@@ -407,6 +568,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)
@@ -430,13 +614,19 @@ func NewVmess(option VmessOption) (*Vmess, error) {
tlsConfig = &mihomoVMess.TLSConfig{
Host: option.ServerName,
SkipCertVerify: option.SkipCertVerify,
NameCertVerify: option.NameCertVerify,
FingerPrint: option.Fingerprint,
Certificate: option.Certificate,
PrivateKey: option.PrivateKey,
ClientFingerprint: option.ClientFingerprint,
NextProtos: []string{"h2"},
ECH: v.echConfig,
ShadowTLS: v.shadowTLSConfig,
Restls: v.restlsConfig,
JLS: v.jlsConfig,
Reality: v.realityConfig,
TLSMirror: option.TLSMirrorOpts.Build(),
TLSMirrorDialer: proxydialer.New(v, false).DialContext,
}
if option.ServerName == "" {
host, _, _ := net.SplitHostPort(v.addr)
+2 -2
View File
@@ -482,7 +482,7 @@ func (w *WireGuard) genIpcConf(ctx context.Context, updateOnly bool) (string, er
ipcConf += "endpoint=" + destination.String() + "\n"
if len(peer.Reserved) > 0 {
var reserved [3]uint8
copy(reserved[:], w.option.Reserved)
copy(reserved[:], peer.Reserved)
w.bind.SetReservedForEndpoint(destination, reserved)
}
if updateOnly {
@@ -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
}
+14
View File
@@ -111,6 +111,13 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error)
break
}
proxy, err = outbound.NewTuic(*tuicOption)
case "shadowquic":
shadowQuicOption := &outbound.ShadowQuicOption{BasicOption: basicOption}
err = decoder.Decode(mapping, shadowQuicOption)
if err != nil {
break
}
proxy, err = outbound.NewShadowQuic(*shadowQuicOption)
case "gost-relay":
relayOption := &outbound.GostRelayOption{BasicOption: basicOption}
err = decoder.Decode(mapping, relayOption)
@@ -139,6 +146,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)
+10
View File
@@ -16,6 +16,7 @@ type overrideSchema struct {
Down *string `provider:"down,omitempty"`
DialerProxy *string `provider:"dialer-proxy,omitempty"`
SkipCertVerify *bool `provider:"skip-cert-verify,omitempty"`
NameCertVerify *string `provider:"name-cert-verify,omitempty"`
Interface *string `provider:"interface-name,omitempty"`
RoutingMark *int `provider:"routing-mark,omitempty"`
IPVersion *string `provider:"ip-version,omitempty"`
@@ -23,6 +24,7 @@ type overrideSchema struct {
AdditionalPrefix *string `provider:"additional-prefix,omitempty"`
AdditionalSuffix *string `provider:"additional-suffix,omitempty"`
ProxyName []overrideProxyNameSchema `provider:"proxy-name,omitempty"`
OverrideExpr []OverrideExpr `provider:"override-expr,omitempty"`
}
type overrideProxyNameSchema struct {
@@ -59,6 +61,9 @@ func (o *overrideSchema) Apply(mapping map[string]any) error {
if o.SkipCertVerify != nil {
mapping["skip-cert-verify"] = *o.SkipCertVerify
}
if o.NameCertVerify != nil {
mapping["name-cert-verify"] = *o.NameCertVerify
}
if o.Interface != nil {
mapping["interface-name"] = *o.Interface
}
@@ -83,6 +88,11 @@ func (o *overrideSchema) Apply(mapping map[string]any) error {
if o.AdditionalSuffix != nil {
mapping["name"] = fmt.Sprintf("%s%s", mapping["name"], *o.AdditionalSuffix)
}
for idx, expr := range o.OverrideExpr {
if err := expr.Apply(mapping); err != nil {
return fmt.Errorf("override-expr[%d] %q: %w", idx, expr.String(), err)
}
}
return nil
}
File diff suppressed because it is too large. Load diff
+488
View File
@@ -0,0 +1,488 @@
package provider
import (
"math"
"testing"
"github.com/stretchr/testify/require"
"github.com/metacubex/mihomo/common/structure"
)
func mustOverrideExprs(t *testing.T, sources ...string) []OverrideExpr {
t.Helper()
expressions := make([]OverrideExpr, len(sources))
for idx, source := range sources {
expr, err := NewOverrideExpr(source)
require.NoError(t, err)
expressions[idx] = expr
}
return expressions
}
func TestOverrideExprDecode(t *testing.T) {
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
var schema overrideSchema
err := decoder.Decode(map[string]any{
"override-expr": []any{
".udp = true",
`.name = "prefix-" + .name`,
},
}, &schema)
require.NoError(t, err)
require.Len(t, schema.OverrideExpr, 2)
require.Equal(t, ".udp = true", schema.OverrideExpr[0].String())
require.Equal(t, `.name = "prefix-" + .name`, schema.OverrideExpr[1].String())
}
func TestOverrideExprTextRoundTrip(t *testing.T) {
const source = ` .name = "prefix-" + .name # keep formatting`
var expr OverrideExpr
require.NoError(t, expr.UnmarshalText([]byte(source)))
text, err := expr.MarshalText()
require.NoError(t, err)
require.Equal(t, source, string(text))
require.Equal(t, source, expr.String())
}
func TestOverrideExprAssignments(t *testing.T) {
mapping := map[string]any{
"name": "node",
"existing": "keep",
"ports": []any{80, 443},
"tags": []any{"base"},
"weights": map[string]any{"a": 1, "b": 2},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.udp = true`,
`.skip-cert-verify = false`,
`.plugin-opts.mode = "tls"`,
`.ports[1] = 8443`,
`.slots[2].enabled = true`,
`.weights[] += 1`,
`."quoted.field" = "quoted"`,
`.tags += ["edge"]`,
`.missing = .missing // "fallback"`,
`.existing = .existing // "ignored"`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, true, mapping["udp"])
require.Equal(t, false, mapping["skip-cert-verify"])
require.Equal(t, map[string]any{"mode": "tls"}, mapping["plugin-opts"])
require.Equal(t, []any{80, 8443}, mapping["ports"])
require.Equal(t, []any{nil, nil, map[string]any{"enabled": true}}, mapping["slots"])
require.Equal(t, map[string]any{"a": 2, "b": 3}, mapping["weights"])
require.Equal(t, "quoted", mapping["quoted.field"])
require.Equal(t, []any{"base", "edge"}, mapping["tags"])
require.Equal(t, "fallback", mapping["missing"])
require.Equal(t, "keep", mapping["existing"])
}
func TestOverrideExprUpdateFunctionsAndConditionalPath(t *testing.T) {
mapping := map[string]any{
"name": "HK-01",
"score": 3,
"labels": []any{"edge", "premium"},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.name |= sub("^HK-(.*)$"; "Hong Kong $1")`,
`.name = "[Provider] " + .name`,
`.score *= 2`,
`.labels[] |= upcase`,
`.enabled = (.score >= 6 and has("name"))`,
`(select(.score > 5) | .tier) = "fast" | (select(.score <= 5) | .tier) = "slow"`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, "[Provider] Hong Kong 01", mapping["name"])
require.Equal(t, 6, mapping["score"])
require.Equal(t, []any{"EDGE", "PREMIUM"}, mapping["labels"])
require.Equal(t, true, mapping["enabled"])
require.Equal(t, "fast", mapping["tier"])
}
func TestOverrideExprCollectionsAndDelete(t *testing.T) {
mapping := map[string]any{
"password": "secret",
"obsolete": true,
"ports": []any{80, 443, 8080},
"options": map[string]any{
"tls": map[string]any{"sni": "example.com"},
},
"servers": []any{
map[string]any{"host": "a", "secret": "x"},
map[string]any{"host": "b", "secret": "y"},
},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.options *= {"tls": {"enabled": true}, "retries": 3}`,
`.ports -= [80, 8080]`,
`del(.password, .obsolete)`,
`del(.servers[].secret)`,
)}
require.NoError(t, override.Apply(mapping))
require.NotContains(t, mapping, "password")
require.NotContains(t, mapping, "obsolete")
require.Equal(t, []any{443}, mapping["ports"])
require.Equal(t, map[string]any{
"tls": map[string]any{"sni": "example.com", "enabled": true},
"retries": 3,
}, mapping["options"])
require.Equal(t, []any{
map[string]any{"host": "a"},
map[string]any{"host": "b"},
}, mapping["servers"])
}
func TestOverrideExprDeleteUsesOriginalArrayIndexes(t *testing.T) {
mapping := map[string]any{"values": []any{0, 1, 2, 3}}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t, `del(.values[0], .values[2])`)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, []any{1, 3}, mapping["values"])
}
func TestOverrideExprRunsAfterStructuredOverride(t *testing.T) {
udp := true
override := overrideSchema{
UDP: &udp,
OverrideExpr: mustOverrideExprs(t, `.udp = false`),
}
mapping := map[string]any{"name": "node"}
require.NoError(t, override.Apply(mapping))
require.Equal(t, false, mapping["udp"])
}
func TestOverrideExprYQCompatibility(t *testing.T) {
mapping := map[string]any{
"name": "edge-01",
"key.with.dot": "quoted",
"items": []any{"first", "last"},
"csv": "a,b,c",
"number": "42",
"options": map[string]any{"b": 2, "a": 1},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.quoted = .["key.with.dot"]`,
`.quoted-again = ."key.with.dot"`,
`.last = .items[-1]`,
`.csv |= split(",") | .csv |= join("-")`,
`.number |= tonumber`,
`.name-length = .name | .name-length |= length`,
`.option-keys = .options | .option-keys |= keys`,
`.fallback = false // "default"`,
`.calculated = (5 + 3) * 2`,
`. = . * {"root-merged": true}`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, "quoted", mapping["quoted"])
require.Equal(t, "quoted", mapping["quoted-again"])
require.Equal(t, "last", mapping["last"])
require.Equal(t, "a-b-c", mapping["csv"])
require.Equal(t, 42, mapping["number"])
require.Equal(t, 7, mapping["name-length"])
require.Equal(t, []any{"a", "b"}, mapping["option-keys"])
require.Equal(t, "default", mapping["fallback"])
require.Equal(t, 16, mapping["calculated"])
require.Equal(t, true, mapping["root-merged"])
}
func TestOverrideExprOperatorsAndFunctions(t *testing.T) {
testCases := []struct {
name string
input any
expr string
expected any
}{
{name: "negative literal", input: 4, expr: `.value = -4`, expected: -4},
{name: "not", input: true, expr: `.value |= not`, expected: false},
{name: "numeric subtraction", input: 5, expr: `.value -= 2`, expected: 3},
{name: "division", input: 5, expr: `.value = .value / 2`, expected: 2.5},
{name: "string division", input: "a,b", expr: `.value = .value / ","`, expected: []any{"a", "b"}},
{name: "empty string division", input: "", expr: `.value = .value / ","`, expected: []any{}},
{name: "split null can default", input: nil, expr: `.value = (.value | split(",")) // "fallback"`, expected: "fallback"},
{name: "modulo", input: 5, expr: `.value = .value % 2`, expected: 1},
{name: "float modulo", input: 5.5, expr: `.value = .value % 2`, expected: 1.5},
{name: "repeat", input: "ab", expr: `.value *= 2`, expected: "abab"},
{name: "repeat with integer first", input: "ab", expr: `.value = 2 * .value`, expected: "abab"},
{name: "multiply null identity", input: []any{1}, expr: `.value = .value * null`, expected: []any{1}},
{name: "multiply arrays replaces left", input: []any{1}, expr: `.value = .value * [2]`, expected: []any{2}},
{name: "sub replaces all", input: "a-b-c", expr: `.value |= sub("-", "_")`, expected: "a_b_c"},
{name: "test", input: "edge-01", expr: `.value |= test("^edge-")`, expected: true},
{name: "contains string", input: "edge-01", expr: `.value |= contains("ge-")`, expected: true},
{name: "contains array", input: []any{1, 2}, expr: `.value |= contains([2])`, expected: true},
{name: "contains scalar", input: 2, expr: `.value |= contains(2)`, expected: true},
{name: "string plus number", input: "port-", expr: `.value = .value + 443`, expected: "port-443"},
{name: "array plus scalar", input: []any{1}, expr: `.value = .value + 2`, expected: []any{1, 2}},
{name: "null subtraction", input: nil, expr: `.value = .value - 2`, expected: 2},
{name: "shallow map addition", input: map[string]any{"a": 1, "nested": map[string]any{"left": true}}, expr: `.value += {"b": 2, "nested": {"right": true}}`, expected: map[string]any{"a": 1, "b": 2, "nested": map[string]any{"right": true}}},
{name: "not equal", input: 2, expr: `.value = .value != 1`, expected: true},
{name: "numeric types are distinct", input: 1, expr: `.value = .value == 1.0`, expected: false},
{name: "scalar equality uses text", input: 1, expr: `.value = .value == "1"`, expected: true},
{name: "boolean equality uses text", input: true, expr: `.value = .value == "true"`, expected: true},
{name: "less than", input: 1, expr: `.value = .value < 2`, expected: true},
{name: "boolean or", input: false, expr: `.value = (.value or true)`, expected: true},
{name: "trim downcase", input: " EDGE ", expr: `.value |= trim | .value |= downcase`, expected: "edge"},
{name: "comma function arguments", input: "a-b", expr: `.value |= sub("-", "_")`, expected: "a_b"},
{name: "to string", input: []any{1, 2}, expr: `.value |= tostring`, expected: "- 1\n- 2"},
{name: "map to string", input: map[string]any{"a": 1}, expr: `.value |= tostring`, expected: "a: 1"},
{name: "type", input: []any{1}, expr: `.value |= type`, expected: "!!seq"},
{name: "map type", input: map[string]any{"a": 1}, expr: `.value |= type`, expected: "!!map"},
{name: "array keys", input: []any{"a", "b"}, expr: `.value |= keys`, expected: []any{0, 1}},
{name: "has array index", input: []any{"a"}, expr: `.value |= has(0)`, expected: true},
{name: "has negative array index", input: []any{"a"}, expr: `.value |= has(-1)`, expected: true},
{name: "contains keeps scalar tags distinct", input: 1, expr: `.value |= contains(1.0)`, expected: false},
{name: "test accepts global option", input: "edge-edge", expr: `.value |= test("edge", "g")`, expected: true},
{name: "null alternative", input: nil, expr: `.value = ~ // "fallback"`, expected: "fallback"},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
mapping := map[string]any{"value": testCase.input}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t, testCase.expr)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, testCase.expected, mapping["value"])
})
}
}
func TestOverrideExprDivisionAndModuloByZero(t *testing.T) {
mapping := map[string]any{"one": 1, "zero": 0, "float": 1.5}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.infinite = .one / .zero`,
`.not-a-number = .zero / .zero`,
`.float-modulo = .float % .zero`,
)}
require.NoError(t, override.Apply(mapping))
require.True(t, math.IsInf(mapping["infinite"].(float64), 1))
require.True(t, math.IsNaN(mapping["not-a-number"].(float64)))
require.True(t, math.IsNaN(mapping["float-modulo"].(float64)))
}
func TestOverrideExprSelectAndPipelines(t *testing.T) {
mapping := map[string]any{
"name": " edge ",
"score": 8,
"servers": []any{
map[string]any{"name": "first", "enabled": true},
map[string]any{"name": "second", "enabled": false},
},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.name = (.name | trim | upcase)`,
`(select(.score > 5) | .tier) = "fast"`,
`(select(.score < 0) | .ignored) = true`,
`(.servers[] | select(.enabled) | .name) |= upcase`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, "EDGE", mapping["name"])
require.Equal(t, "fast", mapping["tier"])
require.NotContains(t, mapping, "ignored")
require.Equal(t, []any{
map[string]any{"name": "FIRST", "enabled": true},
map[string]any{"name": "second", "enabled": false},
}, mapping["servers"])
lowScore := map[string]any{"score": 3}
conditional := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`(select(.score > 5) | .tier) = "fast" | (select(.score <= 5) | .tier) = "slow"`,
)}
require.NoError(t, conditional.Apply(lowScore))
require.Equal(t, "slow", lowScore["tier"])
}
func TestOverrideExprYQBehaviorDetails(t *testing.T) {
testCases := []struct {
name string
input any
expr string
expected any
}{
{name: "scalar path produces null", input: "text", expr: `.result = .value.missing`, expected: nil},
{name: "scalar path can default", input: "text", expr: `.result = .value.missing // "fallback"`, expected: "fallback"},
{name: "recursive contains array", input: []any{map[string]any{"a": 1, "b": 2}}, expr: `.result = (.value | contains([{"a": 1}]))`, expected: true},
{name: "recursive contains map", input: map[string]any{"a": map[string]any{"b": 1, "c": 2}}, expr: `.result = (.value | contains({"a": {"b": 1}}))`, expected: true},
{name: "float type", input: 1.0, expr: `.result = (.value | type)`, expected: "!!float"},
{name: "number length", input: 1234, expr: `.result = (.value | length)`, expected: 4},
{name: "bool length", input: false, expr: `.result = (.value | length)`, expected: 5},
{name: "null length", input: nil, expr: `.result = (.value | length)`, expected: 0},
{name: "array length", input: []any{1, 2}, expr: `.result = (.value | length)`, expected: 2},
{name: "map length", input: map[string]any{"a": 1, "b": 2}, expr: `.result = (.value | length)`, expected: 2},
{name: "unicode byte length", input: "a界", expr: `.result = (.value | length)`, expected: 4},
{name: "join skips collections", input: []any{"a", nil, []any{1}, map[string]any{"a": 1}, 2}, expr: `.result = (.value | join("-"))`, expected: "a----2"},
{name: "has rejects float index", input: []any{"a"}, expr: `.result = (.value | has(0.5))`, expected: false},
{name: "decimal leading zero", input: "010", expr: `.result = (.value | tonumber)`, expected: 10},
{name: "octal", input: "0o10", expr: `.result = (.value | tonumber)`, expected: 8},
{name: "hexadecimal", input: "0x10", expr: `.result = (.value | tonumber)`, expected: 16},
{name: "float", input: "1.5", expr: `.result = (.value | tonumber)`, expected: 1.5},
{name: "unknown string escape stays literal", input: nil, expr: `.result = "a\tb\u754c"`, expected: `a\tb\u754c`},
{name: "array equality", input: []any{1, 2}, expr: `.result = (.value == [1, 2])`, expected: false},
{name: "mapping inequality", input: map[string]any{"a": 1}, expr: `.result = (.value != {"a": 1})`, expected: true},
{name: "null comparison", input: nil, expr: `.result = (.value < false)`, expected: false},
{name: "null equality comparison", input: nil, expr: `.result = (.value <= null)`, expected: true},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
mapping := map[string]any{"value": testCase.input}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t, testCase.expr)}
require.NoError(t, override.Apply(mapping))
require.Contains(t, mapping, "result")
require.Equal(t, testCase.expected, mapping["result"])
})
}
}
func TestOverrideExprInterpolationAndCollections(t *testing.T) {
mapping := map[string]any{
"name": "node",
"type": "ss",
"port": 443,
"options": map[string]any{"b": 2, "a": 1},
"mixed": []any{3, nil, false, 2, true},
"duplicates": []any{1, 1, "1", "1"},
"nested": []any{1, []any{2, []any{3}}},
"truthy": []any{nil, false, "value"},
"all-true": []any{1, "value", true},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.label = "[\(.type)] \(.name):\(.port)"`,
`.fallback-label = "\(.missing // \"default\")-\(.name)"`,
`.first-label = "\((.name, .type))"`,
`.options-text = "\(.options)"`,
`.hex = 0x10`,
`.reversed = (.mixed | reverse)`,
`.sorted = (.mixed | sort)`,
`.deduplicated = (.duplicates | unique)`,
`.flattened = (.nested | flatten)`,
`.flattened-once = (.nested | flatten(1))`,
`.has-truthy = (.truthy | any)`,
`.all-truthy = (.all-true | all)`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, "[ss] node:443", mapping["label"])
require.Equal(t, "default-node", mapping["fallback-label"])
require.Equal(t, "node", mapping["first-label"])
require.Equal(t, "a: 1\nb: 2", mapping["options-text"])
require.Equal(t, 16, mapping["hex"])
require.Equal(t, []any{true, 2, false, nil, 3}, mapping["reversed"])
require.Equal(t, []any{nil, false, true, 2, 3}, mapping["sorted"])
require.Equal(t, []any{1}, mapping["deduplicated"])
require.Equal(t, []any{1, 2, 3}, mapping["flattened"])
require.Equal(t, []any{1, 2, []any{3}}, mapping["flattened-once"])
require.Equal(t, true, mapping["has-truthy"])
require.Equal(t, true, mapping["all-truthy"])
}
func TestOverrideExprMultiResultPipelines(t *testing.T) {
mapping := map[string]any{
"items": []any{
map[string]any{"name": "first", "port": 80, "enabled": true},
map[string]any{"name": "second", "port": 443, "enabled": false},
},
"scores": map[string]any{"a": 1, "b": 2},
"options": map[string]any{"a": 1, "b": 2},
}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.names = [.items[].name]`,
`.enabled-names = [.items[] | select(.enabled) | .name]`,
`.name-ports = [.items[] | (.name, .port)]`,
`.incremented-ports = [.items[].port + 1]`,
`.mapped-names = (.items | map(.name))`,
`.mapped-union = (.items | map(.name, .port))`,
`.filtered = (.items | filter(.enabled))`,
`.mapped-scores = (.scores | map_values(. + 1))`,
`.selected-scores = (.scores | map_values(select(. > 1)))`,
`.entries = (.options | to_entries)`,
`.roundtrip = (.options | to_entries | from_entries)`,
`.upper-options = (.options | with_entries(.key |= upcase))`,
`.has-large-port = ([.items[].port] | any_c(. > 100))`,
`.all-positive = ([.items[].port] | all_c(. > 0))`,
`.no-matches = [.items[] | select(false)]`,
`.defaults = [.items[].missing // "default"]`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, []any{"first", "second"}, mapping["names"])
require.Equal(t, []any{"first"}, mapping["enabled-names"])
require.Equal(t, []any{"first", "second", 80, 443}, mapping["name-ports"])
require.Equal(t, []any{81, 444}, mapping["incremented-ports"])
require.Equal(t, []any{"first", "second"}, mapping["mapped-names"])
require.Equal(t, []any{"first", "second", 80, 443}, mapping["mapped-union"])
require.Equal(t, []any{map[string]any{"name": "first", "port": 80, "enabled": true}}, mapping["filtered"])
require.Equal(t, map[string]any{"a": 2, "b": 3}, mapping["mapped-scores"])
require.Equal(t, map[string]any{"a": 1, "b": 2}, mapping["selected-scores"])
require.Equal(t, []any{
map[string]any{"key": "a", "value": 1},
map[string]any{"key": "b", "value": 2},
}, mapping["entries"])
require.Equal(t, map[string]any{"a": 1, "b": 2}, mapping["roundtrip"])
require.Equal(t, map[string]any{"A": 1, "B": 2}, mapping["upper-options"])
require.Equal(t, true, mapping["has-large-port"])
require.Equal(t, true, mapping["all-positive"])
require.Equal(t, []any{}, mapping["no-matches"])
require.Equal(t, []any{"default", "default"}, mapping["defaults"])
}
func TestOverrideExprMappingValuesUseYQStreamSemantics(t *testing.T) {
mapping := map[string]any{"items": []any{1, 2}}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`.result = {"omitted": select(false), "last": (.items[])}`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, map[string]any{"last": 2}, mapping["result"])
}
func TestOverrideExprRequiresMultiResultsToBeCollected(t *testing.T) {
mapping := map[string]any{"items": []any{1, 2}}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t, `.result = (.items[])`)}
err := override.Apply(mapping)
require.ErrorContains(t, err, "expression produced 2 results")
require.ErrorContains(t, err, "collect them with [...]")
}
func TestOverrideExprTopLevelFilterPipeline(t *testing.T) {
mapping := map[string]any{"name": "node", "udp": false}
override := overrideSchema{OverrideExpr: mustOverrideExprs(t,
`. | with_entries(.key |= upcase)`,
`{"name": .NAME, "udp": .UDP, "type": "ss"}`,
)}
require.NoError(t, override.Apply(mapping))
require.Equal(t, map[string]any{"name": "node", "udp": false, "type": "ss"}, mapping)
}
func TestOverrideExprErrors(t *testing.T) {
t.Run("syntax", func(t *testing.T) {
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
var schema overrideSchema
err := decoder.Decode(map[string]any{"override-expr": []any{`.udp =`}}, &schema)
require.ErrorContains(t, err, "override-expr[0]")
require.ErrorContains(t, err, "expected value")
})
t.Run("runtime", func(t *testing.T) {
override := overrideSchema{OverrideExpr: mustOverrideExprs(t, `.port += [1]`)}
mapping := map[string]any{"port": 443}
err := override.Apply(mapping)
require.ErrorContains(t, err, `override-expr[0] ".port += [1]"`)
require.ErrorContains(t, err, "operator + cannot be used")
})
t.Run("string repeat limit", func(t *testing.T) {
override := overrideSchema{OverrideExpr: mustOverrideExprs(t, `.value = "x" * 10000001`)}
err := override.Apply(map[string]any{"value": "x"})
require.ErrorContains(t, err, "cannot exceed 10 million")
})
}
+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 }
+3 -1
View File
@@ -28,7 +28,9 @@ func (c *CachedConn) Read(b []byte) (n int, err error) {
func (c *CachedConn) ReadCached() *buf.Buffer { // call in sing/common/bufio.Copy
if len(c.data) > 0 {
return buf.As(c.data)
data := c.data
c.data = nil
return buf.As(data)
}
return nil
}
+22
View File
@@ -37,3 +37,25 @@ func SetupContextForConn(ctx context.Context, conn net.Conn) (done func(*error))
}
}
}
// RelayContext copies between left and right bidirectionally.
// If ctx is canceled, both connections are closed to interrupt pending I/O.
func RelayContext(ctx context.Context, leftConn, rightConn net.Conn) error {
if ctx.Done() == nil {
Relay(leftConn, rightConn)
return nil
}
done := make(chan struct{})
stop := contextutils.AfterFunc(ctx, func() {
_ = leftConn.Close()
_ = rightConn.Close()
close(done)
})
Relay(leftConn, rightConn)
if !stop() {
<-done
return ctx.Err()
}
return nil
}
+29
View File
@@ -101,3 +101,32 @@ func TestSetupContextForConnWithTimeout2(t *testing.T) {
t.Fatal("conn not be canceled")
}
}
func TestRelayContextWithCancel(t *testing.T) {
t.Parallel()
leftConn, leftPeer := N.Pipe()
rightConn, rightPeer := N.Pipe()
defer leftPeer.Close()
defer rightPeer.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
errc := make(chan error)
go func() {
errc <- N.RelayContext(ctx, leftConn, rightConn)
}()
select {
case <-errc:
t.Fatal("relay stopped before cancel")
case <-time.After(100 * time.Millisecond):
cancel()
}
select {
case err := <-errc:
assert.ErrorIs(t, err, context.Canceled)
case <-time.After(100 * time.Millisecond):
t.Fatal("relay was not canceled")
}
}
+28
View File
@@ -0,0 +1,28 @@
package net
import "net"
type netConn interface {
NetConn() net.Conn
}
// FindUpstream finds a value in an upstream wrapper chain. If accept rejects a
// matching value, the search continues so an outer wrapper cannot hide a valid
// inner value of the same type.
func FindUpstream[T any](value any, accept func(T) bool) (T, bool) {
for value != nil {
if candidate, ok := value.(T); ok && (accept == nil || accept(candidate)) {
return candidate, true
}
switch wrapper := value.(type) {
case WithUpstream:
value = wrapper.Upstream()
case netConn:
value = wrapper.NetConn()
default:
value = nil
}
}
var zero T
return zero, false
}
+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 }
+17 -6
View File
@@ -77,11 +77,12 @@ func GetCertPool() *x509.CertPool {
}
type Option struct {
TLSConfig *tls.Config
Fingerprint string
ZeroTrust bool
Certificate string
PrivateKey string
TLSConfig *tls.Config
Fingerprint string
NameCertVerify string
ZeroTrust bool
Certificate string
PrivateKey string
}
func GetTLSConfig(opt Option) (tlsConfig *tls.Config, err error) {
@@ -106,7 +107,17 @@ func GetTLSConfig(opt Option) (tlsConfig *tls.Config, err error) {
// [ConnectionState.ServerName] can return the actual ServerName needed for verification,
// avoiding inconsistencies caused by [tlsConfig.ServerName] being modified after the [NewFingerprintVerifier] call.
// https://github.com/golang/go/issues/36736#issuecomment-587925536
return verifier(state.PeerCertificates, state.ServerName)
serverName := state.ServerName
if opt.NameCertVerify != "" {
serverName = opt.NameCertVerify
}
return verifier(state.PeerCertificates, serverName)
}
tlsConfig.InsecureSkipVerify = true
} else if opt.NameCertVerify != "" {
verifier := NewNameCertVerifier(opt.NameCertVerify, tlsConfig.RootCAs, tlsConfig.Time)
tlsConfig.VerifyConnection = func(state tls.ConnectionState) error {
return verifier(state.PeerCertificates)
}
tlsConfig.InsecureSkipVerify = true
}
+31
View File
@@ -0,0 +1,31 @@
package ca
import (
"crypto/x509"
"errors"
"time"
)
// NewNameCertVerifier returns a verifier for a certificate chain and an explicit DNSName.
func NewNameCertVerifier(dnsName string, roots *x509.CertPool, now func() time.Time) func([]*x509.Certificate) error {
return func(certificates []*x509.Certificate) error {
if len(certificates) == 0 {
return errors.New("tls: no peer certificates")
}
intermediates := x509.NewCertPool()
for _, certificate := range certificates[1:] {
intermediates.AddCert(certificate)
}
verifyOptions := x509.VerifyOptions{
Roots: roots,
Intermediates: intermediates,
DNSName: dnsName,
}
if now != nil {
verifyOptions.CurrentTime = now()
}
_, err := certificates[0].Verify(verifyOptions)
return err
}
}
+98
View File
@@ -0,0 +1,98 @@
package ca
import (
"crypto/x509"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestNameCertVerifier(t *testing.T) {
roots := x509.NewCertPool()
roots.AddCert(rootCert)
untrustedRoots := x509.NewCertPool()
untrustedRoots.AddCert(smimeRootCert)
tests := []struct {
name string
dnsName string
roots *x509.CertPool
now func() time.Time
certificates []*x509.Certificate
wantErr bool
}{
{
name: "valid chain",
dnsName: leafServerName,
roots: roots,
now: certTime,
certificates: []*x509.Certificate{leafCert, intermediateCert},
},
{
name: "valid chain with root",
dnsName: leafServerName,
roots: roots,
now: certTime,
certificates: []*x509.Certificate{leafCert, intermediateCert, rootCert},
},
{
name: "wrong DNS name",
dnsName: wrongLeafServerName,
roots: roots,
now: certTime,
certificates: []*x509.Certificate{leafCert, intermediateCert},
wantErr: true,
},
{
name: "no certificates",
dnsName: leafServerName,
roots: roots,
now: certTime,
wantErr: true,
},
{
name: "missing intermediate",
dnsName: leafServerName,
roots: roots,
now: certTime,
certificates: []*x509.Certificate{leafCert},
wantErr: true,
},
{
name: "untrusted root",
dnsName: leafServerName,
roots: untrustedRoots,
now: certTime,
certificates: []*x509.Certificate{leafCert, intermediateCert},
wantErr: true,
},
{
name: "expired certificate",
dnsName: leafServerName,
roots: roots,
now: func() time.Time { return leafCert.NotAfter.Add(time.Second) },
certificates: []*x509.Certificate{leafCert, intermediateCert},
wantErr: true,
},
{
name: "invalid certificate signature",
dnsName: leafServerName,
roots: roots,
now: certTime,
certificates: []*x509.Certificate{leafWithInvalidHashCert, intermediateCert},
wantErr: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := NewNameCertVerifier(test.dnsName, test.roots, test.now)(test.certificates)
if test.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}
}
+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:
+98 -83
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)
}
@@ -985,11 +997,11 @@ func parseListeners(cfg *RawConfig) (listeners map[string]C.InboundListener, err
for index, mapping := range cfg.Listeners {
inboundListener, err := listener.ParseListener(mapping)
if err != nil {
return nil, fmt.Errorf("proxy %d: %w", index, err)
return nil, fmt.Errorf("listener %d: %w", index, err)
}
name := inboundListener.Name()
if _, exist := mapping[name]; exist {
if _, exist := listeners[name]; exist {
return nil, fmt.Errorf("listener %s is the duplicate name", name)
}
@@ -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,
+6
View File
@@ -22,6 +22,7 @@ const (
Compatible
Pass
PassRule
Rematch
Dns
Relay
@@ -48,6 +49,7 @@ const (
Sudoku
Masque
TrustTunnel
ShadowQuic
OpenVPN
Tailscale
GostRelay
@@ -186,6 +188,8 @@ func (at AdapterType) String() string {
return "Pass"
case PassRule:
return "PassRule"
case Rematch:
return "Rematch"
case Dns:
return "Dns"
case Shadowsocks:
@@ -224,6 +228,8 @@ func (at AdapterType) String() string {
return "Masque"
case TrustTunnel:
return "TrustTunnel"
case ShadowQuic:
return "ShadowQuic"
case OpenVPN:
return "OpenVPN"
case Tailscale:
+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)
}
+6
View File
@@ -42,6 +42,7 @@ const (
MIERU
SUDOKU
TRUSTTUNNEL
SHADOWQUIC
INNER
)
@@ -121,6 +122,8 @@ func (t Type) String() string {
return "Sudoku"
case TRUSTTUNNEL:
return "TrustTunnel"
case SHADOWQUIC:
return "ShadowQuic"
case INNER:
return "Inner"
default:
@@ -169,6 +172,8 @@ func ParseType(t string) (*Type, error) {
res = SUDOKU
case "TRUSTTUNNEL":
res = TRUSTTUNNEL
case "SHADOWQUIC":
res = SHADOWQUIC
case "INNER":
res = INNER
default:
@@ -197,6 +202,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,
+5 -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"
@@ -68,13 +69,14 @@ type dnsOverHTTPS struct {
dialer *dnsDialer
addr string
skipCertVerify bool
nameCertVerify string
}
// type check
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 {
@@ -99,6 +101,7 @@ func newDoHClient(urlString string, r *Resolver, preferH3 bool, params map[strin
if params["skip-cert-verify"] == "true" {
doh.skipCertVerify = true
}
doh.nameCertVerify = params["name-cert-verify"]
runtime.SetFinalizer(doh, (*dnsOverHTTPS).Close)
@@ -405,6 +408,7 @@ func (doh *dnsOverHTTPS) createTransport(ctx context.Context) (t http.RoundTripp
MinVersion: tls.VersionTLS12,
SessionTicketsDisabled: false,
},
NameCertVerify: doh.nameCertVerify,
})
if err != nil {
return nil, err
+5 -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"
@@ -61,13 +62,14 @@ type dnsOverQUIC struct {
addr string
dialer *dnsDialer
skipCertVerify bool
nameCertVerify string
}
// type check
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),
@@ -80,6 +82,7 @@ func newDoQ(addr string, resolver *Resolver, params map[string]string, proxyAdap
if params["skip-cert-verify"] == "true" {
doq.skipCertVerify = true
}
doq.nameCertVerify = params["name-cert-verify"]
runtime.SetFinalizer(doq, (*dnsOverQUIC).Close)
return doq
@@ -348,6 +351,7 @@ func (doq *dnsOverQUIC) openConnection(ctx context.Context) (quicConn *quic.Conn
},
SessionTicketsDisabled: false,
},
NameCertVerify: doq.nameCertVerify,
})
if err != nil {
return nil, err
+5 -1
View File
@@ -3,6 +3,7 @@ package dns
import (
"context"
"fmt"
"github.com/metacubex/mihomo/component/resolver"
"net"
"runtime"
"sync"
@@ -23,6 +24,7 @@ type dnsOverTLS struct {
host string
dialer *dnsDialer
skipCertVerify bool
nameCertVerify string
disableReuse bool
access sync.Mutex
@@ -127,6 +129,7 @@ func (t *dnsOverTLS) dialContext(ctx context.Context) (net.Conn, error) {
ServerName: t.host,
InsecureSkipVerify: t.skipCertVerify,
},
NameCertVerify: t.nameCertVerify,
})
if err != nil {
_ = conn.Close()
@@ -159,7 +162,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,
@@ -170,6 +173,7 @@ func newDoTClient(addr string, resolver *Resolver, params map[string]string, pro
if params["skip-cert-verify"] == "true" {
c.skipCertVerify = true
}
c.nameCertVerify = params["name-cert-verify"]
if params["disable-reuse"] == "true" {
c.disableReuse = true
}
+1 -1
View File
@@ -82,7 +82,7 @@ func withHosts(mapping *lru.LruCache[netip.Addr, string]) middleware {
case D.TypeAAAA:
handleIPs()
case D.TypeCNAME:
handleCName(r, record.Domain)
handleCName(msg, record.Domain)
default:
return next(ctx, r)
}
+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
+574 -31
View File
File diff suppressed because it is too large. Load diff
+16 -15
View File
@@ -6,45 +6,46 @@ 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
github.com/metacubex/fswatch v0.1.1
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759
github.com/metacubex/http v0.1.6
github.com/metacubex/jls-quic-go v0.0.0-20260717074316-85a8decdd355
github.com/metacubex/jls-tls v0.0.0-20260716145614-4bf88db633e2
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-20260711142031-e2257fe61058
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 +79,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 +118,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
+32 -30
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=
@@ -131,6 +131,10 @@ github.com/metacubex/hpke v0.1.0 h1:gu2jUNhraehWi0P/z5HX2md3d7L1FhPQE6/Q0E9r9xQ=
github.com/metacubex/hpke v0.1.0/go.mod h1:vfDm6gfgrwlXUxKDkWbcE44hXtmc1uxLDm2BcR11b3U=
github.com/metacubex/http v0.1.6 h1:xvXuvXMCMxCWMF5nEJF4yiKvXL+p2atWMzs37e80m1I=
github.com/metacubex/http v0.1.6/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
github.com/metacubex/jls-quic-go v0.0.0-20260717074316-85a8decdd355 h1:DD4qraoIY3IbkHxaBbpJR68sWNzrdKHfFRfFhT6m1W8=
github.com/metacubex/jls-quic-go v0.0.0-20260717074316-85a8decdd355/go.mod h1:dbfkDUKqohALRmgUrVIOLirCNfKjgaos9nfTnBRTpS8=
github.com/metacubex/jls-tls v0.0.0-20260716145614-4bf88db633e2 h1:n+qiR8opOJEerewq/S92zGoHBDXZb+dKmyYq0aKJtis=
github.com/metacubex/jls-tls v0.0.0-20260716145614-4bf88db633e2/go.mod h1:mmqs889W/TqPlfNRDa2UyJvRiLyiTJIEnWHkcj3SKB8=
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df h1:S0vBzqjXok24VopstOgPd1JdgglW9tXehrqvwpQWbQ8=
github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df/go.mod h1:F4sVXat6QjPXkNsKRDyyG3BhSkxPFFnRPEIwmmyCgbg=
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604 h1:hJwCVlE3ojViC35MGHB+FBr8TuIf3BUFn2EQ1VIamsI=
@@ -145,28 +149,26 @@ 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=
github.com/metacubex/sing-shadowsocks v0.2.12/go.mod h1:2e5EIaw0rxKrm1YTRmiMnDulwbGxH9hAFlrwQLQMQkU=
github.com/metacubex/sing-shadowsocks2 v0.2.7 h1:hSuuc0YpsfiqYqt1o+fP4m34BQz4e6wVj3PPBVhor3A=
github.com/metacubex/sing-shadowsocks2 v0.2.7/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE=
github.com/metacubex/sing-shadowtls v0.0.0-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 +177,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-20260711142031-e2257fe61058 h1:TFM/yl2XvyMDQY16GHDxXtuJMa8DGz7roRpY6plxLMk=
github.com/metacubex/tailscale v0.0.0-20260711142031-e2257fe61058/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
+50 -4
View File
@@ -15,6 +15,9 @@ import (
"github.com/metacubex/mihomo/component/ech"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/jls"
"github.com/metacubex/mihomo/listener/restls"
"github.com/metacubex/mihomo/listener/shadowtls"
"github.com/metacubex/mihomo/listener/sing"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/mihomo/transport/anytls/padding"
@@ -35,7 +38,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"),
@@ -43,6 +46,9 @@ func New(config LC.AnyTLSServer, tunnel C.Tunnel, additions ...inbound.Addition)
}
}
var shadowTLSBuilder *shadowtls.Builder
var restlsBuilder *restls.Builder
var jlsBuilder *jls.Builder
tlsConfig := &tls.Config{Time: ntp.Now}
if config.Certificate != "" && config.PrivateKey != "" {
certLoader, err := ca.NewTLSKeyPairLoader(config.Certificate, config.PrivateKey)
@@ -73,6 +79,40 @@ func New(config LC.AnyTLSServer, tunnel C.Tunnel, additions ...inbound.Addition)
}
tlsConfig.ClientCAs = pool
}
if tlsConfig.ClientAuth != tls.NoClientCert && tlsConfig.GetCertificate == nil {
return nil, errors.New("client-auth requires certificate")
}
securityModes := make([]string, 0, 4)
if tlsConfig.GetCertificate != nil {
securityModes = append(securityModes, "certificate")
}
if config.ShadowTLS.Enable {
securityModes = append(securityModes, "shadow-tls")
}
if config.ResTLS.Enable {
securityModes = append(securityModes, "res-tls")
}
if config.JLSConfig.Enable {
securityModes = append(securityModes, "jls")
}
if len(securityModes) > 1 {
return nil, errors.New("security modes are mutually exclusive: " + strings.Join(securityModes, ", "))
}
if config.ShadowTLS.Enable {
shadowTLSBuilder, err = shadowtls.New(config.ShadowTLS, tunnel)
if err != nil {
return nil, err
}
}
if config.ResTLS.Enable {
restlsBuilder = restls.New(config.ResTLS, tunnel)
}
if config.JLSConfig.Enable {
jlsBuilder, err = jls.New(config.JLSConfig, tunnel)
if err != nil {
return nil, err
}
}
sl = &Listener{
config: config,
@@ -106,14 +146,20 @@ func New(config LC.AnyTLSServer, tunnel C.Tunnel, additions ...inbound.Addition)
addr := addr
//TCP
l, err := inbound.Listen("tcp", addr)
l, err := lc.Listen(context.Background(), "tcp", addr)
if err != nil {
return nil, err
}
if tlsConfig.GetCertificate != nil {
if shadowTLSBuilder != nil {
l = shadowTLSBuilder.NewListener(l)
} else if restlsBuilder != nil {
l = restlsBuilder.NewListener(l)
} else if jlsBuilder != nil {
l = jlsBuilder.NewListener(l)
} else if tlsConfig.GetCertificate != nil {
l = tls.NewListener(l, tlsConfig)
} else if !config.AllowInsecure {
return nil, errors.New("disallow using AnyTLS without certificates/allow-insecure config")
return nil, errors.New("disallow using AnyTLS without certificates/shadow-tls/res-tls/jls/allow-insecure config")
}
sl.listeners = append(sl.listeners, l)
+5 -2
View File
@@ -8,11 +8,14 @@ type AnyTLSServer struct {
Enable bool `yaml:"enable" json:"enable"`
Listen string `yaml:"listen" json:"listen"`
Users map[string]string `yaml:"users" json:"users,omitempty"`
Certificate string `yaml:"certificate" json:"certificate"`
PrivateKey string `yaml:"private-key" json:"private-key"`
Certificate string `yaml:"certificate,omitempty" json:"certificate,omitempty"`
PrivateKey string `yaml:"private-key,omitempty" json:"private-key,omitempty"`
ClientAuthType string `yaml:"client-auth-type" json:"client-auth-type,omitempty"`
ClientAuthCert string `yaml:"client-auth-cert" json:"client-auth-cert,omitempty"`
EchKey string `yaml:"ech-key" json:"ech-key,omitempty"`
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
ResTLS ResTLS `yaml:"res-tls" json:"res-tls,omitempty"`
JLSConfig JLSConfig `yaml:"jls-config" json:"jls-config,omitempty"`
AllowInsecure bool `yaml:"allow-insecure" json:"allow-insecure,omitempty"`
PaddingScheme string `yaml:"padding-scheme" json:"padding-scheme,omitempty"`
}
+1
View File
@@ -49,6 +49,7 @@ type Hysteria2RealmOption struct {
// for ServerURL
SNI string `yaml:"sni" json:"sni,omitempty"`
SkipCertVerify bool `yaml:"skip-cert-verify" json:"skip-cert-verify,omitempty"`
NameCertVerify string `yaml:"name-cert-verify" json:"name-cert-verify,omitempty"`
Fingerprint string `yaml:"fingerprint" json:"fingerprint,omitempty"`
Certificate string `yaml:"certificate" json:"certificate,omitempty"`
PrivateKey string `yaml:"private-key" json:"private-key,omitempty"`
+16
View File
@@ -0,0 +1,16 @@
package config
type JLSConfig struct {
Enable bool
Users []JLSUser
SNI string
Dest string
ALPN []string
Proxy string
RateLimit uint64
}
type JLSUser struct {
Username string
Password string
}
+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)
}
+47
View File
@@ -0,0 +1,47 @@
package config
import (
"encoding/json"
"github.com/metacubex/mihomo/listener/sing"
)
type ShadowQuicUser struct {
Username string `yaml:"username" json:"username"`
Password string `yaml:"password" json:"password"`
}
type ShadowQuicJLSUpstream struct {
Addr string `yaml:"addr" json:"addr"`
SNI string `yaml:"sni" json:"sni,omitempty"`
Proxy string `yaml:"proxy" json:"proxy,omitempty"`
RateLimit uint64 `yaml:"rate-limit" json:"rate-limit,omitempty"`
QUICVersionProbe bool `yaml:"quic-version-probe" json:"quic-version-probe,omitempty"`
}
type ShadowQuicServer struct {
Enable bool `yaml:"enable" json:"enable"`
Listen string `yaml:"listen" json:"listen"`
Users []ShadowQuicUser `yaml:"users" json:"users,omitempty"`
JLSUpstream ShadowQuicJLSUpstream `yaml:"jls-upstream" json:"jls-upstream"`
ALPN []string `yaml:"alpn" json:"alpn,omitempty"`
QUICVersions []string `yaml:"quic-versions" json:"quic-versions,omitempty"`
ZeroRTT bool `yaml:"zero-rtt" json:"zero-rtt,omitempty"`
CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
Up string `yaml:"up" json:"up,omitempty"`
Down string `yaml:"down" json:"down,omitempty"`
IgnoreClientBandwidth bool `yaml:"ignore-client-bandwidth" json:"ignore-client-bandwidth,omitempty"`
MaxIdleTime int `yaml:"max-idle-time" json:"max-idle-time,omitempty"`
MaxDatagramFrameSize int `yaml:"max-datagram-frame-size" json:"max-datagram-frame-size,omitempty"`
ReceiveWindowConn int `yaml:"recv-window-conn" json:"recv-window-conn,omitempty"`
ReceiveWindow int `yaml:"recv-window" json:"recv-window,omitempty"`
DisableMTUDiscovery bool `yaml:"disable-mtu-discovery" json:"disable-mtu-discovery,omitempty"`
CWND int `yaml:"cwnd" json:"cwnd,omitempty"`
BBRProfile string `yaml:"bbr-profile" json:"bbr-profile,omitempty"`
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
}
func (s ShadowQuicServer) String() string {
b, _ := json.Marshal(s)
return string(b)
}
+2
View File
@@ -14,6 +14,8 @@ 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"`
JLSConfig JLSConfig `yaml:"jls-config" json:"jls-config,omitempty"`
KcpTun KcpTun `yaml:"kcp-tun" json:"kcp-tun,omitempty"`
SimpleObfs SimpleObfs `yaml:"simple-obfs" json:"simple-obfs,omitempty"`
}
+20
View File
@@ -0,0 +1,20 @@
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"`
ResTLS ResTLS `yaml:"res-tls" json:"res-tls,omitempty"`
JLSConfig JLSConfig `yaml:"jls-config" json:"jls-config,omitempty"`
}
func (c SnellServer) String() string {
b, _ := json.Marshal(c)
return string(b)
}
+4 -1
View File
@@ -24,7 +24,10 @@ type TrojanServer struct {
ClientAuthCert string
EchKey string
AllowInsecure bool
RealityConfig reality.Config
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
ResTLS ResTLS `yaml:"res-tls" json:"res-tls,omitempty"`
JLSConfig JLSConfig `yaml:"jls-config" json:"jls-config,omitempty"`
RealityConfig reality.Config `yaml:"reality-config" json:"reality-config,omitempty"`
MuxOption sing.MuxOption
TrojanSSOption TrojanSSOption
}
+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
+4 -1
View File
@@ -27,7 +27,10 @@ type VlessServer struct {
ClientAuthCert string
EchKey string
AllowInsecure bool
RealityConfig reality.Config
ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"`
ResTLS ResTLS `yaml:"res-tls" json:"res-tls,omitempty"`
JLSConfig JLSConfig `yaml:"jls-config" json:"jls-config,omitempty"`
RealityConfig reality.Config `yaml:"reality-config" json:"reality-config,omitempty"`
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
}
+57 -2
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 {
@@ -24,8 +25,62 @@ type VmessServer struct {
ClientAuthType string
ClientAuthCert string
EchKey string
RealityConfig reality.Config
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"`
JLSConfig JLSConfig `yaml:"jls-config" json:"jls-config,omitempty"`
RealityConfig reality.Config `yaml:"reality-config" json:"reality-config,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
}
Loaded 100 of 293 files, more files were not shown because too many files have changed in this diff. Show more